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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575 | //! Fades, vignettes, cut-out and punched-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 six
//! panels are painted the same way — one flat rectangle each — and differ only
//! in the mask in force. The fifth is the third's mask turned inside out. The
//! sixth draws its letters dark on a white backdrop, the colour the mask reads
//! wherever its drawing paints nothing, and bends what it reads through a
//! curve, so the letters let the panel through at half strength.
//!
//! 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, and what
//! the fifth is punched out by.
//!
//! 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, Exponential, ExtGState, ExtendEnds, 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;
#[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 panel, in points.
const PANEL: (f64, f64) = (215.0, 100.0);
/// The bottom-left corner of each panel.
const CORNERS: &[(f64, f64)] = &[
(70.0, 630.0),
(305.0, 630.0),
(70.0, 500.0),
(305.0, 500.0),
(70.0, 370.0),
(305.0, 370.0),
];
/// How many masked panels the page lays out.
const PANEL_COUNT: usize = 6;
/// 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, six 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",
"Punched out by the same letters, turned inside out",
"Letters on a white backdrop, eased by a curve",
],
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, six 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, lu comme une couverture, jamais affiché.",
],
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, non sur sa clarté",
"Évidé par les mêmes lettres, masque inversé",
"Lettres sur fond blanc, adoucies par une courbe",
],
cut: ["ÔTE", "ÇA"],
whole: "ENTIER",
band: "Une bande qui s’éteint sous un masque, une étiquette qu’un second état peint entière",
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Eén effen rechthoek, zes maskers",
intro: [
"Elk paneel hieronder is dezelfde rechthoek in dezelfde kleur. Wat verschilt is het masker dat",
"geldt: een tekening die los van de pagina wordt samengesteld en als dekking gelezen in plaats van getoond.",
],
captions: [
"Weggevaagd door een verloop van zwart naar wit",
"In het midden vastgehouden door een radiaal verloop",
"Uitgesneden door letters die het masker tekende",
"Gelezen uit hoe dekkend het masker uitviel",
"Uitgestanst door dezelfde letters, binnenstebuiten",
"Letters op een witte achtergrond, verzacht door een curve",
],
cut: ["MASKER", "DIT"],
whole: "HEEL",
band: "Een band die onder een masker uitloopt, en een label dat een tweede status helemaal schildert",
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Um retângulo liso, seis máscaras",
intro: [
"Cada painel abaixo é o mesmo retângulo na mesma cor. O que muda é a máscara",
"em vigor: um desenho composto à parte da página e lido como cobertura em vez de ser mostrado.",
],
captions: [
"Esbatido por um degradé do preto ao branco",
"Preso ao meio por um radial",
"Recortado através de letras que a máscara desenhou",
"Lido pela opacidade com que a máscara saiu",
"Perfurado pelas mesmas letras, do avesso",
"Letras sobre fundo branco, suavizadas por uma curva",
],
cut: ["MÁSCARA", "ESTE"],
whole: "INTEIRO",
band: "Uma faixa que se apaga sob uma máscara, e uma etiqueta que um segundo estado pinta inteira",
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Un rettangolo piatto, sei maschere",
intro: [
"Ogni pannello qui sotto è lo stesso rettangolo dello stesso colore. Ciò che cambia è la maschera",
"in vigore: un disegno composto a parte dalla pagina e letto come copertura anziché mostrato.",
],
captions: [
"Sfumato da un gradiente dal nero al bianco",
"Tenuto al centro da uno radiale",
"Ritagliato attraverso lettere disegnate dalla maschera",
"Letto da quanto opaca è uscita la maschera",
"Traforato dalle stesse lettere, rovesciate",
"Lettere su fondo bianco, ammorbidite da una curva",
],
cut: ["MASCHERA", "QUESTO"],
whole: "INTERO",
band: "Una fascia che si spegne sotto una maschera, e un’etichetta che un secondo stato dipinge intera",
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Un rectángulo plano, seis máscaras",
intro: [
"Cada panel de abajo es el mismo rectángulo del mismo color. Lo que cambia es la máscara",
"vigente: un dibujo compuesto aparte de la página y leído como cobertura en vez de mostrarse.",
],
captions: [
"Desvanecido por un degradado de negro a blanco",
"Sostenido en el centro por uno radial",
"Recortado a través de letras que dibujó la máscara",
"Leído según lo opaca que salió la máscara",
"Perforado por las mismas letras, del revés",
"Letras sobre un fondo blanco, suavizadas por una curva",
],
cut: ["MÁSCARA", "ESTE"],
whole: "ENTERO",
band: "Una banda que se apaga bajo una máscara, y una etiqueta que un segundo estado pinta entera",
};
/// The page in German.
const GERMAN: Words = Words {
title: "Ein flaches Rechteck, sechs Masken",
intro: [
"Jedes Feld unten ist dasselbe Rechteck in derselben Farbe. Was sich unterscheidet, ist die",
"wirksame Maske: eine getrennt von der Seite zusammengesetzte Zeichnung, als Deckung gelesen.",
],
captions: [
"Durch einen Verlauf von Schwarz nach Weiß ausgeblendet",
"Durch einen radialen Verlauf in der Mitte gehalten",
"Durch Buchstaben geschnitten, die die Maske zeichnete",
"Aus der Deckkraft gelesen, mit der die Maske herauskam",
"Von denselben Buchstaben ausgestanzt, umgekehrt",
"Buchstaben auf weißem Hintergrund, durch eine Kurve gemildert",
],
cut: ["MASKE", "DIESE"],
whole: "GANZ",
band: "Ein Band, das unter einer Maske ausläuft, und ein Etikett, das ein zweiter Zustand ganz malt",
};
/// 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(())
}
/// 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 five panels, in the order they are drawn.
panels: [GStateHandle; PANEL_COUNT],
/// 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(ExtendEnds {
before: false,
after: 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, 38.0, x2 + 12.0, y2 + 56.0, words.cut[0])?;
text(&mut letters, font, 38.0, x2 + 12.0, y2 + 14.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 fifth: the same letters, and the mask turned inside out, so the
// letters stop the panel and everything round them lets it through.
let (x4, y4, width4, height4) = box_of(CORNERS[4]);
let mut punched = Content::new();
punched.set_fill(white)?;
text(&mut punched, font, 38.0, x4 + 12.0, y4 + 56.0, words.cut[0])?;
text(&mut punched, font, 38.0, x4 + 12.0, y4 + 14.0, words.cut[1])?;
let punch = doc.add_ext_gstate(
ExtGState::new().soft_mask(
SoftMask::luminosity(
Drawing::new(punched, Rect::new(x4, y4, width4, height4)),
DeviceSpace::Rgb,
)
.inverted(),
),
);
// 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, 72.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, 72.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),
))));
let eased = eased(doc, font, words)?;
// 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, 130.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, 130.0)),
DeviceSpace::Rgb,
)));
let whole = doc.add_ext_gstate(ExtGState::new().without_soft_mask());
Ok(Masks {
panels: [fade, hold, cut, through, punch, eased],
band: run_out,
whole,
})
}
/// The mask of the sixth panel: the letters drawn dark, on a backdrop of white.
///
/// Where the drawing paints nothing the mask reads the backdrop and lets the
/// panel through; the curve lifts the dark of the letters halfway, so they let
/// half of it through.
fn eased(
doc: &mut Document,
font: &FontHandle,
words: &'static Words,
) -> Result<GStateHandle, hqf_pdf::Error> {
let (x5, y5, width5, height5) = box_of(CORNERS[5]);
let mut dark = Content::new();
dark.set_fill(Rgb::gray(0.0))?;
text(&mut dark, font, 38.0, x5 + 12.0, y5 + 56.0, words.cut[0])?;
text(&mut dark, font, 38.0, x5 + 12.0, y5 + 14.0, words.cut[1])?;
Ok(doc.add_ext_gstate(
ExtGState::new().soft_mask(
SoftMask::luminosity(
Drawing::new(dark, Rect::new(x5, y5, width5, height5)),
DeviceSpace::Rgb,
)
.backdrop([1.0, 1.0, 1.0])
.transfer(Exponential::new([0.0, 1.0], 1.0).endpoints([0.5], [1.0])),
),
))
}
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("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, 130.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, where two
/// languages spell a word alike.
const SPARED: [&str; 2] = [
// Written the same way in Portuguese.
r#""ESTE""#,
r#""MÁSCARA""#,
];
#[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:?}"
);
}
}
|