Content shown and hidden by layer

One floor plan on four layers a reader shows and hides: the furniture and the dimensions shown, the notes hidden until asked for, and a draft mark that is looked at but never printed.

Rust write_layers.rs 374 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
//! Draws one plan on four layers a reader can show and hide.
//!
//! The walls are the page's own ink and are always there. Everything else
//! belongs to a layer: the furniture and the dimensions start shown, the notes
//! start hidden, and the draft mark is looked at but never printed. Open the
//! file and the reader's layers panel lists all four; print it and the draft
//! mark is gone without anyone touching that panel.
//!
//! The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. A layer's name is language too: the reader's panel shows
//! it, and the legend under the plan names the same field, so the panel and the
//! page can never disagree.
//!
//! Usage: `cargo run --example write_layers -- tmp/layers.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_layers -- tmp/calques.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{Slant, Stamp};
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;

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 plan's outer wall: where it sits on the page and how big it is.
const PLAN: (f64, f64, f64, f64) = (80.0, 380.0, 435.0, 320.0);

/// How many layers the plan is drawn on.
const LAYER_COUNT: usize = 4;

/// How many notes the hidden layer holds.
const NOTE_COUNT: usize = 3;

/// The two distances the plan is measured at. Neither is language.
const ALONG: &str = "7.25 m";
const ACROSS: &str = "5.00 m";

/// The words the page is written in, one set per language.
///
/// A layer's name is here: the reader's panel shows it, and so does the legend.
/// The two distances are not: a metre is a metre.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// What stands under it, saying what a layer is.
    intro: &'static str,
    /// What each layer is called, in the order they are added. The reader's
    /// panel lists these, and the legend names them again.
    layers: [&'static str; LAYER_COUNT],
    /// What the legend says each layer holds and how it starts.
    holdings: [&'static str; LAYER_COUNT],
    /// The notes the hidden layer holds, in the order they are placed.
    notes: [&'static str; NOTE_COUNT],
    /// The word the draft mark is stamped in.
    draft: &'static str,
    /// The two lines under the legend, saying that the draft mark takes itself
    /// off the printed page.
    printing: [&'static str; 2],
}

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 plan, four layers",
    intro: "The walls are always there. Everything else is a layer the reader can show and hide.",
    layers: ["Furniture", "Dimensions", "Notes", "Draft"],
    holdings: [
        "shown; turn it off and the rooms stand empty",
        "shown; the distances around the plan",
        "hidden; turn it on to read them",
        "shown on screen, never printed",
    ],
    notes: [
        "Table seats six.",
        "Bed against the party wall.",
        "Counter, waste under.",
    ],
    draft: "DRAFT",
    printing: [
        "The draft mark carries its own answer for the printer, so nothing has to",
        "be switched off before the page is printed.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Un plan, quatre calques",
    intro: "Les murs sont toujours là. Tout le reste est un calque à afficher ou masquer.",
    layers: ["Mobilier", "Cotes", "Notes", "Brouillon"],
    holdings: [
        "affiché ; désactivez-le et les pièces sont vides",
        "affiché ; les distances autour du plan",
        "masqué ; activez-le pour les lire",
        "affiché à l'écran, jamais imprimé",
    ],
    notes: [
        "Table pour six personnes.",
        "Lit contre le mur mitoyen.",
        "Plan de travail, poubelle dessous.",
    ],
    draft: "BROUILLON",
    printing: [
        "La mention de brouillon porte sa propre consigne pour l'imprimante :",
        "rien n'a besoin d'être masqué avant d'imprimer la page.",
    ],
};

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

/// Draws the walls: the outer room and the partition that splits it.
fn walls(content: &mut Content) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLAN;
    content.save_state();
    content.set_stroke(Rgb::gray(0.15))?;
    content.set_line_width(3.0)?;
    content.rect(x, y, width, height)?.stroke();
    content
        .move_to(x + 265.0, y)?
        .line_to(x + 265.0, y + 190.0)?;
    content.stroke();
    content.restore_state();
    Ok(())
}

/// Draws the furniture: a table, a bed and a counter, each a filled outline.
fn furniture(content: &mut Content) -> Result<(), hqf_pdf::Error> {
    let (x, y, _, height) = PLAN;
    let pieces = [
        (x + 40.0, y + height - 110.0, 120.0, 70.0),
        (x + 300.0, y + height - 130.0, 90.0, 110.0),
        (x + 290.0, y + 30.0, 110.0, 40.0),
    ];
    content.save_state();
    content.set_fill(Rgb::new(0.85, 0.88, 0.93))?;
    content.set_stroke(Rgb::new(0.35, 0.45, 0.6))?;
    content.set_line_width(1.0)?;
    for (px, py, pw, ph) in pieces {
        content.rect(px, py, pw, ph)?.fill();
        content.rect(px, py, pw, ph)?.stroke();
    }
    content.restore_state();
    Ok(())
}

/// Draws the dimensions: a line under the plan and one beside it, each with the
/// distance it stands for.
fn dimensions(content: &mut Content, font: &FontHandle) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLAN;
    let below = y - 26.0;
    let beside = x - 46.0;

    content.save_state();
    content.set_stroke(Rgb::new(0.2, 0.5, 0.35))?;
    content.set_fill(Rgb::new(0.2, 0.5, 0.35))?;
    content.set_line_width(0.8)?;

    content.move_to(x, below)?.line_to(x + width, below)?;
    content.move_to(x, below - 5.0)?.line_to(x, below + 5.0)?;
    content
        .move_to(x + width, below - 5.0)?
        .line_to(x + width, below + 5.0)?;
    content.move_to(beside, y)?.line_to(beside, y + height)?;
    content.move_to(beside - 5.0, y)?.line_to(beside + 5.0, y)?;
    content
        .move_to(beside - 5.0, y + height)?
        .line_to(beside + 5.0, y + height)?;
    content.stroke();

    text(
        content,
        font,
        9.0,
        x + width / 2.0 - 18.0,
        below + 8.0,
        ALONG,
    )?;
    text(content, font, 9.0, beside + 6.0, y + height / 2.0, ACROSS)?;
    content.restore_state();
    Ok(())
}

/// Draws the notes: what someone reading the plan wants said, and a reader who
/// is only looking at the rooms does not.
fn notes(
    content: &mut Content,
    font: &FontHandle,
    words: &'static Words,
) -> Result<(), hqf_pdf::Error> {
    let (x, y, _, height) = PLAN;
    let places = [
        (x + 44.0, y + height - 130.0),
        (x + 292.0, y + height - 148.0),
        (x + 292.0, y + 16.0),
    ];
    content.save_state();
    content.set_fill(Rgb::new(0.7, 0.25, 0.1))?;
    for ((nx, ny), line) in places.into_iter().zip(words.notes) {
        text(content, font, 8.0, nx, ny, line)?;
    }
    content.restore_state();
    Ok(())
}

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

    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(
        content,
        font,
        10.0,
        80.0,
        baseline - 12.0,
        words.printing[0],
    )?;
    text(
        content,
        font,
        10.0,
        80.0,
        baseline - 26.0,
        words.printing[1],
    )?;
    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(())
}

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("layers")));
    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 furniture_layer = doc.add_layer(Layer::new(words.layers[0]))?;
    let dimensions_layer = doc.add_layer(Layer::new(words.layers[1]))?;
    let notes_layer = doc.add_layer(Layer::new(words.layers[2]).visible(false))?;
    let draft_layer = doc.add_layer(Layer::new(words.layers[3]).on_screen(true).printed(false))?;

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

    walls(&mut content)?;
    on_layer(&mut content, &furniture_layer, furniture)?;
    on_layer(&mut content, &dimensions_layer, |content| {
        dimensions(content, &font)
    })?;
    on_layer(&mut content, &notes_layer, |content| {
        notes(content, &font, words)
    })?;
    on_layer(&mut content, &draft_layer, |content| {
        let (x, y, width, height) = PLAN;
        Stamp::new(&font, words.draft)
            .slant(Slant::Up)
            .color(Rgb::new(0.8, 0.3, 0.3))
            .draw(content, x, y, width, height)
    })?;
    legend(&mut content, &font, words)?;

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

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

    /// The lines two languages are allowed to write the same way. A note is a
    /// note in English and in French.
    const SPARED: [&str; 1] = ["\"Notes\""];

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

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