odox-ui 0.7.0

The shared window of the odox OpenDocument editors: style mapping, document rendering, editing and chrome
Documentation
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
//! Drawing an ODF body: the block renderer all three applications share.
//!
//! ODF's content model is the same in a text document, a spreadsheet cell and a
//! slide's text frame — `text:p`, `text:span`, `text:list`, `table:table`,
//! `draw:frame` — so this is written against that model and not against a format.
//! A text document hands it the body; a spreadsheet hands it a cell; a
//! presentation hands it a frame.
//!
//! What it does not do is paginate. A page layout says how wide a line may be and
//! that width is what it is given; page boxes, widows, floats and columns are
//! typesetting, and a reading view is what this draws.
//
// Author: David M. Anderson
// Built with AI assistance (Claude, Anthropic)

use std::collections::HashMap;
use std::sync::Arc;

use eframe::egui::accesskit::Role;
use eframe::egui::emath::TSTransform;
use eframe::egui::text_selection::accesskit_text::update_accesskit_for_text_widget;
use eframe::egui::{
    Align, Color32, ColorImage, Context, CursorIcon, Galley, Pos2, Rect, Response, Sense, Stroke,
    StrokeKind, TextFormat, TextureHandle, TextureOptions, Ui, pos2,
    text::{CCursor, CCursorRange, LayoutJob},
    text_selection::{LabelSelectionState, visuals::paint_text_selection},
    vec2,
};
use egui_richedit::{Laid, OffsetMap, ParagraphJob};
use odox_core::{
    Border, Document, Element, Family, Node, Ns, Properties, TextAlign, TextProperties, edit,
};

use crate::find::Highlights;
use crate::flow_model::PageEditor;
use crate::format::{self, DEFAULT_SIZE};
use crate::links;

/// Pictures already decoded, kept for as long as the document is open.
///
/// A failed decode is remembered as a failure, so that a picture in a format
/// nothing here reads is not decoded again on every frame.
#[derive(Default)]
pub struct Pictures {
    textures: HashMap<String, Option<TextureHandle>>,
}

impl Pictures {
    /// The texture for a picture the document refers to, decoding it once.
    pub fn get(
        &mut self,
        ctx: &Context,
        document: &Document,
        href: &str,
    ) -> Option<&TextureHandle> {
        if !self.textures.contains_key(href) {
            let texture = document
                .picture(href)
                .and_then(decode)
                .map(|image| ctx.load_texture(href, image, TextureOptions::LINEAR));
            self.textures.insert(href.to_owned(), texture);
        }
        self.textures.get(href).and_then(Option::as_ref)
    }

    /// Forget every picture, for a window that has closed its document.
    pub fn clear(&mut self) {
        self.textures.clear();
    }
}

fn decode(bytes: &[u8]) -> Option<ColorImage> {
    let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
    let size = [decoded.width() as usize, decoded.height() as usize];
    Some(ColorImage::from_rgba_unmultiplied(size, decoded.as_raw()))
}

/// The state a run of blocks is drawn with.
pub struct Flow<'a> {
    /// The document, for its styles and its pictures.
    pub document: &'a Document,
    /// Pictures decoded so far.
    pub pictures: &'a mut Pictures,
    /// Screen points per ODF point.
    pub zoom: f32,
    /// The colours to draw in where the document names none.
    pub palette: format::Palette,
    /// The heading, counted from zero in document order, to bring into view.
    ///
    /// Set by a panel that lists a document's headings. It is answered while the
    /// body is drawn, because the only moment a heading's position is known is
    /// the moment it is laid out.
    pub scroll_to_heading: Option<usize>,
    /// A place in the document to bring into view: a bookmark's name, or a
    /// heading's text written `Name|outline`. Answered while the body is drawn,
    /// for the same reason `scroll_to_heading` is.
    pub scroll_to_place: Option<String>,
    /// A place in the document that a link just followed asked for, for the
    /// view to set `scroll_to_place` to on the next frame.
    pub followed: Option<String>,
    /// How many headings have been drawn this pass.
    headings_seen: usize,
    /// The page editor, which puts a caret in every paragraph under the root
    /// and paints them. Outside edit mode there is none.
    pub page: Option<&'a mut PageEditor>,
    /// The matches of a search, drawn behind the text they are in.
    pub find: Option<Highlights<'a>>,
    /// Whether text in the page can be dragged over to select it. Off on a
    /// slide in edit mode, where a drag moves the shape instead.
    pub selectable: bool,
    /// Where the flow is, as a path of child indices from the root, or from
    /// wherever [`Self::start_at`] said the root sits.
    path: Vec<usize>,
    /// Inside a frame anchored in a paragraph, which is reached by a clone
    /// and not by a path, or in the second and later copies of a repeated
    /// cell, whose copies share one path: nothing in either can be edited in
    /// place.
    detached: bool,
}

impl<'a> Flow<'a> {
    /// A flow over a document, drawing at a zoom.
    pub fn new(document: &'a Document, pictures: &'a mut Pictures, zoom: f32) -> Self {
        Self {
            document,
            pictures,
            zoom,
            palette: format::Palette::default(),
            scroll_to_heading: None,
            scroll_to_place: None,
            followed: None,
            headings_seen: 0,
            page: None,
            find: None,
            selectable: true,
            path: Vec::new(),
            detached: false,
        }
    }

    /// Name where the root this flow draws sits under something larger, so
    /// that every path it reports and matches is from that larger root: a
    /// slide's label is drawn from the shape and edited from the page.
    pub fn start_at(&mut self, prefix: Vec<usize>) {
        self.path = prefix;
    }
}

/// How far each list level is indented, in ODF points.
const LIST_STEP: f32 = 18.0;
/// The space a list label is drawn in, left of its item's text.
const LIST_GUTTER: f32 = 20.0;
/// The gap between a label and the text it belongs to.
const LABEL_GAP: f32 = 5.0;

/// A paragraph's margins and first-line indent, in screen points.
struct Spacing {
    /// Space outside the paragraph's left edge.
    left: f32,
    /// Space outside its right edge.
    right: f32,
    /// The first line's extra indent, negative for a hanging one.
    indent: f32,
    /// Space above the paragraph.
    before: f32,
    /// Space below it.
    after: f32,
}

impl Spacing {
    fn of(properties: &odox_core::ParagraphProperties, zoom: f32) -> Self {
        let points = |length: Option<odox_core::Length>| {
            length.map_or(0.0, odox_core::Length::points) * zoom
        };
        Self {
            left: points(properties.margin.left),
            right: points(properties.margin.right),
            indent: points(properties.text_indent),
            before: points(properties.margin.top),
            after: points(properties.margin.bottom),
        }
    }
}

/// What a run of text inherits from the text it sits inside.
///
/// One argument rather than four, because a span inside a link inside a
/// paragraph passes all of them down together and they only ever travel as a set.
#[derive(Clone, Copy)]
struct Run<'a> {
    /// The character properties in force.
    inherited: &'a TextProperties,
    /// The size in points those properties resolve to, which is what a relative
    /// size inside this run is relative to.
    size: f32,
    /// What egui draws the run with.
    format: &'a TextFormat,
    /// The colours to use where the document names none.
    palette: format::Palette,
    /// Whether the run's characters are the paragraph's own text, which the
    /// caret moves through, or a field's value, which it steps over.
    counted: bool,
}

/// Where a list's counters stand, one per level.
#[derive(Default)]
struct Counters(Vec<usize>);

impl Counters {
    fn bump(&mut self, level: usize, start: usize) -> usize {
        while self.0.len() <= level {
            self.0.push(0);
        }
        // A level that has not been counted at yet begins at the level style's
        // start value, which is one unless the document says otherwise.
        if self.0[level] == 0 {
            self.0[level] = start;
        } else {
            self.0[level] += 1;
        }
        // Entering a list resets everything below it, which is what makes 2.1
        // follow 1.3.
        self.0.truncate(level + 1);
        self.0[level]
    }

    fn at(&self, level: usize) -> usize {
        self.0.get(level).copied().unwrap_or(1)
    }
}

impl Flow<'_> {
    /// Draw every block under an element, in order.
    ///
    /// `width` is the space available in screen points, and is what a paragraph
    /// wraps to.
    pub fn blocks(&mut self, ui: &mut Ui, parent: &Element, width: f32) {
        let mut counters = Counters::default();
        self.blocks_with(ui, parent, width, &mut counters);
    }

    fn blocks_with(&mut self, ui: &mut Ui, parent: &Element, width: f32, counters: &mut Counters) {
        for (index, element) in parent.elements_indexed() {
            self.path.push(index);
            match () {
                () if element.is(&Ns::Text, "p") || element.is(&Ns::Text, "h") => {
                    self.paragraph(ui, element, width, None);
                }
                () if element.is(&Ns::Text, "list") => {
                    // Numbering belongs to a list, not to the body: a second
                    // list starts at one again unless it says it is continuing
                    // the one before it, which is what `text:continue-numbering`
                    // and `text:continue-list` are for.
                    let continues = element.attr(&Ns::Text, "continue-numbering") == Some("true")
                        || element.attr(&Ns::Text, "continue-list").is_some();
                    if !continues {
                        *counters = Counters::default();
                    }
                    self.list(ui, element, width, 0, None, counters);
                }
                () if element.is(&Ns::Table, "table") => self.table(ui, element, width),
                () if element.is(&Ns::Draw, "frame") => self.frame(ui, element, width),
                () if element.is(&Ns::Text, "soft-page-break") => self.page_break(ui, width),
                () if edit::is_block_container(element) => {
                    self.blocks_with(ui, element, width, counters);
                }
                () => {}
            }
            self.path.pop();
        }
    }

    /// The resolved style of a paragraph or heading.
    fn style_of(&self, element: &Element, family: &Family) -> std::rc::Rc<Properties> {
        let name = element
            .attr(&Ns::Text, "style-name")
            .or_else(|| element.attr(&Ns::Table, "style-name"))
            .unwrap_or("Standard");
        self.document.styles.resolve(family, name)
    }

    /// Colour the matches of a search in a paragraph, and scroll to the current
    /// one when a search has just moved to it.
    fn show_matches(&self, ui: &Ui, galley: &mut Arc<Galley>, map: &OffsetMap, origin: Pos2) {
        let Some(find) = self.find.as_ref().filter(|_| !self.detached) else {
            return;
        };
        let hits = find.within(&self.path);
        if hits.is_empty() {
            return;
        }
        let at = |offset: usize| CCursor::new(map.to_galley(offset.min(map.model_len())));
        for (range, current) in hits {
            let mut visuals = ui.visuals().clone();
            visuals.selection.bg_fill = format::match_fill(current);
            visuals.selection.stroke.color = Color32::BLACK;
            let cursors = CCursorRange::two(at(range.start), at(range.end));
            paint_text_selection(galley, &visuals, &cursors, None);
            if current && find.reveal() {
                let start = galley.pos_from_cursor(at(range.start));
                let end = galley.pos_from_cursor(at(range.end));
                ui.scroll_to_rect(
                    start.union(end).translate(origin.to_vec2()),
                    Some(Align::Center),
                );
            }
        }
    }

    /// A link under the pointer shows where it goes, and is followed by a click
    /// where the text is being read and by Ctrl and a click where it is being
    /// edited, a plain click there being how the caret is put down.
    #[allow(clippy::too_many_arguments)]
    fn follow_link(
        &mut self,
        ui: &Ui,
        response: &Response,
        links: &[(std::ops::Range<usize>, &str)],
        galley: &Galley,
        map: &OffsetMap,
        origin: Pos2,
        editing: bool,
    ) {
        let Some(pointer) = response
            .hover_pos()
            .or_else(|| response.interact_pointer_pos())
        else {
            return;
        };
        let cursor = galley.cursor_from_pos(pointer - origin);
        let caret = galley.pos_from_cursor(cursor).center().x + origin.x;
        let character = if pointer.x < caret {
            cursor.index.0.saturating_sub(1)
        } else {
            cursor.index.0
        };
        let offset = map.to_model(character);
        let Some(href) = links
            .iter()
            .find(|(range, _)| range.contains(&offset))
            .map(|&(_, href)| href)
        else {
            return;
        };
        let Some(target) = links::target(href) else {
            return;
        };
        let reaching = !editing || ui.input(|input| input.modifiers.command);
        if reaching {
            ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
        }
        if response.hovered() {
            response.clone().on_hover_text(href);
        }
        if reaching && response.clicked() {
            match target {
                links::Target::External(address) => links::open(ui.ctx(), address),
                links::Target::Within(place) => self.followed = Some(place.to_owned()),
            }
        }
    }

    /// One paragraph or heading, with an optional list label drawn in its margin.
    fn paragraph(&mut self, ui: &mut Ui, element: &Element, width: f32, label: Option<&str>) {
        let properties = self.style_of(element, &Family::Paragraph);
        let zoom = self.zoom;
        let size = format::size_of(&properties.text, DEFAULT_SIZE);

        let Spacing {
            left,
            right,
            indent,
            before,
            after,
        } = Spacing::of(&properties.paragraph, zoom);

        // The first line's indent may be negative — a hanging indent — and the
        // text then starts left of the rest of the paragraph, which is where a
        // list label goes.
        let body_width = (width - left - right).max(1.0);
        let wrap = (body_width - indent.max(0.0)).max(1.0);

        if before > 0.0 {
            ui.add_space(before);
        }

        let base = format::text_format(&properties.text, DEFAULT_SIZE, zoom, self.palette);

        let (job, frames) = self.layout_job(element, &properties, &base, size, wrap);
        let (job, map) = job.into_parts();

        let galley = ui.ctx().fonts_mut(|fonts| fonts.layout_job(job));
        let height = galley.size().y;
        let edited = !self.detached && self.page.is_some();
        // Click and drag, and not merely hover: the selection plugin begins a
        // selection only on a response whose sense includes drag, which is what
        // `Label` adds to its own when it is selectable, and the click half is
        // what lets a double-click take a word and a triple-click a line.
        // Without the drag the pointer reaches the scroll area instead and
        // nothing is selected — measured, not read. The page editor selects
        // the same way, and on a slide in edit mode, where a drag moves the
        // shape, it takes clicks alone.
        let sense = if self.selectable {
            Sense::click_and_drag()
        } else {
            Sense::click()
        };
        let (rect, response) = ui.allocate_exact_size(vec2(width, height), sense);

        if element.is(&Ns::Text, "h") {
            if self.scroll_to_heading == Some(self.headings_seen) {
                ui.scroll_to_rect(rect, Some(Align::TOP));
            }
            self.headings_seen += 1;
        }
        if let Some(place) = &self.scroll_to_place
            && holds_place(element, place)
        {
            ui.scroll_to_rect(rect, Some(Align::TOP));
        }

        if let Some(fill) = properties.paragraph.background {
            ui.painter().rect_filled(rect, 0.0, format::color32(fill));
        }
        paint_borders(ui, rect, &properties.paragraph.border, zoom);

        // The anchor the galley was laid out around: its rows are positioned
        // relative to this, which is what makes a centred paragraph centre each
        // of its rows rather than its block.
        let anchor = match properties.paragraph.align.unwrap_or(TextAlign::Start) {
            TextAlign::Center => rect.left() + left + indent.max(0.0) + wrap / 2.0,
            TextAlign::End => rect.left() + left + indent.max(0.0) + wrap,
            _ => rect.left() + left + indent.max(0.0),
        };
        // Through the page editor in edit mode, and through egui's selection
        // plugin otherwise, rather than the painter: either is what lets a
        // person drag across the page and press Ctrl+C. Both paint the galley
        // themselves, at the same anchor the painter would have taken, so
        // alignment is untouched. Both are called for every paragraph and not
        // only the visible ones: the plugin drops a selection whose ends it did
        // not see this frame, and the editor moves Up and Down through where
        // each paragraph was drawn.
        let origin = pos2(anchor, rect.top());
        let mut galley = galley;
        self.show_matches(ui, &mut galley, &map, origin);
        let readable = Arc::clone(&galley);
        let links = edit::links(element);
        let hit = (!links.is_empty()).then(|| (Arc::clone(&galley), map.clone()));
        if let Some(page) = self.page.as_deref_mut().filter(|_| edited) {
            let laid = Laid {
                galley,
                map,
                origin,
            };
            page.paragraph(ui, &response, &self.path, laid);
        } else {
            LabelSelectionState::label_text_selection(
                ui,
                &response,
                origin,
                galley,
                base.color,
                Stroke::NONE,
            );
        }

        expose(ui, &response, element, &readable, origin, edited);

        if let Some((galley, map)) = hit {
            self.follow_link(ui, &response, &links, &galley, &map, origin, edited);
        }

        if let Some(label) = label {
            let mut label_job = LayoutJob::default();
            label_job.append(label, 0.0, base.clone());
            let label_galley = ui.ctx().fonts_mut(|fonts| fonts.layout_job(label_job));
            // Ending just before the text begins, in the gutter the list opened
            // for it. Painting left of the allocated rectangle is deliberate: the
            // gutter is space the caller reserved and nothing else draws there.
            let x = rect.left() + left - label_galley.size().x - LABEL_GAP * zoom;
            ui.painter()
                .galley(pos2(x, rect.top()), label_galley, base.color);
        }

        // Reached by a clone rather than by a path, so nothing inside is
        // edited in place.
        let was_detached = self.detached;
        self.detached = true;
        for frame in frames {
            self.frame(ui, &frame, body_width);
        }
        self.detached = was_detached;
        if after > 0.0 {
            ui.add_space(after);
        }
    }

    /// The layout job for a paragraph, and the frames anchored inside it,
    /// which are drawn after it.
    fn layout_job(
        &self,
        element: &Element,
        properties: &Properties,
        base: &TextFormat,
        size: f32,
        wrap: f32,
    ) -> (ParagraphJob, Vec<Element>) {
        let job = LayoutJob {
            wrap: eframe::egui::text::TextWrapping {
                max_width: wrap,
                ..Default::default()
            },
            halign: match properties.paragraph.align.unwrap_or(TextAlign::Start) {
                TextAlign::Center => Align::Center,
                TextAlign::End => Align::Max,
                _ => Align::Min,
            },
            justify: properties.paragraph.align == Some(TextAlign::Justify),
            ..LayoutJob::default()
        };
        let mut job = ParagraphJob::new(job);
        let mut frames = Vec::new();
        let run = Run {
            inherited: &properties.text,
            size,
            format: base,
            palette: self.palette,
            counted: true,
        };
        self.runs(element, &run, &mut job, &mut frames);

        // An empty paragraph is a blank line and has to take its height, which an
        // empty layout job would not.
        if job.is_empty() {
            job.atom(" ", 0, base.clone());
        }
        if let Some(measure) = properties.paragraph.line_height {
            // A proportional line height is a proportion of each run's own
            // size, so a span set larger than its paragraph takes a taller
            // line; an absolute one is the same for every run.
            for format in job.formats_mut() {
                let own = format.font_id.size / self.zoom;
                format.line_height = Some(measure.resolve(own) * self.zoom);
            }
        }
        (job, frames)
    }

    /// Append the text of a paragraph's children to a layout job.
    ///
    /// Anything that is not text is either resolved into characters — ODF spells
    /// out runs of spaces, tabs and line breaks rather than writing them
    /// literally — or collected to be drawn after the paragraph, which is what
    /// happens to a picture anchored inside one.
    ///
    /// Each piece is recorded against the characters [`edit::text`] gives the
    /// paragraph, so that a caret placed in what is drawn lands in the text an
    /// edit changes: where the two differ, as a tab drawn as spaces or a field
    /// drawn as its value, the piece is an atom the caret steps over.
    fn runs(
        &self,
        parent: &Element,
        run: &Run<'_>,
        job: &mut ParagraphJob,
        frames: &mut Vec<Element>,
    ) {
        let Run {
            inherited,
            size,
            format,
            palette,
            counted,
        } = *run;
        let put = |job: &mut ParagraphJob, shown: &str, model_len: usize| {
            if !counted {
                job.atom(shown, 0, format.clone());
            } else if shown.chars().count() == model_len {
                job.text(shown, format.clone());
            } else {
                job.atom(shown, model_len, format.clone());
            }
        };
        for child in &parent.children {
            match child {
                Node::Text(text) | Node::CData(text) => put(job, text, text.chars().count()),
                Node::Comment(_) | Node::ProcessingInstruction(_) => {}
                Node::Element(element) => {
                    if element.is(&Ns::Text, "s") {
                        let count = element.attr_usize(&Ns::Text, "c").unwrap_or(1);
                        put(job, &" ".repeat(count.min(256)), count);
                    } else if element.is(&Ns::Text, "tab") {
                        // egui lays out a tab as a glyph rather than advancing to
                        // a stop, so the paragraph's tab stops are approximated
                        // by a fixed advance. A document whose layout depends on
                        // tab stops is one §6 of DESIGN.md names.
                        put(job, "    ", 1);
                    } else if element.is(&Ns::Text, "line-break") {
                        put(job, "\n", 1);
                    } else if element.is(&Ns::Text, "span") {
                        let style = self.style_of(element, &Family::Text);
                        let merged = style.text.over(inherited);
                        let inner_size = format::size_of(&merged, size);
                        let inner = format::text_format(&merged, size, self.zoom, palette);
                        let run = Run {
                            inherited: &merged,
                            size: inner_size,
                            format: &inner,
                            palette,
                            counted,
                        };
                        self.runs(element, &run, job, frames);
                    } else if element.is(&Ns::Text, "a") {
                        let style = self.style_of(element, &Family::Text);
                        let merged = style.text.over(inherited);
                        let inner_size = format::size_of(&merged, size);
                        let inner = format::link_format(&merged, size, self.zoom, palette);
                        let run = Run {
                            inherited: &merged,
                            size: inner_size,
                            format: &inner,
                            palette,
                            counted,
                        };
                        self.runs(element, &run, job, frames);
                    } else if element.is(&Ns::Draw, "frame") {
                        frames.push(element.clone());
                    } else if element.is(&Ns::Text, "note") {
                        // The citation is part of the text; the body is a
                        // footnote and belongs at the foot of a page this view
                        // does not have.
                        if let Some(citation) = element.child(&Ns::Text, "note-citation") {
                            let mut raised = format.clone();
                            raised.font_id.size *= 0.7;
                            raised.valign = Align::TOP;
                            job.atom(&citation.plain_text(), 0, raised);
                        }
                    } else if edit::is_inline_passthrough(element) {
                        // A mark's contents are the paragraph's text; a field's
                        // are its value, which the paragraph's text does not
                        // hold.
                        let run = Run {
                            counted: counted && edit::holds_text(element),
                            ..*run
                        };
                        self.runs(element, &run, job, frames);
                    }
                }
            }
        }
    }

    /// A list, and the lists nested inside it.
    fn list(
        &mut self,
        ui: &mut Ui,
        element: &Element,
        width: f32,
        level: usize,
        inherited_style: Option<&str>,
        counters: &mut Counters,
    ) {
        let style_name = element
            .attr(&Ns::Text, "style-name")
            .or(inherited_style)
            .unwrap_or_default()
            .to_owned();
        // The indent is absolute rather than relative, because a nested list is
        // drawn by a recursive call and not inside an indented region: a level
        // knows how deep it is and puts itself there.
        #[allow(clippy::cast_precision_loss)]
        let indent = LIST_STEP * self.zoom * (level as f32 + 1.0);
        let gutter = LIST_GUTTER * self.zoom;

        for (item_index, item) in element.elements_indexed() {
            let numbered = item.is(&Ns::Text, "list-item");
            if !numbered && !item.is(&Ns::Text, "list-header") {
                continue;
            }
            self.path.push(item_index);
            let label = if numbered {
                let level_style = self.level_style(&style_name, level);
                let start = level_style
                    .as_ref()
                    .and_then(|s| s.attr_usize(&Ns::Text, "start-value"))
                    .unwrap_or(1);
                let number = counters.bump(level, start);
                Self::label(level_style.as_ref(), level, number, counters)
            } else {
                // A list header is the paragraph a list may begin with, and it
                // is not numbered and does not count.
                String::new()
            };

            let mut first = true;
            for (block_index, block) in item.elements_indexed() {
                self.path.push(block_index);
                if block.is(&Ns::Text, "list") {
                    self.list(ui, block, width, level + 1, Some(&style_name), counters);
                    self.path.pop();
                    continue;
                }
                let on_this_block = if first && !label.is_empty() {
                    Some(label.as_str())
                } else {
                    None
                };
                if block.is(&Ns::Text, "p") || block.is(&Ns::Text, "h") {
                    first = false;
                    // The label is drawn in the gutter this space opens, left
                    // of where the text begins, so that a wide label crowds the
                    // indent rather than the first word.
                    ui.horizontal_top(|ui| {
                        ui.add_space(indent + gutter);
                        self.paragraph(ui, block, width - indent - gutter, on_this_block);
                    });
                } else if block.is(&Ns::Table, "table") {
                    first = false;
                    ui.horizontal_top(|ui| {
                        ui.add_space(indent + gutter);
                        self.table(ui, block, width - indent - gutter);
                    });
                } else if block.is(&Ns::Draw, "frame") {
                    first = false;
                    ui.horizontal_top(|ui| {
                        ui.add_space(indent + gutter);
                        self.frame(ui, block, width - indent - gutter);
                    });
                }
                self.path.pop();
            }
            self.path.pop();
        }
    }

    /// The level style of a list, which says whether the level is numbered or
    /// bulleted and how.
    fn level_style(&self, list_style: &str, level: usize) -> Option<Element> {
        let style = self.document.styles.list_style(list_style)?;
        style
            .elements()
            .find(|e| e.attr_usize(&Ns::Text, "level") == Some(level + 1))
            .cloned()
    }

    /// The text drawn in front of a list item.
    fn label(
        level_style: Option<&Element>,
        level: usize,
        number: usize,
        counters: &Counters,
    ) -> String {
        let Some(style) = level_style else {
            // A list whose style the document did not write, which happens in a
            // document assembled by something that left the style behind.
            return "\u{2022}".to_owned();
        };
        if style.is(&Ns::Text, "list-level-style-bullet") {
            return style
                .attr(&Ns::Text, "bullet-char")
                .unwrap_or("\u{2022}")
                .to_owned();
        }
        if style.is(&Ns::Text, "list-level-style-number") {
            let format = style.attr(&Ns::Style, "num-format").unwrap_or("1");
            let prefix = style.attr(&Ns::Style, "num-prefix").unwrap_or_default();
            let suffix = style.attr(&Ns::Style, "num-suffix").unwrap_or_default();
            // `text:display-levels` is how 1.2.3 is written: the level's own
            // number preceded by its ancestors'.
            let display = style
                .attr_usize(&Ns::Text, "display-levels")
                .unwrap_or(1)
                .max(1);
            let mut numbers = Vec::new();
            let first = (level + 1).saturating_sub(display);
            for ancestor in first..level {
                numbers.push(edit::number_text(counters.at(ancestor), format));
            }
            numbers.push(edit::number_text(number, format));
            return format!("{prefix}{}{suffix}", numbers.join("."));
        }
        // A level drawn with an image, which is a picture this does not fetch.
        "\u{2022}".to_owned()
    }

    /// A table, drawn as a grid of cells with the document's own widths.
    fn table(&mut self, ui: &mut Ui, table: &Element, width: f32) {
        let columns = column_widths(self.document, table, width, self.zoom);
        if columns.is_empty() {
            return;
        }
        ui.add_space(4.0 * self.zoom);
        self.rows(ui, table, &columns);
        ui.add_space(4.0 * self.zoom);
    }

    fn rows(&mut self, ui: &mut Ui, parent: &Element, columns: &[f32]) {
        for (index, element) in parent.elements_indexed() {
            self.path.push(index);
            if element.is(&Ns::Table, "table-row") {
                self.row(ui, element, columns);
            } else if element.is(&Ns::Table, "table-header-rows")
                || element.is(&Ns::Table, "table-rows")
                || element.is(&Ns::Table, "table-row-group")
            {
                self.rows(ui, element, columns);
            }
            self.path.pop();
        }
    }

    fn row(&mut self, ui: &mut Ui, row: &Element, columns: &[f32]) {
        // The backgrounds and the borders have to be painted behind the text, and
        // the row's height is only known once the text is laid out, so the shapes
        // are reserved now and filled in after.
        let reserved = ui.painter().add(eframe::egui::Shape::Noop);
        let mut painted = Vec::new();

        let response = ui.horizontal_top(|ui| {
            ui.spacing_mut().item_spacing.x = 0.0;
            let mut column = 0usize;
            for (cell_index, cell) in row.elements_indexed() {
                let covered = cell.is(&Ns::Table, "covered-table-cell");
                if !covered && !cell.is(&Ns::Table, "table-cell") {
                    continue;
                }
                let repeat = cell
                    .attr_usize(&Ns::Table, "number-columns-repeated")
                    .unwrap_or(1)
                    .max(1);
                let spanned = cell
                    .attr_usize(&Ns::Table, "number-columns-spanned")
                    .unwrap_or(1)
                    .max(1);
                for copy in 0..repeat {
                    // The width covers every column the cell spans; the position
                    // advances by one. ODF writes a `table:covered-table-cell`
                    // for each further column a span reaches, so advancing by the
                    // span here as well would count those columns twice and push
                    // the rest of the row off the end of the table.
                    let width: f32 = columns
                        .iter()
                        .skip(column)
                        .take(spanned)
                        .sum::<f32>()
                        .max(8.0);
                    if !covered {
                        let properties = self.style_of(cell, &Family::TableCell);
                        let padding = properties
                            .cell
                            .padding
                            .left
                            .map_or(2.0, odox_core::Length::points)
                            * self.zoom;
                        let inner = ui
                            .allocate_ui_with_layout(
                                vec2(width, 0.0),
                                eframe::egui::Layout::top_down(Align::Min),
                                |ui| {
                                    ui.add_space(padding);
                                    ui.set_min_width(width);
                                    ui.set_max_width(width);
                                    let content = (width - padding * 2.0).max(8.0);
                                    self.path.push(cell_index);
                                    let was_detached = self.detached;
                                    self.detached |= copy > 0;
                                    self.blocks(ui, cell, content);
                                    self.detached = was_detached;
                                    self.path.pop();
                                    ui.add_space(padding);
                                },
                            )
                            .response
                            .rect;
                        painted.push((inner, properties));
                    }
                    column += 1;
                }
            }
        });

        let row_rect = response.response.rect;
        let mut shapes = Vec::new();
        for (rect, properties) in painted {
            let cell_rect = Rect::from_min_max(
                pos2(rect.left(), row_rect.top()),
                pos2(rect.right(), row_rect.bottom()),
            );
            if let Some(fill) = properties.cell.background {
                shapes.push(eframe::egui::Shape::rect_filled(
                    cell_rect,
                    0.0,
                    format::color32(fill),
                ));
            }
            for (edge, from, to) in edges(cell_rect) {
                if let Some(border) = edge_of(&properties.cell.border, edge) {
                    shapes.push(eframe::egui::Shape::line_segment(
                        [from, to],
                        Stroke::new(
                            (border.width.points() * self.zoom).max(1.0),
                            format::color32(border.color),
                        ),
                    ));
                }
            }
        }
        ui.painter().set(reserved, eframe::egui::Shape::Vec(shapes));
    }

    /// A frame: a box with a picture, a text box or an object in it.
    ///
    /// Public because a slide reaches it directly. Everywhere else a frame is
    /// found among a parent's children by [`Self::blocks`], but a shape on a
    /// slide *is* the frame, and asking `blocks` to draw it would look inside it
    /// for blocks and find a `draw:image`, which is not one.
    pub fn frame(&mut self, ui: &mut Ui, frame: &Element, width: f32) {
        let zoom = self.zoom;
        let declared = |local: &str| {
            frame
                .attr(&Ns::Svg, local)
                .and_then(odox_core::Length::parse)
                .map(|l| l.points() * zoom)
        };

        // A frame states its picture more than once where the producer had more
        // than one rendering of it — an SVG and then a PNG of the same drawing,
        // which is how the presentation templates carry their decorations — in
        // the producer's order of preference. The first one that decodes is the
        // answer, so a reader of two formats still draws a template that
        // prefers a third.
        let found = frame
            .elements()
            .filter(|child| child.is(&Ns::Draw, "image"))
            .find_map(|image| {
                let href = image.attr(&Ns::Xlink, "href")?.to_owned();
                self.pictures
                    .get(ui.ctx(), self.document, &href)
                    .map(|texture| (texture.id(), texture.size()))
            });
        if let Some((id, [pixels_wide, pixels_high])) = found {
            #[allow(clippy::cast_precision_loss)]
            let aspect = if pixels_wide == 0 {
                1.0
            } else {
                pixels_high as f32 / pixels_wide as f32
            };
            let w = declared("width").unwrap_or(width).min(width);
            let h = declared("height").unwrap_or(w * aspect);
            let size = vec2(w, h);
            ui.add(eframe::egui::Image::new((id, size)).fit_to_exact_size(size));
            return;
        }

        // A text box draws the blocks inside it; anything else — an embedded
        // object, a chart, a formula — is a box the size the document asked for,
        // so that the page does not silently lose the space it occupied.
        if let Some((box_index, box_)) = frame
            .elements_indexed()
            .find(|(_, e)| e.is(&Ns::Draw, "text-box"))
        {
            let w = declared("width").unwrap_or(width).min(width);
            ui.allocate_ui_with_layout(
                vec2(w, 0.0),
                eframe::egui::Layout::top_down(Align::Min),
                |ui| {
                    ui.set_max_width(w);
                    eframe::egui::Frame::group(ui.style()).show(ui, |ui| {
                        self.path.push(box_index);
                        self.blocks(ui, box_, w - 16.0 * zoom);
                        self.path.pop();
                    });
                },
            );
            return;
        }

        let w = declared("width").unwrap_or(width).min(width);
        let h = declared("height").unwrap_or(48.0 * zoom);
        let (rect, _) = ui.allocate_exact_size(vec2(w, h), Sense::hover());
        ui.painter().rect_stroke(
            rect,
            2.0,
            Stroke::new(1.0, self.palette.ink.gamma_multiply(0.3)),
            StrokeKind::Inside,
        );
    }

    /// Where the document says a page ended.
    ///
    /// Not a page: this view does not paginate, and drawing the break the
    /// producer recorded is how a reader sees that the document has them.
    fn page_break(&mut self, ui: &mut Ui, width: f32) {
        ui.add_space(8.0 * self.zoom);
        let (rect, _) = ui.allocate_exact_size(vec2(width, 1.0), Sense::hover());
        ui.painter().hline(
            rect.x_range(),
            rect.center().y,
            Stroke::new(1.0, self.palette.ink.gamma_multiply(0.3)),
        );
        ui.add_space(8.0 * self.zoom);
    }
}

/// Which edge of a cell a border belongs to.
#[derive(Clone, Copy)]
enum Edge {
    Left,
    Right,
    Top,
    Bottom,
}

fn edges(rect: Rect) -> [(Edge, Pos2, Pos2); 4] {
    [
        (Edge::Left, rect.left_top(), rect.left_bottom()),
        (Edge::Right, rect.right_top(), rect.right_bottom()),
        (Edge::Top, rect.left_top(), rect.right_top()),
        (Edge::Bottom, rect.left_bottom(), rect.right_bottom()),
    ]
}

fn edge_of(borders: &odox_core::Edges<Border>, edge: Edge) -> Option<Border> {
    match edge {
        Edge::Left => borders.left,
        Edge::Right => borders.right,
        Edge::Top => borders.top,
        Edge::Bottom => borders.bottom,
    }
}

fn paint_borders(ui: &Ui, rect: Rect, borders: &odox_core::Edges<Border>, zoom: f32) {
    for (edge, from, to) in edges(rect) {
        if let Some(border) = edge_of(borders, edge) {
            ui.painter().line_segment(
                [from, to],
                Stroke::new(
                    (border.width.points() * zoom).max(1.0),
                    format::color32(border.color),
                ),
            );
        }
    }
}

/// The width of each of a table's columns in screen points.
///
/// A column style usually gives one. Where none does, the available width is
/// divided evenly, which is what a producer that wrote no widths meant.
fn column_widths(document: &Document, table: &Element, width: f32, zoom: f32) -> Vec<f32> {
    let mut declared = Vec::new();
    collect_columns(document, table, &mut declared);
    if declared.is_empty() {
        return Vec::new();
    }
    let total: f32 = declared.iter().filter_map(|w| *w).sum();
    let unstated = declared.iter().filter(|w| w.is_none()).count();

    // A table wider than the space is scaled down rather than clipped, which is
    // what a reading view owes a document written for a wider page.
    let scaled = total * zoom;
    let factor = if scaled > width && scaled > 0.0 {
        width / scaled
    } else {
        1.0
    };
    #[allow(clippy::cast_precision_loss)]
    let share = if unstated == 0 {
        0.0
    } else {
        ((width - scaled * factor) / unstated as f32).max(16.0)
    };
    declared
        .into_iter()
        .map(|w| w.map_or(share, |points| points * zoom * factor))
        .collect()
}

fn collect_columns(document: &Document, parent: &Element, into: &mut Vec<Option<f32>>) {
    for element in parent.elements() {
        if element.is(&Ns::Table, "table-column") {
            let repeat = element
                .attr_usize(&Ns::Table, "number-columns-repeated")
                .unwrap_or(1)
                .clamp(1, 1024);
            let width = element
                .attr(&Ns::Table, "style-name")
                .map(|name| document.styles.resolve(&Family::TableColumn, name))
                .and_then(|p| p.column_width)
                .map(odox_core::Length::points);
            for _ in 0..repeat {
                into.push(width);
            }
        } else if element.is(&Ns::Table, "table-columns")
            || element.is(&Ns::Table, "table-header-columns")
            || element.is(&Ns::Table, "table-column-group")
        {
            collect_columns(document, element, into);
        }
    }
}

/// Tell assistive technology what a paragraph is: its text, and a heading's
/// level. Where the page editor draws the paragraph it has already said the
/// text and where the caret is, and only the role is put right.
fn expose(
    ui: &Ui,
    response: &Response,
    element: &Element,
    galley: &Galley,
    origin: Pos2,
    edited: bool,
) {
    let heading = edit::heading_level(element);
    if !edited {
        let to_global = ui
            .ctx()
            .layer_transform_to_global(ui.layer_id())
            .unwrap_or_default();
        update_accesskit_for_text_widget(
            ui.ctx(),
            response.id,
            None,
            if heading.is_some() {
                Role::Heading
            } else {
                Role::Paragraph
            },
            to_global * TSTransform::from_translation(origin.to_vec2()),
            galley,
        );
    }
    if let Some(level) = heading {
        ui.ctx().accesskit_node_builder(response.id, |node| {
            node.set_role(Role::Heading);
            node.set_level(usize::from(level));
        });
    }
}

/// Whether a paragraph is what an internal link names: a bookmark in it, by
/// name, or a heading by its text, which `LibreOffice` writes `Name|outline`.
fn holds_place(element: &Element, place: &str) -> bool {
    if let Some(name) = place.strip_suffix("|outline") {
        return element.is(&Ns::Text, "h") && element.plain_text().trim() == name.trim();
    }
    element.elements().any(|e| {
        let marks = e.is(&Ns::Text, "bookmark") || e.is(&Ns::Text, "bookmark-start");
        (marks && e.attr(&Ns::Text, "name") == Some(place)) || holds_place(e, place)
    })
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::{Flow, Pictures};
    use crate::format::{self, DEFAULT_SIZE};
    use odox_core::{Document, Element, Family, edit, media_type};

    const ANY: &[&str] = &[
        media_type::TEXT,
        media_type::TEXT_WEB,
        media_type::SPREADSHEET,
        media_type::PRESENTATION,
    ];

    fn documents(directory: &Path, into: &mut Vec<Document>) {
        let Ok(entries) = std::fs::read_dir(directory) else {
            return;
        };
        for path in entries.filter_map(Result::ok).map(|entry| entry.path()) {
            if path.is_dir() {
                documents(&path, into);
            } else if matches!(
                path.extension().and_then(|e| e.to_str()),
                Some("odt" | "ods" | "odp")
            ) {
                let bytes = std::fs::read(&path).expect("a corpus document reads");
                into.push(Document::read(&bytes, ANY).expect("a corpus document parses"));
            }
        }
    }

    fn paragraphs<'a>(element: &'a Element, into: &mut Vec<&'a Element>) {
        for child in element.elements() {
            if edit::is_paragraph(child) {
                into.push(child);
            }
            paragraphs(child, into);
        }
    }

    /// The caret is placed in what is drawn and an edit changes what the tree
    /// holds, so for every paragraph in the corpus the two have to agree on
    /// how many characters there are.
    #[test]
    fn what_is_drawn_maps_onto_the_text_an_edit_changes() {
        let mut corpus = Vec::new();
        documents(
            &Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"),
            &mut corpus,
        );
        assert!(!corpus.is_empty(), "the corpus is where it was");
        let mut checked = 0;
        for document in &corpus {
            let mut pictures = Pictures::default();
            let flow = Flow::new(document, &mut pictures, 1.0);
            let mut found = Vec::new();
            paragraphs(&document.content, &mut found);
            for paragraph in found {
                let properties = flow.style_of(paragraph, &Family::Paragraph);
                let base = format::text_format(&properties.text, DEFAULT_SIZE, 1.0, flow.palette);
                let size = format::size_of(&properties.text, DEFAULT_SIZE);
                let (job, _) = flow.layout_job(paragraph, &properties, &base, size, 400.0);
                let (_, map) = job.into_parts();
                let text = edit::text(paragraph);
                assert_eq!(map.model_len(), text.chars().count(), "{text:?}");
                checked += 1;
            }
        }
        assert!(checked > 0);
    }
}