write_tagged_pictures.rs

Die Rust-Datei des Beispiels „Eine Liste, deren Bilder ebenfalls sprechen“. Eine Teileliste, deren erste Spalte ein Bild statt eines Wortes ist. Jedes Bild trägt den Satz, den jemand an seiner Stelle hört, sodass in der Liste nichts für einen Leser verloren geht, der sie nicht sehen kann. Auf der Seite sind die Bilder einfach Bilder.

Rust 558 Zeilen

Wofür dieses Beispiel da ist

Lesen Sie eine Teileliste am Telefon vor, und Sie sagen, was jedes Bild zeigt: den Deckel, das Typenschild, die kleine Temperaturanzeige. Eine Software, die ein Dokument vorliest, sagt gar nichts, denn ein Bild ist für sie nur ein Bild — und in einer Liste, in der das Bild die Spalte ist, die einen Artikel vom anderen unterscheidet, ist das keine verlorene Verzierung. Die ganze Zeile verstummt.

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
558
//! Writes a tagged parts list whose first column is a picture, not a word.
//!
//! A picture says nothing to something that reads a document aloud, so a tagged
//! file has to say it instead: each picture is marked as a figure of its own
//! and carries the words a reader hears in its place. That is what `Cell::alt`
//! is for, and this is what it comes to — a table whose every row is a row of
//! the structure tree, whose text cells are read as text, and whose picture
//! cells are read as the sentence the catalogue gave them.
//!
//! The tree is not built by hand here: the table hands back the branch
//! describing itself, figures and all, from the same counter the page numbers
//! its marks from. That is what keeps a number in the stream and a number in
//! the tree from drifting apart.
//!
//! Where [`write_tagged`](write_tagged) shows prose, headings and a table of
//! figures, this shows the one thing prose cannot: a picture inside a cell,
//! standing for something a reader must be told about.
//!
//! The list is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is written. The language a document is in is part of what makes it
//! readable aloud: the structure tree carries the tag of the language its words
//! are in, and it comes from the same set of words as the words themselves.
//!
//! Usage: `cargo run --example write_tagged_pictures -- tmp/tagged_pictures.pdf
//! [font.ttf]`
//!        `cargo run --example write_tagged_pictures -- tmp/out.pdf --archival`
//!        `cargo run --example write_tagged_pictures -- tmp/out.pdf --ua`
//!        `HQF_PDF_LANG=fr cargo run --example write_tagged_pictures --
//! tmp/pieces.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::layout::{
    Align, Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table, TableFrame, TextFlow,
    VAlign,
};
use hqf_pdf::metadata::xmp::{Metadata, PdfA, PdfUa};
use hqf_pdf::{
    Artifact, Document, Font, FontHandle, Image, ImageHandle, License, Marks, Page, Rgb,
    StructElement, StructureTree,
};

#[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 pictures the list shows, committed with the tests.
fn pictures() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("images")
}

/// The left edge everything is set from, and the room it all has.
const MARGIN: f64 = 64.0;

/// The room the table has across an A4 page between the margins.
const WIDTH: f64 = 595.276 - 2.0 * MARGIN;

/// The colour the heading row is painted on.
const HEAD_FILL: Rgb = Rgb::gray(0.88);

/// How many parts the list holds.
const PARTS: usize = 3;

/// The picture each part is shown by, under the committed images. A picture is
/// the same picture in every language.
const PICTURES: [&str; PARTS] = ["logo.png", "hqf_development.png", "indexed_16colours.png"];

/// The words the list is written in, one set per language.
///
/// The tag of the language is here too: a document that says nothing about the
/// language its words are in cannot be read aloud properly, and it is one more
/// thing a set of words has to get right.
#[derive(Debug)]
struct Words {
    /// The tag the structure tree carries, saying what the words below are in.
    lang: &'static str,
    /// The title the document is filed under, in its information dictionary and
    /// in its metadata both.
    title: &'static str,
    /// The line at the head of the page.
    heading: &'static str,
    /// The heading of each column, in the order the columns are set.
    columns: [&'static str; 3],
    /// What each part is called, in the order the rows are written.
    names: [&'static str; PARTS],
    /// What each part is for.
    purposes: [&'static str; PARTS],
    /// What each picture is, said in words. A figure with nothing here is a
    /// figure nothing can read out, and a validator says so.
    alts: [&'static str; PARTS],
    /// The paragraph under the list.
    closing: &'static str,
    /// The page number at the foot, which is furniture rather than what the
    /// document says.
    footer: &'static str,
}

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

/// The list in English.
const ENGLISH: Words = Words {
    lang: "en-GB",
    title: "A tagged parts list",
    heading: "Parts of the housing",
    columns: ["Picture", "Part", "What it is for"],
    names: ["Cover plate", "Rating label", "Heat scale"],
    purposes: [
        "Closes the housing once the board is seated.",
        "Carries the serial number and the supply it is rated for.",
        "Read against the winding to say how hot it is running.",
    ],
    alts: [
        "The house mark: a ring, one half blue and the other yellow.",
        "The maker's name, printed across the label in full.",
        "A band running from red at the top down to blue at the bottom.",
    ],
    closing: "Every picture above is marked as a figure and carries the words a \
         reader hears in its place, so nothing in this list is lost on somebody \
         who cannot see it. The table itself is a branch of the structure tree: \
         each row is a row there too, and each cell says which column it sits \
         in.",
    footer: "Page 1 of 1",
};

/// The list in French.
const FRENCH: Words = Words {
    lang: "fr-FR",
    title: "Une liste de pièces balisée",
    heading: "Les pièces du boîtier",
    columns: ["Image", "Pièce", "À quoi elle sert"],
    names: ["Couvercle", "Plaque signalétique", "Échelle de température"],
    purposes: [
        "Ferme le boîtier une fois la carte en place.",
        "Indique le numéro de série et l’alimentation nominale.",
        "Posée sur le bobinage, indique la température à laquelle il fonctionne.",
    ],
    alts: [
        "La marque de la maison : un anneau, moitié bleu, moitié jaune.",
        "Le nom du fabricant, imprimé en entier sur l’étiquette.",
        "Une bande qui va du rouge en haut au bleu en bas.",
    ],
    closing: "Chaque image ci-dessus est balisée comme figure et s’accompagne des mots qu’on \
entend à sa place : rien de cette liste n’échappe à qui ne la voit pas. Le \
tableau lui-même est une branche de l’arbre de structure : chaque ligne y est \
aussi une ligne, et chaque cellule indique sa colonne.",
    footer: "Page 1 sur 1",
};

/// The list in Dutch.
const DUTCH: Words = Words {
    lang: "nl-NL",
    title: "Een getagde onderdelenlijst",
    heading: "Onderdelen van de behuizing",
    columns: ["Afbeelding", "Onderdeel", "Waarvoor het dient"],
    names: ["Afdekplaat", "Typeplaatje", "Warmteschaal"],
    purposes: [
        "Sluit de behuizing zodra de print op zijn plaats zit.",
        "Vermeldt het serienummer en de voeding waarvoor het bestemd is.",
        "Wordt tegen de wikkeling afgelezen om te zeggen hoe warm ze draait.",
    ],
    alts: [
        "Het huismerk: een ring, de ene helft blauw en de andere geel.",
        "De naam van de fabrikant, voluit over het plaatje gedrukt.",
        "Een band die van rood bovenaan naar blauw onderaan loopt.",
    ],
    closing: "Elke afbeelding hierboven is gemarkeerd als figuur en heeft de woorden die een lezer in haar plaats hoort, dus gaat niets van deze lijst verloren voor wie haar niet kan zien. De tabel zelf is een tak van de structuurboom: elke rij is daar ook een rij, en elke cel zegt in welke kolom ze staat.",
    footer: "Pagina 1 van 1",
};

/// The list in Portuguese.
const PORTUGUESE: Words = Words {
    lang: "pt-PT",
    title: "Uma lista de peças etiquetada",
    heading: "Peças da caixa",
    columns: ["Imagem", "Peça", "Para que serve"],
    names: ["Tampa", "Placa de características", "Escala térmica"],
    purposes: [
        "Fecha a caixa depois de assente a placa.",
        "Leva o número de série e a alimentação para que está dimensionada.",
        "Lê-se junto ao enrolamento para saber a que temperatura trabalha.",
    ],
    alts: [
        "A marca da casa: um anel, metade azul e metade amarelo.",
        "O nome do fabricante, impresso por extenso ao longo da placa.",
        "Uma faixa que vai do vermelho em cima ao azul em baixo.",
    ],
    closing: "Cada imagem acima está marcada como figura e leva as palavras que um leitor ouve no seu lugar, por isso nada desta lista se perde para quem não a pode ver. A própria tabela é um ramo da árvore de estrutura: cada linha é também uma linha lá, e cada célula diz em que coluna está.",
    footer: "Página 1 de 1",
};

/// The list in Italian.
const ITALIAN: Words = Words {
    lang: "it-IT",
    title: "Un elenco di pezzi marcato",
    heading: "Pezzi del carter",
    columns: ["Immagine", "Pezzo", "A cosa serve"],
    names: ["Coperchio", "Targhetta dati", "Scala termica"],
    purposes: [
        "Chiude il carter una volta alloggiata la scheda.",
        "Porta il numero di serie e l’alimentazione per cui è dimensionato.",
        "Si legge sull’avvolgimento per sapere a che temperatura lavora.",
    ],
    alts: [
        "Il marchio della casa: un anello, metà blu e metà giallo.",
        "Il nome del produttore, stampato per intero lungo la targhetta.",
        "Una fascia che va dal rosso in alto al blu in basso.",
    ],
    closing: "Ogni immagine qui sopra è marcata come figura e porta le parole che un lettore sente al suo posto, così niente di questo elenco va perso per chi non può vederlo. La tabella stessa è un ramo dell’albero di struttura: ogni riga è una riga anche lì, e ogni cella dice in quale colonna sta.",
    footer: "Pagina 1 di 1",
};

/// The list in Spanish.
const SPANISH: Words = Words {
    lang: "es-ES",
    title: "Una lista de piezas etiquetada",
    heading: "Piezas de la carcasa",
    columns: ["Imagen", "Pieza", "Para qué sirve"],
    names: ["Tapa", "Placa de características", "Escala térmica"],
    purposes: [
        "Cierra la carcasa una vez asentada la placa.",
        "Lleva el número de serie y la alimentación para la que está calculada.",
        "Se lee frente al bobinado para saber a qué temperatura funciona.",
    ],
    alts: [
        "La marca de la casa: un anillo, mitad azul y mitad amarilla.",
        "El nombre del fabricante, impreso entero a lo ancho de la placa.",
        "Una banda que va del rojo arriba al azul abajo.",
    ],
    closing: "Cada imagen de arriba está marcada como figura y lleva las palabras que oye un lector en su lugar, así que nada de esta lista se pierde para quien no puede verla. La propia tabla es una rama del árbol de estructura: cada fila es también una fila allí, y cada celda dice en qué columna está.",
    footer: "Página 1 de 1",
};

/// The list in German.
const GERMAN: Words = Words {
    lang: "de-DE",
    title: "Eine getaggte Stückliste",
    heading: "Teile des Gehäuses",
    columns: ["Bild", "Teil", "Wozu es dient"],
    names: ["Deckplatte", "Typenschild", "Wärmeskala"],
    purposes: [
        "Schließt das Gehäuse, sobald die Platine sitzt.",
        "Trägt die Seriennummer und die Versorgung, für die es ausgelegt ist.",
        "Wird an der Wicklung abgelesen, um zu sagen, wie heiß sie läuft.",
    ],
    alts: [
        "Das Hauszeichen: ein Ring, eine Hälfte blau, die andere gelb.",
        "Der Name des Herstellers, voll ausgeschrieben quer über das Schild gedruckt.",
        "Ein Band, das oben rot beginnt und unten blau endet.",
    ],
    closing: "Jedes Bild oben ist als Abbildung markiert und trägt die Worte, die ein Leser an seiner Stelle hört, also geht nichts in dieser Liste für jemanden verloren, der es nicht sehen kann. Die Tabelle selbst ist ein Zweig des Strukturbaums: Jede Zeile ist auch dort eine Zeile, und jede Zelle sagt, in welcher Spalte sie steht.",
    footer: "Seite 1 von 1",
};

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

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

/// The heading, marked and numbered so that the tree can point at it.
fn heading(
    content: &mut Content,
    font: &FontHandle,
    marks: &mut Marks,
    page: usize,
    words: &'static Words,
) -> Result<StructElement, hqf_pdf::Error> {
    let id = marks.next_id();
    content.begin_tagged(&Name::new("H1"), id);
    text(content, font, 18.0, MARGIN, 762.0, words.heading)?;
    content.end_marked();
    Ok(StructElement::new("H1").content(page, id))
}

/// The closing paragraph, broken into lines and marked as one run.
#[allow(clippy::expect_used, reason = "the paragraph is one marked run")]
fn closing(
    content: &mut Content,
    font: &FontHandle,
    marks: &mut Marks,
    page: usize,
    top: f64,
    words: &'static Words,
) -> Result<StructElement, hqf_pdf::Error> {
    let flow = TextFlow::new(font, 10.0)
        .leading(15.0)
        .align(Align::Justify);
    let lines = flow.break_lines(words.closing, WIDTH);
    // The flow writes the text operators and nothing around them, so the caller
    // opens and closes the text object itself.
    content.begin_text();
    let numbers = flow.draw_tagged(content, &lines, MARGIN, top, WIDTH, &Name::new("P"), marks)?;
    content.end_text();
    let number = numbers
        .first()
        .copied()
        .expect("the paragraph is one marked run");
    Ok(StructElement::new("P").content(page, number))
}

/// The parts list, and the branch of the tree describing it.
///
/// The pictures are drawn by the table, each into whatever rectangle its cell
/// came to, and each marked as a figure carrying its own words.
fn list(
    content: &mut Content,
    font: &FontHandle,
    handles: &[ImageHandle],
    marks: &mut Marks,
    page: usize,
    words: &'static Words,
) -> Result<(StructElement, f64), hqf_pdf::Error> {
    let mut table = Table::new(Columns::new(
        vec![
            ColumnWidth::Points(96.0),
            ColumnWidth::Points(120.0),
            ColumnWidth::Points(WIDTH - 216.0),
        ],
        WIDTH,
    )?);
    table.header(1);
    table.rule(Rule::Frame, Stroke::black(0.8));
    table.rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.7)));

    let mut head = Row::new().fill(HEAD_FILL);
    for label in words.columns {
        head = head.cell(
            Cell::new(font, 10.0, label)
                .align(Align::Left)
                .padding(Padding::symmetric(6.0, 5.0)),
        );
    }
    table.push(head);

    for ((handle, name), (purpose, alt)) in handles
        .iter()
        .zip(words.names)
        .zip(words.purposes.into_iter().zip(words.alts))
    {
        table.push(
            Row::new()
                .min_height(54.0)
                .cell(
                    Cell::image(handle)
                        .alt(alt)
                        .align(Align::Center)
                        .valign(VAlign::Middle)
                        .padding(Padding::uniform(5.0)),
                )
                .cell(
                    Cell::new(font, 10.0, name)
                        .valign(VAlign::Middle)
                        .padding(Padding::symmetric(6.0, 5.0)),
                )
                .cell(
                    Cell::new(font, 10.0, purpose)
                        .valign(VAlign::Middle)
                        .padding(Padding::symmetric(6.0, 5.0)),
                ),
        );
    }

    let placement = table.fit(TableFrame::new(MARGIN, 736.0, 620.0), 0)?;
    let bottom = placement.bottom();
    Ok((placement.draw_tagged(content, page, marks)?, bottom))
}

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: Vec<String> = env::args().skip(1).collect();

    let evaluation = args.iter().any(|arg| arg == "--evaluation");
    // Level A is the level that demands the structure tree, which is the whole
    // subject here.
    let archival = args.iter().any(|arg| arg == "--archival");
    let ua = args.iter().any(|arg| arg == "--ua");
    args.retain(|arg| !arg.starts_with("--"));

    let mut args = args.into_iter();
    // 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 path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("tagged_pictures")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(if evaluation {
        License::evaluation()
    } else {
        licence::licensed()
    });
    if archival {
        doc.set_conformance(PdfA::A3A);
    }
    if ua {
        doc.set_ua_conformance(PdfUa::One);
    }
    if archival || ua {
        let mut facts = Metadata::default();
        facts.title = Some(words.title.to_owned());
        facts.producer = Some("hqf-pdf".to_owned());
        facts.created = Some("2026-07-26T09:30:00+02:00".to_owned());
        doc.set_metadata(facts);
    }
    doc.set_info(Name::new("Title"), words.title);

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let mut handles = Vec::with_capacity(PARTS);
    for picture in PICTURES {
        handles.push(doc.add_image(Image::parse(fs::read(pictures().join(picture))?)?));
    }

    let mut content = Content::new();
    let mut marks = Marks::new();
    let mut section = StructElement::new("Sect");
    section = section.child(heading(&mut content, &font, &mut marks, 0, words)?);
    let (table, bottom) = list(&mut content, &font, &handles, &mut marks, 0, words)?;
    section = section.child(table);
    section = section.child(closing(
        &mut content,
        &font,
        &mut marks,
        0,
        bottom - 24.0,
        words,
    )?);

    // The page number is furniture, not what the document says, so it carries
    // no number and the tree never points at it.
    content.begin_artifact(Artifact::Footer);
    text(&mut content, &font, 9.0, MARGIN, 48.0, words.footer)?;
    content.end_marked();

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;

    doc.set_structure(
        StructureTree::new()
            .lang(words.lang)
            .child(StructElement::new("Document").child(section)),
    );

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;
    println!("wrote {} ({} bytes)", path, bytes.len());
    Ok(())
}

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

    /// The lines two languages are allowed to write the same way. Every line
    /// here is a sentence, a name or a language tag, and two languages write
    /// one alike only where they spell it alike.
    const SPARED: [&str; 3] = [
        // Written the same way in Portuguese.
        r#""Escala térmica""#,
        r#""Placa de características""#,
        r#"footer: "Página 1 de 1""#,
    ];

    #[test]
    fn every_language_writes_the_list_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the list says these in more than one language: {untranslated:?}"
        );
    }

    /// The words a reader hears in place of a picture say what the picture is.
    /// A language that repeats the name of the part there leaves that reader
    /// with the row's own text twice over and nothing about the picture.
    #[test]
    fn every_language_says_what_each_picture_is_rather_than_naming_the_part() {
        for (language, words) in WORDS {
            for index in 0..PARTS {
                let alt = words.alts[index];
                assert!(
                    !alt.is_empty(),
                    "{} leaves picture {index} without words",
                    language.code()
                );
                assert_ne!(
                    alt,
                    words.names[index],
                    "{} hears the name of picture {index} rather than the picture",
                    language.code()
                );
            }
        }
    }
}