write_gradient.rs

Le fichier Rust de l'exemple « Dégradés en ligne droite, en cercle, et une couleur lue dans une fonction ». Cinq panneaux : un bandeau dont la couleur s'éteint, le même fondu posé en diagonale, une lueur prolongée au-delà de son cercle pour que les coins se remplissent, un dégradé qui passe par une troisième couleur, et un damier dont la couleur se calcule à partir de l'endroit où se tient chaque point, plus rouge vers la droite et plus vert vers le haut.

Rust 334 lignes

À quoi sert cet exemple

Un dégradé est le moyen le moins cher de donner à une page plate l'air d'avoir été dessinée par quelqu'un : un en-tête qui s'estompe, un bandeau qui prend un peu d'épaisseur, un panneau qui n'est pas juste un rectangle d'une seule couleur. C'est aussi ce qu'on imite le plus souvent avec une image, et l'imitation se voit dès qu'on imprime la page ou qu'on la regarde de près.

Ce que montre cet exemple

  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
//! Paints axial, radial and function-based gradients, each into a clipped box.
//!
//! Five panels: a horizontal two-colour gradient, a diagonal one, a radial one
//! whose outer colour is extended to fill the corners, a three-stop gradient
//! built from a stitched function, and a checkerboard whose colour is read from
//! a calculation of both coordinates of the point, the reader asked to filter
//! its sudden colour steps against aliasing. Each is added to the document
//! once, then painted into a rectangle the page clips to.
//!
//! The title and the five labels are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn.
//!
//! Usage: `cargo run --example write_gradient -- tmp/gradient.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_gradient -- tmp/degrade.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::shading::FunctionBased;
use hqf_pdf::{
    Axial, Calculation, DeviceSpace, Document, Exponential, ExtendEnds, Font, FontHandle, Op, Page,
    Radial, Rgb, Shading, ShadingHandle, Stitching,
};

#[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.
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 title across the top of the page.
    title: &'static str,
    /// The label under each of the five panels.
    horizontal: &'static str,
    diagonal: &'static str,
    radial: &'static str,
    three_stops: &'static str,
    checkerboard: &'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: "Gradients, and a colour read from a function",
    horizontal: "Axial, two colours",
    diagonal: "Axial, on the diagonal",
    radial: "Radial, outer extended",
    three_stops: "Axial, three stops",
    checkerboard: "Function-based: a checkerboard on x and y at once, anti-aliasing asked for",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Dégradés, et une couleur lue dans une fonction",
    horizontal: "En ligne droite, deux couleurs",
    diagonal: "En ligne droite, en diagonale",
    radial: "En cercle, couleur extérieure prolongée",
    three_stops: "En ligne droite, trois couleurs",
    checkerboard: "Par fonction : un damier en largeur et en hauteur à la fois, anticrénelage demandé",
};

/// 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 width and height of every panel, in points.
const BOX: (f64, f64) = (210.0, 170.0);

/// How many squares the checkerboard is cut into along each of its two axes.
const SQUARES: f64 = 8.0;

/// How much of the colour it lands on a darkened square of the checkerboard
/// keeps.
const SHADED: f64 = 0.45;

/// Paints a gradient into the box at `(x, y)`, sized [`BOX`], and writes a
/// label under it.
fn panel(
    content: &mut Content,
    font: &FontHandle,
    shading: &ShadingHandle,
    x: f64,
    y: f64,
    label: &str,
) -> Result<(), hqf_pdf::Error> {
    content.save_state();
    content.rect(x, y, BOX.0, BOX.1)?.clip().end_path();
    content.draw_shading(shading);
    content.restore_state();

    content.begin_text();
    content.set_font(font, 10.0)?;
    content.text_origin(x, y - 15.0)?;
    content.show_glyphs(&font.glyphs(label));
    content.end_text();
    Ok(())
}

/// The gradient that paints a checkerboard into the box at `(x, y)`, sized
/// [`BOX`], its colour read from a calculation of both coordinates of the point
/// at once: red grows across the box, green grows up it, and every other square
/// of the [`SQUARES`] by [`SQUARES`] board keeps only [`SHADED`] of the colour
/// it lands on. The reader is asked to filter the sudden steps between squares
/// against aliasing.
fn checkerboard(x: f64, y: f64) -> Result<Shading, hqf_pdf::Error> {
    Ok(Shading::from(
        FunctionBased::new(
            [[0.0, 1.0], [0.0, 1.0]],
            [BOX.0, 0.0, 0.0, BOX.1, x, y],
            DeviceSpace::Rgb,
            Calculation::new(
                [[0.0, 1.0], [0.0, 1.0]],
                [[0.0, 1.0]; 3],
                vec![
                    Op::Integer(2),
                    Op::Copy,
                    Op::Real(SQUARES),
                    Op::Multiply,
                    Op::Floor,
                    Op::Exchange,
                    Op::Real(SQUARES),
                    Op::Multiply,
                    Op::Floor,
                    Op::Add,
                    Op::ToInteger,
                    Op::Integer(2),
                    Op::Modulo,
                    Op::Integer(0),
                    Op::NotEqual,
                    Op::Integer(3),
                    Op::Integer(1),
                    Op::Roll,
                    Op::Real(0.2),
                    Op::Integer(4),
                    Op::Integer(3),
                    Op::Roll,
                    Op::If(vec![
                        Op::Real(SHADED),
                        Op::Multiply,
                        Op::Integer(3),
                        Op::Integer(1),
                        Op::Roll,
                        Op::Real(SHADED),
                        Op::Multiply,
                        Op::Integer(3),
                        Op::Integer(1),
                        Op::Roll,
                        Op::Real(SHADED),
                        Op::Multiply,
                        Op::Integer(3),
                        Op::Integer(1),
                        Op::Roll,
                    ]),
                ],
            ),
        )?
        .anti_alias(true),
    ))
}

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

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

    // Left column x, right column x, then the foot of each of the three rows.
    let (left, right, top, middle, bottom) = (70.0, 315.0, 560.0, 320.0, 100.0);

    // A horizontal two-colour gradient across the top-left box.
    let horizontal = doc.add_shading(&Shading::from(Axial::rgb(
        (left, top),
        (left + BOX.0, top),
        Rgb::new(0.85, 0.12, 0.12),
        Rgb::new(0.12, 0.2, 0.8),
    )))?;

    // A diagonal two-colour gradient across the top-right box.
    let diagonal = doc.add_shading(&Shading::from(Axial::rgb(
        (right, middle + BOX.1),
        (right + BOX.0, top + BOX.1),
        Rgb::new(0.95, 0.8, 0.1),
        Rgb::new(0.1, 0.55, 0.2),
    )))?;

    // A radial gradient in the middle-left box, its outer colour extended so it
    // reaches the corners.
    let radial = doc.add_shading(&Shading::from(
        Radial::rgb(
            (left + BOX.0 / 2.0, middle + BOX.1 / 2.0, 0.0),
            (left + BOX.0 / 2.0, middle + BOX.1 / 2.0, BOX.0 / 2.0),
            Rgb::new(1.0, 1.0, 1.0),
            Rgb::new(0.1, 0.15, 0.45),
        )
        .extend(ExtendEnds {
            before: false,
            after: true,
        }),
    ))?;

    // A three-stop gradient in the middle-right box, from a stitched function:
    // red to green over the first half, green to blue over the second.
    let rainbow_function = Stitching::new(
        [0.0, 1.0],
        vec![
            Exponential::new([0.0, 1.0], 1.0)
                .endpoints(vec![0.85, 0.12, 0.12], vec![0.12, 0.6, 0.2])
                .into(),
            Exponential::new([0.0, 1.0], 1.0)
                .endpoints(vec![0.12, 0.6, 0.2], vec![0.12, 0.2, 0.8])
                .into(),
        ],
        vec![0.5],
        vec![[0.0, 1.0], [0.0, 1.0]],
    );
    let rainbow = doc.add_shading(&Shading::from(Axial::new(
        (right, middle),
        (right + BOX.0, middle),
        DeviceSpace::Rgb,
        rainbow_function,
    )?))?;

    // A checkerboard across the bottom-left box.
    let board = doc.add_shading(&checkerboard(left, bottom)?)?;

    let mut content = Content::new();

    content.begin_text();
    content.set_font(&handle, 18.0)?;
    content.text_origin(left, 770.0)?;
    content.show_glyphs(&handle.glyphs(words.title));
    content.end_text();

    panel(
        &mut content,
        &handle,
        &horizontal,
        left,
        top,
        words.horizontal,
    )?;
    panel(&mut content, &handle, &diagonal, right, top, words.diagonal)?;
    panel(&mut content, &handle, &radial, left, middle, words.radial)?;
    panel(
        &mut content,
        &handle,
        &rainbow,
        right,
        middle,
        words.three_stops,
    )?;
    panel(
        &mut content,
        &handle,
        &board,
        left,
        bottom,
        words.checkerboard,
    )?;

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

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

    /// The lines two languages are allowed to write the same way. There are
    /// none: every word is a word of the language it is written in.
    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:?}"
        );
    }
}