Transparence et modes de fusion

Des aplats à moitié transparents qui se chevauchent et se mélangent, et un carré orange posé sur une barre bleue de quatre façons différentes de mélanger les couleurs.

Rust write_transparency.rs 194 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
//! Shows two things an extended graphics state opens: half-opacity fills that
//! overlap and mix, and one colour laid over another in four blend modes.
//!
//! The opacity panel draws three rectangles, each at half opacity, so the
//! colours show through one another where they overlap. The blend panel lays
//! the same orange square over a blue bar four times, once in each of four
//! modes, so the mode each square is painted in can be read from the colour it
//! leaves.
//!
//! The two headings are held in `Words`, once per language, and `HQF_PDF_LANG`
//! picks which set is drawn. Each square is labelled with the name the file
//! writes for its blend mode, which is the same in every language.
//!
//! Usage: `cargo run --example write_transparency -- tmp/transparency.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_transparency --
//! tmp/transparence.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{BlendMode, Document, ExtGState, Font, GStateHandle, Page, Rgb, TextFlow};

#[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 left edge the panels line up on.
const X: f64 = 80.0;

/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: each square is labelled with the name
/// the file writes for its blend mode.
#[derive(Debug)]
struct Words {
    /// The heading above the opacity panel.
    opacity: &'static str,
    /// The heading above the blend panel.
    blends: &'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 {
    opacity: "Half-opacity fills overlap and mix.",
    blends: "One orange square over a blue bar, in four blend modes.",
};

/// The page in French.
const FRENCH: Words = Words {
    opacity: "Des aplats à moitié transparents se chevauchent et se mélangent.",
    blends: "Un carré orange sur une barre bleue, dans quatre modes de fusion.",
};

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

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("transparency")));
    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);

    // The states the two panels apply, added once and shared.
    let half = doc.add_ext_gstate(ExtGState::new().fill_alpha(0.5));
    let modes = [
        ("Normal", BlendMode::Normal),
        ("Multiply", BlendMode::Multiply),
        ("Screen", BlendMode::Screen),
        ("Difference", BlendMode::Difference),
    ];
    let blends: Vec<(&str, GStateHandle)> = modes
        .into_iter()
        .map(|(label, mode)| (label, doc.add_ext_gstate(ExtGState::new().blend_mode(mode))))
        .collect();

    let mut c = Content::new();

    // The opacity panel: three overlapping rectangles, each at half opacity.
    heading(&mut c, &handle, 720.0, words.opacity, X)?;
    let colors = [
        (0.0, Rgb::new(0.85, 0.15, 0.15)),
        (30.0, Rgb::new(0.15, 0.65, 0.20)),
        (60.0, Rgb::new(0.15, 0.30, 0.85)),
    ];
    for (offset, color) in colors {
        c.save_state().set_ext_gstate(&half).set_fill(color)?;
        c.rect(X + offset, 590.0, 90.0, 90.0)?.fill();
        c.restore_state();
    }

    // The blend panel: an orange square over a blue bar, once per mode.
    heading(&mut c, &handle, 520.0, words.blends, X)?;
    let square = 80.0;
    let gap = 20.0;
    let mut left = X;
    for (label, state) in &blends {
        c.set_fill(Rgb::new(0.15, 0.35, 0.80))?
            .rect(left, 380.0, square, square)?
            .fill();
        c.save_state()
            .set_ext_gstate(state)
            .set_fill(Rgb::new(0.95, 0.55, 0.10))?;
        c.rect(left + 20.0, 360.0, square, square)?.fill();
        c.restore_state();
        heading(&mut c, &handle, 350.0, label, left)?;
        left += square + gap;
    }

    let mut page = Page::a4();
    page.content = c.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(())
}

/// Sets a one-line label with its baseline at `top`, left edge at `left`.
fn heading(
    c: &mut Content,
    handle: &hqf_pdf::FontHandle,
    top: f64,
    label: &str,
    left: f64,
) -> Result<(), Box<dyn std::error::Error>> {
    let flow = TextFlow::new(handle, 8.0);
    let lines = flow.break_lines(label, 400.0);
    c.begin_text();
    flow.draw(c, &lines, left, top, 400.0)?;
    c.end_text();
    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:?}"
        );
    }
}