Couper un mot trop long

Un mot trop large pour sa colonne : laissé entier, ou coupé au bord.

Rust write_flow_break.rs 183 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
//! Sets one paragraph in a column too narrow for a word in it, twice: above as
//! it comes, below cut to the column.
//!
//! The paragraph and the two headings are held in `Words`, once per language,
//! and `HQF_PDF_LANG` picks which set is drawn. Each heading opens with the
//! name the library gives its setting, which is the same in every language.
//!
//! Usage: `cargo run --example write_flow_break -- tmp/flow_break.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_flow_break --
//! tmp/coupure.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::Overlong;
use hqf_pdf::{Document, Font, Page, 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 payment reference the paragraph carries: one word to a line breaker,
/// longer than the column it is put in, and the same in every language.
const REFERENCE: &str = "GB29NWBK60161331926819-2026-07-DEPOSIT";

/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: the payment reference reads the same
/// wherever the page is read, and each heading opens with the name the library
/// gives the setting it stands over.
#[derive(Debug)]
struct Words {
    /// The heading over the setting that leaves the long word whole.
    overflow: &'static str,
    /// The heading over the setting that cuts it.
    breaking: &'static str,
    /// The paragraph, cut where the reference goes into it.
    paragraph_before: &'static str,
    paragraph_after: &'static str,
}

impl Words {
    /// The words the page is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }

    /// The paragraph both settings are given, with the reference in it.
    fn paragraph(&self) -> String {
        format!(
            "{}{REFERENCE}{}",
            self.paragraph_before, self.paragraph_after
        )
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    overflow: "Overflow: the word is left whole, and runs past the edge.",
    breaking: "Break: the word is cut after its last glyph that fits.",
    paragraph_before: "Paid by bank transfer, reference ",
    paragraph_after: ", to be matched against the purchase order before the accounts are closed.",
};

/// The page in French.
const FRENCH: Words = Words {
    overflow: "Overflow : le mot reste entier et déborde du bord.",
    breaking: "Break : le mot est coupé après son dernier glyphe qui tient.",
    paragraph_before: "Réglé par virement, référence ",
    paragraph_after: ", à rapprocher du bon de commande avant la clôture des comptes.",
};

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

const COLUMN: f64 = 150.0;

/// The left edge of both columns. They are stacked rather than set side by
/// side, so that the overflowing line runs out into the margin and not through
/// the text of the other setting.
const X: f64 = 80.0;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);
    let paragraph = words.paragraph();

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

    let mut c = Content::new();

    for (top, label, overlong) in [
        (760.0, words.overflow, Overlong::Overflow),
        (620.0, words.breaking, Overlong::Break),
    ] {
        let heading = TextFlow::new(&handle, 8.0);
        let heading_lines = heading.break_lines(label, 400.0);
        c.begin_text();
        heading.draw(&mut c, &heading_lines, X, top, 400.0)?;
        c.end_text();

        let text_top = top - 20.0;
        let flow = TextFlow::new(&handle, 11.0)
            .leading(15.0)
            .overlong(overlong);
        let lines = flow.break_lines(&paragraph, COLUMN);
        c.begin_text();
        flow.draw(&mut c, &lines, X, text_top, COLUMN)?;
        c.end_text();

        // The column's edge, to show what each setting does about it.
        let height = flow.height(&lines);
        c.save_state();
        c.set_stroke_rgb(0.8, 0.8, 0.8)?
            .set_line_width(0.5)?
            .rect(X, text_top - height, COLUMN, height)?
            .stroke();
        c.restore_state();
    }

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

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

    /// The lines two languages are allowed to write the same way. There are
    /// none: the reference the paragraph carries is held outside the 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:?}"
        );
    }
}