The device a file's colours are meant for

The output intent a file carries, printed on the page it describes: the printing conditions, their description and the profile behind them, with a ramp and one swatch per ink painted through that same profile. Hand a press profile on the command line and the page is drawn in that press's inks instead.

Rust write_output_intent.rs 578 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! The device a document's colours are meant for, stated in the file.
//!
//! A page that fills a rectangle with four numbers has said four numbers and
//! nothing about what colour they are. The output intent is the answer: the
//! profile of the device the job was prepared for, travelling inside the file,
//! together with the name of that device's condition. An archival claim makes
//! stating one compulsory, and a job separated for a press states the press's
//! own profile rather than the screen the library falls back to.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is written in. What the file states is not language: the
//! name of the condition and the name of the profile travel as they are given.
//!
//! Usage: `cargo run --example write_output_intent -- tmp/intent.pdf [font.ttf]
//! [press.icc]`
//!        `HQF_PDF_LANG=fr cargo run --example write_output_intent --
//! tmp/intention.pdf`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::color::icc;
use hqf_pdf::content::Content;
use hqf_pdf::metadata::xmp::{Metadata, PdfA};
use hqf_pdf::{
    Color, ColorSpaceHandle, Document, Error, Font, FontHandle, IccBased, OutputIntent, Page,
};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The left edge of everything.
const LEFT: f64 = 70.0;

/// How far in from `LEFT` the values of the intent's rows are set, which is the
/// room the labels beside them have.
const VALUE_IN: f64 = 100.0;

/// The date the document says it was made on, so that two runs of the example
/// produce the same bytes.
const MADE: &str = "2026-07-25T10:00:00+02:00";

/// The claim the file makes, which is a name the standard gives rather than
/// anything a language says.
const CLAIM: &str = "PDF/A-3B";

/// The tints the ramp runs through, all the profile's channels together.
const TINTS: &[f64] = &[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];
/// The width of one cell of the ramp, the gap to the next, and its height.
const RAMP_CELL: f64 = 38.0;
/// See [`RAMP_CELL`].
const RAMP_GAP: f64 = 3.5;
/// See [`RAMP_CELL`].
const RAMP_HEIGHT: f64 = 86.0;
/// The bottom edge of the ramp.
const RAMP_Y: f64 = 440.0;

/// The size of one channel swatch, the gap to the next, and their bottom edge.
const CHANNEL_CELL: f64 = 90.0;
/// See [`CHANNEL_CELL`].
const CHANNEL_GAP: f64 = 15.0;
/// See [`CHANNEL_CELL`].
const CHANNEL_Y: f64 = 230.0;

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title over the page, which is also the title the file states.
    title: &'static str,
    /// The two lines under the title.
    intro: [&'static str; 2],
    /// The heading over the panel that lists what the file carries.
    intent_panel: &'static str,
    /// The heading over the ramp, and the line under it.
    profile_panel: &'static str,
    /// See [`Words::profile_panel`].
    profile_note: &'static str,
    /// The heading over the channel swatches.
    channel_panel: &'static str,
    /// What the four rows of the intent panel are called.
    rows: [&'static str; 4],
    /// What stands between the size of the profile and what it describes, so
    /// that the row reads as one sentence in every language.
    profile_size: &'static str,
    /// What follows the name of the claim on its row.
    claim_note: &'static str,
    /// What a colour is made of, in words, in a grey, an RGB and a CMYK space.
    described: [&'static str; 3],
    /// The one channel of a grey space.
    gray_channels: [&'static str; 1],
    /// The three channels of an RGB space.
    rgb_channels: [&'static str; 3],
    /// The four channels of a CMYK space.
    cmyk_channels: [&'static str; 4],
    /// What the caller is told a profile of their own would do, under the
    /// swatches.
    closing: [&'static str; 2],
    /// What the condition is called when a profile is handed over on the
    /// command line, which is prose rather than a registered name.
    custom_info: &'static str,
}

impl Words {
    /// The words the page is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }

    /// The channels a colour in `space` is made of, in the order their numbers
    /// are given.
    const fn channels(&self, space: hqf_pdf::DeviceSpace) -> &[&'static str] {
        match space {
            hqf_pdf::DeviceSpace::Gray => &self.gray_channels,
            hqf_pdf::DeviceSpace::Rgb => &self.rgb_channels,
            hqf_pdf::DeviceSpace::Cmyk => &self.cmyk_channels,
        }
    }

    /// What a colour in `space` is made of, in words.
    const fn described(&self, space: hqf_pdf::DeviceSpace) -> &'static str {
        match space {
            hqf_pdf::DeviceSpace::Gray => self.described[0],
            hqf_pdf::DeviceSpace::Rgb => self.described[1],
            hqf_pdf::DeviceSpace::Cmyk => self.described[2],
        }
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "What the numbers on this page mean",
    intro: [
        "A file states the device it was prepared for, and the profile of that device travels \
         inside it.",
        "Nothing else in the file says what its colours are: the numbers alone say none.",
    ],
    intent_panel: "The output intent this file carries",
    profile_panel: "The same profile, painted through",
    profile_note: "One profile does both jobs: it says what the file is for, and it is what these \
                   swatches are painted in. The file carries it once.",
    channel_panel: "One channel at a time, at full strength",
    rows: ["Condition", "Description", "Profile", "Claim"],
    profile_size: " bytes, describing ",
    claim_note: ", which makes stating one compulsory",
    described: ["grey", "red, green and blue", "the four printing inks"],
    gray_channels: ["Grey"],
    rgb_channels: ["Red", "Green", "Blue"],
    cmyk_channels: ["Cyan", "Magenta", "Yellow", "Black"],
    closing: [
        "Hand a press profile on the command line and the page is drawn in its inks instead, \
         under its own",
        "condition. A file that paints in CMYK and states a screen is a file a validator refuses.",
    ],
    custom_info: "A profile handed over on the command line",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Ce que veulent dire les nombres de cette page",
    intro: [
        "Un fichier dit l'appareil pour lequel il a été préparé, et le profil de cet appareil \
         voyage dedans.",
        "Rien d'autre dans le fichier ne dit ce que sont ses couleurs : les nombres seuls n'en \
         disent rien.",
    ],
    intent_panel: "L'intention de sortie que porte ce fichier",
    profile_panel: "Le même profil, utilisé pour peindre",
    profile_note: "Un seul profil fait les deux : il dit à quoi sert le fichier, et c'est lui qui \
                   peint ces pastilles. Le fichier ne le porte qu'une fois.",
    channel_panel: "Une composante à la fois, à pleine force",
    rows: ["Condition", "Description", "Profil", "Revendication"],
    profile_size: " octets, décrivant ",
    claim_note: ", qui rend la mention obligatoire",
    described: [
        "le gris",
        "le rouge, le vert et le bleu",
        "les quatre encres d'imprimerie",
    ],
    gray_channels: ["Gris"],
    rgb_channels: ["Rouge", "Vert", "Bleu"],
    cmyk_channels: ["Cyan", "Magenta", "Jaune", "Noir"],
    closing: [
        "Donnez un profil de presse en ligne de commande et la page est peinte dans ses encres, \
         sous sa propre",
        "condition. Un fichier qui peint en CMJN en annonçant un écran est refusé par un \
         validateur.",
    ],
    custom_info: "Un profil donné en ligne de commande",
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// What the caller says the condition is called when a profile is handed over
/// on the command line.
///
/// ISO 32000-1 table 365 asks for `Custom` where the condition is not one of
/// the registered characterizations, which a profile read off a disk is not.
const CUSTOM: &str = "Custom";
/// What the condition is called when the library's own profile is used, and the
/// name that profile is registered under.
const BUILT_IN: (&str, &str) = ("sRGB", "sRGB IEC61966-2.1");

/// A profile and what the condition it describes is called.
struct Stated {
    profile: Vec<u8>,
    identifier: &'static str,
    info: String,
}

/// Draws one line of text with its baseline at `(x, y)`.
fn text(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    x: f64,
    y: f64,
    line: &str,
) -> Result<(), Error> {
    content.begin_text();
    content.set_font(font.name(), size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// Draws the title and the two lines saying what the page is showing.
fn heading(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    text(content, font, 15.0, LEFT, 780.0, words.title)?;
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(content, font, 10.0, LEFT, 762.0, words.intro[0])?;
    text(content, font, 10.0, LEFT, 748.0, words.intro[1])?;
    content.restore_state();
    Ok(())
}

/// Draws one panel's heading, with the line under it that a panel may have.
fn panel_heading(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    title: &str,
    under: Option<&str>,
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.2))?;
    text(content, font, 11.0, LEFT, y, title)?;
    if let Some(line) = under {
        content.set_fill(Color::Gray(0.45))?;
        text(content, font, 8.0, LEFT, y - 16.0, line)?;
    }
    content.restore_state();
    Ok(())
}

/// Draws the intent's parts, one to a line, as the file carries them.
fn intent_panel(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    intent: &OutputIntent,
    bytes: usize,
) -> Result<(), Error> {
    let described = words.described(intent.profile().space());
    let values = [
        intent.identifier().to_owned(),
        intent.info().to_owned(),
        format!("{bytes}{}{described}", words.profile_size),
        format!("{CLAIM}{}", words.claim_note),
    ];

    let mut y = 672.0;
    for (label, value) in words.rows.iter().zip(&values) {
        content.save_state();
        content.set_fill(Color::Gray(0.45))?;
        text(content, font, 9.0, LEFT, y, label)?;
        content.set_fill(Color::Gray(0.15))?;
        text(content, font, 9.0, LEFT + VALUE_IN, y, value)?;
        content.restore_state();
        y -= 18.0;
    }
    Ok(())
}

/// Frames a swatch, so that one painted white is a swatch rather than a hole.
fn frame(content: &mut Content, x: f64, y: f64, width: f64, height: f64) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.75))?;
    content
        .rect(x - 1.0, y - 1.0, width + 2.0, height + 2.0)?
        .fill();
    content.restore_state();
    Ok(())
}

/// Draws the ramp: every channel of the profile at the same tint, from none of
/// it to all of it.
fn ramp(
    content: &mut Content,
    font: &FontHandle,
    space: &ColorSpaceHandle,
    width: usize,
) -> Result<(), Error> {
    let mut x = LEFT;
    for tint in TINTS {
        frame(content, x, RAMP_Y, RAMP_CELL, RAMP_HEIGHT)?;
        content.save_state();
        content.set_fill_space(space);
        content.set_fill_components(&vec![*tint; width])?;
        content.rect(x, RAMP_Y, RAMP_CELL, RAMP_HEIGHT)?.fill();
        content.restore_state();

        content.save_state();
        content.set_fill(Color::Gray(0.45))?;
        text(
            content,
            font,
            7.0,
            x,
            RAMP_Y - 12.0,
            &format!("{:.0}%", tint * 100.0),
        )?;
        content.restore_state();
        x += RAMP_CELL + RAMP_GAP;
    }
    Ok(())
}

/// Draws one swatch per channel, each at full strength with the others empty.
fn channel_swatches(
    content: &mut Content,
    font: &FontHandle,
    space: &ColorSpaceHandle,
    names: &[&str],
) -> Result<(), Error> {
    let mut x = LEFT;
    for (channel, name) in names.iter().enumerate() {
        let mut components = vec![0.0; names.len()];
        components[channel] = 1.0;

        frame(content, x, CHANNEL_Y, CHANNEL_CELL, CHANNEL_CELL)?;
        content.save_state();
        content.set_fill_space(space);
        content.set_fill_components(&components)?;
        content
            .rect(x, CHANNEL_Y, CHANNEL_CELL, CHANNEL_CELL)?
            .fill();
        content.restore_state();

        content.save_state();
        content.set_fill(Color::Gray(0.45))?;
        text(content, font, 8.0, x, CHANNEL_Y - 12.0, name)?;
        content.restore_state();
        x += CHANNEL_CELL + CHANNEL_GAP;
    }
    Ok(())
}

/// Draws the closing note under the swatches.
fn closing(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(content, font, 9.0, LEFT, 160.0, words.closing[0])?;
    text(content, font, 9.0, LEFT, 146.0, words.closing[1])?;
    content.restore_state();
    Ok(())
}

/// The profile the document is stated for, and what its condition is called:
/// the file named on the command line, or the one the library builds.
fn stated_for(path: Option<String>, words: &Words) -> Result<Stated, Box<dyn std::error::Error>> {
    match path {
        Some(path) => Ok(Stated {
            profile: fs::read(path)?,
            identifier: CUSTOM,
            info: words.custom_info.to_owned(),
        }),
        None => Ok(Stated {
            profile: icc::srgb(),
            identifier: BUILT_IN.0,
            info: BUILT_IN.1.to_owned(),
        }),
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("intent")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);
    let stated = stated_for(args.next(), words)?;
    let bytes = &stated.profile;

    let described =
        icc::space(bytes).ok_or("the profile must describe a grey, RGB or CMYK space")?;
    let intent = OutputIntent::new(
        IccBased::new(bytes, described)?,
        stated.identifier,
        &stated.info,
    )?;
    let names = words.channels(described);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_conformance(PdfA::A3B);
    doc.set_metadata(Metadata {
        title: Some(words.title.to_owned()),
        producer: Some("hqf-pdf".to_owned()),
        created: Some(MADE.to_owned()),
        ..Metadata::default()
    });
    doc.set_output_intent(intent.clone());

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let space = doc.add_color_space(IccBased::new(bytes, described)?);

    let mut content = Content::new();
    heading(&mut content, &font, words)?;
    panel_heading(&mut content, &font, 700.0, words.intent_panel, None)?;
    intent_panel(&mut content, &font, words, &intent, bytes.len())?;

    panel_heading(
        &mut content,
        &font,
        566.0,
        words.profile_panel,
        Some(words.profile_note),
    )?;
    ramp(&mut content, &font, &space, names.len())?;

    panel_heading(&mut content, &font, 360.0, words.channel_panel, None)?;
    channel_swatches(&mut content, &font, &space, names)?;
    closing(&mut content, &font, words)?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;

    let written = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &written)?;
    println!(
        "wrote {out}: {} bytes, stated for {} through a profile of {} bytes",
        written.len(),
        stated.identifier,
        bytes.len()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Document, Font};

    use super::{CHANNEL_CELL, CHANNEL_GAP, CLAIM, LEFT, VALUE_IN, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Two of the
    /// row labels and two of the printing inks are the same word in English and
    /// in French; the rest of the page is prose, and no two languages write one
    /// line of it alike.
    const SPARED: [&str; 4] = [
        "\"Condition\"",
        "\"Description\"",
        "\"Cyan\"",
        "\"Magenta\"",
    ];

    /// A4's width, and the room a line that stands over nothing has: it only
    /// has to stay on the paper.
    const PAGE_WIDTH: f64 = 595.276;
    /// See [`PAGE_WIDTH`].
    const PAPER: f64 = PAGE_WIDTH - LEFT;

    /// The longest a value of the intent panel may run: the paper, less the
    /// room the labels are given in front of it.
    const VALUE_ROOM: f64 = PAPER - VALUE_IN;

    /// The room a channel's name has under its swatch, which is the swatch and
    /// the gap to the one beside it.
    const CHANNEL_ROOM: f64 = CHANNEL_CELL + CHANNEL_GAP;

    #[test]
    fn every_language_draws_the_page_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the page says these in more than one language: {untranslated:?}"
        );
    }

    /// Nothing on the page is broken to a width: a line longer than the room it
    /// is given runs over the swatch beside it, or off the sheet.
    #[test]
    fn every_language_writes_lines_no_wider_than_the_room_they_are_given() {
        let mut doc = Document::new();
        let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
            .expect("the committed font parses");
        let text = doc.add_font(font);

        for (named, words) in WORDS {
            let code = named.code();
            // The size of the profile is a number the page reads off the file,
            // and the widest it can be is the widest profile a caller hands
            // over; what is measured here is the words around it.
            let rows = [
                format!("{}{}", words.profile_size, words.described[2]),
                format!("{CLAIM}{}", words.claim_note),
                words.custom_info.to_owned(),
            ];

            let lines = std::iter::once((15.0, words.title.to_owned(), PAPER))
                .chain(words.intro.map(|line| (10.0, line.to_owned(), PAPER)))
                .chain([
                    (11.0, words.intent_panel.to_owned(), PAPER),
                    (11.0, words.profile_panel.to_owned(), PAPER),
                    (8.0, words.profile_note.to_owned(), PAPER),
                    (11.0, words.channel_panel.to_owned(), PAPER),
                ])
                .chain(words.rows.map(|label| (9.0, label.to_owned(), VALUE_IN)))
                .chain(rows.map(|value| (9.0, value, VALUE_ROOM)))
                .chain(
                    words
                        .cmyk_channels
                        .map(|name| (8.0, name.to_owned(), CHANNEL_ROOM)),
                )
                .chain(
                    words
                        .rgb_channels
                        .map(|name| (8.0, name.to_owned(), CHANNEL_ROOM)),
                )
                .chain(
                    words
                        .gray_channels
                        .map(|name| (8.0, name.to_owned(), CHANNEL_ROOM)),
                )
                .chain(words.closing.map(|line| (9.0, line.to_owned(), PAPER)));

            for (size, line, room) in lines {
                let measured = text.measure(&line, size);
                assert!(
                    measured <= room,
                    "the {code} page draws {line:?} over {measured:.1} points, \
                     and it is given {room:.1}"
                );
            }
        }
    }
}