Les fonctions, la forme que suit une couleur

Ce qu'une fonction fait faire à une couleur, dans chacune de ses quatre formes : un spectre lu dans une table de valeurs, un dégradé découpé en bandes par un petit programme de calcul, une encre dont la recette de conversion est un programme imprimé sous ses pastilles, et une table recollée bout à bout entre deux extrémités.

Rust write_functions.rs 555 lignes
  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
//! The four kinds of PDF function, and what each is good for.
//!
//! A gradient, a spot ink, a transfer curve: each is a number going in and a
//! tuple of numbers coming out, and the file says how. Four panels: a spectrum
//! read off a table of samples, a stepped ramp worked out by a stack program,
//! an ink whose tint transform is a program of its own, and the table and a
//! pair of endpoints stitched end to end. Each program is printed under what it
//! draws.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is captioned in. The two programs are not language: what
//! is printed under the second and third panels is the very working the file
//! carries, and it is spelled the same way whoever reads the page.
//!
//! Usage: `cargo run --example write_functions -- tmp/functions.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_functions --
//! tmp/fonctions.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    Axial, Calculation, ColorSpaceHandle, DeviceSpace, Document, Exponential, Font, FontHandle,
    Function, Op, Page, Rgb, SampleDepth, Sampled, Separation, Shading, ShadingHandle, Stitching,
};

#[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 panel runs.
const LEFT: f64 = 70.0;
/// See [`LEFT`].
const WIDTH: f64 = 455.0;
/// How tall a painted bar is.
const BAR: f64 = 74.0;

/// The foot of each of the four panels, down the page.
const SPECTRUM_FOOT: f64 = 632.0;
/// See [`SPECTRUM_FOOT`].
const STEPPED_FOOT: f64 = 476.0;
/// See [`SPECTRUM_FOOT`].
const INK_FOOT: f64 = 310.0;
/// See [`SPECTRUM_FOOT`].
const JOINED_FOOT: f64 = 150.0;

/// The seven colours the spectrum is read off, red round to violet.
const SPECTRUM: &[[f64; 3]] = &[
    [0.85, 0.12, 0.12],
    [0.95, 0.55, 0.10],
    [0.95, 0.85, 0.15],
    [0.15, 0.65, 0.25],
    [0.10, 0.60, 0.75],
    [0.15, 0.20, 0.75],
    [0.45, 0.15, 0.60],
];

/// The left edge of each tint swatch, and how wide one runs.
const TINT_X: &[f64] = &[70.0, 135.0, 200.0, 265.0, 330.0, 395.0, 460.0];
/// See [`TINT_X`].
const SWATCH: f64 = 59.0;

/// The tints the ink is shown at, and what each of them is called.
const TINTS: &[(f64, &str)] = &[
    (0.1, "10%"),
    (0.25, "25%"),
    (0.4, "40%"),
    (0.55, "55%"),
    (0.7, "70%"),
    (0.85, "85%"),
    (1.0, "100%"),
];

/// The working printed under the stepped ramp, which is the program the file
/// carries rather than anything a language writes.
const STEPPED_PROGRAM: &str = "{ 7 mul cvi dup 6 gt { pop 6 } if 6 div dup 1 exch sub 0.25 }";
/// The working printed under the ink, likewise.
const INK_PROGRAM: &str = "{ dup 0.9 mul exch dup 0.6 mul exch 3 exp 0.4 mul 0 exch }";

/// The words the page is captioned in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title over the page.
    title: &'static str,
    /// The two lines under the title.
    intro: [&'static str; 2],
    /// The caption over each of the four panels, and the note under it. The two
    /// notes that stand under a program hold only what follows it.
    captions: [[&'static str; 2]; 4],
    /// The two lines of the closing note.
    closing: [&'static str; 2],
}

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

    /// The note under the stepped ramp: the program the file carries, then what
    /// the caption says about it.
    fn stepped_note(&self) -> String {
        format!("{STEPPED_PROGRAM}{}", self.captions[1][1])
    }

    /// The note under the ink, likewise.
    fn ink_note(&self) -> String {
        format!("{INK_PROGRAM}{}", self.captions[2][1])
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "What a function says a colour does",
    intro: [
        "A gradient, an ink, a curve: one number goes in and a colour comes out, and the file says \
         how.",
        "It can say it by naming two ends, by tabulating the answer, or by writing out the working.",
    ],
    captions: [
        [
            "Read off a table: seven colours, sixteen bits apiece",
            "The table holds what the colour is at seven points; between them the reader draws the \
             line.",
        ],
        [
            "Worked out: a program that cuts the input into bands",
            "  — the reader runs this.",
        ],
        [
            "One ink, shown through a program where the press is not to hand",
            "  — the black lags, then catches up.",
        ],
        [
            "Stitched: the table over the first half, two endpoints over the second",
            "A piece written as a stream stands as an object of its own, and the joint points at \
             it.",
        ],
    ],
    closing: [
        "A table and a program are both written as streams, which is what lets them hold as much \
         as they do.",
        "The program is built here as steps, not as text, so what reaches the file is what can be \
         written.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Ce qu'une fonction fait dire à une couleur",
    intro: [
        "Un dégradé, une encre, une courbe : un nombre entre, une couleur sort, et le fichier dit \
         comment.",
        "Il peut le dire en nommant deux extrémités, en tabulant la réponse, ou en écrivant le \
         calcul.",
    ],
    captions: [
        [
            "Lu dans une table : sept couleurs, seize bits chacune",
            "La table dit la couleur en sept points ; entre eux, le lecteur trace la droite.",
        ],
        [
            "Calculé : un programme qui découpe l'entrée en bandes",
            "  — le lecteur exécute ceci.",
        ],
        [
            "Une encre, montrée par un programme quand la presse n'est pas là",
            "  — le noir traîne, puis rattrape.",
        ],
        [
            "Cousu : la table sur la première moitié, deux extrémités sur la seconde",
            "Un morceau écrit comme un flux est un objet à part, et la couture pointe dessus.",
        ],
    ],
    closing: [
        "Une table et un programme s'écrivent tous deux comme des flux, ce qui leur permet d'en \
         contenir autant.",
        "Le programme est construit ici en étapes, pas en texte, donc ce qui arrive au fichier est \
         ce qui peut s'écrire.",
    ],
};

/// 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<(), hqf_pdf::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 a caption over a panel whose foot is at `base`, and the note that goes
/// under it.
fn caption(
    content: &mut Content,
    font: &FontHandle,
    base: f64,
    heading: &str,
    note: &str,
) -> Result<(), hqf_pdf::Error> {
    content.save_state();
    content.set_fill(Rgb::gray(0.2))?;
    text(content, font, 11.0, LEFT, base + BAR + 10.0, heading)?;
    content.set_fill(Rgb::gray(0.4))?;
    text(content, font, 8.5, LEFT, base - 26.0, note)?;
    content.restore_state();
    Ok(())
}

/// Paints a gradient across the width of the page, its foot at `y`.
fn bar(content: &mut Content, shading: &ShadingHandle, y: f64) -> Result<(), hqf_pdf::Error> {
    content.save_state();
    content.rect(LEFT, y, WIDTH, BAR)?.clip().end_path();
    content.draw_shading(shading);
    content.restore_state();
    Ok(())
}

/// Draws the ink at every tint, each swatch labelled with how much goes down.
fn tint_ramp(
    content: &mut Content,
    font: &FontHandle,
    ink: &ColorSpaceHandle,
    y: f64,
) -> Result<(), hqf_pdf::Error> {
    for (x, (tint, name)) in TINT_X.iter().zip(TINTS) {
        content.save_state();
        content.set_fill_space(ink);
        content.set_fill_components(&[*tint])?;
        content.rect(*x, y, SWATCH, BAR)?.fill();
        content.restore_state();

        content.save_state();
        content.set_fill(Rgb::gray(0.35))?;
        text(content, font, 7.5, *x, y - 11.0, name)?;
        content.restore_state();
    }
    Ok(())
}

/// The table the spectrum is read off: every colour of [`SPECTRUM`], red first.
fn spectrum_table() -> Vec<f64> {
    SPECTRUM.iter().flatten().copied().collect()
}

/// The program that steps a ramp: the input is cut into seven bands, the last
/// of which takes the input's own top end, and the band runs one output up
/// while it runs another down.
fn stepped() -> Vec<Op> {
    vec![
        Op::Integer(7),
        Op::Multiply,
        Op::ToInteger,
        Op::Duplicate,
        Op::Integer(6),
        Op::Greater,
        Op::If(vec![Op::Pop, Op::Integer(6)]),
        Op::Integer(6),
        Op::Divide,
        Op::Duplicate,
        Op::Integer(1),
        Op::Exchange,
        Op::Subtract,
        Op::Real(0.25),
    ]
}

/// The program an ink is shown through: the tint runs the cyan and the magenta
/// plates straight up, leaves the yellow one empty, and lets the black one lag
/// behind until the ink is nearly solid.
fn ink_transform() -> Vec<Op> {
    vec![
        Op::Duplicate,
        Op::Real(0.9),
        Op::Multiply,
        Op::Exchange,
        Op::Duplicate,
        Op::Real(0.6),
        Op::Multiply,
        Op::Exchange,
        Op::Integer(3),
        Op::Power,
        Op::Real(0.4),
        Op::Multiply,
        Op::Integer(0),
        Op::Exchange,
    ]
}

/// Draws the page: the title, the four panels and what is said under them.
fn draw(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    gradients: (&ShadingHandle, &ShadingHandle, &ShadingHandle),
    ink: &ColorSpaceHandle,
) -> Result<(), hqf_pdf::Error> {
    let (spectrum, steps, joined) = gradients;

    text(content, font, 16.0, LEFT, 786.0, words.title)?;
    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(content, font, 10.0, LEFT, 767.0, words.intro[0])?;
    text(content, font, 10.0, LEFT, 753.0, words.intro[1])?;
    content.restore_state();

    bar(content, spectrum, SPECTRUM_FOOT)?;
    caption(
        content,
        font,
        SPECTRUM_FOOT,
        words.captions[0][0],
        words.captions[0][1],
    )?;

    bar(content, steps, STEPPED_FOOT)?;
    caption(
        content,
        font,
        STEPPED_FOOT,
        words.captions[1][0],
        &words.stepped_note(),
    )?;

    tint_ramp(content, font, ink, INK_FOOT)?;
    caption(
        content,
        font,
        INK_FOOT,
        words.captions[2][0],
        &words.ink_note(),
    )?;

    bar(content, joined, JOINED_FOOT)?;
    caption(
        content,
        font,
        JOINED_FOOT,
        words.captions[3][0],
        words.captions[3][1],
    )?;

    content.save_state();
    content.set_fill(Rgb::gray(0.45))?;
    text(content, font, 9.0, LEFT, 96.0, words.closing[0])?;
    text(content, font, 9.0, LEFT, 82.0, words.closing[1])?;
    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("functions")));
    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)?)?);

    // A spectrum no pair of endpoints could describe: seven colours on a grid,
    // and the reader draws the line between one point and the next.
    let points = u32::try_from(SPECTRUM.len())?;
    let table = || {
        Sampled::new(
            [[0.0, 1.0]],
            [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]],
            [points],
            spectrum_table(),
        )
        .map(|table| table.depth(SampleDepth::Bits16))
    };
    let spectrum = doc.add_shading(&Shading::from(Axial::new(
        (LEFT, SPECTRUM_FOOT),
        (LEFT + WIDTH, SPECTRUM_FOOT),
        DeviceSpace::Rgb,
        table()?,
    )))?;

    // A ramp with corners in it: the program cuts the input into bands, which
    // no interpolation between endpoints can do.
    let bands = Calculation::new([[0.0, 1.0]], [[0.0, 1.0]; 3], stepped());
    let steps = doc.add_shading(&Shading::from(Axial::new(
        (LEFT, STEPPED_FOOT),
        (LEFT + WIDTH, STEPPED_FOOT),
        DeviceSpace::Rgb,
        bands,
    )))?;

    let ink = doc.add_color_space(Separation::new(
        "Corporate Blue",
        DeviceSpace::Cmyk,
        Calculation::new([[0.0, 1.0]], [[0.0, 1.0]; 4], ink_transform()),
    ));

    // The table over the first half of the run, and a fade into the dark over
    // the second: a joint holds pieces of whatever kind, and the one that is a
    // stream stands as an object of its own.
    let joined = doc.add_shading(&Shading::from(Axial::new(
        (LEFT, JOINED_FOOT),
        (LEFT + WIDTH, JOINED_FOOT),
        DeviceSpace::Rgb,
        Stitching::new(
            [0.0, 1.0],
            vec![
                Function::from(table()?),
                Function::from(
                    Exponential::new([0.0, 1.0], 1.0)
                        .endpoints(vec![0.45, 0.15, 0.60], vec![0.06, 0.05, 0.12]),
                ),
            ],
            vec![0.5],
            vec![[0.0, 1.0], [0.0, 1.0]],
        ),
    )))?;

    let mut content = Content::new();
    draw(
        &mut content,
        &font,
        words,
        (&spectrum, &steps, &joined),
        &ink,
    )?;

    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, a table of {} colours, two programs and a joint",
        bytes.len(),
        SPECTRUM.len()
    );
    Ok(())
}

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

    use super::{LEFT, SPECTRUM, TINTS, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Every line
    /// here is a title, a caption or a note, and no two languages write one
    /// alike; the two programs are not in `Words` at all.
    const SPARED: [&str; 0] = [];

    /// A4's width, and the room a line of the page has: nothing on it is broken
    /// to a measure, so a line only has to stay on the paper.
    const PAGE_WIDTH: f64 = 595.276;
    /// See [`PAGE_WIDTH`].
    const PAPER: f64 = PAGE_WIDTH - LEFT;

    /// How many colours the table is read off, and how many tints the ink is
    /// shown at: the first caption spells the one out in words, and no language
    /// works either of them out from the page.
    const POINTS: usize = 7;

    #[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 or a note longer
    /// than the paper runs off the sheet, and the two notes that carry a
    /// program are the longest lines the page draws.
    #[test]
    fn every_language_writes_lines_no_wider_than_the_paper() {
        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((16.0, words.title.to_owned()))
                .chain(words.intro.map(|line| (10.0, line.to_owned())))
                .chain(words.captions.map(|caption| (11.0, caption[0].to_owned())))
                .chain([
                    (8.5, words.captions[0][1].to_owned()),
                    (8.5, words.stepped_note()),
                    (8.5, words.ink_note()),
                    (8.5, words.captions[3][1].to_owned()),
                ])
                .chain(words.closing.map(|line| (9.0, line.to_owned())));

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

    /// The first caption counts the colours of the table in words, which no
    /// language reads off the page, and the ink is shown at one tint per
    /// colour: a point added or dropped leaves every language saying a number
    /// the page no longer holds.
    #[test]
    fn the_table_holds_the_colours_the_first_caption_counts() {
        assert_eq!(SPECTRUM.len(), POINTS);
        assert_eq!(TINTS.len(), POINTS);
    }
}