Un rectangle, quatre masques

Le même rectangle uni quatre fois de suite, chacun sous un masque différent — un fondu en dégradé, un assombrissement des bords, des lettres découpées dedans, et une découpe lue sur la transparence — plus un bandeau qui s'efface, avec à l'intérieur une étiquette qui, elle, reste entière.

Rust write_soft_mask.rs 393 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
//! Fades, vignettes and cut-out letters, all from soft masks.
//!
//! A soft mask is a drawing composited apart from the page and then read as a
//! coverage rather than shown: where it comes out light, what the state paints
//! goes through whole; where it comes out dark, nothing does. The same four
//! panels are painted the same way — one flat rectangle each — and differ only
//! in the mask in force.
//!
//! The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The two words the third mask is drawn in are language as
//! much as the captions are: they are what the panel is seen through.
//!
//! Usage: `cargo run --example write_soft_mask -- tmp/soft_mask.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_soft_mask --
//! tmp/masque.pdf`

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

use hqf_pdf::color::DeviceSpace;
use hqf_pdf::content::Content;
use hqf_pdf::{
    Axial, Document, Drawing, ExtGState, Font, FontHandle, GStateHandle, Page, Radial, Rect, Rgb,
    Shading, SoftMask,
};

#[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 size of one panel, in points.
const PANEL: (f64, f64) = (215.0, 150.0);

/// The bottom-left corner of each panel.
const CORNERS: &[(f64, f64)] = &[(70.0, 560.0), (305.0, 560.0), (70.0, 380.0), (305.0, 380.0)];

/// How many masked panels the page lays out.
const PANEL_COUNT: usize = 4;

/// The words the page is written in, one set per language.
///
/// The two words the third mask is drawn in are here with the rest: the panel
/// is seen through their shapes, so a reader reads them as much as a caption.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The two lines under it, saying what a mask is.
    intro: [&'static str; 2],
    /// What each panel shows, in the order they are laid out.
    captions: [&'static str; PANEL_COUNT],
    /// The two words the third panel is cut through.
    cut: [&'static str; 2],
    /// The word on the tag the band's last state paints whole.
    whole: &'static str,
    /// What stands under the band.
    band: &'static str,
}

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: "One flat rectangle, four masks",
    intro: [
        "Each panel below is the same rectangle in the same colour. What differs is the mask in",
        "force: a drawing composited apart from the page and read as a coverage rather than shown.",
    ],
    captions: [
        "Faded away by a black-to-white gradient",
        "Held in the middle by a radial one",
        "Cut through letters the mask drew",
        "Read from how opaque the mask came out",
    ],
    cut: ["MASK", "THIS"],
    whole: "WHOLE",
    band: "A band running out under a mask, and a tag a second state paints whole",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Un rectangle plat, quatre masques",
    intro: [
        "Chaque panneau ci-dessous est le même rectangle, dans la même couleur. Seul change le",
        "masque en vigueur : un dessin composé à part de la page et lu comme une couverture.",
    ],
    captions: [
        "Estompé par un dégradé du noir au blanc",
        "Retenu au centre par un dégradé radial",
        "Découpé par les lettres du masque",
        "Lu sur l'opacité du masque, pas sa clarté",
    ],
    cut: ["ÔTE", "ÇA"],
    whole: "ENTIER",
    band: "Une bande qui s'éteint sous un masque, et une étiquette peinte entière",
};

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

/// The rectangle of the panel at `corner`, as a quadruple.
const fn box_of(corner: (f64, f64)) -> (f64, f64, f64, f64) {
    let (width, height) = PANEL;
    (corner.0, corner.1, width, height)
}

/// A group that paints `shading` across the panel at `corner` and nothing
/// outside it.
fn painted_group(
    content: &mut Content,
    corner: (f64, f64),
    shading: &hqf_pdf::ShadingHandle,
) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = box_of(corner);
    content.save_state();
    content.rect(x, y, width, height)?.clip();
    content.end_path();
    content.draw_shading(shading);
    content.restore_state();
    Ok(())
}

/// The states the page applies, in the order they are added to the document.
struct Masks {
    /// The mask of each of the four panels, in the order they are drawn.
    panels: [GStateHandle; 4],
    /// The mask the band at the foot runs out under.
    band: GStateHandle,
    /// The state that drops whatever mask is in force.
    whole: GStateHandle,
}

/// Builds every mask the page uses, and the state that drops one.
fn masks(
    doc: &mut Document,
    font: &FontHandle,
    words: &'static Words,
) -> Result<Masks, hqf_pdf::Error> {
    let black = Rgb::gray(0.0);
    let white = Rgb::gray(1.0);

    // The mask of the first panel: a gradient running the panel's width, dark
    // at the left and light at the right.
    let (x0, y0, width0, _) = box_of(CORNERS[0]);
    let sweep = doc.add_shading(&Shading::from(Axial::rgb(
        (x0, y0),
        (x0 + width0, y0),
        black,
        white,
    )))?;
    let mut faded = Content::new();
    painted_group(&mut faded, CORNERS[0], &sweep)?;
    let fade = doc.add_ext_gstate(ExtGState::new().soft_mask(SoftMask::luminosity(
        Drawing::new(faded, Rect::new(x0, y0, width0, PANEL.1)),
        DeviceSpace::Rgb,
    )));

    // The second: light in the middle of the panel and dark at its edge, so
    // what it masks is held in the middle and let go at the sides.
    let (x1, y1, width1, height1) = box_of(CORNERS[1]);
    let middle = (x1 + width1 / 2.0, y1 + height1 / 2.0);
    let halo = doc.add_shading(&Shading::from(
        Radial::rgb(
            (middle.0, middle.1, 0.0),
            (middle.0, middle.1, height1 / 2.0),
            white,
            black,
        )
        .extend(false, true),
    ))?;
    let mut vignette = Content::new();
    painted_group(&mut vignette, CORNERS[1], &halo)?;
    let hold = doc.add_ext_gstate(ExtGState::new().soft_mask(SoftMask::luminosity(
        Drawing::new(vignette, Rect::new(x1, y1, width1, height1)),
        DeviceSpace::Rgb,
    )));

    // The third: letters in white on nothing at all. Everything the mask left
    // alone stays black, which lets nothing through, so the panel is seen only
    // through the shapes of the letters.
    let (x2, y2, width2, height2) = box_of(CORNERS[2]);
    let mut letters = Content::new();
    letters.set_fill(white)?;
    text(&mut letters, font, 44.0, x2 + 12.0, y2 + 84.0, words.cut[0])?;
    text(&mut letters, font, 44.0, x2 + 12.0, y2 + 34.0, words.cut[1])?;
    let cut = doc.add_ext_gstate(ExtGState::new().soft_mask(SoftMask::luminosity(
        Drawing::new(letters, Rect::new(x2, y2, width2, height2)),
        DeviceSpace::Rgb,
    )));

    // The fourth reads how opaque the mask came out rather than how light, so
    // the shapes it paints let the panel through by exactly the opacity they
    // were painted at, whatever colour they were.
    let dimmed = doc.add_ext_gstate(ExtGState::new().alpha(0.4));
    let (x3, y3, width3, height3) = box_of(CORNERS[3]);
    let mut shapes = Content::new();
    shapes.set_fill(Rgb::new(0.2, 0.6, 0.9))?;
    shapes.rect(x3 + 14.0, y3 + 14.0, 90.0, 122.0)?.fill();
    shapes.save_state();
    shapes.set_ext_gstate(&dimmed);
    shapes.set_fill(Rgb::new(0.9, 0.4, 0.1))?;
    shapes.rect(x3 + 112.0, y3 + 14.0, 90.0, 122.0)?.fill();
    shapes.restore_state();
    let through = doc.add_ext_gstate(ExtGState::new().soft_mask(SoftMask::alpha(Drawing::new(
        shapes,
        Rect::new(x3, y3, width3, height3),
    ))));

    // The last: a band running out towards its right edge, and the state that
    // drops the mask again for what is painted inside it.
    let run_out = doc.add_shading(&Shading::from(Axial::rgb(
        (70.0, 200.0),
        (520.0, 200.0),
        white,
        black,
    )))?;
    let mut band = Content::new();
    band.save_state();
    band.rect(70.0, 200.0, 450.0, 150.0)?.clip();
    band.end_path();
    band.draw_shading(&run_out);
    band.restore_state();
    let run_out = doc.add_ext_gstate(ExtGState::new().soft_mask(SoftMask::luminosity(
        Drawing::new(band, Rect::new(70.0, 200.0, 450.0, 150.0)),
        DeviceSpace::Rgb,
    )));
    let whole = doc.add_ext_gstate(ExtGState::new().without_soft_mask());

    Ok(Masks {
        panels: [fade, hold, cut, through],
        band: run_out,
        whole,
    })
}

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("soft_mask")));
    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 masks = masks(&mut doc, &font, words)?;

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

    let ink = Rgb::new(0.12, 0.28, 0.52);
    let states = &masks.panels;
    for ((corner, caption), state) in CORNERS.iter().zip(words.captions).zip(states) {
        let (x, y, width, height) = box_of(*corner);

        content.save_state();
        content.set_fill(Rgb::new(0.96, 0.96, 0.94))?;
        content.rect(x, y, width, height)?.fill();
        content.set_ext_gstate(state);
        content.set_fill(ink)?;
        content.rect(x, y, width, height)?.fill();
        content.restore_state();

        content.save_state();
        content.set_stroke(Rgb::gray(0.55))?;
        content.set_line_width(0.6)?;
        content.rect(x, y, width, height)?.stroke();
        content.set_fill(Rgb::gray(0.35))?;
        text(&mut content, &font, 9.0, x, y - 14.0, caption)?;
        content.restore_state();
    }

    // A mask holds until the state that set it is restored, or until a state
    // drops it: the band fades out, and the tag inside it is painted whole.
    let (x4, y4) = (70.0, 200.0);
    let (width4, height4) = (450.0, 150.0);
    content.save_state();
    content.set_fill(Rgb::new(0.96, 0.96, 0.94))?;
    content.rect(x4, y4, width4, height4)?.fill();
    content.set_ext_gstate(&masks.band);
    content.set_fill(ink)?;
    content.rect(x4, y4, width4, height4)?.fill();

    content.save_state();
    content.set_ext_gstate(&masks.whole);
    content.set_fill(Rgb::new(0.85, 0.42, 0.15))?;
    content.rect(x4 + 300.0, y4 + 45.0, 120.0, 60.0)?.fill();
    content.set_fill(Rgb::gray(1.0))?;
    text(
        &mut content,
        &font,
        13.0,
        x4 + 318.0,
        y4 + 68.0,
        words.whole,
    )?;
    content.restore_state();
    content.restore_state();

    content.save_state();
    content.set_stroke(Rgb::gray(0.55))?;
    content.set_line_width(0.6)?;
    content.rect(x4, y4, width4, height4)?.stroke();
    content.set_fill(Rgb::gray(0.35))?;
    text(&mut content, &font, 9.0, x4, y4 - 14.0, words.band)?;
    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, {} masked panels and a band that runs out",
        bytes.len(),
        CORNERS.len()
    );
    Ok(())
}

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

    /// The lines two languages are allowed to write the same way. There are
    /// none.
    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:?}"
        );
    }
}