A plan that shows what can be read

A land plan whose layers decide by themselves when to appear. A wide name stands over the plot while the plan is looked at whole, the fine wall figures come in once it is enlarged twice over, and the sentence under the plan is there in two languages, of which a reader shows the one it is set to.

This page is the whole program, for whoever writes your software. There is nothing here to read otherwise. Go back to the document it writes.

Rust write_self_showing_layers.rs 509 lines
  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
//! Draws a land plan whose layers decide for themselves when to be shown.
//!
//! The plot and the house it holds are the page's own ink and are always there.
//! Three kinds of layer sit on top and nobody has to touch the reader's panel
//! for any of them: one wide label stands over the plot while the plan is
//! looked at whole, the fine figures come in once the plan is enlarged twice
//! over, and one layer per language carries the sentence under the plan, so a
//! reader set to French reads French.
//!
//! The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The table of words is also what the language layers are
//! built from: writing one more set of words gives the document one more layer,
//! without a line that draws being touched. The distances are not words — a
//! metre is a metre.
//!
//! Usage: `cargo run --example write_self_showing_layers -- tmp/plot.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_self_showing_layers`

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

use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font, FontHandle, Layer, LayerHandle, Page, Rgb};

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

/// Where the page's text begins, in points from the left edge.
const LEFT: f64 = 80.0;

/// The plot: where its lower left corner sits on the page, and how big it is.
const PLOT: (f64, f64, f64, f64) = (LEFT, 380.0, 435.0, 360.0);

/// The house inside the plot, as an inset from the plot's lower left corner and
/// a size of its own.
const HOUSE: (f64, f64, f64, f64) = (60.0, 90.0, 200.0, 170.0);

/// The magnification the wide label gives way to the fine figures at.
///
/// The label is shown below it and the figures from it, so exactly one of the
/// two stands at every magnification.
const CROSSOVER: f64 = 2.0;

/// How many layers watch the magnification.
const SCALED_COUNT: usize = 2;

/// How many lines say how to see all of it.
const SEEING_COUNT: usize = 2;

/// The distances the plan is measured at, each written inside the line it
/// stands for. None of them is language: a metre is a metre.
const PLOT_ALONG: &str = "24.30";
const PLOT_ACROSS: &str = "17.60";
const HOUSE_ALONG: &str = "11.20";
const HOUSE_ACROSS: &str = "8.40";
const SIDE_SETBACK: &str = "3.35";
const FOOT_SETBACK: &str = "5.10";

/// The two sides of the plot, written the way the wide label states them.
const OVERALL: &str = "24.30 m × 17.60 m";

/// The words the page is written in, one set per language.
///
/// The name of the language and the sentence under the plan are the language
/// layer's own: the reader's panel shows the one and the page shows the other,
/// and both stay in their language whatever language the rest of the page is
/// in. Everything else follows the page.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// What stands under it, saying what the page is about.
    intro: &'static str,
    /// What this language is called, which is the name its layer carries in the
    /// reader's panel.
    tongue: &'static str,
    /// The sentence this language's layer carries under the plan.
    caption: &'static str,
    /// What the two layers that watch the magnification are called.
    scaled: [&'static str; SCALED_COUNT],
    /// What the legend says each of them holds.
    holdings: [&'static str; SCALED_COUNT],
    /// The wide label the plot carries while the plan is looked at whole.
    whole: &'static str,
    /// What the legend says about the layers that carry the wording.
    wording: &'static str,
    /// The lines under the legend saying how to see all of it.
    seeing: [&'static str; SEEING_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: "A plan that shows what can be read",
    intro: "Every layer here decides for itself, by the magnification and by the language.",
    tongue: "English",
    caption: "Plot 12, Mill Lane — sold with the barn and the well.",
    scaled: ["Whole plot", "Fine figures"],
    holdings: [
        "stands over the plan while it is looked at whole",
        "comes in once the plan is enlarged twice over",
    ],
    whole: "PLOT 12",
    wording: "one layer a language, and a reader shows the one it is set to",
    seeing: [
        "Enlarge the plan past two hundred per cent: the figures on the walls come in as the",
        "wide label steps back. Set the reader to another language and the sentence follows.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Un plan qui montre ce qui se lit",
    intro: "Chaque calque décide ici tout seul, par l'agrandissement et par la langue.",
    tongue: "Français",
    caption: "Parcelle 12, chemin du Moulin — vendue avec la grange et le puits.",
    scaled: ["Parcelle entière", "Cotes fines"],
    holdings: [
        "se tient sur le plan tant qu'on le regarde en entier",
        "arrivent dès que le plan est agrandi deux fois",
    ],
    whole: "PARCELLE 12",
    wording: "un calque par langue, et le lecteur montre celle sur laquelle il est réglé",
    seeing: [
        "Agrandissez le plan au-delà de deux cents pour cent : les cotes des murs arrivent",
        "et le grand titre s'efface. Réglez le lecteur sur une autre langue, la phrase suit.",
    ],
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here, and the document gains its layer.
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 house, as a place and a size on the page.
const fn house() -> (f64, f64, f64, f64) {
    let (x, y, _, _) = PLOT;
    let (inset_x, inset_y, width, height) = HOUSE;
    (x + inset_x, y + inset_y, width, height)
}

/// Draws the ink the plan always carries: the plot's boundary and the house
/// standing in it.
fn ground(content: &mut Content) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLOT;
    let (hx, hy, hw, hh) = house();
    content.save_state();
    content.set_stroke(Rgb::gray(0.2))?;
    content.set_line_width(1.6)?;
    content.rect(x, y, width, height)?.stroke();
    content.set_fill(Rgb::new(0.9, 0.91, 0.94))?;
    content.set_line_width(1.2)?;
    content.rect(hx, hy, hw, hh)?.fill();
    content.rect(hx, hy, hw, hh)?.stroke();
    content.restore_state();
    Ok(())
}

/// Draws the wide label: what the plot is called and how big it is, in type
/// that reads from across a desk.
fn wide_label(
    content: &mut Content,
    font: &FontHandle,
    words: &'static Words,
) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLOT;
    let middle = x + width / 2.0;
    content.save_state();
    content.set_fill(Rgb::new(0.35, 0.42, 0.55))?;
    let name = font.measure(words.whole, 26.0);
    text(
        content,
        font,
        26.0,
        middle - name / 2.0,
        y + height - 54.0,
        words.whole,
    )?;
    let sizes = font.measure(OVERALL, 12.0);
    text(
        content,
        font,
        12.0,
        middle - sizes / 2.0,
        y + height - 76.0,
        OVERALL,
    )?;
    content.restore_state();
    Ok(())
}

/// Draws the fine figures: the distance each wall and each setback stands for,
/// in type too small to read until the plan is enlarged.
fn fine_figures(content: &mut Content, font: &FontHandle) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLOT;
    let (hx, hy, hw, hh) = house();
    let figures = [
        (x + width / 2.0, y + 5.0, PLOT_ALONG),
        (x + 14.0, y + height / 2.0, PLOT_ACROSS),
        (hx + hw / 2.0, hy + 5.0, HOUSE_ALONG),
        (hx + 14.0, hy + hh / 2.0, HOUSE_ACROSS),
        (f64::midpoint(x, hx), hy + hh / 2.0, SIDE_SETBACK),
        (hx + hw / 2.0, f64::midpoint(y, hy), FOOT_SETBACK),
    ];
    content.save_state();
    content.set_fill(Rgb::new(0.2, 0.45, 0.35))?;
    for (at, up, figure) in figures {
        text(
            content,
            font,
            4.5,
            at - font.measure(figure, 4.5) / 2.0,
            up,
            figure,
        )?;
    }
    content.restore_state();
    Ok(())
}

/// Draws the legend under the plan: what each layer holds and when it stands.
fn legend(
    content: &mut Content,
    font: &FontHandle,
    words: &'static Words,
) -> Result<(), hqf_pdf::Error> {
    let mut baseline = 300.0;
    for (name, what) in words.scaled.into_iter().zip(words.holdings) {
        text(content, font, 10.0, LEFT, baseline, name)?;
        content.save_state();
        content.set_fill(Rgb::gray(0.35))?;
        text(content, font, 10.0, LEFT + 110.0, baseline, what)?;
        content.restore_state();
        baseline -= 18.0;
    }

    let tongues: Vec<&str> = WORDS.iter().map(|(_, words)| words.tongue).collect();
    text(content, font, 10.0, LEFT, baseline, &tongues.join(" · "))?;
    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(content, font, 10.0, LEFT + 110.0, baseline, words.wording)?;
    for (rank, line) in words.seeing.into_iter().enumerate() {
        #[expect(
            clippy::cast_precision_loss,
            reason = "two lines are counted, and two is exact in an f64"
        )]
        let step = rank as f64 * 14.0;
        text(content, font, 10.0, LEFT, baseline - 32.0 - step, line)?;
    }
    content.restore_state();
    Ok(())
}

/// Draws `body` inside `layer`, so a reader shows and hides all of it at once.
fn on_layer<F>(content: &mut Content, layer: &LayerHandle, body: F) -> Result<(), hqf_pdf::Error>
where
    F: FnOnce(&mut Content) -> Result<(), hqf_pdf::Error>,
{
    content.begin_layer(layer);
    body(content)?;
    content.end_marked();
    Ok(())
}

/// The document the example writes, in `words`, drawn with the font at
/// `font_path`.
///
/// # Errors
///
/// Returns whatever reading the font, adding a layer or drawing hands back.
fn build(
    language: Language,
    words: &'static Words,
    font_path: &Path,
) -> Result<Document, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(font_path)?)?);

    let wide = doc.add_layer(Layer::new(words.scaled[0]).zoom(0.0, CROSSOVER))?;
    let fine = doc.add_layer(Layer::new(words.scaled[1]).zoom(CROSSOVER, f64::INFINITY))?;
    // One layer a language, built from the same table the page is written from.
    // The one the page itself is in is the one a reader falls back on when it
    // is set to a language no layer states.
    let mut spoken = Vec::with_capacity(WORDS.len());
    for (named, said) in WORDS {
        let layer = Layer::new(said.tongue);
        let layer = if named == language {
            layer.preferred_language(named.code())
        } else {
            layer.language(named.code())
        };
        spoken.push((doc.add_layer(layer)?, said));
    }

    let mut content = Content::new();
    text(&mut content, &font, 15.0, LEFT, 790.0, words.title)?;
    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(&mut content, &font, 10.0, LEFT, 770.0, words.intro)?;
    content.restore_state();

    ground(&mut content)?;
    on_layer(&mut content, &wide, |content| {
        wide_label(content, &font, words)
    })?;
    on_layer(&mut content, &fine, |content| fine_figures(content, &font))?;
    // Every language's sentence stands on a line of its own, so a reader that
    // states no language of its own reads them one under the other rather than
    // one over the other.
    for (rank, (layer, said)) in spoken.iter().enumerate() {
        #[expect(
            clippy::cast_precision_loss,
            reason = "the languages of the examples are counted on one hand"
        )]
        let step = rank as f64 * 15.0;
        on_layer(&mut content, layer, |content| {
            text(content, &font, 10.0, LEFT, 350.0 - step, said.caption)
        })?;
    }
    legend(&mut content, &font, words)?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;
    Ok(doc)
}

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("plot")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let doc = build(language, words, &font_path)?;
    let layers = SCALED_COUNT + WORDS.len();

    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, {layers} layers", bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::layout::TextFlow;
    use hqf_pdf::{Document, Font};

    use super::{LEFT, WORDS, Words, build, default_font, language};

    /// The room a line of the legend has: the page less the margin either side.
    const ROOM: f64 = 595.0 - 2.0 * LEFT;

    /// The test font, added to a document so that lines can be measured on it.
    fn handle() -> (Document, hqf_pdf::FontHandle) {
        let mut doc = Document::new();
        let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
            .expect("the committed font parses");
        let handle = doc.add_font(font);
        (doc, handle)
    }

    #[test]
    fn every_language_draws_the_page_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &[]);

        assert!(
            untranslated.is_empty(),
            "the plan says these in more than one language: {untranslated:?}"
        );
    }

    /// Every line the page sets on one line stays on one line: one that wrapped
    /// would run off the right edge, since nothing here is flowed.
    #[test]
    fn every_line_of_the_page_fits_the_page() {
        let (_doc, handle) = handle();
        let flow = TextFlow::new(&handle, 10.0);

        for (named, words) in WORDS {
            let Words {
                intro,
                caption,
                wording,
                seeing,
                ..
            } = words;
            let mut lines = vec![*intro, *caption, *wording];
            lines.extend(seeing);
            for line in lines {
                assert_eq!(
                    flow.break_lines(line, ROOM).len(),
                    1,
                    "the {} line {line:?} does not fit the page",
                    named.code()
                );
            }
        }
    }

    /// What the legend says a layer holds stands in the column beside the
    /// layer's name, and the two must not run into each other.
    #[test]
    fn every_holding_fits_the_column_it_stands_in() {
        let (_doc, handle) = handle();
        let flow = TextFlow::new(&handle, 10.0);
        let room = ROOM - 110.0;

        for (named, words) in WORDS {
            for holding in words.holdings {
                assert_eq!(
                    flow.break_lines(holding, room).len(),
                    1,
                    "the {} holding {holding:?} does not fit its column",
                    named.code()
                );
            }
        }
    }

    /// The point of the page: the two layers that watch the magnification meet
    /// without overlapping, and every language of the table has a layer of its
    /// own that the reader is told the language of.
    #[test]
    fn every_layer_states_when_it_shows_itself() {
        for (named, words) in WORDS {
            let mut doc = build(named, words, &default_font()).expect("the document builds");
            doc.set_compression(false);
            let pdf =
                String::from_utf8_lossy(&doc.to_bytes().expect("the document writes")).into_owned();

            assert!(pdf.contains("/max 2"), "the wide label gives way at two");
            assert!(pdf.contains("/min 2"), "the fine figures come in at two");
            for (spoken, _) in WORDS {
                assert!(
                    pdf.contains(&format!("({})", spoken.code())),
                    "no layer states {}",
                    spoken.code()
                );
            }
            assert_eq!(
                pdf.matches("/Preferred /ON").count(),
                1,
                "one language is fallen back on, and one only"
            );
            // A reader settles all of it by itself, so every one of the four
            // stands under the viewing event of the configuration.
            assert!(pdf.contains("/AS ["), "the configuration lists the events");
        }
    }
}