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
576
577
578
579
580
581
582
583
584
585
586
587
588
589 | //! Draws the four ways a line lays its ink down: its pattern, its ends, its
//! corners, and a table ruled with them.
//!
//! A stroke states a width and a colour, and now also a line style: the dashes
//! and gaps it follows, the shape at its two ends, and the shape where two of
//! its segments meet. A table's rules and a cell's border carry one, so a
//! statement is ruled with hairline dots rather than with solid lines.
//!
//! Both sets of words are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn.
//!
//! Usage: `cargo run --example write_dotted_rules -- tmp/dotted.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_dotted_rules`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{Border, Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table};
use hqf_pdf::{
Align, Dash, Document, Font, FontHandle, LineCap, LineJoin, LineStyle, Page, Rgb, TextFlow,
};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
use language::Language;
/// The font the page is set in when the caller names none: the one committed
/// for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
/// The page's title.
title: &'static str,
/// What the page is about.
lead: &'static str,
/// The heading over the four sample lines.
patterns: &'static str,
/// What each of the four sample lines is called.
pattern_names: [&'static str; 4],
/// The heading over the three ends.
ends: &'static str,
/// What each of the three ends is called.
end_names: [&'static str; 3],
/// The heading over the three corners.
corners: &'static str,
/// What each of the three corners is called.
corner_names: [&'static str; 3],
/// The heading over the ruled table.
ruled: &'static str,
/// The two column headings of that table.
columns: [&'static str; 2],
/// What the four rows of that table are called.
rows: [&'static str; 4],
/// The label on the total row.
total: &'static str,
/// What a dash of no length needs to be seen.
caveat: &'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: "Lines that are not solid",
lead: "A stroke says how thick it is and what colour it is drawn in, and it \
may also say how the ink is laid down: the dashes and gaps it \
follows, the shape at its two ends, and the shape where two of its \
segments meet. Nothing below is drawn twice — each line is one \
stroke, told what to look like.",
patterns: "Four patterns",
pattern_names: [
"Solid, which is what a stroke does when it is told nothing",
"Dashes of four points, gaps of two",
"Dashes and gaps of the same three points",
"Dots, which are dashes of no length at all",
],
ends: "Three ends",
end_names: ["Squared off", "Rounded", "Squared off past the end"],
corners: "Three corners",
corner_names: ["Pointed", "Rounded", "Cut off"],
ruled: "A statement ruled with dots",
columns: ["Description", "Amount"],
rows: [
"Drawing office, February",
"Plates and proofs",
"Delivery, two crates",
"Storage, one month",
],
total: "Total",
caveat: "A dot is a dash of no length, so it puts ink down only under a \
rounded end: told to square its ends off, the same pattern draws \
nothing at all. That is why the dotted lines here ask for both.",
};
/// The page in French.
const FRENCH: Words = Words {
title: "Des traits qui ne sont pas pleins",
lead: "Un trait dit son épaisseur et sa couleur, et il peut aussi dire \
comment l'encre est posée : les tirets et les blancs qu'il suit, la \
forme de ses deux bouts, et la forme de l'angle où deux de ses \
segments se rejoignent. Rien ci-dessous n'est dessiné deux fois : \
chaque ligne est un seul trait, à qui l'on a dit de quoi avoir \
l'air.",
patterns: "Quatre motifs",
pattern_names: [
"Plein, ce que fait un trait à qui l'on ne dit rien",
"Tirets de quatre points, blancs de deux",
"Tirets et blancs des mêmes trois points",
"Pointillé, c'est-à-dire des tirets sans aucune longueur",
],
ends: "Trois bouts",
end_names: ["Coupé net", "Arrondi", "Coupé net au-delà du bout"],
corners: "Trois angles",
corner_names: ["En pointe", "Arrondi", "Abattu"],
ruled: "Un relevé réglé en pointillé",
columns: ["Désignation", "Montant"],
rows: [
"Bureau d'études, février",
"Plaques et épreuves",
"Livraison, deux caisses",
"Entreposage, un mois",
],
total: "Total",
caveat: "Un point est un tiret sans longueur : il ne pose d'encre que sous \
un bout arrondi. À qui lui demande des bouts coupés net, le même \
motif ne dessine rien du tout. C'est pourquoi les traits en \
pointillé de cette page demandent les deux.",
};
/// 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)];
/// The left edge of everything on the page.
const LEFT: f64 = 72.0;
/// How wide a block of text, and the table, are.
const WIDTH: f64 = 451.0;
/// How far the sample lines run.
const SAMPLE: f64 = 150.0;
/// The four amounts the statement carries, in cents.
const AMOUNTS: [i64; 4] = [125_000, 48_050, 9_600, 21_025];
/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
c: &mut Content,
handle: &FontHandle,
size: f64,
top: f64,
text: &str,
) -> Result<f64, hqf_pdf::Error> {
let flow = TextFlow::new(handle, size);
let lines = flow.break_lines(text, WIDTH);
c.begin_text();
flow.draw(c, &lines, LEFT, top, WIDTH)?;
c.end_text();
Ok(top - flow.height(&lines))
}
/// The four patterns the page draws, in the order it draws them.
fn patterns() -> Result<[LineStyle; 4], hqf_pdf::Error> {
Ok([
LineStyle::new().solid(),
LineStyle::new().dash(Dash::on_off(4.0, 2.0)?),
LineStyle::new().dash(Dash::even(3.0)?),
LineStyle::new()
.dash(Dash::dotted(4.0)?)
.cap(LineCap::Round),
])
}
/// Draws one sample line at `y`, under `style`, and its name beside it.
fn sample(
c: &mut Content,
handle: &FontHandle,
y: f64,
style: &LineStyle,
name: &str,
) -> Result<(), hqf_pdf::Error> {
c.save_state();
c.set_line_width(1.5)?
.set_line_style(style)?
.move_to(LEFT, y)?
.line_to(LEFT + SAMPLE, y)?
.stroke();
c.restore_state();
let flow = TextFlow::new(handle, 9.5);
c.begin_text();
flow.draw(
c,
&flow.break_lines(name, WIDTH - SAMPLE - 16.0),
LEFT + SAMPLE + 16.0,
y + 3.0,
WIDTH - SAMPLE - 16.0,
)?;
c.end_text();
Ok(())
}
/// Draws one corner at `x`, its two arms meeting at a point above them, under
/// `join`, and its name under it.
fn corner(
c: &mut Content,
handle: &FontHandle,
x: f64,
y: f64,
join: LineJoin,
name: &str,
) -> Result<(), hqf_pdf::Error> {
c.save_state();
c.set_line_width(9.0)?
.set_line_join(join)
.move_to(x, y)?
.line_to(x + 24.0, y + 34.0)?
.line_to(x + 48.0, y)?
.stroke();
c.restore_state();
let flow = TextFlow::new(handle, 8.5);
c.begin_text();
flow.draw(c, &flow.break_lines(name, 96.0), x, y - 8.0, 96.0)?;
c.end_text();
Ok(())
}
/// Draws one line end at `y`, under `cap`, and its name beside it.
fn end(
c: &mut Content,
handle: &FontHandle,
y: f64,
cap: LineCap,
name: &str,
) -> Result<(), hqf_pdf::Error> {
c.save_state();
c.set_line_width(9.0)?
.set_line_cap(cap)
.set_stroke(Rgb::gray(0.45))?
.move_to(LEFT + 12.0, y)?
.line_to(LEFT + 90.0, y)?
.stroke();
c.restore_state();
// The thin line the ends are measured against: the ink of a squared-off end
// stops on it, and the ink of the other two runs past it.
c.save_state();
c.set_line_width(0.4)?
.set_stroke(Rgb::new(0.75, 0.1, 0.1))?
.move_to(LEFT + 90.0, y - 10.0)?
.line_to(LEFT + 90.0, y + 10.0)?
.stroke();
c.restore_state();
let flow = TextFlow::new(handle, 9.5);
c.begin_text();
flow.draw(
c,
&flow.break_lines(name, WIDTH - 130.0),
LEFT + 118.0,
y + 3.0,
WIDTH - 130.0,
)?;
c.end_text();
Ok(())
}
/// The statement, ruled with dotted hairlines between its rows and a solid
/// frame around it.
fn statement<'f>(words: &Words, text: &'f FontHandle) -> Result<Table<'f>, hqf_pdf::Error> {
let dotted = Stroke::new(0.6, Rgb::gray(0.45)).styled(
LineStyle::new()
.dash(Dash::dotted(2.5)?)
.cap(LineCap::Round),
);
let columns = Columns::new(
vec![ColumnWidth::Fraction(1.0), ColumnWidth::Points(110.0)],
WIDTH,
)?;
let mut table = Table::new(columns);
table.header(1);
table
.rule(Rule::Frame, Stroke::black(0.75))
.rule(Rule::HorizontalOther, dotted.clone())
.rule(Rule::Vertical(1), dotted);
let pad = Padding::symmetric(5.0, 4.0);
let heading = |label: &str, align| {
Cell::new(text, 9.5, label)
.padding(pad)
.align(align)
.fill(Rgb::new(0.93, 0.94, 0.97))
};
table.push(
Row::new()
.cell(heading(words.columns[0], Align::Left))
.cell(heading(words.columns[1], Align::Right))
.min_height(19.0),
);
for (label, amount) in words.rows.iter().zip(AMOUNTS) {
table.push(
Row::new()
.cell(Cell::new(text, 9.0, *label).padding(pad))
.cell(
Cell::new(text, 9.0, money(amount))
.padding(pad)
.align(Align::Right),
)
.min_height(16.0),
);
}
// The total is held off the rows above it by a dashed border of its own,
// which is a cell's line style rather than the table's.
let dashed = Stroke::black(0.8).styled(LineStyle::new().dash(Dash::on_off(3.0, 2.0)?));
let border = Border::none().top(&dashed);
let sum: i64 = AMOUNTS.iter().sum();
table.push(
Row::new()
.cell(
Cell::new(text, 9.5, words.total)
.padding(pad)
.border(&border),
)
.cell(
Cell::new(text, 9.5, money(sum))
.padding(pad)
.align(Align::Right)
.border(&border),
)
.min_height(18.0),
);
Ok(table)
}
/// An amount of cents, its thousands parted by a no-break space and its
/// decimals by a point, which is how every language this example is written in
/// writes one.
fn money(cents: i64) -> String {
let (whole, fraction) = (cents / 100, cents % 100);
let digits = whole.to_string();
let mut out = String::with_capacity(digits.len() + 8);
for (index, digit) in digits.chars().enumerate() {
if index > 0 && (digits.len() - index) % 3 == 0 {
out.push('\u{00A0}');
}
out.push(digit);
}
format!("{out}.{fraction:02}\u{00A0}EUR")
}
/// Draws the whole page.
fn build(words: &Words, font: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut doc = Document::new();
doc.set_license(licence::licensed());
let text = doc.add_font(Font::parse(fs::read(font)?)?);
let mut c = Content::new();
let mut top = 782.0;
top = block(&mut c, &text, 17.0, top, words.title)? - 12.0;
top = block(&mut c, &text, 9.5, top, words.lead)? - 22.0;
top = block(&mut c, &text, 11.0, top, words.patterns)? - 16.0;
for (style, name) in patterns()?.iter().zip(words.pattern_names) {
sample(&mut c, &text, top, style, name)?;
top -= 20.0;
}
top -= 10.0;
top = block(&mut c, &text, 11.0, top, words.ends)? - 18.0;
for (cap, name) in [LineCap::Butt, LineCap::Round, LineCap::Projecting]
.into_iter()
.zip(words.end_names)
{
end(&mut c, &text, top, cap, name)?;
top -= 26.0;
}
top -= 6.0;
top = block(&mut c, &text, 11.0, top, words.corners)? - 46.0;
for (index, (join, name)) in [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel]
.into_iter()
.zip(words.corner_names)
.enumerate()
{
#[expect(
clippy::cast_precision_loss,
reason = "three corners, spaced a fixed step apart"
)]
#[expect(
clippy::suboptimal_flops,
reason = "a fused multiply-add rounds once, and the Python twin \
rounds twice"
)]
let x = LEFT + index as f64 * 150.0;
corner(&mut c, &text, x, top, join, name)?;
}
// The names sit under the corners, so the next heading starts below them.
top -= 34.0;
top = block(&mut c, &text, 11.0, top, words.ruled)? - 12.0;
let placed = statement(words, &text)?.fit(LEFT, top, top - 96.0, 0)?;
placed.draw(&mut c)?;
top = placed.bottom() - 24.0;
c.set_fill(Rgb::gray(0.35))?;
block(&mut c, &text, 8.5, top, words.caveat)?;
let mut page = Page::a4();
page.content = c.into_bytes();
doc.add_page(page)?;
Ok(doc.to_bytes()?)
}
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("dotted_rules")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let bytes = build(words, &font_path)?;
if let Some(parent) = Path::new(&out).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&out, &bytes)?;
println!("wrote {out}: {} bytes", bytes.len());
Ok(())
}
#[cfg(test)]
mod tests {
use hqf_pdf::{Dash, Font, FontHandle, LineCap, LineStyle};
use super::{AMOUNTS, LEFT, SAMPLE, WIDTH, WORDS, default_font, language, money, patterns};
/// The font the page is set in, to measure what it draws.
fn handle() -> FontHandle {
let mut doc = hqf_pdf::Document::new();
doc.add_font(
Font::parse(std::fs::read(default_font()).expect("the test font")).expect("a font"),
)
}
/// The lines two languages are allowed to write the same way: the label on
/// the total row is the same word in English and in French.
const SPARED: [&str; 1] = ["total: \"Total\""];
#[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:?}"
);
}
#[test]
fn every_name_beside_a_sample_line_fits_the_room_left_beside_it() {
let font = handle();
// A name is set to the right of the line and of the gap after it.
let room = WIDTH - SAMPLE - 16.0;
for (_, words) in &WORDS {
for name in words.pattern_names {
assert!(
font.measure(name, 9.5) <= room,
"{name:?} needs {} of {room}",
font.measure(name, 9.5)
);
}
for name in words.end_names {
let beside = WIDTH - 130.0;
assert!(
font.measure(name, 9.5) <= beside,
"{name:?} needs {} of {beside}",
font.measure(name, 9.5)
);
}
for name in words.corner_names {
assert!(
font.measure(name, 8.5) <= 96.0,
"{name:?} needs {} of 96",
font.measure(name, 8.5)
);
}
}
}
#[test]
fn every_heading_of_the_statement_fits_its_own_column() {
let font = handle();
// The right column is 110 points wide and every cell is padded by five
// points on each side.
let amounts = 110.0 - 10.0;
for (_, words) in &WORDS {
assert!(
font.measure(words.columns[1], 9.5) <= amounts,
"{:?} needs {} of {amounts}",
words.columns[1],
font.measure(words.columns[1], 9.5)
);
for label in words.rows {
let left = WIDTH - 110.0 - 10.0;
assert!(
font.measure(label, 9.0) <= left,
"{label:?} needs {} of {left}",
font.measure(label, 9.0)
);
}
}
}
#[test]
fn the_page_stays_inside_its_own_left_margin() {
// The three corners are drawn a fixed step apart, and the last of them
// is 48 points wide.
let last = 2.0_f64.mul_add(150.0, LEFT) + 48.0;
assert!(last <= LEFT + WIDTH, "the corners run to {last}");
}
#[test]
fn the_dotted_pattern_asks_for_the_round_end_that_shows_it() {
let styles = patterns().expect("valid patterns");
let mut solid = hqf_pdf::Content::new();
solid.set_line_style(&styles[0]).expect("finite");
let mut dotted = hqf_pdf::Content::new();
dotted.set_line_style(&styles[3]).expect("finite");
assert_eq!(solid.as_bytes(), b"[] 0 d\n");
assert_eq!(
dotted.as_bytes(),
b"[0 4] 0 d\n1 J\n",
"a dash of no length puts no ink down under any other end"
);
// The same pattern, built the other way round, is the same bytes.
let same = LineStyle::new()
.dash(Dash::new(vec![0.0, 4.0]).expect("valid"))
.cap(LineCap::Round);
let mut written = hqf_pdf::Content::new();
written.set_line_style(&same).expect("finite");
assert_eq!(written.as_bytes(), dotted.as_bytes());
}
#[test]
fn an_amount_is_written_with_a_space_between_its_thousands() {
assert_eq!(money(9_600), "96.00\u{00A0}EUR");
assert_eq!(money(48_050), "480.50\u{00A0}EUR");
assert_eq!(money(125_000), "1\u{00A0}250.00\u{00A0}EUR");
assert_eq!(
money(AMOUNTS.iter().sum()),
"2\u{00A0}036.75\u{00A0}EUR",
"the total the page draws"
);
}
}
|