The same numbers, through spaces that say what they mean

Six colours and a grey ramp painted three times over with the very same numbers: first left to the device, then said in two ways that state the white they are measured against, the curve applied to them, and how far the base colours reach. All of that travels in a handful of numbers, with no profile to carry.

Rust write_calibrated_color.rs 426 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
//! The same numbers, painted through spaces that say what they mean.
//!
//! `0.8 0.1 0.1 rg` is three numbers and a hope. A calibrated space says
//! instead what white the numbers are measured against, what exponent they are
//! raised to and — for colour — what the three primaries actually reach, so the
//! same numbers are the same colour wherever the file is opened. The page below
//! paints one row of colours and one grey ramp three times over, changing
//! nothing but the space they are said in.
//!
//! What the page reads is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The numbers the bands are painted
//! from are not language: they are the same colours whoever reads the page.
//!
//! Usage: `cargo run --example write_calibrated_color -- tmp/calibrated.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_calibrated_color --
//! tmp/calibree.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    CalGray, CalRgb, Color, ColorSpaceHandle, Document, Error, Font, FontHandle, Page, Rgb,
};

#[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, and how wide a row runs.
const LEFT: f64 = 70.0;
/// See [`LEFT`].
const RUN: f64 = 455.0;

/// The white every calibrated space on the page is measured against, as CIE
/// XYZ.
const WHITE: [f64; 3] = [0.9505, 1.0, 1.089];

/// The six colours the first three rows paint, each as three numbers.
const COLORS: &[[f64; 3]] = &[
    [0.80, 0.10, 0.10],
    [0.90, 0.50, 0.10],
    [0.90, 0.85, 0.20],
    [0.15, 0.55, 0.30],
    [0.15, 0.35, 0.70],
    [0.45, 0.20, 0.55],
];

/// The size of one colour swatch, and the gap to the next.
const SWATCH: (f64, f64) = (70.0, 55.0);
/// See [`SWATCH`].
const SWATCH_GAP: f64 = 7.0;

/// How many steps the grey ramp is cut into, and how tall it stands.
const STEPS: usize = 10;
/// See [`STEPS`].
const RAMP_HEIGHT: f64 = 45.0;

/// The words the page is written in, one set per language.
///
/// The numbers the bands are painted from are not here: three numbers are the
/// same three numbers in every language.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The two lines under it, saying that nothing below was painted twice.
    intro: [&'static str; 2],
    /// The heading of each panel, and the line under it.
    panels: [[&'static str; 2]; 2],
    /// The caption each band stands under, in the order the bands are painted.
    captions: [&'static str; 6],
    /// The three lines at the foot of the page.
    closing: [&'static str; 3],
}

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

/// The page in English.
const ENGLISH: Words = Words {
    title: "The same numbers, through spaces that say what they mean",
    intro: [
        "Nothing below was painted twice with different numbers. Each band holds the very same \
         numbers as",
        "the one above it, and what changes is the space they are said in.",
    ],
    panels: [
        [
            "Six colours, three ways of meaning them",
            "The three numbers are the same in every band. The primaries under them are not.",
        ],
        [
            "One grey ramp, three exponents",
            "Ten steps from 0.05 to 0.95, painted with the same ten numbers each time.",
        ],
    ],
    captions: [
        "Left to the device",
        "Through one set of primaries",
        "Through a wider set of primaries",
        "Left to the device",
        "Measured, raised to 1",
        "Measured, raised to 2.2",
    ],
    closing: [
        "A calibrated space carries its measurement in a handful of numbers rather than in a \
         profile,",
        "so a file states what its colours are without embedding anything and without asking \
         the",
        "reader to have the right profile installed.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Les mêmes nombres, dans des espaces qui disent ce qu'ils valent",
    intro: [
        "Rien, plus bas, n'a été peint deux fois avec des nombres différents. Chaque bande \
         porte les mêmes",
        "nombres que celle du dessus, et ce qui change est l'espace dans lequel on les dit.",
    ],
    panels: [
        [
            "Six couleurs, trois façons de les définir",
            "Les trois nombres sont les mêmes dans chaque bande. Les primaires sous eux, non.",
        ],
        [
            "Une rampe de gris, trois exposants",
            "Dix marches de 0.05 à 0.95, peintes à chaque fois avec les mêmes dix nombres.",
        ],
    ],
    captions: [
        "Laissé à l'appareil",
        "À travers un jeu de primaires",
        "À travers un jeu de primaires plus large",
        "Laissé à l'appareil",
        "Mesuré, élevé à 1",
        "Mesuré, élevé à 2.2",
    ],
    closing: [
        "Un espace calibré porte sa mesure dans une poignée de nombres plutôt que dans un \
         profil,",
        "si bien qu'un fichier dit ce que sont ses couleurs sans rien embarquer et sans \
         exiger",
        "que le lecteur ait le bon profil installé.",
    ],
};

/// 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)];

/// 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(())
}

/// Writes the small caption a band stands under.
fn caption(content: &mut Content, font: &FontHandle, y: f64, line: &str) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    text(content, font, 8.0, LEFT, y, line)?;
    content.restore_state();
    Ok(())
}

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

/// Paints the six colours across, in whichever space `space` names; without one
/// they are left to the device.
fn band(content: &mut Content, space: Option<&ColorSpaceHandle>, bottom: f64) -> Result<(), Error> {
    let mut x = LEFT;
    for color in COLORS {
        content.save_state();
        match space {
            Some(space) => {
                content.set_fill_space(space);
                content.set_fill_components(color)?;
            }
            None => {
                content.set_fill(Rgb::new(color[0], color[1], color[2]))?;
            }
        }
        content.rect(x, bottom, SWATCH.0, SWATCH.1)?.fill();
        content.restore_state();
        x += SWATCH.0 + SWATCH_GAP;
    }
    Ok(())
}

/// Paints the grey ramp across, in whichever space `space` names; without one
/// it is left to the device.
fn ramp(content: &mut Content, space: Option<&ColorSpaceHandle>, bottom: f64) -> Result<(), Error> {
    #[expect(
        clippy::cast_precision_loss,
        reason = "ten steps are far short of what an f64 counts exactly"
    )]
    let width = RUN / STEPS as f64;
    let mut x = LEFT;
    let mut grey = 0.05;
    for _ in 0..STEPS {
        content.save_state();
        match space {
            Some(space) => {
                content.set_fill_space(space);
                content.set_fill_components(&[grey])?;
            }
            None => {
                content.set_fill(Color::Gray(grey))?;
            }
        }
        content.rect(x, bottom, width, RAMP_HEIGHT)?.fill();
        content.restore_state();
        x += width;
        grey += 0.1;
    }
    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 the closing note.
fn closing(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    for (y, line) in [140.0, 126.0, 112.0].into_iter().zip(words.closing) {
        text(content, font, 9.0, LEFT, y, line)?;
    }
    content.restore_state();
    Ok(())
}

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("calibrated")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let ordinary = doc.add_color_space(CalRgb::new(WHITE).gamma([2.2, 2.2, 2.2]).primaries(
        [0.4124, 0.2126, 0.0193],
        [0.3576, 0.7152, 0.1192],
        [0.1805, 0.0722, 0.9505],
    ));
    let wider = doc.add_color_space(CalRgb::new(WHITE).gamma([2.2, 2.2, 2.2]).primaries(
        [0.5767, 0.2974, 0.0270],
        [0.1856, 0.6273, 0.0707],
        [0.1882, 0.0753, 0.9911],
    ));
    let straight = doc.add_color_space(CalGray::new(WHITE).gamma(1.0));
    let bent = doc.add_color_space(CalGray::new(WHITE).gamma(2.2));

    let mut content = Content::new();
    heading(&mut content, &font, words)?;

    panel_heading(
        &mut content,
        &font,
        706.0,
        words.panels[0][0],
        words.panels[0][1],
    )?;
    caption(&mut content, &font, 668.0, words.captions[0])?;
    band(&mut content, None, 610.0)?;
    caption(&mut content, &font, 594.0, words.captions[1])?;
    band(&mut content, Some(&ordinary), 536.0)?;
    caption(&mut content, &font, 520.0, words.captions[2])?;
    band(&mut content, Some(&wider), 462.0)?;

    panel_heading(
        &mut content,
        &font,
        420.0,
        words.panels[1][0],
        words.panels[1][1],
    )?;
    caption(&mut content, &font, 382.0, words.captions[3])?;
    ramp(&mut content, None, 334.0)?;
    caption(&mut content, &font, 318.0, words.captions[4])?;
    ramp(&mut content, Some(&straight), 270.0)?;
    caption(&mut content, &font, 254.0, words.captions[5])?;
    ramp(&mut content, Some(&bent), 206.0)?;
    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, {} colours and {STEPS} greys painted three times each",
        written.len(),
        COLORS.len()
    );
    Ok(())
}

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

    use super::{LEFT, RUN, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Every line
    /// here is a heading, a sentence or a caption, and no two languages write
    /// one alike.
    const SPARED: [&str; 0] = [];

    /// A4's width, and the room the lines that stand over nothing have: they
    /// only have to stay on the paper.
    const PAGE_WIDTH: f64 = 595.276;
    /// See [`PAGE_WIDTH`].
    const PAPER: f64 = PAGE_WIDTH - LEFT;

    #[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 caption longer than the band
    /// it stands over runs past it, and the title and the two lines under it,
    /// which stand over nothing, run off the sheet.
    #[test]
    fn every_language_writes_lines_no_wider_than_the_bands_they_stand_over() {
        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();
            let lines = std::iter::once((15.0, words.title, PAPER))
                .chain(words.intro.map(|line| (10.0, line, PAPER)))
                .chain(words.panels.map(|panel| (11.0, panel[0], RUN)))
                .chain(words.panels.map(|panel| (8.0, panel[1], RUN)))
                .chain(words.captions.map(|line| (8.0, line, RUN)))
                .chain(words.closing.map(|line| (9.0, line, RUN)));

            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}"
                );
            }
        }
    }
}