write_fitted.rs

Die Rust-Datei des Beispiels „Ein in ein Rechteck eingepasstes Bild“. Ein Bild, auf acht Arten in ein Rechteck einer Größe eingepasst: drei Arten, es zu bemessen, dasselbe in die linke obere Ecke gestellt mit einem Einzug von 12 Punkt, eine Vierteldrehung nach links, eine Vierteldrehung nach rechts, eine Drehung um 20 Grad und eine Spiegelung von links nach rechts — jedes Feld zeichnet das Bild an der Stelle und in der Größe, die die Bibliothek berechnet hat. Eine zweite Seite fügt acht weitere hinzu: das Bild in seiner eigenen Größe, dann doppelt so groß und dort abgeschnitten, wo es übersteht; nur verkleinert, wenn es zu groß ist; an neun Positionen zugleich gesetzt; ein Viertel nach innen und nach unten platziert; um eine halbe Drehung gedreht; und von oben nach unten gespiegelt.

Rust 557 Zeilen

Wofür dieses Beispiel da ist

Ein Bild von außen hat selten die Proportionen des Rechtecks, in das es muss. Auf das Rechteck gestreckt, verliert es seine Proportionen; in seiner eigenen Größe belassen, lässt es leeren Raum um sich oder läuft über den Rand. Diese Entscheidung stellt sich bei jedem Katalog und jedem Bericht neu, den Sie erzeugen.

Was dieses Beispiel zeigt

  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
//! Fits one picture into boxes of one size eight ways, and labels each.
//!
//! A [`FitBox`] says how a picture is sized to a box, where it sits in it, how
//! far the box is inset first, and how far the picture is turned and mirrored
//! on its way in. Every panel here hands the same picture and the same box to a
//! different policy, and draws what comes back the same way: concatenate the
//! matrix the policy gives, then draw the picture at the origin at its natural
//! size. No panel computes the scale or the offset of its picture itself.
//!
//! The panel that covers its box is the one case that overflows on purpose, so
//! it is clipped to the box it covers; every other panel stays inside.
//!
//! A second page lays out eight more: the picture at its natural size, then
//! twice as large and clipped; shrunk to fit when it is twice as large, and
//! left as it is when it is half as large; a quarter as large at each of the
//! nine named anchors; half as large at a point a quarter in from the left and
//! a quarter down, upright and unmirrored; turned upside down; and mirrored top
//! to bottom. Those panels hand the policy the picture's size multiplied by the
//! panel's scale, and draw the picture at that size.
//!
//! The title and the eight captions are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The first four captions open with
//! the name the library gives the policy they describe — `contain`, `cover`,
//! `stretch` — which is the same in every language.
//!
//! Usage: `cargo run --example write_fitted -- tmp/fitted.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_fitted -- tmp/ajuste.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    Anchor, Document, FitBox, FitMode, Font, FontHandle, Image, ImageHandle, Mirror, Page, Rect,
    Rgb, Turn,
};

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

/// The picture every panel fits: the JPEG committed for the tests.
fn default_image() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("images")
        .join("photo.jpg")
}

const PAGE_WIDTH: f64 = 595.276;
const MARGIN: f64 = 56.0;
/// The gap between the two columns of panels.
const GAP: f64 = 24.0;
/// The box every panel fits its picture into.
const BOX_WIDTH: f64 = (PAGE_WIDTH - 2.0 * MARGIN - GAP) / 2.0;
const BOX_HEIGHT: f64 = 130.0;
/// The top of the first row of boxes, and the drop from one row to the next.
const FIRST_ROW: f64 = 750.0;
const ROW_PITCH: f64 = 176.0;
/// How far under a box its caption's baseline sits.
const CAPTION_DROP: f64 = 14.0;

/// How many policies the page lays out.
const PANEL_COUNT: usize = 8;

/// The words the page is written in, one set per language.
///
/// The first four captions open with the name the library gives the policy they
/// describe — `contain`, `cover`, `stretch` — and those names are the same in
/// every language.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// What is written under each box, in the order `panels` lays them out.
    captions: [&'static str; PANEL_COUNT],
    /// The line at the head of the second page.
    more_title: &'static str,
    /// What is written under each box of the second page, in the order
    /// `more_panels` lays them out.
    more_captions: [&'static str; PANEL_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: "One picture, one box, eight fitting policies",
    captions: [
        "contain: as large as fits, its shape kept",
        "cover: no gap left, the overflow clipped",
        "stretch: the box filled, its shape lost",
        "contain, top left, inset 12 points",
        "a quarter turn anticlockwise",
        "a quarter turn clockwise",
        "turned 20 degrees, still inside its box",
        "mirrored left to right",
    ],
    more_title: "The same picture, sized and placed other ways",
    more_captions: [
        "natural: its own size, whatever the box",
        "natural, twice as large, what hangs over clipped",
        "shrink to fit, twice as large: made smaller",
        "shrink to fit, half as large: left, mirrored both ways",
        "natural, a quarter as large, at the nine anchors",
        "a quarter in from the left and a quarter down",
        "a half turn",
        "mirrored top to bottom",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Une image, une boîte, huit façons de l’ajuster",
    captions: [
        "contain : aussi grande que possible, proportions gardées",
        "cover : aucun vide laissé, le débordement rogné",
        "stretch : la boîte remplie, les proportions perdues",
        "contain, en haut à gauche, 12 points de retrait",
        "un quart de tour, sens antihoraire",
        "un quart de tour, sens horaire",
        "tournée de 20 degrés, toujours dans sa boîte",
        "inversée de gauche à droite",
    ],
    more_title: "La même image, dimensionnée et placée autrement",
    more_captions: [
        "natural : à sa propre taille, quelle que soit la boîte",
        "natural, deux fois plus grande, le débordement rogné",
        "shrink to fit, deux fois plus grande : réduite",
        "shrink to fit, demi-taille : à gauche, double miroir",
        "natural, quatre fois moins grande, aux neuf ancres",
        "à un quart du bord gauche et à un quart du haut",
        "un demi-tour",
        "en miroir de haut en bas",
    ],
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Eén afbeelding, één kader, acht manieren van passen",
    captions: [
        "contain: zo groot als past, vorm behouden",
        "cover: geen gat, het overschot afgesneden",
        "stretch: het kader gevuld, de vorm kwijt",
        "contain, linksboven, 12 punten ingesprongen",
        "een kwartslag tegen de klok in",
        "een kwartslag met de klok mee",
        "20 graden gedraaid, nog binnen het kader",
        "links-rechts gespiegeld",
    ],
    more_title: "Dezelfde afbeelding, op andere manieren bemeten en geplaatst",
    more_captions: [
        "natural: eigen grootte, wat het kader ook is",
        "natural, twee keer zo groot, het uitstekende afgesneden",
        "verkleinen om te passen, twee keer zo groot: kleiner gemaakt",
        "verkleinen om te passen, half zo groot: links, in beide richtingen gespiegeld",
        "natural, een kwart zo groot, op de negen ankers",
        "een kwart vanaf links en een kwart naar beneden",
        "een halve slag",
        "boven-onder gespiegeld",
    ],
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Uma imagem, uma caixa, oito formas de a encaixar",
    captions: [
        "contain: o maior que cabe, com a sua forma",
        "cover: sem vazios, o excesso recortado",
        "stretch: a caixa cheia, a forma perdida",
        "contain, em cima à esquerda, margem de 12 pontos",
        "um quarto de volta para a esquerda",
        "um quarto de volta para a direita",
        "rodada 20 graus, ainda dentro da caixa",
        "espelhada da esquerda para a direita",
    ],
    more_title: "A mesma imagem, dimensionada e colocada de outras formas",
    more_captions: [
        "natural: o seu tamanho, seja qual for a caixa",
        "natural, o dobro, o que sobra recortado",
        "reduzir para caber, o dobro: fica mais pequena",
        "reduzir para caber, metade: à esquerda, espelhada nos dois sentidos",
        "natural, um quarto do tamanho, nas nove âncoras",
        "a um quarto da esquerda e um quarto para baixo",
        "meia volta",
        "espelhada de cima para baixo",
    ],
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Un’immagine, un riquadro, otto modi di adattarla",
    captions: [
        "contain: la più grande che ci sta, forma conservata",
        "cover: nessun vuoto, l’eccesso ritagliato",
        "stretch: il riquadro pieno, la forma persa",
        "contain, in alto a sinistra, margine di 12 punti",
        "un quarto di giro in senso antiorario",
        "un quarto di giro in senso orario",
        "ruotata di 20 gradi, ancora nel suo riquadro",
        "specchiata da sinistra a destra",
    ],
    more_title: "La stessa immagine, dimensionata e collocata in altri modi",
    more_captions: [
        "natural: la sua dimensione, qualunque sia il riquadro",
        "natural, il doppio, la parte sporgente ritagliata",
        "riduci per adattare, il doppio: rimpicciolita",
        "riduci per adattare, la metà: a sinistra, specchiata nei due sensi",
        "natural, un quarto della dimensione, sui nove ancoraggi",
        "a un quarto da sinistra e un quarto in basso",
        "mezzo giro",
        "specchiata dall’alto in basso",
    ],
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Una imagen, una caja, ocho formas de encajarla",
    captions: [
        "contain: lo más grande que cabe, con su forma",
        "cover: sin huecos, lo que sobra recortado",
        "stretch: la caja llena, la forma perdida",
        "contain, arriba a la izquierda, margen de 12 puntos",
        "un cuarto de vuelta a la izquierda",
        "un cuarto de vuelta a la derecha",
        "girada 20 grados, aún dentro de su caja",
        "reflejada de izquierda a derecha",
    ],
    more_title: "La misma imagen, dimensionada y colocada de otras formas",
    more_captions: [
        "natural: su propio tamaño, sea cual sea la caja",
        "natural, el doble, lo que sobresale recortado",
        "reducir para caber, el doble: se hace más pequeña",
        "reducir para caber, la mitad: a la izquierda, reflejada en ambos sentidos",
        "natural, un cuarto del tamaño, en los nueve anclajes",
        "a un cuarto desde la izquierda y un cuarto hacia abajo",
        "media vuelta",
        "reflejada de arriba abajo",
    ],
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Ein Bild, ein Rahmen, acht Arten der Einpassung",
    captions: [
        "contain: so groß, wie es passt, die Form bleibt",
        "cover: keine Lücke, der Überstand abgeschnitten",
        "stretch: Rahmen gefüllt, die Form verloren",
        "contain, oben links, 12 Punkt eingerückt",
        "eine Vierteldrehung gegen den Uhrzeigersinn",
        "eine Vierteldrehung im Uhrzeigersinn",
        "um 20 Grad gedreht, noch im Rahmen",
        "von links nach rechts gespiegelt",
    ],
    more_title: "Dasselbe Bild, anders bemessen und platziert",
    more_captions: [
        "natural: eigene Größe, unabhängig vom Rahmen",
        "natural, doppelt so groß, Überstand abgeschnitten",
        "shrink to fit, doppelt so groß: verkleinert",
        "shrink to fit, halb so groß: links, doppelt gespiegelt",
        "natural, ein Viertel so groß, an den neun Ankern",
        "ein Viertel von links und ein Viertel von oben",
        "eine halbe Drehung",
        "von oben nach unten gespiegelt",
    ],
};

/// 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),
];

/// One panel: what it says it does, the policies it draws the picture by, once
/// each, whether what it draws has to be held to the box, and what the
/// picture's size is multiplied by before it is fitted.
struct Panel {
    caption: &'static str,
    fitted: Vec<FitBox>,
    clipped: bool,
    scale: f64,
}

/// The eight policies, in the order they are laid out: the three sizing modes
/// and one of them anchored and inset first, then the three turns and the
/// mirror, each under the caption `words` gives it.
fn panels(words: &'static Words) -> Vec<Panel> {
    let fitted = [
        (FitBox::new(FitMode::Contain), false),
        (FitBox::new(FitMode::Cover), true),
        (FitBox::new(FitMode::Stretch), false),
        (
            FitBox::new(FitMode::Contain)
                .anchor(Anchor::TOP_LEFT)
                .margin(12.0),
            false,
        ),
        (FitBox::new(FitMode::Contain).turn(Turn::Left), false),
        (FitBox::new(FitMode::Contain).turn(Turn::Right), false),
        (
            FitBox::new(FitMode::Contain).turn(Turn::Angle(20.0_f64.to_radians())),
            false,
        ),
        (
            FitBox::new(FitMode::Contain).mirror(Mirror::LeftToRight),
            false,
        ),
    ];

    fitted
        .into_iter()
        .zip(words.captions)
        .map(|((fitted, clipped), caption)| Panel {
            caption,
            fitted: vec![fitted],
            clipped,
            scale: 1.0,
        })
        .collect()
}

/// The nine named anchors, bottom row first, each left to right.
const ANCHORS: [Anchor; 9] = [
    Anchor::BOTTOM_LEFT,
    Anchor::BOTTOM,
    Anchor::BOTTOM_RIGHT,
    Anchor::LEFT,
    Anchor::CENTER,
    Anchor::RIGHT,
    Anchor::TOP_LEFT,
    Anchor::TOP,
    Anchor::TOP_RIGHT,
];

/// The second page's eight policies, in the order they are laid out: the
/// natural size, then twice as large and clipped; shrinking to fit twice and
/// half as large; the nine anchors; a point between them, upright and not
/// mirrored; the half turn and the mirror top to bottom.
fn more_panels(words: &'static Words) -> Vec<Panel> {
    let natural = FitBox::new(FitMode::Natural);
    let fitted = [
        (vec![natural], false, 1.0),
        (vec![natural], true, 2.0),
        (vec![FitBox::new(FitMode::ShrinkToFit)], false, 2.0),
        (
            vec![FitBox::new(FitMode::ShrinkToFit).mirror(Mirror::Both)],
            false,
            0.5,
        ),
        (
            ANCHORS
                .iter()
                .map(|anchor| natural.anchor(*anchor))
                .collect(),
            false,
            0.25,
        ),
        (
            vec![
                natural
                    .anchor(Anchor::fraction(0.25, 0.75))
                    .turn(Turn::Upright)
                    .mirror(Mirror::Neither),
            ],
            false,
            0.5,
        ),
        (
            vec![FitBox::new(FitMode::Contain).turn(Turn::UpsideDown)],
            false,
            1.0,
        ),
        (
            vec![FitBox::new(FitMode::Contain).mirror(Mirror::TopToBottom)],
            false,
            1.0,
        ),
    ];

    fitted
        .into_iter()
        .zip(words.more_captions)
        .map(|((fitted, clipped, scale), caption)| Panel {
            caption,
            fitted,
            clipped,
            scale,
        })
        .collect()
}

/// The box the panel at `index` fits into: two to a row, filled left to right.
fn panel_box(index: u32) -> Rect {
    let x = f64::from(index % 2).mul_add(BOX_WIDTH + GAP, MARGIN);
    let top = f64::from(index / 2).mul_add(-ROW_PITCH, FIRST_ROW);
    Rect::new(x, top - BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT)
}

/// Draws one line of text with its left edge at `x` and its baseline at `y`.
fn line(
    content: &mut Content,
    font: &FontHandle,
    text: &str,
    size: f64,
    x: f64,
    y: f64,
) -> Result<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(text));
    content.end_text();
    Ok(())
}

/// Draws one panel: its box's outline, the picture fitted into it, and its
/// caption underneath.
fn draw_panel(
    content: &mut Content,
    font: &FontHandle,
    image: &ImageHandle,
    panel: &Panel,
    box_: Rect,
) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = (box_.x(), box_.y(), box_.width(), box_.height());

    content.save_state();
    content.set_stroke(Rgb::gray(0.75))?;
    content.set_line_width(0.5)?;
    content.rect(x, y, width, height)?;
    content.stroke();
    content.restore_state();

    let natural = image.size();
    let size = (natural.0 * panel.scale, natural.1 * panel.scale);
    content.save_state();
    if panel.clipped {
        content.rect(x, y, width, height)?;
        content.clip();
        content.end_path();
    }
    for fitted in &panel.fitted {
        content.save_state();
        content.transform(fitted.matrix(size, box_))?;
        content.draw_image(image, 0.0, 0.0, size.0, size.1)?;
        content.restore_state();
    }
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    line(content, font, panel.caption, 8.5, x, y - CAPTION_DROP)?;
    content.restore_state();
    Ok(())
}

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

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let image = doc.add_image(Image::parse(fs::read(&image_path)?)?);

    let panels = panels(words);
    let more = more_panels(words);
    for (title, laid) in [(words.title, &panels), (words.more_title, &more)] {
        let mut content = Content::new();
        line(&mut content, &font, title, 16.0, MARGIN, 790.0)?;
        for (index, panel) in laid.iter().enumerate() {
            let box_ = panel_box(u32::try_from(index)?);
            draw_panel(&mut content, &font, &image, panel, box_)?;
        }

        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, {} panels of one {}x{} picture",
        bytes.len(),
        panels.len() + more.len(),
        image.width(),
        image.height()
    );
    Ok(())
}

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

    /// The lines two languages are allowed to write the same way. There are
    /// none: a caption names its policy and then says what it does in 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:?}"
        );
    }
}