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 | //! Several named colorants at once, each on a plate of its own.
//!
//! A colour in such a space is one tint per colorant, and one program says what
//! the lot of them look like where those plates are not to hand. Naming some of
//! the process plates and no others is how a document lays ink on those and
//! leaves the rest as they stand; naming inks of its own is how a press that
//! carries more than four is painted in.
//!
//! The words the page draws are held in `Words`, one set per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The colorants are not words: their
//! names are written into the file and drawn back from it.
//!
//! Usage: `cargo run --example write_devicen -- tmp/devicen.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_devicen -- tmp/devicen_fr.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::{
Calculation, ColorSpaceHandle, DeviceN, DeviceSpace, Document, Font, FontHandle, Op, 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.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// The left edge of everything.
const LEFT: f64 = 70.0;
/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: a colorant's name is written into the
/// file and drawn back from it, and so are the programs and the tints.
#[derive(Debug)]
struct Words {
/// The title across the top of the page.
title: &'static str,
/// The two lines under the title, each already broken to the page.
lead: [&'static str; 2],
/// The heading of the panel of subsets.
subsets: &'static str,
/// The heading of the panel of two inks, and the line under it.
inks: &'static str,
inks_under: &'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: "Several plates at once, each with a tint of its own",
lead: [
"Naming some of the process plates and no others lays ink on those and leaves the rest as",
"they stand, which painting in full CMYK cannot do. One program fills in the plates left out.",
],
subsets: "Subsets of the process plates, and the program each one is shown through",
inks: "Two inks of the press's own on one space, every tint of each against the other",
inks_under: "Down the side, Corporate Blue. Across the top, Corporate Gold. Two numbers say a \
colour here.",
};
/// The page in French.
const FRENCH: Words = Words {
title: "Plusieurs plaques à la fois, chacune à son intensité",
lead: [
"Nommer certaines plaques et pas les autres pose de l'encre sur celles-là et laisse les",
"autres intactes, ce que la quadrichromie ne peut pas. Un programme remplit les manquantes.",
],
subsets: "Sous-ensembles des plaques d'impression, et le programme qui montre chacun",
inks: "Deux encres propres à la presse sur un espace, chaque intensité de l'une contre l'autre",
inks_under: "Sur le côté, Corporate Blue. En haut, Corporate Gold. Deux nombres disent une \
couleur ici.",
};
/// 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 subset of the process plates: the plates it names, the program that
/// fills in the ones it leaves out, and the tint each named plate is shown at.
struct Subset {
colorants: &'static [&'static str],
body: &'static [Op],
tints: &'static [f64],
}
/// The subsets the first panel shows, each with the program that turns its
/// tints into a full set of process inks.
const SUBSETS: &[Subset] = &[
Subset {
colorants: &["Cyan"],
body: &[Op::Integer(0), Op::Integer(0), Op::Integer(0)],
tints: &[0.8],
},
Subset {
colorants: &["Magenta"],
body: &[
Op::Integer(0),
Op::Integer(0),
Op::Integer(0),
Op::Integer(4),
Op::Integer(1),
Op::Roll,
],
tints: &[0.8],
},
Subset {
colorants: &["Yellow"],
body: &[
Op::Integer(0),
Op::Integer(0),
Op::Integer(0),
Op::Integer(4),
Op::Integer(2),
Op::Roll,
],
tints: &[0.8],
},
Subset {
colorants: &["Black"],
body: &[
Op::Integer(0),
Op::Integer(0),
Op::Integer(0),
Op::Integer(4),
Op::Integer(3),
Op::Roll,
],
tints: &[0.8],
},
Subset {
colorants: &["Cyan", "Magenta"],
body: &[Op::Integer(0), Op::Integer(0)],
tints: &[0.7, 0.7],
},
Subset {
colorants: &["Cyan", "Yellow"],
body: &[Op::Integer(0), Op::Exchange, Op::Integer(0)],
tints: &[0.7, 0.7],
},
Subset {
colorants: &["Magenta", "Yellow"],
body: &[
Op::Integer(0),
Op::Integer(0),
Op::Integer(4),
Op::Integer(1),
Op::Roll,
],
tints: &[0.7, 0.7],
},
Subset {
colorants: &["Cyan", "Magenta", "Yellow"],
body: &[Op::Integer(0)],
tints: &[0.6, 0.6, 0.6],
},
];
/// The left edge of each column of the first panel, and the size of one swatch.
const SUBSET_X: &[f64] = &[70.0, 185.0, 300.0, 415.0];
/// See [`SUBSET_X`].
const SUBSET_SIZE: (f64, f64) = (100.0, 52.0);
/// The baseline the first row of swatches sits on, and the drop to the second.
const SUBSET_Y: f64 = 620.0;
/// See [`SUBSET_Y`].
const SUBSET_DROP: f64 = 108.0;
/// The two inks the second panel paints in, as the process inks show them at
/// full strength.
const BLUE: [f64; 4] = [0.92, 0.58, 0.0, 0.06];
/// See [`BLUE`].
const GOLD: [f64; 4] = [0.0, 0.28, 0.95, 0.04];
/// The tints the duotone grid runs through, along both of its axes.
const DUOTONE_TINTS: &[f64] = &[0.0, 0.25, 0.5, 0.75, 1.0];
/// The left edge and the top of the duotone grid, and the size of one cell.
const DUOTONE_ORIGIN: (f64, f64) = (110.0, 355.0);
/// See [`DUOTONE_ORIGIN`].
const DUOTONE_CELL: f64 = 52.0;
/// 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 program mixing two inks: each output is the first ink's share of that
/// process plate taken at the first tint, plus the second ink's taken at the
/// second.
///
/// Both tints stay at the bottom of the stack while the four outputs are worked
/// out above them, so each one is reached again by counting down past the
/// outputs already there; the pair is then turned to the top and thrown away.
fn mix_two_inks() -> Calculation {
let mut body = Vec::new();
for (plate, (first, second)) in BLUE.iter().zip(&GOLD).enumerate() {
let reach = i64::try_from(plate).expect("four plates count") + 1;
body.extend([
Op::Integer(reach),
Op::Index,
Op::Real(*first),
Op::Multiply,
Op::Integer(reach),
Op::Index,
Op::Real(*second),
Op::Multiply,
Op::Add,
]);
}
body.extend([Op::Integer(6), Op::Integer(4), Op::Roll, Op::Pop, Op::Pop]);
Calculation::new([[0.0, 1.0]; 2], [[0.0, 1.0]; 4], body)
}
/// Draws one swatch of a subset of the process plates, with the plates it names
/// above it and the program that fills in the rest below.
fn subset_swatch(
content: &mut Content,
font: &FontHandle,
space: &ColorSpaceHandle,
subset: &Subset,
x: f64,
y: f64,
) -> Result<(), hqf_pdf::Error> {
let (width, height) = SUBSET_SIZE;
content.save_state();
content.set_fill_space(space);
content.set_fill_components(subset.tints)?;
content.rect(x, y, width, height)?.fill();
content.restore_state();
content.save_state();
content.set_fill(Rgb::gray(0.2))?;
text(
content,
font,
8.0,
x,
y + height + 7.0,
&subset.colorants.join(" "),
)?;
content.set_fill(Rgb::gray(0.45))?;
text(
content,
font,
7.0,
x,
y - 11.0,
&Calculation::new(
vec![[0.0, 1.0]; subset.colorants.len()],
[[0.0, 1.0]; 4],
subset.body,
)
.program()?,
)?;
content.restore_state();
Ok(())
}
/// Draws the grid of the two inks against one another, every tint of the first
/// crossed with every tint of the second.
fn duotone_grid(
content: &mut Content,
font: &FontHandle,
space: &ColorSpaceHandle,
) -> Result<(), hqf_pdf::Error> {
let (left, top) = DUOTONE_ORIGIN;
for (row, blue) in DUOTONE_TINTS.iter().enumerate() {
#[expect(
clippy::cast_precision_loss,
reason = "the grid is five cells each way, so the count is exact as a real"
)]
let down = (row as f64).mul_add(-DUOTONE_CELL, top);
for (column, gold) in DUOTONE_TINTS.iter().enumerate() {
#[expect(
clippy::cast_precision_loss,
reason = "the grid is five cells each way, so the count is exact as a real"
)]
let across = (column as f64).mul_add(DUOTONE_CELL, left);
content.save_state();
content.set_fill_space(space);
content.set_fill_components(&[*blue, *gold])?;
content
.rect(across, down, DUOTONE_CELL - 4.0, DUOTONE_CELL - 4.0)?
.fill();
content.restore_state();
}
content.save_state();
content.set_fill(Rgb::gray(0.45))?;
text(
content,
font,
7.0,
LEFT,
down + DUOTONE_CELL / 2.0 - 7.0,
&format!("{:.0}%", blue * 100.0),
)?;
content.restore_state();
}
for (column, gold) in DUOTONE_TINTS.iter().enumerate() {
#[expect(
clippy::cast_precision_loss,
reason = "the grid is five cells each way, so the count is exact as a real"
)]
let across = (column as f64).mul_add(DUOTONE_CELL, left);
content.save_state();
content.set_fill(Rgb::gray(0.45))?;
text(
content,
font,
7.0,
across,
top + DUOTONE_CELL - 1.0,
&format!("{:.0}%", gold * 100.0),
)?;
content.restore_state();
}
Ok(())
}
/// Draws the title and the two lines saying what the page is showing.
fn heading(
content: &mut Content,
font: &FontHandle,
words: &'static Words,
) -> Result<(), hqf_pdf::Error> {
text(content, font, 15.0, LEFT, 780.0, words.title)?;
content.save_state();
content.set_fill(Rgb::gray(0.35))?;
text(content, font, 10.0, LEFT, 762.0, words.lead[0])?;
text(content, font, 10.0, LEFT, 748.0, words.lead[1])?;
content.restore_state();
Ok(())
}
/// Draws one panel's heading, with the line under it that a panel may have.
fn panel_heading(
content: &mut Content,
font: &FontHandle,
y: f64,
title: &str,
under: Option<&str>,
) -> Result<(), hqf_pdf::Error> {
content.save_state();
content.set_fill(Rgb::gray(0.2))?;
text(content, font, 11.0, LEFT, y, title)?;
if let Some(line) = under {
content.set_fill(Rgb::gray(0.45))?;
text(content, font, 8.0, LEFT, y - 16.0, line)?;
}
content.restore_state();
Ok(())
}
/// Draws every subset of the process plates, four to a row.
fn subset_panel(
doc: &mut Document,
content: &mut Content,
font: &FontHandle,
) -> Result<(), hqf_pdf::Error> {
for (place, subset) in SUBSETS.iter().enumerate() {
let space = doc.add_color_space(DeviceN::new(
subset
.colorants
.iter()
.map(|colorant| (*colorant).to_owned())
.collect::<Vec<_>>(),
DeviceSpace::Cmyk,
Calculation::new(
vec![[0.0, 1.0]; subset.colorants.len()],
[[0.0, 1.0]; 4],
subset.body,
),
)?);
let x = SUBSET_X[place % SUBSET_X.len()];
#[expect(
clippy::cast_precision_loss,
reason = "the panel holds two rows, so the count is exact as a real"
)]
let y = ((place / SUBSET_X.len()) as f64).mul_add(-SUBSET_DROP, SUBSET_Y);
subset_swatch(content, font, &space, subset, x, y)?;
}
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("devicen")));
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();
heading(&mut content, &font, words)?;
panel_heading(&mut content, &font, 700.0, words.subsets, None)?;
subset_panel(&mut doc, &mut content, &font)?;
panel_heading(
&mut content,
&font,
440.0,
words.inks,
Some(words.inks_under),
)?;
let inks = doc.add_color_space(DeviceN::new(
vec!["Corporate Blue".to_owned(), "Corporate Gold".to_owned()],
DeviceSpace::Cmyk,
mix_two_inks(),
)?);
duotone_grid(&mut content, &font, &inks)?;
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, {} subsets of the process plates and two inks of its own",
bytes.len(),
SUBSETS.len()
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::{WORDS, language};
/// The lines two languages are allowed to write the same way. There are
/// none: an ink's name is drawn from the file, not from `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:?}"
);
}
}
|