write_measured_color.rs

Die Rust-Datei des Beispiels „Farbe, die das Dokument definiert“. Dieselben sechs Farben, als bloße Zahlen angegeben und dann durch das Bildschirmprofil gelesen, das die Datei enthält, dazu ein Verlauf von hell nach dunkel und eine Reihe gemessener Farbtöne: Farbe, die auf einem anderen Bildschirm und in einer Druckmaschine noch dasselbe bedeutet.

Rust 515 Zeilen

Wofür dieses Beispiel da ist

Drei in eine Datei geschriebene Zahlen sagen nur drei Zahlen. Wie sie aussehen, bleibt dem überlassen, was sie gerade zeigt; deshalb ist das Hausblau auf der Rechnung, die Sie senden, nicht ganz das Hausblau auf der, die Ihr Kunde druckt.

Was dieses Beispiel zeigt

  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
//! Colour the document defines, next to colour it leaves to the device.
//!
//! `0.2 0.4 0.8 rg` says three numbers and leaves what they look like to
//! whatever shows them. The rows below say colour two other ways: through the
//! ICC profile the file carries, so the numbers mean what they meant when the
//! document was made, and as CIE 1976 L*a*b*, where lightness and colour are
//! separate numbers by construction.
//!
//! What the page reads is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The numbers the swatches are
//! painted from are not language: they are the same colours whoever reads the
//! page.
//!
//! Usage: `cargo run --example write_measured_color -- tmp/measured.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_measured_color --
//! tmp/mesuree.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::{
    ColorSpace, ColorSpaceHandle, DeviceSpace, Document, Font, FontHandle, IccBased, Lab, Page, Rgb,
};

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

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

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

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

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 size of one swatch, in points.
const SWATCH: (f64, f64) = (70.0, 60.0);

/// The left edge of the first swatch.
const LEFT: f64 = 70.0;

/// The left edge of each swatch in a row: the first one, then every
/// seventy-eight points across.
const COLUMN_X: &[f64] = &[70.0, 148.0, 226.0, 304.0, 382.0, 460.0];

/// The six colours the first two rows are painted in, as three numbers each.
const COLORS: &[[f64; 3]] = &[
    [0.85, 0.20, 0.15],
    [0.92, 0.58, 0.10],
    [0.20, 0.55, 0.30],
    [0.12, 0.40, 0.70],
    [0.45, 0.25, 0.60],
    [0.20, 0.20, 0.22],
];

/// Six lightnesses at one colour, as `L*`, `a*` and `b*`.
const LIGHTNESSES: &[[f64; 3]] = &[
    [20.0, 40.0, 25.0],
    [35.0, 40.0, 25.0],
    [50.0, 40.0, 25.0],
    [65.0, 40.0, 25.0],
    [80.0, 40.0, 25.0],
    [95.0, 40.0, 25.0],
];

/// Six colours at one lightness, as `L*`, `a*` and `b*`.
const HUES: &[[f64; 3]] = &[
    [60.0, 60.0, 40.0],
    [60.0, 20.0, 60.0],
    [60.0, -50.0, 45.0],
    [60.0, -40.0, -20.0],
    [60.0, 10.0, -55.0],
    [60.0, 50.0, -20.0],
];

/// The words the page is written in, one set per language.
///
/// The numbers the swatches 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 what the first two rows hold.
    intro: [&'static str; 2],
    /// What each row of swatches shows, in the order the rows are drawn.
    rows: [&'static str; 4],
    /// The line under the stroked rule.
    rule: &'static str,
    /// 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: "Colour the document defines, not the device",
    intro: [
        "The first two rows hold the same six sets of three numbers. The second row names a colour",
        "space the file carries the profile for, so what those numbers mean travels with the file.",
    ],
    rows: [
        "Three numbers said as they are, left to whatever shows them",
        "The same three numbers, read through the sRGB profile the file carries",
        "One colour at six lightnesses, as L*a*b* over a measured black: only the first number changes",
        "Six colours at one lightness: only the other two change",
    ],
    rule: "A rule stroked in the same space, by the stroking operators",
    closing: [
        "The first two rows look alike on a screen that is already sRGB, and that is the point:",
        "the difference is not what they look like here. It is that the second row still names these",
        "colours on a press, on another screen, and in ten years, because the file says what it means.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "La couleur que le document définit, pas celle de l’appareil",
    intro: [
        "Les deux premières rangées reprennent les six mêmes jeux de trois nombres. La deuxième",
        "nomme un espace dont le fichier contient le profil : ces nombres gardent leur \
sens partout.",
    ],
    rows: [
        "Trois nombres donnés tels quels : chaque appareil les affiche à sa façon",
        "Les trois mêmes nombres, interprétés selon le profil sRGB que contient le fichier",
        "Une même couleur à six clartés, en L*a*b* sur un noir mesuré : seul le premier nombre change",
        "Six couleurs à une même clarté : seuls les deux autres changent",
    ],
    rule: "Un filet tracé dans le même espace colorimétrique, par les opérateurs de contour",
    closing: [
        "Les deux premières rangées se ressemblent sur un écran déjà sRGB, et c’est voulu :",
        "la différence ne se voit pas ici. Elle tient à ce que la deuxième rangée définit encore",
        "ces couleurs sur une presse, un autre écran ou dans dix ans : le fichier dit \
ce qu’elles sont.",
    ],
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Kleur die het document bepaalt, niet het apparaat",
    intro: [
        "De eerste twee rijen bevatten dezelfde zes groepen van drie getallen. De tweede noemt een",
        "kleurruimte met haar profiel in het bestand: wat die getallen betekenen, reist mee.",
    ],
    rows: [
        "Drie getallen zoals ze zijn, overgelaten aan wat ze toont",
        "Dezelfde drie getallen, gelezen via het sRGB-profiel dat in het bestand zit",
        "Eén kleur in zes lichtheden, als L*a*b* boven een gemeten zwart: alleen het eerste getal verandert",
        "Zes kleuren in één lichtheid: alleen de andere twee veranderen",
    ],
    rule: "Een lijn getrokken in dezelfde ruimte, met de lijnoperatoren",
    closing: [
        "Op een scherm dat al sRGB is, lijken de eerste twee rijen op elkaar, en daar gaat het om:",
        "het verschil is niet hoe ze er hier uitzien. De tweede rij blijft deze kleuren benoemen",
        "op een pers, op een ander scherm en over tien jaar: het bestand zegt wat ze betekenen.",
    ],
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Cor definida pelo documento, não pelo dispositivo",
    intro: [
        "As duas primeiras linhas têm os mesmos seis trios de números. A segunda nomeia",
        "um espaço de cor cujo perfil o ficheiro contém: o que os números significam viaja com ele.",
    ],
    rows: [
        "Três números tal como estão, entregues a quem os mostrar",
        "Os mesmos três números, lidos através do perfil sRGB que o ficheiro leva",
        "Uma cor em seis luminosidades, como L*a*b* sobre um preto medido: só muda o primeiro número",
        "Seis cores numa luminosidade: só mudam os outros dois",
    ],
    rule: "Um filete traçado no mesmo espaço, com os operadores de traço",
    closing: [
        "As duas primeiras linhas parecem iguais num ecrã que já é sRGB, e é essa a questão:",
        "a diferença não é o seu aspeto aqui. É que a segunda linha continua a nomear estas",
        "cores numa impressora, noutro ecrã e daqui a dez anos: o ficheiro diz o que significam.",
    ],
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Colore definito dal documento, non dal dispositivo",
    intro: [
        "Le prime due righe portano gli stessi sei gruppi di tre numeri. La seconda nomina uno spazio",
        "colore di cui il file porta il profilo, così ciò che quei numeri significano viaggia con il file.",
    ],
    rows: [
        "Tre numeri così come sono, lasciati a chi li mostra",
        "Gli stessi tre numeri, letti con il profilo sRGB che il file porta",
        "Un colore in sei luminosità, come L*a*b* su un nero misurato: cambia solo il primo numero",
        "Sei colori in una luminosità: cambiano solo gli altri due",
    ],
    rule: "Un filetto tracciato nello stesso spazio, con gli operatori di tratto",
    closing: [
        "Le prime due righe si somigliano su uno schermo già sRGB, ed è proprio questo il punto:",
        "la differenza non sta in come appaiono qui: la seconda riga nomina ancora questi colori",
        "in tipografia, su un altro schermo e fra dieci anni: il file dice cosa significano.",
    ],
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Color que define el documento, no el dispositivo",
    intro: [
        "Las dos primeras filas dan los mismos seis tríos de números. La segunda nombra un espacio",
        "de color cuyo perfil lleva el archivo, así que lo que significan esos números viaja con él.",
    ],
    rows: [
        "Tres números tal cual, a merced de quien los muestre",
        "Los mismos tres números, leídos con el perfil sRGB que lleva el archivo",
        "Un color en seis claridades, como L*a*b* sobre un negro medido: solo cambia el primer número",
        "Seis colores en una claridad: solo cambian los otros dos",
    ],
    rule: "Una raya trazada en el mismo espacio, con los operadores de trazo",
    closing: [
        "Las dos primeras filas se parecen en una pantalla que ya es sRGB, y esa es la cuestión:",
        "la diferencia no es su aspecto aquí. Es que la segunda fila sigue nombrando estos colores",
        "en una prensa, en otra pantalla y dentro de diez años: el archivo dice lo que significan.",
    ],
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Farbe, die das Dokument festlegt, nicht das Gerät",
    intro: [
        "Die ersten beiden Reihen enthalten dieselben sechs Dreiergruppen. Die zweite nennt",
        "einen Farbraum, dessen Profil die Datei trägt: Die Bedeutung der Zahlen reist mit.",
    ],
    rows: [
        "Drei Zahlen, unverändert dem Gerät überlassen, das sie anzeigt",
        "Dieselben drei Zahlen, gelesen über das sRGB-Profil, das die Datei trägt",
        "Eine Farbe in sechs Helligkeiten, L*a*b* über gemessenem Schwarz: Nur die erste Zahl ändert sich",
        "Sechs Farben in einer Helligkeit: Nur die anderen beiden ändern sich",
    ],
    rule: "Eine Linie im selben Farbraum, mit den Operatoren für Striche gezogen",
    closing: [
        "Die ersten beiden Reihen sehen auf einem sRGB-Bildschirm gleich aus, und darum geht es:",
        "Der Unterschied liegt nicht im Aussehen hier, sondern darin, dass die zweite Reihe diese",
        "Farben auch im Druck, auf anderen Bildschirmen und in zehn Jahren benennt.",
    ],
};

/// 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); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// 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<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// Draws a row of swatches, each painted by `paint`, and captions it.
fn row(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    caption: &str,
    count: usize,
    mut paint: impl FnMut(&mut Content, usize) -> Result<(), hqf_pdf::Error>,
) -> Result<(), hqf_pdf::Error> {
    let (width, height) = SWATCH;

    for (column, x) in COLUMN_X.iter().enumerate().take(count) {
        content.save_state();
        paint(content, column)?;
        content.rect(*x, y, width, height)?.fill();
        content.restore_state();
    }

    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(content, font, 9.0, LEFT, y - 14.0, caption)?;
    content.restore_state();
    Ok(())
}

/// Draws the four rows of swatches.
fn rows(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    profile: &ColorSpaceHandle,
    lab: &ColorSpaceHandle,
) -> Result<(), hqf_pdf::Error> {
    row(
        content,
        font,
        660.0,
        words.rows[0],
        COLORS.len(),
        |content, column| {
            let [r, g, b] = COLORS[column];
            content.set_fill(Rgb::new(r, g, b))?;
            Ok(())
        },
    )?;

    row(
        content,
        font,
        560.0,
        words.rows[1],
        COLORS.len(),
        |content, column| {
            content.set_fill_space(profile);
            content.set_fill_components(&COLORS[column])?;
            Ok(())
        },
    )?;

    row(
        content,
        font,
        460.0,
        words.rows[2],
        LIGHTNESSES.len(),
        |content, column| {
            content.set_fill_space(lab);
            content.set_fill_components(&LIGHTNESSES[column])?;
            Ok(())
        },
    )?;

    row(
        content,
        font,
        360.0,
        words.rows[3],
        HUES.len(),
        |content, column| {
            content.set_fill_space(lab);
            content.set_fill_components(&HUES[column])?;
            Ok(())
        },
    )
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

fn run() -> 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("measured")));
    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 profile = doc.add_color_space(ColorSpace::Icc(IccBased::new(
        &icc::srgb(),
        DeviceSpace::Rgb,
    )?));
    // The white of D65 daylight, as CIE XYZ: the light L*a*b* is measured
    // against here.
    let lab = doc.add_color_space(ColorSpace::Lab(
        Lab::new([0.9505, 1.0, 1.089])
            .black_point([0.0080, 0.0083, 0.0069])
            .range([-100.0, 100.0, -100.0, 100.0]),
    ));

    let mut content = Content::new();
    text(&mut content, &font, 15.0, LEFT, 780.0, words.title)?;
    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(&mut content, &font, 10.0, LEFT, 762.0, words.intro[0])?;
    text(&mut content, &font, 10.0, LEFT, 748.0, words.intro[1])?;
    content.restore_state();

    rows(&mut content, &font, words, &profile, &lab)?;

    // A stroke is said in its own space, by its own operators.
    content.save_state();
    content.set_stroke_space(&lab);
    content.set_stroke_components(&[45.0, 55.0, 35.0])?;
    content.set_line_width(6.0)?;
    content.move_to(LEFT, 300.0)?;
    content.line_to(COLUMN_X[COLORS.len() - 1] + SWATCH.0, 300.0)?;
    content.stroke();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(&mut content, &font, 9.0, LEFT, 280.0, words.rule)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::gray(0.25))?;
    for (y, line) in [235.0, 221.0, 207.0].into_iter().zip(words.closing) {
        text(&mut content, &font, 10.0, LEFT, y, line)?;
    }
    content.restore_state();

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

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!(
        "wrote {out}: {} bytes, {} swatches in two spaces the document defines",
        bytes.len(),
        COLORS.len() * 3
    );
    Ok(())
}

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

    use super::{COLORS, COLUMN_X, LEFT, SWATCH, WORDS, default_font, language};

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

    /// The gap between one swatch and the next.
    const GUTTER: f64 = COLUMN_X[1] - COLUMN_X[0] - SWATCH.0;

    /// The room a line has: the page is laid out around its rows of swatches,
    /// and a line may reach the end of a row and the gap that follows it.
    const MEASURE: f64 = COLUMN_X[COLORS.len() - 1] + SWATCH.0 + GUTTER - 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 line longer than the row of
    /// swatches it explains runs out past them and towards the paper's edge.
    #[test]
    fn every_language_writes_lines_no_wider_than_the_swatches_they_explain() {
        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 = [(15.0, words.title), (9.0, words.rule)]
                .into_iter()
                .chain(words.intro.map(|line| (10.0, line)))
                .chain(words.rows.map(|line| (9.0, line)))
                .chain(words.closing.map(|line| (10.0, line)));

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