Une image ajustée dans une boîte

Une même image logée de huit façons dans une boîte d'une seule taille : mise à quatre tailles différentes, calée contre un bord, tournée d'un quart de tour puis d'un angle quelconque, et retournée en miroir — chaque panneau dessiné à partir du placement que la règle a calculé.

Rust write_fitted.rs 297 lignes
  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
//! 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. Nothing measures anything by hand.
//!
//! 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.
//!
//! The title and the eight captions are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. Each caption opens with the name
//! the library gives the policy it describes, 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, Rgb,
    Turn,
};

#[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: 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.
///
/// Each caption opens with the name the library gives its policy — `contain`,
/// `cover`, `stretch` — which is not 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],
}

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",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Une image, une boîte, huit façons de l'ajuster",
    captions: [
        "contain : la plus grande qui tient, sans déformer",
        "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 vers la gauche",
        "un quart de tour vers la droite",
        "tournée de 20 degrés, toujours dans sa boîte",
        "retournée de gauche à droite",
    ],
};

/// 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 panel: what it says it does, the policy that does it, and whether what
/// it draws has to be held to the box.
struct Panel {
    caption: &'static str,
    fitted: FitBox,
    clipped: bool,
}

/// The eight policies, in the order they are laid out: the five ways of sizing
/// first, then the 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,
            clipped,
        })
        .collect()
}

/// The box the panel at `index` fits into: two to a row, filled left to right.
fn panel_box(index: u32) -> (f64, f64, f64, f64) {
    let x = f64::from(index % 2).mul_add(BOX_WIDTH + GAP, MARGIN);
    let top = f64::from(index / 2).mul_add(-ROW_PITCH, FIRST_ROW);
    (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.name(), 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_: (f64, f64, f64, f64),
) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = box_;

    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 size = image.size();
    content.save_state();
    if panel.clipped {
        content.rect(x, y, width, height)?;
        content.clip();
        content.end_path();
    }
    content.transform(panel.fitted.matrix(size, box_))?;
    content.draw_image(image, 0.0, 0.0, size.0, size.1)?;
    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() -> 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 mut content = Content::new();
    line(&mut content, &font, words.title, 16.0, MARGIN, 790.0)?;

    let panels = panels(words);
    for (index, panel) in panels.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(),
        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:?}"
        );
    }
}