Gris, couleurs écran et couleurs d'impression

Des pastilles dans chacune des trois façons de dire une couleur — un gris en un seul nombre, une couleur d'écran en trois, une couleur d'impression en quatre encres — chacune légendée par l'instruction réellement écrite dans le fichier, et un même gris moyen dit de trois façons.

Rust write_color_spaces.rs 267 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
//! Paints swatches in each of the three colour spaces, captioned with the
//! operators they wrote.
//!
//! A colour is written in the space it was named in: a grey as one number, a
//! screen colour as three, a printing colour as four inks. The same page shows
//! the three, and the bottom row shows one mid-grey said three ways — the same
//! ink on paper, three different sets of numbers in the file.
//!
//! The title and the four headings are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The caption under each swatch is
//! not: it is the operator the swatch wrote, which reads the same everywhere.
//!
//! Usage: `cargo run --example write_color_spaces -- tmp/color_spaces.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_color_spaces --
//! tmp/espaces_de_couleur.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{Cmyk, Color, Document, 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: the
/// one committed for the tests, so that the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

const MARGIN: f64 = 56.0;
/// One swatch, and the gap to the next.
const SWATCH: f64 = 92.0;
const GAP: f64 = 12.0;
/// The room a row of swatches takes, caption included.
const ROW: f64 = 150.0;
/// The top of the first row of swatches.
const FIRST_ROW: f64 = 700.0;

/// How many rows of swatches the page lays out.
const BAND_COUNT: usize = 4;

/// The words the page is written in, one set per language.
///
/// The caption under a swatch is not among them: it is the operator the swatch
/// wrote, and a file says `0.85 0.16 0.16 rg` wherever it is read.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// What each row of swatches demonstrates, from the top of the page down.
    headings: [&'static str; BAND_COUNT],
}

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: "Three colour spaces, one page",
    headings: [
        "A grey, said as one number",
        "A screen colour, said as red, green and blue",
        "A printing colour, said as four inks",
        "One mid-grey, said three ways",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Trois espaces de couleur, une seule page",
    headings: [
        "Un gris, dit en un seul nombre",
        "Une couleur d'écran, dite en rouge, vert et bleu",
        "Une couleur d'impression, dite en quatre encres",
        "Un même gris moyen, dit de trois façons",
    ],
};

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

/// One row of swatches: what it demonstrates, and the colours it paints.
struct Band {
    heading: &'static str,
    swatches: Vec<(Color, &'static str)>,
}

/// The four rows, from the top of the page down, each under the heading `words`
/// gives it.
fn bands(words: &'static Words) -> Vec<Band> {
    vec![
        Band {
            heading: words.headings[0],
            swatches: vec![
                (Color::Gray(0.15), "0.15 g"),
                (Color::Gray(0.4), "0.4 g"),
                (Color::Gray(0.65), "0.65 g"),
                (Color::Gray(0.9), "0.9 g"),
                (Color::Gray(1.0), "1 g"),
            ],
        },
        Band {
            heading: words.headings[1],
            swatches: vec![
                (Rgb::new(0.85, 0.16, 0.16).into(), "0.85 0.16 0.16 rg"),
                (Rgb::new(0.16, 0.6, 0.24).into(), "0.16 0.6 0.24 rg"),
                (Rgb::new(0.16, 0.35, 0.8).into(), "0.16 0.35 0.8 rg"),
                (Rgb::new(0.95, 0.75, 0.1).into(), "0.95 0.75 0.1 rg"),
                (Rgb::new(0.55, 0.2, 0.7).into(), "0.55 0.2 0.7 rg"),
            ],
        },
        Band {
            heading: words.headings[2],
            swatches: vec![
                (Cmyk::new(1.0, 0.0, 0.0, 0.0).into(), "1 0 0 0 k"),
                (Cmyk::new(0.0, 1.0, 0.0, 0.0).into(), "0 1 0 0 k"),
                (Cmyk::new(0.0, 0.0, 1.0, 0.0).into(), "0 0 1 0 k"),
                (Cmyk::new(0.0, 0.0, 0.0, 1.0).into(), "0 0 0 1 k"),
                (Cmyk::new(0.65, 0.0, 0.35, 0.1).into(), "0.65 0 0.35 0.1 k"),
            ],
        },
        Band {
            heading: words.headings[3],
            swatches: vec![
                (Color::Gray(0.5), "0.5 g"),
                (Rgb::gray(0.5).into(), "0.5 0.5 0.5 rg"),
                (Cmyk::new(0.0, 0.0, 0.0, 0.5).into(), "0 0 0 0.5 k"),
            ],
        },
    ]
}

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

/// Draws one row: its heading, its swatches, and under each the operators the
/// swatch wrote.
fn draw_band(
    content: &mut Content,
    font: &FontHandle,
    band: &Band,
    top: f64,
) -> Result<(), hqf_pdf::Error> {
    content.save_state();
    content.set_fill(Rgb::gray(0.15))?;
    line(content, font, band.heading, 11.0, MARGIN, top)?;
    content.restore_state();

    let bottom = top - 20.0 - SWATCH;
    let mut x = MARGIN;
    for (color, caption) in &band.swatches {
        content.save_state();
        content.set_fill(*color)?;
        content.rect(x, bottom, SWATCH, SWATCH)?;
        content.fill();
        content.restore_state();

        content.save_state();
        content.set_stroke(Rgb::gray(0.75))?;
        content.set_line_width(0.5)?;
        content.rect(x, bottom, SWATCH, SWATCH)?;
        content.stroke();
        content.restore_state();

        content.save_state();
        content.set_fill(Rgb::gray(0.35))?;
        line(content, font, caption, 7.5, x, bottom - 12.0)?;
        content.restore_state();

        x += SWATCH + GAP;
    }
    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("color_spaces")));
    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 mut content = Content::new();
    line(&mut content, &font, words.title, 16.0, MARGIN, 760.0)?;

    let bands = bands(words);
    let mut top = FIRST_ROW;
    for band in &bands {
        draw_band(&mut content, &font, band, top)?;
        top -= ROW;
    }

    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)?;
    let swatches: usize = bands.iter().map(|band| band.swatches.len()).sum();
    println!("wrote {out}: {} bytes, {swatches} swatches", bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{WORDS, language};

    /// The lines two languages are allowed to write the same way. There are
    /// none: the captions are operators, and they are held outside the words.
    const SPARED: [&str; 0] = [];

    #[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:?}"
        );
    }
}