1use crate::{
2 document::{DocumentEdit, descendants, edited_nodes, leaves},
3 layout::{InlineSpace, LayoutError, TextEngine, TextLayout},
4};
5use onestore::page::text::{Paragraph, TextProjection};
6use onestore::page::{Definition, Outline, PageParagraph, ParagraphContent, Table, Title};
7use onestore::{
8 ExGuid,
9 document::{Format, Kind},
10};
11use std::{
12 collections::{BTreeMap, BTreeSet},
13 ops::Range,
14 sync::Arc,
15};
16
17pub(crate) const TITLE_WIDTH: f32 = 468.0;
18
19#[derive(Clone, Default)]
20pub struct OutlineLayout {
21 pub paragraphs: Vec<ParagraphLayout>,
22 pub tables: Vec<TableLayout>,
23 /// Pictures, files and handwriting that occupy a paragraph of their own.
24 pub(crate) objects: Vec<ObjectLayout>,
25 pub size: [f32; 2],
26 /// One per root node, so an edit places anew only what it changes and moves what follows.
27 blocks: Vec<Block>,
28 /// The widest root node, at least 36 points, and the widest root text's line boxes; kept so
29 /// an edit sizes an automatic width without measuring every node.
30 pub(crate) widths: [f32; 2],
31}
32
33/// A root node's place in its outline's flow.
34#[derive(Clone)]
35struct Block {
36 /// Where the node's paragraphs, tables and objects start.
37 first: [usize; 3],
38 /// Spacing before and after the node and its own height, or `None` while hidden.
39 metrics: Option<[f32; 3]>,
40 /// The node's right edge and, for text, its line boxes' right edge.
41 extent: [f32; 2],
42 /// The flow's bottom and pending spacing after the node.
43 state: (f64, Option<f32>),
44 /// A table's vertical coordinates before its offset.
45 rel: Vec<f32>,
46 /// The number the next numbered sibling at the node's level continues from.
47 count: Option<Count>,
48}
49
50/// A layout of root nodes `range` once an edit applies, and how the nodes after them move.
51pub(crate) struct Relayout {
52 pub(crate) range: Range<usize>,
53 pub(crate) segment: OutlineLayout,
54 /// Each following node's new top and flow state, up to the first that stays.
55 moved: Vec<(f32, (f64, Option<f32>))>,
56 pub(crate) size: [f32; 2],
57 widths: [f32; 2],
58}
59
60#[derive(Clone)]
61pub(crate) struct ObjectLayout {
62 /// The object's identity, which keys a picture's or file icon's decoded image.
63 pub(crate) id: ExGuid,
64 /// Where the picture, file icon, drawing or placeholder draws, outline-local.
65 pub(crate) rect: [f32; 4],
66 pub(crate) kind: ObjectKind,
67 /// Outline-local bottom of the whole object, label included.
68 pub(crate) bottom: f32,
69 pub(crate) tags: Option<BlockTags>,
70}
71
72/// The note tags of a table, picture or file, which OneNote centres on it in the tag column.
73#[derive(Clone)]
74pub(crate) struct BlockTags {
75 /// The paragraph holding the block.
76 pub(crate) paragraph: ExGuid,
77 /// Its siblings' group, whose list markers the tags clear.
78 parent: Option<ExGuid>,
79 /// The block's left edge, outline-local.
80 x: f32,
81 /// Origins are outline-local.
82 pub(crate) tags: Vec<ParagraphTag>,
83}
84
85impl BlockTags {
86 /// `node`'s tags and those of its content, `content`, shaped as a tagged paragraph of
87 /// `node`'s format would show them; `None` without any.
88 fn new(
89 node: &PageParagraph,
90 content: &[onestore::document::Tag],
91 x: f32,
92 shape: &mut impl FnMut(
93 &PageParagraph,
94 Option<&Count>,
95 f32,
96 &[f32],
97 ) -> Result<ParagraphLayout, LayoutError>,
98 ) -> Result<Option<Self>, LayoutError> {
99 if node.tags.is_empty() && content.is_empty() {
100 return Ok(None);
101 }
102 let mut tagged = caption(node.id, node.id, "", node.format.clone());
103 tagged.tags.clone_from(&node.tags);
104 if let ParagraphContent::Text(text) = &mut tagged.content {
105 text.tags = content.to_vec();
106 }
107 let tags = shape(&tagged, None, ATTACHMENT_WIDTH, &[0.0, 0.0])?.tags;
108 Ok(Some(Self {
109 paragraph: node.id,
110 parent: node.parent,
111 x,
112 tags,
113 }))
114 }
115
116 /// Centres the tags on a block spanning `top..bottom`.
117 fn centre(&mut self, top: f32, bottom: f32) {
118 for tag in &mut self.tags {
119 tag.origin[1] = (top + bottom - tag.size) / 2.0;
120 }
121 }
122
123 fn offset(&mut self, [x, y]: [f32; 2]) {
124 self.x += x;
125 for tag in &mut self.tags {
126 tag.origin[0] += x;
127 tag.origin[1] += y;
128 }
129 }
130}
131
132#[derive(Clone)]
133pub(crate) enum ObjectKind {
134 Picture,
135 /// A file's icon with its name centered below.
136 File(ParagraphLayout),
137 /// Handwriting, whose strokes are relative to the rect's top-left.
138 Ink(onestore::page::Ink),
139 /// Content the canvas cannot draw, marked by a labelled box.
140 Unsupported(ParagraphLayout),
141}
142
143impl ObjectLayout {
144 pub(crate) fn label(&self) -> Option<&ParagraphLayout> {
145 match &self.kind {
146 ObjectKind::File(label) | ObjectKind::Unsupported(label) => Some(label),
147 ObjectKind::Picture | ObjectKind::Ink(_) => None,
148 }
149 }
150
151 /// The whole object, a file's column with its name included.
152 pub fn bounds(&self) -> [f32; 4] {
153 match &self.kind {
154 ObjectKind::File(label) => [
155 label.origin[0],
156 self.rect[1] - 6.0,
157 label.origin[0] + ATTACHMENT_WIDTH,
158 self.bottom,
159 ],
160 _ => [self.rect[0], self.rect[1], self.rect[2], self.bottom],
161 }
162 }
163
164 /// The rect's top and bottom, the object's bottom and its label's top once the object
165 /// starts at `y`, given its own height, and the height it takes in the flow.
166 fn at(&self, y: f32, height: f32) -> ([f32; 4], f32) {
167 match &self.kind {
168 ObjectKind::File(label) => {
169 let top = y + 6.0;
170 let label_top = top + height + 10.5;
171 let bottom = label_top + label.text.height() + 9.0;
172 ([top, top + height, bottom, label_top], bottom - y)
173 }
174 ObjectKind::Unsupported(_) => ([y, y + height, y + height, y + 8.0], height),
175 ObjectKind::Picture | ObjectKind::Ink(_) => ([y, y + height, y + height, 0.0], height),
176 }
177 }
178
179 fn place(&mut self, y: f32, height: f32) -> f32 {
180 let ([top, end, bottom, label_top], flow) = self.at(y, height);
181 [self.rect[1], self.rect[3], self.bottom] = [top, end, bottom];
182 if let ObjectKind::File(label) | ObjectKind::Unsupported(label) = &mut self.kind {
183 label.origin[1] = label_top;
184 }
185 let [_, top, _, bottom] = self.bounds();
186 if let Some(tags) = &mut self.tags {
187 tags.centre(top, bottom);
188 }
189 flow
190 }
191}
192
193/// The vertical coordinates of these pieces, in a fixed order.
194fn verticals<'a>(
195 paragraphs: &'a mut [ParagraphLayout],
196 tables: &'a mut [TableLayout],
197 objects: &'a mut [ObjectLayout],
198) -> impl Iterator<Item = &'a mut f32> {
199 let tags = |tags: &'a mut Option<BlockTags>| {
200 tags.iter_mut()
201 .flat_map(|tags| &mut tags.tags)
202 .map(|tag| &mut tag.origin[1])
203 };
204 paragraphs
205 .iter_mut()
206 .map(|paragraph| &mut paragraph.origin[1])
207 .chain(tables.iter_mut().flat_map(move |table| {
208 let cells = table.cells.iter_mut().flat_map(|cell| {
209 let [_, top, _, bottom] = &mut cell.rect;
210 [top, bottom]
211 });
212 cells.chain(tags(&mut table.tags))
213 }))
214 .chain(objects.iter_mut().flat_map(move |object| {
215 let ObjectLayout {
216 rect: [_, top, _, end],
217 bottom,
218 kind,
219 tags: block,
220 ..
221 } = object;
222 let label = match kind {
223 ObjectKind::File(label) | ObjectKind::Unsupported(label) => {
224 Some(&mut label.origin[1])
225 }
226 ObjectKind::Picture | ObjectKind::Ink(_) => None,
227 };
228 [top, end, bottom]
229 .into_iter()
230 .chain(label)
231 .chain(tags(block))
232 }))
233}
234
235/// OneNote centers a file's icon and name in a column this wide.
236const ATTACHMENT_WIDTH: f32 = 54.0;
237/// The grey OneNote gives secondary text such as the page date (its `PageDateTime` style).
238const PLACEHOLDER: u32 = 0x0080_8080;
239
240#[derive(Clone)]
241pub struct TableLayout {
242 pub id: ExGuid,
243 /// Cells are in paragraph order with disjoint visible ranges.
244 pub cells: Vec<CellLayout>,
245 pub borders: bool,
246 pub(crate) tags: Option<BlockTags>,
247}
248
249#[derive(Clone)]
250pub struct CellLayout {
251 pub id: ExGuid,
252 pub rect: [f32; 4],
253 /// Visible paragraph indices, including paragraphs in nested tables.
254 pub(crate) paragraphs: std::ops::Range<usize>,
255}
256
257impl CellLayout {
258 /// Native ink gutters extend beyond the cell borders.
259 pub(crate) fn text_bounds(&self) -> [f32; 4] {
260 [
261 self.rect[0] - 2.7,
262 self.rect[1],
263 self.rect[2] + 4.62,
264 self.rect[3],
265 ]
266 }
267
268 pub(crate) fn clip(&self, rect: parley::BoundingBox) -> Option<parley::BoundingBox> {
269 let [left, top, right, bottom] = self.text_bounds().map(f64::from);
270 let rect = parley::BoundingBox::new(
271 rect.x0.max(left),
272 rect.y0.max(top),
273 rect.x1.min(right),
274 rect.y1.min(bottom),
275 );
276 (rect.width() > 0.0 && rect.height() > 0.0).then_some(rect)
277 }
278}
279
280#[derive(Clone)]
281pub struct ParagraphLayout {
282 pub id: ExGuid,
283 pub origin: [f32; 2],
284 pub projection: TextProjection,
285 pub text: TextLayout,
286 /// Marker x is outline-local; y is paragraph-local so reflow cannot accumulate rounding drift.
287 pub markers: Vec<(TextLayout, [f32; 2])>,
288 /// A numbered paragraph's number, and whether its list restarts the count instead of
289 /// continuing from the previous sibling's.
290 pub(crate) number: Option<(Count, bool)>,
291 pub tags: Vec<ParagraphTag>,
292 /// Its siblings' group, whose list markers its tags clear: the parent paragraph, or the
293 /// table cell holding a cell's top-level paragraph.
294 pub(crate) parent: Option<ExGuid>,
295 /// The equations drawn in two dimensions in spaces of the text, in order.
296 pub math: Vec<crate::math::MathLayout>,
297 /// A highlight of the whole paragraph (its own `highlight`), COLORREF: a band across its
298 /// outline behind its lines, as OneNote marks a conflict page's conflicting changes.
299 pub(crate) band: Option<u32>,
300 /// The font colour and highlight its tags give every run, COLORREF.
301 pub(crate) tag_paint: [Option<u32>; 2],
302}
303
304/// How the page draws a note tag.
305#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
306pub enum TagIcon {
307 /// Symbol `shape` of MS-ONE's NoteTagShape, `checked` only where it is a check box.
308 Symbol { shape: u16, checked: bool },
309 /// An Outlook task, drawn with its stored follow-up flag and never checked from the page.
310 Task { shape: u16 },
311}
312
313impl TagIcon {
314 /// How the page draws tag symbol `shape`, `checked` where it is a check box; none for
315 /// shape 0, which marks the text instead.
316 pub fn of(shape: u16, checked: bool) -> Option<Self> {
317 (shape != 0).then_some(Self::Symbol {
318 shape,
319 checked: checked && checkable(shape),
320 })
321 }
322
323 pub(crate) fn checkable(self) -> bool {
324 matches!(self, Self::Symbol { shape, .. } if checkable(shape))
325 }
326}
327
328/// Whether tag symbol `shape` is a check box, as MS-ONE's NoteTagShape marks them.
329pub fn checkable(shape: u16) -> bool {
330 matches!(
331 shape,
332 1..=12 | 28 | 30 | 32 | 48 | 50 | 52 | 69 | 71 | 73 | 89..=99
333 )
334}
335
336/// OneNote 2010's name for tag symbol `shape`, as its symbol gallery's tooltips give it; the
337/// follow-up flags it keeps for Outlook tasks take MS-ONE's descriptions.
338pub fn symbol_name(shape: u16) -> Option<&'static str> {
339 SYMBOL_NAMES
340 .get(usize::from(shape).checked_sub(1)?)
341 .copied()
342}
343
344const SYMBOL_NAMES: [&str; 143] = [
345 "Green Check Box",
346 "Yellow Check Box",
347 "Blue Check Box",
348 "Green Star Check Box",
349 "Yellow Star Check Box",
350 "Blue Star Check Box",
351 "Green Exclamation Check Box",
352 "Yellow Exclamation Check Box",
353 "Blue Exclamation Check Box",
354 "Green Arrow Check Box",
355 "Yellow Arrow Check Box",
356 "Blue Arrow Check Box",
357 "Yellow Star",
358 "Follow-up Flag",
359 "Question",
360 "Blue Right Arrow",
361 "High Priority",
362 "Telephone",
363 "Calendar",
364 "Clock",
365 "Light Bulb",
366 "Pushpin",
367 "Home",
368 "Comment",
369 "Smiley",
370 "Award Ribbon",
371 "Key",
372 "Blue Check Box 1",
373 "Blue Circle 1",
374 "Blue Check Box 2",
375 "Blue Circle 2",
376 "Blue Check Box 3",
377 "Blue Circle 3",
378 "Blue 8-Point Star",
379 "Blue Check Mark",
380 "Blue Circle",
381 "Blue Down Arrow",
382 "Blue Left Arrow",
383 "Blue Solid Target",
384 "Blue Star",
385 "Blue Sun",
386 "Blue Target",
387 "Blue Triangle",
388 "Blue Umbrella",
389 "Blue Up Arrow",
390 "Blue X with Dots",
391 "Blue X",
392 "Green Check Box 1",
393 "Green Circle 1",
394 "Green Check Box 2",
395 "Green Circle 2",
396 "Green Check Box 3",
397 "Green Circle 3",
398 "Green 8-Point Star",
399 "Green Check Mark",
400 "Green Circle",
401 "Green Down Arrow",
402 "Green Left Arrow",
403 "Green Right Arrow",
404 "Green Solid Target",
405 "Green Star",
406 "Green Sun",
407 "Green Target",
408 "Green Triangle",
409 "Green Umbrella",
410 "Green Up Arrow",
411 "Green X with Dots",
412 "Green X",
413 "Yellow Check Box 1",
414 "Yellow Circle 1",
415 "Yellow Check Box 2",
416 "Yellow Circle 2",
417 "Yellow Check Box 3",
418 "Yellow Circle 3",
419 "Yellow 8-Point Star",
420 "Yellow Check Mark",
421 "Yellow Circle",
422 "Yellow Down Arrow",
423 "Yellow Left Arrow",
424 "Yellow Right Arrow",
425 "Yellow Solid Target",
426 "Yellow Sun",
427 "Yellow Target",
428 "Yellow Triangle",
429 "Yellow Umbrella",
430 "Yellow Up Arrow",
431 "Yellow X with Dots",
432 "Yellow X",
433 "Follow Up Today Flag",
434 "Follow Up Tomorrow Flag",
435 "Follow Up This Week Flag",
436 "Follow Up Next Week Flag",
437 "No Follow Up Date Flag",
438 "To Do Blue Person",
439 "To Do Yellow Person",
440 "To Do Green Person",
441 "To Do Blue Flag",
442 "To Do Yellow Flag",
443 "To Do Green Flag",
444 "Red Square (Project A)",
445 "Yellow Square (Project B)",
446 "Blue Square (Project C)",
447 "Green Square",
448 "Orange Square",
449 "Pink Square",
450 "E-mail",
451 "Envelope (Closed)",
452 "Envelope (Opened)",
453 "Mobile phone",
454 "Telephone with Clock",
455 "Question Balloon",
456 "Paperclip",
457 "Frowning",
458 "IM contact",
459 "Person",
460 "Two People",
461 "Reminder Bell",
462 "Contact (like Outlook's)",
463 "Flowers Bouquet",
464 "Date",
465 "Music Note",
466 "Movie Clip",
467 "Quote Mark",
468 "Globe",
469 "Link Globe",
470 "Laptop",
471 "Plane",
472 "Car",
473 "Binoculars",
474 "Presentation",
475 "Padlock",
476 "Book (Open)",
477 "Notebook Icon",
478 "Paper (blank with lines)",
479 "Research Icon",
480 "Marker",
481 "Dollar sign $",
482 "Coins with window behind it",
483 "Schedule Task",
484 "Lighting Bolt",
485 "Cloud",
486 "Heart",
487 "Flower",
488];
489
490#[derive(Clone, Debug, PartialEq)]
491pub struct ParagraphTag {
492 pub icon: TagIcon,
493 /// Coordinates are outline-local in x and paragraph-local in y.
494 pub origin: [f32; 2],
495 /// The icon's side, which follows its paragraph's first run.
496 pub size: f32,
497 pub label: String,
498 pub disabled: bool,
499}
500
501impl ParagraphTag {
502 /// The icon's side beside 10 to 17.5 pt text.
503 pub(crate) const SIZE: f32 = 12.0;
504 /// How far a 12 pt icon starts left of its text when no sibling has a list marker.
505 pub(crate) const INSET: f32 = 20.25;
506 /// Space between a tag and the leftmost list marker among its paragraph's siblings.
507 const MARKER_GAP: f32 = 0.9;
508
509 /// Where an icon of `side` starts below its paragraph's top, for a first line whose
510 /// baseline is `baseline` below it and a first run of `size` points: OneNote 2010 centres
511 /// it 0.357 of the run's size, less 0.2 pt, above the baseline (within 0.75 pt, 8 to 60 pt).
512 fn top(baseline: f32, size: f32, side: f32) -> f32 {
513 baseline - 0.357 * size + 0.2 - side / 2.0
514 }
515
516 /// OneNote 2010's icon side for text of `size` points.
517 fn side(size: f32) -> f32 {
518 match size {
519 24.0.. => 24.0,
520 18.0.. => 18.0,
521 10.0.. => Self::SIZE,
522 _ => 9.0,
523 }
524 }
525
526 /// Where a one-tag column of `side` starts for text at `x` among siblings whose leftmost
527 /// list marker starts at `marker`; its right edge stays put as the icon grows.
528 fn column(x: f32, marker: Option<f32>, side: f32) -> f32 {
529 let right = x - Self::INSET + Self::SIZE;
530 marker.map_or(right, |marker| right.min(marker - Self::MARKER_GAP)) - side
531 }
532}
533
534/// How far a 12 pt icon starts left of a picture or file on the page, as OneNote 2010 draws
535/// one (`corpus/object-tags`).
536const PAGE_INSET: f32 = 24.75;
537
538/// The note tags of a picture or file on the page, whose bounds are `bounds`: oldest first in
539/// a column ending left of it, centred on it; a tag whose definition is missing draws nothing.
540pub(crate) fn object_tags(
541 tags: &[onestore::document::Tag],
542 definitions: &BTreeMap<ExGuid, Definition>,
543 [x, top, _, bottom]: [f32; 4],
544) -> Vec<ParagraphTag> {
545 let side = ParagraphTag::side(crate::layout::DEFAULT_FONT_SIZE);
546 let mut drawn: Vec<ParagraphTag> = tags
547 .iter()
548 .rev()
549 .filter_map(|tag| {
550 let (icon, label) = if tag.status & 4 != 0 {
551 let shape = tag.shape.unwrap_or(0);
552 (TagIcon::Task { shape }, None)
553 } else {
554 let Kind::TagDefinition { shape, label, .. } =
555 &definitions.get(tag.definition.as_ref()?)?.kind
556 else {
557 return None;
558 };
559 let checked = tag.status & 1 != 0;
560 (TagIcon::of(shape.unwrap_or(0), checked)?, label.as_deref())
561 };
562 Some(ParagraphTag {
563 icon,
564 origin: [0.0, (top + bottom - side) / 2.0],
565 size: side,
566 label: label.unwrap_or_default().to_owned(),
567 disabled: tag.status & 2 != 0,
568 })
569 })
570 .collect();
571 let right = x - PAGE_INSET + ParagraphTag::SIZE;
572 let count = drawn.len() as f32;
573 for (index, tag) in drawn.iter_mut().enumerate() {
574 tag.origin[0] = right - side * (count - index as f32);
575 }
576 drawn
577}
578
579/// How much further than its list spacing OneNote 2010 sets a marker's advance from its text.
580const MARKER_OFFSET: f32 = 3.9;
581/// Points an equation's linear text lays out at, holding the caret without showing.
582const HELD: f32 = 0.01;
583
584/// A one-run paragraph standing in for an object's caption, so it lays out through the same
585/// shaping (and caching) as the outline's text.
586fn caption(id: ExGuid, text_id: ExGuid, text: &str, format: Format) -> PageParagraph {
587 PageParagraph {
588 id,
589 parent: None,
590 level: 1,
591 style: None,
592 format: Format::default(),
593 content: ParagraphContent::Text(onestore::page::TextObject {
594 id: text_id,
595 date_field: None,
596 text: Paragraph::new(text.into(), format),
597 tags: Vec::new(),
598 }),
599 lists: Vec::new(),
600 tags: Vec::new(),
601 media: Default::default(),
602 collapsed: false,
603 }
604}
605
606/// A file's column at `x`, before it is placed: its icon centred over its name, which OneNote
607/// shows without the extension; and the icon's height.
608fn file_column(
609 file: &onestore::page::Attachment,
610 paragraph: ExGuid,
611 format: &Format,
612 x: f32,
613 shape: &mut impl FnMut(
614 &PageParagraph,
615 Option<&Count>,
616 f32,
617 &[f32],
618 ) -> Result<ParagraphLayout, LayoutError>,
619) -> Result<(ObjectLayout, f32), LayoutError> {
620 let [w, h] = file.size.unwrap_or([24.0, 24.0]);
621 let left = x + (ATTACHMENT_WIDTH - w) / 2.0;
622 let name = std::path::Path::new(&file.filename)
623 .file_stem()
624 .and_then(|stem| stem.to_str())
625 .unwrap_or(&file.filename);
626 let format = Format {
627 alignment: Some(1),
628 ..format.clone()
629 };
630 let mut label = shape(
631 &caption(paragraph, file.id, name, format),
632 None,
633 ATTACHMENT_WIDTH,
634 &[0.0, 0.0],
635 )?;
636 label.reset_origin(x);
637 let object = ObjectLayout {
638 id: file.id,
639 rect: [left, 0.0, left + w, 0.0],
640 kind: ObjectKind::File(label),
641 bottom: 0.0,
642 tags: None,
643 };
644 Ok((object, h))
645}
646
647/// A file on the page as OneNote draws one, relative to its position: the column a
648/// paragraph's file takes, with its text in the page's default format.
649pub(crate) fn page_file(
650 engine: &mut TextEngine,
651 file: &onestore::page::Attachment,
652) -> Result<ObjectLayout, LayoutError> {
653 let (mut object, height) = file_column(
654 file,
655 file.id,
656 &Format::default(),
657 0.0,
658 &mut |paragraph, previous, width, indents| {
659 ParagraphLayout::shape(
660 engine,
661 paragraph,
662 previous,
663 width,
664 indents,
665 &BTreeMap::new(),
666 )
667 },
668 )?;
669 object.place(0.0, height);
670 Ok(object)
671}
672
673/// A picture's displayed size: the user-set layout size, else its intrinsic size.
674pub(crate) fn image_size(image: &onestore::page::Image) -> Option<[f32; 2]> {
675 let size = [
676 image.layout.max_width.or(image.size.map(|s| s[0]))?,
677 image.layout.max_height.or(image.size.map(|s| s[1]))?,
678 ];
679 size.iter()
680 .all(|v| v.is_finite() && *v > 0.0)
681 .then_some(size)
682}
683
684/// The step OneNote gives each level past the end of an indentation table.
685const MISSING_INDENT: f64 = 27.0;
686
687/// Text offset of `level` from its outline: entry `n` of `indents` steps level `n` in from
688/// level `n - 1`; entry 0 moves nothing OneNote 2010 draws, text nor markers.
689pub(crate) fn indentation(level: u32, indents: &[f32], width: f32) -> Result<f32, LayoutError> {
690 if indents.iter().any(|v| !v.is_finite() || *v < 0.0) || level == 0 {
691 return Err(LayoutError::InvalidIndentation);
692 }
693 let known = (level as usize).min(indents.len().saturating_sub(1));
694 let indent = (indents
695 .get(1..=known)
696 .unwrap_or_default()
697 .iter()
698 .map(|v| f64::from(*v))
699 .sum::<f64>()
700 + f64::from(level - known as u32) * MISSING_INDENT) as f32;
701 if !indent.is_finite() || indent >= width {
702 return Err(LayoutError::InvalidIndentation);
703 }
704 Ok(indent)
705}
706
707/// A numbered paragraph's number and its NumberListFormat.
708#[derive(Clone, Debug, PartialEq)]
709pub(crate) struct Count {
710 pub(crate) number: u32,
711 format: Arc<str>,
712}
713
714/// The number after a previous sibling's in the same `format`, or the first. A number in
715/// another format starts again at 1 even where one in this format came before it; siblings
716/// without a number leave the count alone (`evidence/toolbar-17/restart.txt`).
717fn next(previous: Option<&Count>, format: &str) -> u32 {
718 previous
719 .filter(|count| &*count.format == format)
720 .map_or(1, |count| count.number.saturating_add(1))
721}
722
723/// The number a paragraph laid out as `number` takes once it follows `previous`.
724fn follows(number: Option<&(Count, bool)>, previous: Option<&Count>) -> Option<Count> {
725 number.map(|(count, restart)| Count {
726 number: if *restart {
727 count.number
728 } else {
729 next(previous, &count.format)
730 },
731 format: count.format.clone(),
732 })
733}
734
735/// What the numbered sibling after `node`, numbered `number`, continues from: siblings without
736/// a number leave the count alone, as do empty numbered ones after another number
737/// (`evidence/structural-edits/xml/c8-bs-1.xml`, `c8-enter-empty-1.xml`, `c2s-num-1.xml`).
738fn tally(node: &PageParagraph, number: Option<Count>, previous: Option<Count>) -> Option<Count> {
739 number
740 .filter(|_| {
741 previous.is_none() || node.text().is_some_and(|text| !text.text.text().is_empty())
742 })
743 .or(previous)
744}
745
746/// Removes deeper paragraphs' entries from a flow's `(level, count)` stack of the latest
747/// paragraph at each level, and the previous sibling's at `level`, returning that one's count.
748fn sibling(siblings: &mut Vec<(u32, Option<Count>)>, level: u32) -> Option<Count> {
749 while siblings.last().is_some_and(|(deeper, _)| *deeper > level) {
750 siblings.pop();
751 }
752 match siblings.last() {
753 Some((same, _)) if *same == level => siblings.pop().unwrap().1,
754 _ => None,
755 }
756}
757
758/// `text` in `font` as a Unicode font shows it. Windows' Symbol font is symbol-encoded, so
759/// its bytes map through the Adobe Symbol encoding (a bullet is `U+00B7` there); Wingdings'
760/// map into the private use area their symbol cmaps cover, which also keeps a shaper from
761/// dropping `U+00AD` as a soft hyphen.
762pub fn symbol_text(font: &str, text: &str) -> String {
763 /// The Adobe Symbol encoding from 0x20 and from 0xA0, after Unicode's `SYMBOL.TXT`.
764 const SYMBOL: [&str; 2] = [
765 " !∀#∃%&∋()∗+,−./0123456789:;<=>?≅ΑΒΧΔΕΦΓΗΙϑΚΛΜΝΟΠΘΡΣΤΥςΩΞΨΖ[∴]⊥_‾αβχδεφγηιϕκλμνοπθρστυϖωξψζ{|}∼",
766 "€ϒ′≤⁄∞ƒ♣♦♥♠↔←↑→↓°±″≥×∝∂•÷≠≡≈…⏐⎯↵ℵℑℜ℘⊗⊕∅∩∪⊃⊇⊄⊂⊆∈∉∠∇®©™∏√⋅¬∧∨⇔⇐⇑⇒⇓◊〈®©™∑⎛⎜⎝⎡⎢⎣⎧⎨⎩⎪\u{f8ff}〉∫⌠⎮⌡⎞⎟⎠⎤⎥⎦⎫⎬⎭",
767 ];
768 if font.eq_ignore_ascii_case("Symbol") {
769 text.chars()
770 .map(|c| {
771 let (range, from) = match u32::from(c) {
772 code @ 0x20..0x7f => (SYMBOL[0], code - 0x20),
773 code @ 0xa0..0xff => (SYMBOL[1], code - 0xa0),
774 _ => return c,
775 };
776 range.chars().nth(from as usize).unwrap_or(c)
777 })
778 .collect()
779 } else if font.to_ascii_lowercase().starts_with("wingdings") {
780 text.chars()
781 .map(|c| match u32::from(c) {
782 code @ 0x20..0x100 => char::from_u32(0xf000 + code).unwrap_or(c),
783 _ => c,
784 })
785 .collect()
786 } else {
787 text.to_owned()
788 }
789}
790
791/// The marker NumberListFormat `format` shows for `number`.
792pub fn numbered(format: &str, number: u32) -> Result<String, LayoutError> {
793 let (prefix, rest) = format
794 .split_once('\u{fffd}')
795 .ok_or(LayoutError::InvalidList)?;
796 let mut rest = rest.chars();
797 Ok(format!(
798 "{prefix}{}{}",
799 numeral(rest.next(), number)?,
800 rest.as_str()
801 ))
802}
803
804/// `number` in a list numbering sequence: 0 arabic, 1 and 2 upper and lower roman, 3 and 4
805/// upper and lower letters, 5 ordinal, 6 and 7 cardinal and ordinal words, 22 arabic of two
806/// digits at least, as OneNote 2010's `numberSequence` spells them in English
807/// (`evidence/toolbar-17/sequences.txt`).
808pub(crate) fn numeral(sequence: Option<char>, number: u32) -> Result<String, LayoutError> {
809 let roman = |number: u32| {
810 const DIGITS: [(u32, &str); 13] = [
811 (1000, "M"),
812 (900, "CM"),
813 (500, "D"),
814 (400, "CD"),
815 (100, "C"),
816 (90, "XC"),
817 (50, "L"),
818 (40, "XL"),
819 (10, "X"),
820 (9, "IX"),
821 (5, "V"),
822 (4, "IV"),
823 (1, "I"),
824 ];
825 // Past 3999 the thousands run on as Ms; a million, far past what was observed,
826 // would lay out a thousand of them.
827 if !(1..1_000_000).contains(&number) {
828 return Err(LayoutError::UnsupportedContent);
829 }
830 let mut rest = number;
831 let mut text = String::new();
832 for (value, digits) in DIGITS {
833 while rest >= value {
834 text.push_str(digits);
835 rest -= value;
836 }
837 }
838 Ok(text)
839 };
840 // Past Z a letter repeats, AA to ZZ, up to thirty times, then starts over at A.
841 let letter = |number: u32| {
842 let index = number
843 .checked_sub(1)
844 .ok_or(LayoutError::UnsupportedContent)?;
845 let letter = char::from(b'A' + (index % 26) as u8);
846 Ok(std::iter::repeat_n(letter, (index / 26 % 30) as usize + 1).collect::<String>())
847 };
848 match sequence.map(u32::from) {
849 Some(0) => Ok(number.to_string()),
850 Some(22) => Ok(format!("{number:02}")),
851 Some(1) => roman(number),
852 Some(2) => roman(number).map(|text| text.to_lowercase()),
853 Some(3) => letter(number),
854 Some(4) => letter(number).map(|text| text.to_lowercase()),
855 Some(5) => {
856 let suffix = match (number % 10, number % 100) {
857 (_, 11..=13) => "th",
858 (1, _) => "st",
859 (2, _) => "nd",
860 (3, _) => "rd",
861 _ => "th",
862 };
863 Ok(format!("{number}{suffix}"))
864 }
865 Some(sequence @ (6 | 7)) => {
866 let mut words = cardinal(number)?;
867 if sequence == 7 {
868 // The last word turns ordinal: one to first, twenty to twentieth.
869 let at = words.rfind([' ', '-']).map_or(0, |at| at + 1);
870 let last = &words[at..];
871 let ordinal = match last {
872 "one" => "first".to_owned(),
873 "two" => "second".to_owned(),
874 "three" => "third".to_owned(),
875 "five" => "fifth".to_owned(),
876 "eight" => "eighth".to_owned(),
877 "nine" => "ninth".to_owned(),
878 "twelve" => "twelfth".to_owned(),
879 _ if last.ends_with('y') => format!("{}ieth", &last[..last.len() - 1]),
880 _ => format!("{last}th"),
881 };
882 words.replace_range(at.., &ordinal);
883 }
884 let mut chars = words.chars();
885 let first = chars.next().unwrap_or_default();
886 Ok(first.to_uppercase().chain(chars).collect())
887 }
888 _ => Err(LayoutError::UnsupportedContent),
889 }
890}
891
892/// `number` in lowercase English words, "one hundred twenty-one", below a million.
893fn cardinal(number: u32) -> Result<String, LayoutError> {
894 const SMALL: [&str; 20] = [
895 "zero",
896 "one",
897 "two",
898 "three",
899 "four",
900 "five",
901 "six",
902 "seven",
903 "eight",
904 "nine",
905 "ten",
906 "eleven",
907 "twelve",
908 "thirteen",
909 "fourteen",
910 "fifteen",
911 "sixteen",
912 "seventeen",
913 "eighteen",
914 "nineteen",
915 ];
916 const TENS: [&str; 10] = [
917 "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
918 ];
919 fn below_thousand(number: u32) -> String {
920 let (hundreds, rest) = (number / 100, number % 100);
921 let rest = match rest {
922 0 => None,
923 1..20 => Some(SMALL[rest as usize].to_owned()),
924 _ if rest % 10 == 0 => Some(TENS[(rest / 10) as usize].to_owned()),
925 _ => Some(format!(
926 "{}-{}",
927 TENS[(rest / 10) as usize],
928 SMALL[(rest % 10) as usize]
929 )),
930 };
931 match (hundreds, rest) {
932 (0, rest) => rest.unwrap_or_default(),
933 (hundreds, None) => format!("{} hundred", SMALL[hundreds as usize]),
934 (hundreds, Some(rest)) => format!("{} hundred {rest}", SMALL[hundreds as usize]),
935 }
936 }
937 match number {
938 1..1000 => Ok(below_thousand(number)),
939 1000..1_000_000 => {
940 let (thousands, rest) = (number / 1000, number % 1000);
941 let head = format!("{} thousand", below_thousand(thousands));
942 Ok(if rest == 0 {
943 head
944 } else {
945 format!("{head} {}", below_thousand(rest))
946 })
947 }
948 _ => Err(LayoutError::UnsupportedContent),
949 }
950}
951
952fn spacing(format: &Format) -> Result<[f32; 2], LayoutError> {
953 let spacing = [format.space_before, format.space_after].map(|space| space.unwrap_or(0.0));
954 if spacing.iter().any(|v| !v.is_finite() || *v < 0.0) {
955 return Err(LayoutError::InvalidSpacing);
956 }
957 Ok(spacing)
958}
959
960/// Where a node with `spacing` starts after the flow `state` of a bottom and pending spacing.
961fn top(state: &mut (f64, Option<f32>), [before, after]: [f32; 2]) -> f32 {
962 if let Some(previous) = state.1 {
963 state.0 += f64::from(previous.max(before));
964 }
965 state.1 = Some(after);
966 state.0 as f32
967}
968
969impl ParagraphLayout {
970 pub(crate) fn reset_origin(&mut self, x: f32) {
971 let offset = x - self.origin[0];
972 self.origin = [x, 0.0];
973 for (_, origin) in &mut self.markers {
974 origin[0] += offset;
975 }
976 for tag in &mut self.tags {
977 tag.origin[0] += offset;
978 }
979 }
980
981 fn size(&self) -> [f32; 2] {
982 [
983 self.origin[0] + self.text.shaped.width(),
984 self.markers
985 .iter()
986 .map(|(layout, _)| layout.height())
987 .fold(self.text.height(), f32::max),
988 ]
989 }
990
991 /// Lays out a text paragraph after a sibling numbered `previous`.
992 pub(crate) fn shape(
993 engine: &mut TextEngine,
994 paragraph: &PageParagraph,
995 previous: Option<&Count>,
996 width: f32,
997 indents: &[f32],
998 definitions: &BTreeMap<ExGuid, Definition>,
999 ) -> Result<Self, LayoutError> {
1000 if !width.is_finite() || width <= 0.0 {
1001 return Err(LayoutError::InvalidWidth);
1002 }
1003 let indent = indentation(paragraph.level, indents, width)?;
1004 let source = paragraph.text().ok_or(LayoutError::UnsupportedContent)?;
1005 let projection = source
1006 .text
1007 .project()
1008 .map_err(|_| LayoutError::InvalidSourceRange)?;
1009 let format = &projection.text().spans()[0].format;
1010 let spacing = format.list_spacing.unwrap_or(7.2);
1011 if !spacing.is_finite() || spacing < 0.0 {
1012 return Err(LayoutError::InvalidSpacing);
1013 }
1014 // Stored newest first; OneNote lists and paints tags oldest first.
1015 // An Outlook task tag carries no definition but its own icon; a tag whose definition
1016 // is missing shows nothing, as OneNote draws no icon for it.
1017 let mut tag_definitions: Vec<_> = paragraph
1018 .tags
1019 .iter()
1020 .chain(&source.tags)
1021 .filter_map(|tag| {
1022 if tag.status & 4 != 0 {
1023 return Some((tag, None, None, None, None));
1024 }
1025 match &definitions.get(tag.definition.as_ref()?)?.kind {
1026 Kind::TagDefinition {
1027 shape,
1028 label,
1029 color,
1030 highlight,
1031 ..
1032 } => Some((tag, Some(*shape), label.as_deref(), *color, *highlight)),
1033 _ => None,
1034 }
1035 })
1036 .collect();
1037 tag_definitions.reverse();
1038 // The newest tag that sets a colour wins.
1039 let color = tag_definitions.iter().rev().find_map(|tag| tag.3);
1040 let highlight = tag_definitions.iter().rev().find_map(|tag| tag.4);
1041 // Equations with objects draw in two dimensions in a space kept in their line; their
1042 // linear text stays in the text, too small to see, to hold the caret.
1043 let visible = projection.text();
1044 let mut equations = Vec::new();
1045 for zone in crate::math::built(visible) {
1046 let units = |byte| {
1047 visible
1048 .utf16_offset(byte)
1049 .map_err(|_| LayoutError::InvalidSourceRange)
1050 };
1051 let math = visible
1052 .slice(units(zone.start)?..units(zone.end)?)
1053 .map_err(|_| LayoutError::InvalidSourceRange)?;
1054 // An equation that does not parse shows its linear text.
1055 if let Ok(math) = crate::math::layout(engine, &math) {
1056 equations.push((zone, math));
1057 }
1058 }
1059 let spaces: Vec<_> = equations
1060 .iter()
1061 .map(|(zone, math)| InlineSpace {
1062 index: zone.start,
1063 width: math.size[0],
1064 ascent: math.baseline,
1065 descent: math.size[1] - math.baseline,
1066 })
1067 .collect();
1068 // URL text shows as a link, as OneNote links it on opening a page.
1069 let mut marks: Vec<(Range<usize>, bool)> = crate::editor::shown_urls(visible)
1070 .into_iter()
1071 .map(|url| (url, false))
1072 .chain(equations.iter().map(|(zone, _)| (zone.clone(), true)))
1073 .collect();
1074 marks.sort_by_key(|(range, _)| range.start);
1075 let mut text = if color.is_none() && highlight.is_none() && marks.is_empty() {
1076 engine.layout(visible, width - indent)?
1077 } else {
1078 let mut start = 0;
1079 let runs = visible.spans().iter().flat_map(|span| {
1080 let mut format = span.format.clone();
1081 format.color = color.or(format.color);
1082 format.highlight = highlight.or(format.highlight);
1083 let mut runs = Vec::new();
1084 let mut from = start;
1085 for (range, equation) in &marks {
1086 let (a, b) = (
1087 range.start.clamp(from, span.end),
1088 range.end.clamp(from, span.end),
1089 );
1090 if a < b {
1091 runs.push((visible.text()[from..a].to_owned(), format.clone()));
1092 let marked = if *equation {
1093 Format {
1094 font_size: Some(HELD),
1095 superscript: None,
1096 subscript: None,
1097 ..format.clone()
1098 }
1099 } else {
1100 Format {
1101 hyperlink: Some(true),
1102 ..format.clone()
1103 }
1104 };
1105 runs.push((visible.text()[a..b].to_owned(), marked));
1106 from = b;
1107 }
1108 }
1109 runs.push((visible.text()[from..span.end].to_owned(), format));
1110 start = span.end;
1111 runs
1112 });
1113 engine.layout_with(
1114 &Paragraph::from_runs(
1115 runs.filter(|(text, _)| !text.is_empty())
1116 .collect::<Vec<_>>(),
1117 ),
1118 width - indent,
1119 &spaces,
1120 )?
1121 };
1122 let mut markers = Vec::new();
1123 let mut marker_x = indent - MARKER_OFFSET;
1124 let mut number = None;
1125 for id in paragraph.lists.iter().rev() {
1126 let definition = definitions.get(id).ok_or(LayoutError::InvalidList)?;
1127 let Kind::List {
1128 font,
1129 format: Some(value),
1130 restart,
1131 ..
1132 } = &definition.kind
1133 else {
1134 return Err(LayoutError::InvalidList);
1135 };
1136 let mut color = definition.format.color;
1137 let value = if value.contains('\u{fffd}') {
1138 // An empty numbered paragraph shows its number as a gray placeholder.
1139 if source.text.text().is_empty() {
1140 color = Some(PLACEHOLDER);
1141 }
1142 let current = restart.unwrap_or(next(previous, value));
1143 let format = value.as_str().into();
1144 number = Some((
1145 Count {
1146 number: current,
1147 format,
1148 },
1149 restart.is_some(),
1150 ));
1151 numbered(value, current)?
1152 } else {
1153 value.clone()
1154 };
1155 if value.contains('\u{fffd}') {
1156 return Err(LayoutError::UnsupportedContent);
1157 }
1158 // Without a font of its own a marker takes its text's, as a number does.
1159 let font = font
1160 .clone()
1161 .or_else(|| definition.format.font.clone())
1162 .or_else(|| format.font.clone());
1163 let value = font
1164 .as_deref()
1165 .map_or(value.clone(), |font| symbol_text(font, &value));
1166 let marker = Paragraph::new(
1167 value,
1168 Format {
1169 font,
1170 font_size: definition.format.font_size.or(format.font_size),
1171 color,
1172 ..Format::default()
1173 },
1174 );
1175 let layout = engine.layout(&marker, width)?;
1176 if layout.lines().count() != 1 {
1177 return Err(LayoutError::InvalidList);
1178 }
1179 let (line, metrics) = layout.lines().next().unwrap();
1180 marker_x -= spacing + line.metrics().advance;
1181 if !marker_x.is_finite() {
1182 return Err(LayoutError::InvalidSpacing);
1183 }
1184 let y = text.lines().next().unwrap().1.baseline - metrics.baseline;
1185 markers.push((layout, [marker_x, y]));
1186 }
1187 text.minimum_line_height(format.line_spacing.unwrap_or(0.0))?;
1188 let baseline = text.lines().next().unwrap().1.baseline;
1189 let mut tags = Vec::new();
1190 for tag in &tag_definitions {
1191 let (tag, shape, label) = (tag.0, tag.1, tag.2);
1192 let icon = match shape {
1193 None => TagIcon::Task {
1194 shape: tag.shape.unwrap_or(0),
1195 },
1196 Some(shape) => match TagIcon::of(shape.unwrap_or(0), tag.status & 1 != 0) {
1197 Some(icon) => icon,
1198 None => continue,
1199 },
1200 };
1201 let size = format.font_size.unwrap_or(crate::layout::DEFAULT_FONT_SIZE);
1202 let side = ParagraphTag::side(size);
1203 tags.push(ParagraphTag {
1204 icon,
1205 origin: [0.0, ParagraphTag::top(baseline, size, side)],
1206 size: side,
1207 label: label.unwrap_or_default().to_owned(),
1208 disabled: tag.status & 2 != 0,
1209 });
1210 }
1211 let math = equations.into_iter().map(|(_, math)| math).collect();
1212 let mut result = Self {
1213 id: paragraph.id,
1214 origin: [indent, 0.0],
1215 projection,
1216 text,
1217 markers,
1218 number,
1219 tags,
1220 math,
1221 parent: paragraph.parent,
1222 band: paragraph.format.highlight,
1223 tag_paint: [color, highlight],
1224 };
1225 result.place_tags(result.marker_left());
1226 Ok(result)
1227 }
1228
1229 fn marker_left(&self) -> Option<f32> {
1230 self.markers.iter().map(|(_, [x, _])| *x).reduce(f32::min)
1231 }
1232
1233 fn place_tags(&mut self, marker: Option<f32>) {
1234 place_tags(&mut self.tags, self.origin[0], marker);
1235 }
1236}
1237
1238/// Places the tags of content at `x` among siblings whose leftmost marker starts at
1239/// `marker`; later tags follow the first to its right, toward the content.
1240fn place_tags(tags: &mut [ParagraphTag], x: f32, marker: Option<f32>) {
1241 for (index, tag) in tags.iter_mut().enumerate() {
1242 tag.origin[0] = ParagraphTag::column(x, marker, tag.size) + tag.size * index as f32;
1243 }
1244}
1245
1246pub(crate) fn visible_paragraphs<'a>(
1247 nodes: impl Iterator<Item = &'a PageParagraph>,
1248) -> impl Iterator<Item = &'a PageParagraph> {
1249 let mut hidden = BTreeSet::new();
1250 nodes.filter(move |paragraph| {
1251 let invisible = paragraph
1252 .parent
1253 .is_some_and(|parent| hidden.contains(&parent));
1254 if invisible || paragraph.collapsed {
1255 hidden.insert(paragraph.id);
1256 }
1257 !invisible
1258 })
1259}
1260
1261impl OutlineLayout {
1262 /// OneNote gives an outline one tag column, as wide as its most-tagged paragraph needs; each
1263 /// paragraph's tags start at the column's left edge. Tag origins assume a one-tag column.
1264 pub(crate) fn tag_column_offset(&self) -> f32 {
1265 -self
1266 .paragraphs
1267 .iter()
1268 .map(|p| p.tags.as_slice())
1269 .chain(self.block_tags().map(|block| block.tags.as_slice()))
1270 .map(|tags| tags.iter().skip(1).map(|tag| tag.size).sum::<f32>())
1271 .fold(0.0, f32::max)
1272 }
1273
1274 fn block_tags(&self) -> impl Iterator<Item = &BlockTags> {
1275 let tables = self.tables.iter().filter_map(|table| table.tags.as_ref());
1276 tables.chain(
1277 self.objects
1278 .iter()
1279 .filter_map(|object| object.tags.as_ref()),
1280 )
1281 }
1282
1283 /// Every note tag the outline draws, with the paragraph it marks and its outline-local
1284 /// origin before `tag_column_offset`.
1285 pub fn tags(&self) -> impl Iterator<Item = (ExGuid, [f32; 2], &ParagraphTag)> {
1286 let text = self.paragraphs.iter().flat_map(|paragraph| {
1287 paragraph.tags.iter().map(move |tag| {
1288 let y = paragraph.origin[1] + tag.origin[1];
1289 (paragraph.id, [tag.origin[0], y], tag)
1290 })
1291 });
1292 let blocks = self.block_tags().flat_map(|block| {
1293 block
1294 .tags
1295 .iter()
1296 .map(|tag| (block.paragraph, tag.origin, tag))
1297 });
1298 text.chain(blocks)
1299 }
1300
1301 /// Innermost table cell containing a visible paragraph index.
1302 pub(crate) fn paragraph_cell(&self, index: usize) -> Option<&CellLayout> {
1303 self.tables.iter().rev().find_map(|table| {
1304 let cell = table
1305 .cells
1306 .partition_point(|cell| cell.paragraphs.end <= index);
1307 table
1308 .cells
1309 .get(cell)
1310 .filter(|cell| cell.paragraphs.contains(&index))
1311 })
1312 }
1313
1314 fn append(&mut self, mut child: Self, origin: [f32; 2]) {
1315 for paragraph in &mut child.paragraphs {
1316 paragraph.origin[0] += origin[0];
1317 paragraph.origin[1] += origin[1];
1318 for (_, marker) in &mut paragraph.markers {
1319 marker[0] += origin[0];
1320 }
1321 for tag in &mut paragraph.tags {
1322 tag.origin[0] += origin[0];
1323 }
1324 }
1325 for table in &mut child.tables {
1326 for cell in &mut table.cells {
1327 cell.paragraphs.start += self.paragraphs.len();
1328 cell.paragraphs.end += self.paragraphs.len();
1329 for (value, offset) in cell.rect.iter_mut().zip(origin.into_iter().cycle()) {
1330 *value += offset;
1331 }
1332 }
1333 if let Some(tags) = &mut table.tags {
1334 tags.offset(origin);
1335 }
1336 }
1337 for object in &mut child.objects {
1338 for (value, offset) in object.rect.iter_mut().zip(origin.into_iter().cycle()) {
1339 *value += offset;
1340 }
1341 object.bottom += origin[1];
1342 if let Some(tags) = &mut object.tags {
1343 tags.offset(origin);
1344 }
1345 if let ObjectKind::File(label) | ObjectKind::Unsupported(label) = &mut object.kind {
1346 let y = label.origin[1];
1347 label.reset_origin(label.origin[0] + origin[0]);
1348 label.origin[1] = y + origin[1];
1349 }
1350 }
1351 self.paragraphs.extend(child.paragraphs);
1352 self.tables.extend(child.tables);
1353 self.objects.extend(child.objects);
1354 }
1355
1356 pub(crate) fn flow<'a>(
1357 nodes: impl Iterator<Item = &'a PageParagraph>,
1358 indents: &[f32],
1359 width: f32,
1360 fixed_width: bool,
1361 depth: usize,
1362 edit: Option<&DocumentEdit>,
1363 shape: &mut impl FnMut(
1364 &PageParagraph,
1365 Option<&Count>,
1366 f32,
1367 &[f32],
1368 ) -> Result<ParagraphLayout, LayoutError>,
1369 ) -> Result<Self, LayoutError> {
1370 let mut result = Self::stack(
1371 nodes,
1372 indents,
1373 width,
1374 depth,
1375 edit,
1376 BTreeSet::new(),
1377 (0.0, None),
1378 &mut Vec::new(),
1379 shape,
1380 )?;
1381 result.size[0] = if fixed_width { width } else { result.size[0] }.max(result.table_width());
1382 result.place_tags();
1383 Ok(result)
1384 }
1385
1386 /// Moves each paragraph's tags clear of the widest list marker among its siblings.
1387 fn place_tags(&mut self) {
1388 let mut markers = BTreeMap::<Option<ExGuid>, f32>::new();
1389 for paragraph in &self.paragraphs {
1390 if let Some(x) = paragraph.marker_left() {
1391 let left = markers.entry(paragraph.parent).or_insert(x);
1392 *left = left.min(x);
1393 }
1394 }
1395 for paragraph in &mut self.paragraphs {
1396 let marker = markers.get(&paragraph.parent).copied();
1397 paragraph.place_tags(marker);
1398 }
1399 let tables = self
1400 .tables
1401 .iter_mut()
1402 .filter_map(|table| table.tags.as_mut());
1403 let objects = self
1404 .objects
1405 .iter_mut()
1406 .filter_map(|object| object.tags.as_mut());
1407 for block in tables.chain(objects) {
1408 place_tags(
1409 &mut block.tags,
1410 block.x,
1411 markers.get(&block.parent).copied(),
1412 );
1413 }
1414 }
1415
1416 /// Lays out `nodes` after the flow `state` and `siblings` stack, hiding the children of
1417 /// `hiding`; at the root, keeps a block for each node.
1418 #[allow(clippy::too_many_arguments)]
1419 fn stack<'a>(
1420 nodes: impl Iterator<Item = &'a PageParagraph>,
1421 indents: &[f32],
1422 width: f32,
1423 depth: usize,
1424 edit: Option<&DocumentEdit>,
1425 mut hiding: BTreeSet<ExGuid>,
1426 mut state: (f64, Option<f32>),
1427 siblings: &mut Vec<(u32, Option<Count>)>,
1428 shape: &mut impl FnMut(
1429 &PageParagraph,
1430 Option<&Count>,
1431 f32,
1432 &[f32],
1433 ) -> Result<ParagraphLayout, LayoutError>,
1434 ) -> Result<Self, LayoutError> {
1435 if !width.is_finite() || width <= 0.0 {
1436 return Err(LayoutError::InvalidWidth);
1437 }
1438 if depth > 64 {
1439 return Err(LayoutError::UnsupportedContent);
1440 }
1441 let mut result = Self {
1442 size: [36.0, 0.0],
1443 widths: [36.0, f32::NEG_INFINITY],
1444 ..Self::default()
1445 };
1446 for node in nodes {
1447 let hidden = node.parent.is_some_and(|parent| hiding.contains(&parent));
1448 if hidden || node.collapsed {
1449 hiding.insert(node.id);
1450 }
1451 let previous = sibling(siblings, node.level);
1452 let mut number = None;
1453 let mut block = Block {
1454 first: [
1455 result.paragraphs.len(),
1456 result.tables.len(),
1457 result.objects.len(),
1458 ],
1459 metrics: None,
1460 extent: [f32::NEG_INFINITY; 2],
1461 state,
1462 rel: Vec::new(),
1463 count: None,
1464 };
1465 if !hidden {
1466 let (space, height, flow, extent) = match &node.content {
1467 ParagraphContent::Text(_) => {
1468 let mut paragraph = shape(node, previous.as_ref(), width, indents)?;
1469 number = paragraph.number.clone().map(|(count, _)| count);
1470 let space = spacing(&paragraph.projection.text().spans()[0].format)?;
1471 paragraph.origin[1] = top(&mut state, space);
1472 let size = paragraph.size();
1473 block.extent[1] = paragraph.origin[0] + paragraph.text.shaped.width();
1474 result.paragraphs.push(paragraph);
1475 (space, size[1], size[1], size[0])
1476 }
1477 ParagraphContent::Table(table) => {
1478 let x = indentation(node.level, indents, width)?;
1479 let space = spacing(&node.format)?;
1480 let y = top(&mut state, space);
1481 let mut child = Self::table(table, depth + 1, edit, shape)?;
1482 child.tables[0].tags =
1483 BlockTags::new(node, &table.tags, 0.0, shape)?.map(|mut tags| {
1484 tags.centre(0.0, child.size[1]);
1485 tags
1486 });
1487 if depth == 0 {
1488 block.rel = verticals(
1489 &mut child.paragraphs,
1490 &mut child.tables,
1491 &mut child.objects,
1492 )
1493 .map(|value| *value)
1494 .collect();
1495 }
1496 let size = child.size;
1497 result.append(child, [x, y]);
1498 (space, size[1], size[1], x + size[0])
1499 }
1500 content => {
1501 let x = indentation(node.level, indents, width)?;
1502 let space = spacing(&node.format)?;
1503 let y = top(&mut state, space);
1504 let (mut object, height, extent) = match content {
1505 ParagraphContent::Image(image) => {
1506 let [w, h] =
1507 image_size(image).ok_or(LayoutError::UnsupportedContent)?;
1508 let object = ObjectLayout {
1509 id: image.id,
1510 rect: [x, 0.0, x + w, 0.0],
1511 kind: ObjectKind::Picture,
1512 bottom: 0.0,
1513 tags: None,
1514 };
1515 (object, h, x + w)
1516 }
1517 ParagraphContent::Attachment(file) => {
1518 let (object, h) =
1519 file_column(file, node.id, &node.format, x, shape)?;
1520 (object, h, x + ATTACHMENT_WIDTH)
1521 }
1522 ParagraphContent::Ink(ink) => {
1523 // The paragraph reaches from its origin to the farthest stroke point.
1524 let [w, h] = ink
1525 .bounds()
1526 .map(|[x, y, w, h]| [x + w, y + h])
1527 .filter(|size| size.iter().all(|v| v.is_finite() && *v >= 0.0))
1528 .ok_or(LayoutError::UnsupportedContent)?;
1529 let object = ObjectLayout {
1530 id: ink.id,
1531 rect: [x, 0.0, x + w, 0.0],
1532 kind: ObjectKind::Ink(ink.clone()),
1533 bottom: 0.0,
1534 tags: None,
1535 };
1536 (object, h, x + w)
1537 }
1538 ParagraphContent::Unsupported(unsupported) => {
1539 let w = unsupported.layout.max_width.unwrap_or(160.0).max(160.0);
1540 let mut label = shape(
1541 &caption(
1542 node.id,
1543 unsupported.id,
1544 "Unsupported content",
1545 Format::default(),
1546 ),
1547 None,
1548 w - 16.0,
1549 &[0.0, 0.0],
1550 )?;
1551 label.reset_origin(x + 8.0);
1552 let h = unsupported
1553 .layout
1554 .max_height
1555 .unwrap_or(0.0)
1556 .max(label.text.height() + 16.0);
1557 let object = ObjectLayout {
1558 id: unsupported.id,
1559 rect: [x, 0.0, x + w, 0.0],
1560 kind: ObjectKind::Unsupported(label),
1561 bottom: 0.0,
1562 tags: None,
1563 };
1564 (object, h, x + w)
1565 }
1566 ParagraphContent::Text(_) | ParagraphContent::Table(_) => {
1567 unreachable!("text and tables are not objects")
1568 }
1569 };
1570 let tags = match content {
1571 ParagraphContent::Image(image) => image.tags.as_slice(),
1572 ParagraphContent::Attachment(file) => file.tags.as_slice(),
1573 _ => &[],
1574 };
1575 object.tags = BlockTags::new(node, tags, x, shape)?;
1576 let flow = object.place(y, height);
1577 result.objects.push(object);
1578 (space, height, flow, extent)
1579 }
1580 };
1581 state.0 += f64::from(flow);
1582 result.size[0] = result.size[0].max(extent);
1583 result.widths[1] = result.widths[1].max(block.extent[1]);
1584 block.extent[0] = extent;
1585 block.metrics = Some([space[0], space[1], height]);
1586 if !(state.0 as f32).is_finite() || !result.size[0].is_finite() {
1587 return Err(LayoutError::InvalidSpacing);
1588 }
1589 }
1590 block.count = tally(node, number, previous);
1591 siblings.push((node.level, block.count.clone()));
1592 block.state = state;
1593 if depth == 0 {
1594 result.blocks.push(block);
1595 }
1596 }
1597 result.size[1] = state.0 as f32;
1598 result.widths[0] = result.size[0];
1599 Ok(result)
1600 }
1601
1602 /// Root node `root`'s number, when it is numbered text on show.
1603 fn number(&self, nodes: &[PageParagraph], root: usize) -> Option<&(Count, bool)> {
1604 let block = &self.blocks[root];
1605 (block.metrics.is_some() && nodes[root].text().is_some())
1606 .then(|| self.paragraphs[block.first[0]].number.as_ref())
1607 .flatten()
1608 }
1609
1610 /// Where each root node's flow starts and ends in the outline, or `None` while a collapsed
1611 /// parent hides it.
1612 pub(crate) fn spans(&self) -> impl Iterator<Item = Option<[f32; 2]>> + '_ {
1613 let mut state = (0.0, None);
1614 self.blocks.iter().map(move |block| {
1615 let span = block
1616 .metrics
1617 .map(|[before, after, _]| [top(&mut state, [before, after]), block.state.0 as f32]);
1618 state = block.state;
1619 span
1620 })
1621 }
1622
1623 /// The paragraphs, tables and objects of root nodes `range`.
1624 pub(crate) fn pieces(&self, range: Range<usize>) -> [Range<usize>; 3] {
1625 let first = |root: usize| {
1626 self.blocks.get(root).map_or(
1627 [self.paragraphs.len(), self.tables.len(), self.objects.len()],
1628 |block| block.first,
1629 )
1630 };
1631 let [start, end] = [first(range.start), first(range.end)];
1632 [0, 1, 2].map(|kind| start[kind]..end[kind])
1633 }
1634
1635 /// Lays out root nodes `range` of `nodes` once `edit` applies, the edit's own or the table
1636 /// holding its cell, and works out where the nodes after them move. Resizing columns of
1637 /// other nodes or showing or hiding them lays out every node; renumbering lays out the
1638 /// renumbered.
1639 #[allow(clippy::too_many_arguments)]
1640 pub(crate) fn relayout(
1641 &self,
1642 nodes: &[PageParagraph],
1643 edit: &DocumentEdit,
1644 range: Range<usize>,
1645 indents: &[f32],
1646 width: f32,
1647 fixed_width: bool,
1648 shape: &mut impl FnMut(
1649 &PageParagraph,
1650 Option<&Count>,
1651 f32,
1652 &[f32],
1653 ) -> Result<ParagraphLayout, LayoutError>,
1654 ) -> Result<Relayout, LayoutError> {
1655 let resized = |node: &PageParagraph| match &node.content {
1656 ParagraphContent::Table(table) => edit.columns.contains_key(&table.id),
1657 _ => false,
1658 };
1659 let mut range = if edit.columns.len()
1660 == descendants(&nodes[range.clone()], None)
1661 .filter(|(_, _, node)| resized(node))
1662 .count()
1663 {
1664 range
1665 } else {
1666 0..nodes.len()
1667 };
1668 loop {
1669 let old = self.pieces(range.clone());
1670 let sources = leaves(&nodes[range.clone()], None)
1671 .map(|(_, _, node)| (node.id, node))
1672 .collect::<BTreeMap<_, _>>();
1673 let cached = self.paragraphs[old[0].clone()]
1674 .iter()
1675 .filter_map(|layout| Some((layout.id, (*sources.get(&layout.id)?, layout))))
1676 .collect::<BTreeMap<_, _>>();
1677 let count = match edit.container {
1678 None => range.len() - edit.range.len() + edit.replacement.len(),
1679 Some(_) => range.len(),
1680 };
1681 let replacement = edited_nodes(nodes, None, Some(edit))
1682 .skip(range.start)
1683 .take(count);
1684 let supplied = replacement
1685 .clone()
1686 .map(|node| node.id)
1687 .collect::<BTreeSet<_>>();
1688 // Children of a hidden or collapsed earlier node stay hidden.
1689 let hiding = replacement
1690 .clone()
1691 .filter_map(|node| {
1692 let parent = node.parent.filter(|parent| !supplied.contains(parent))?;
1693 let root = nodes[..range.start]
1694 .iter()
1695 .rposition(|node| node.id == parent)?;
1696 (self.blocks[root].metrics.is_none() || nodes[root].collapsed).then_some(parent)
1697 })
1698 .collect();
1699 let start = range
1700 .start
1701 .checked_sub(1)
1702 .map_or((0.0, None), |root| self.blocks[root].state);
1703 // Each earlier level's latest paragraph, back to the nearest at the first level.
1704 let mut siblings = Vec::new();
1705 let mut level = u32::MAX;
1706 for root in (0..range.start).rev() {
1707 if nodes[root].level < level {
1708 level = nodes[root].level;
1709 siblings.push((level, self.blocks[root].count.clone()));
1710 if level <= 1 {
1711 break;
1712 }
1713 }
1714 }
1715 siblings.reverse();
1716 let segment = Self::stack(
1717 replacement.clone(),
1718 indents,
1719 width,
1720 0,
1721 Some(edit),
1722 hiding,
1723 start,
1724 &mut siblings,
1725 &mut |node, previous, width, indents| {
1726 let indent = indentation(node.level, indents, width)?;
1727 if let Some((source, cached)) = cached.get(&node.id)
1728 && *source == node
1729 && follows(cached.number.as_ref(), previous)
1730 == cached.number.clone().map(|(count, _)| count)
1731 && cached.text.shaped.layout_max_advance() == width - indent
1732 && cached
1733 .markers
1734 .iter()
1735 .all(|(marker, _)| marker.shaped.layout_max_advance() == width)
1736 {
1737 let mut result = (*cached).clone();
1738 result.reset_origin(indent);
1739 return Ok(result);
1740 }
1741 shape(node, previous, width, indents)
1742 },
1743 )?;
1744 let hides =
1745 |block: &Block, node: &PageParagraph| block.metrics.is_none() || node.collapsed;
1746 if range.end < nodes.len() {
1747 let now = replacement
1748 .zip(&segment.blocks)
1749 .map(|(node, block)| (node.id, hides(block, node)))
1750 .collect::<BTreeMap<_, _>>();
1751 if nodes[range.clone()]
1752 .iter()
1753 .zip(&self.blocks[range.clone()])
1754 .any(|(node, block)| {
1755 now.get(&node.id)
1756 .is_some_and(|now| *now != hides(block, node))
1757 })
1758 {
1759 range = 0..nodes.len();
1760 continue;
1761 }
1762 }
1763 let mut renumbered = range.end;
1764 for root in range.end..nodes.len() {
1765 let previous = sibling(&mut siblings, nodes[root].level);
1766 let number = self.number(nodes, root);
1767 let now = follows(number, previous.as_ref());
1768 let counted = tally(&nodes[root], now.clone(), previous);
1769 if now.as_ref() != number.map(|(count, _)| count)
1770 || counted != self.blocks[root].count
1771 {
1772 renumbered = root + 1;
1773 }
1774 siblings.push((nodes[root].level, counted));
1775 if nodes[root].level <= 1 && renumbered <= root {
1776 break;
1777 }
1778 }
1779 if renumbered > range.end {
1780 range.end = renumbered;
1781 continue;
1782 }
1783 let mut state = segment.blocks.last().map_or(start, |block| block.state);
1784 let mut incoming = range
1785 .end
1786 .checked_sub(1)
1787 .map_or((0.0, None), |root| self.blocks[root].state);
1788 let mut moved = Vec::new();
1789 for root in range.end..self.blocks.len() {
1790 if state == incoming {
1791 break;
1792 }
1793 let block = &self.blocks[root];
1794 incoming = block.state;
1795 let mut y = 0.0;
1796 if let Some([before, after, height]) = block.metrics {
1797 y = top(&mut state, [before, after]);
1798 let [_, tables, objects] = self.pieces(root..root + 1);
1799 let flow = match self.objects[objects].first() {
1800 Some(object) if tables.is_empty() => object.at(y, height).1,
1801 _ => height,
1802 };
1803 state.0 += f64::from(flow);
1804 if !(state.0 as f32).is_finite() {
1805 return Err(LayoutError::InvalidSpacing);
1806 }
1807 }
1808 moved.push((y, state));
1809 }
1810 let bottom = if moved.len() == self.blocks.len() - range.end {
1811 state.0 as f32
1812 } else {
1813 self.size[1]
1814 };
1815 let widest = |blocks: &[Block], side: usize| {
1816 blocks
1817 .iter()
1818 .map(|block| block.extent[side])
1819 .fold(f32::NEG_INFINITY, f32::max)
1820 };
1821 let widths = [0, 1].map(|side| {
1822 let [before, after] = [
1823 widest(&self.blocks[range.clone()], side),
1824 widest(&segment.blocks, side),
1825 ];
1826 if after >= before || before < self.widths[side] {
1827 self.widths[side].max(after)
1828 } else {
1829 [
1830 &self.blocks[..range.start],
1831 &segment.blocks,
1832 &self.blocks[range.end..],
1833 ]
1834 .into_iter()
1835 .map(|blocks| widest(blocks, side))
1836 .fold([36.0, f32::NEG_INFINITY][side], f32::max)
1837 }
1838 });
1839 let tables = &old[1];
1840 let tables = self.tables[..tables.start]
1841 .iter()
1842 .chain(&segment.tables)
1843 .chain(&self.tables[tables.end..]);
1844 let size = [
1845 if fixed_width { width } else { widths[0] }.max(table_width(tables)),
1846 bottom,
1847 ];
1848 return Ok(Relayout {
1849 range,
1850 segment,
1851 moved,
1852 size,
1853 widths,
1854 });
1855 }
1856 }
1857
1858 /// Puts a [`Relayout`] of this layout in place.
1859 pub(crate) fn commit(&mut self, relayout: Relayout) {
1860 let Relayout {
1861 range,
1862 mut segment,
1863 moved,
1864 size,
1865 widths,
1866 } = relayout;
1867 let [paragraphs, tables, objects] = self.pieces(range.clone());
1868 let first = [paragraphs.start, tables.start, objects.start];
1869 let delta = [
1870 segment.paragraphs.len() as isize - paragraphs.len() as isize,
1871 segment.tables.len() as isize - tables.len() as isize,
1872 segment.objects.len() as isize - objects.len() as isize,
1873 ];
1874 for cell in segment.tables.iter_mut().flat_map(|table| &mut table.cells) {
1875 cell.paragraphs = cell.paragraphs.start + first[0]..cell.paragraphs.end + first[0];
1876 }
1877 for block in &mut segment.blocks {
1878 for (value, first) in block.first.iter_mut().zip(first) {
1879 *value += first;
1880 }
1881 }
1882 let after = range.start + segment.blocks.len();
1883 let later_tables = tables.start + segment.tables.len();
1884 self.paragraphs.splice(paragraphs, segment.paragraphs);
1885 self.tables.splice(tables, segment.tables);
1886 self.objects.splice(objects, segment.objects);
1887 self.blocks.splice(range, segment.blocks);
1888 if delta != [0; 3] {
1889 for block in &mut self.blocks[after..] {
1890 for (value, delta) in block.first.iter_mut().zip(delta) {
1891 *value = value.wrapping_add_signed(delta);
1892 }
1893 }
1894 for cell in self.tables[later_tables..]
1895 .iter_mut()
1896 .flat_map(|table| &mut table.cells)
1897 {
1898 cell.paragraphs = cell.paragraphs.start.wrapping_add_signed(delta[0])
1899 ..cell.paragraphs.end.wrapping_add_signed(delta[0]);
1900 }
1901 }
1902 for (root, (y, state)) in (after..).zip(moved) {
1903 let [paragraphs, tables, objects] = self.pieces(root..root + 1);
1904 let block = &mut self.blocks[root];
1905 block.state = state;
1906 let Some([.., height]) = block.metrics else {
1907 continue;
1908 };
1909 if !tables.is_empty() {
1910 for (value, rel) in verticals(
1911 &mut self.paragraphs[paragraphs],
1912 &mut self.tables[tables],
1913 &mut self.objects[objects],
1914 )
1915 .zip(&block.rel)
1916 {
1917 *value = rel + y;
1918 }
1919 } else if let Some(object) = self.objects[objects].first_mut() {
1920 object.place(y, height);
1921 } else {
1922 self.paragraphs[paragraphs.start].origin[1] = y;
1923 }
1924 }
1925 self.size = size;
1926 self.widths = widths;
1927 self.place_tags();
1928 }
1929
1930 pub(crate) fn table_width(&self) -> f32 {
1931 table_width(&self.tables)
1932 }
1933
1934 /// How far the content reaches, without the 36-point floor of `size`.
1935 pub(crate) fn content_width(&self) -> f32 {
1936 let text = self.paragraphs.iter().map(|paragraph| paragraph.size()[0]);
1937 let objects = self.objects.iter().map(|object| object.rect[2]);
1938 text.chain(objects).fold(self.table_width(), f32::max)
1939 }
1940
1941 fn table(
1942 table: &Table,
1943 depth: usize,
1944 edit: Option<&DocumentEdit>,
1945 shape: &mut impl FnMut(
1946 &PageParagraph,
1947 Option<&Count>,
1948 f32,
1949 &[f32],
1950 ) -> Result<ParagraphLayout, LayoutError>,
1951 ) -> Result<Self, LayoutError> {
1952 let widths = edit.and_then(|edit| edit.columns.get(&table.id));
1953 if widths.is_some_and(|widths| widths.len() != table.columns.len()) {
1954 return Err(LayoutError::InvalidWidth);
1955 }
1956 let width =
1957 |index: usize| widths.map_or(table.columns[index].width, |widths| widths[index]);
1958 if table.columns.is_empty()
1959 || table.rows.is_empty()
1960 || table
1961 .columns
1962 .iter()
1963 .enumerate()
1964 .any(|(index, _)| !width(index).is_finite() || width(index) < 36.0)
1965 {
1966 return Err(LayoutError::InvalidWidth);
1967 }
1968 let mut result = Self {
1969 tables: vec![TableLayout {
1970 id: table.id,
1971 cells: Vec::new(),
1972 borders: table.borders.unwrap_or(true),
1973 tags: None,
1974 }],
1975 size: [
1976 (0..table.columns.len())
1977 .map(|index| width(index) + 4.98)
1978 .sum::<f32>()
1979 - 1.83,
1980 3.54,
1981 ],
1982 ..Self::default()
1983 };
1984 let mut y = 0.0;
1985 for row in &table.rows {
1986 if row.cells.len() != table.columns.len() {
1987 return Err(LayoutError::InvalidWidth);
1988 }
1989 let start = result.tables[0].cells.len();
1990 let mut x = 0.0;
1991 let mut height = 0.0_f32;
1992 for (index, cell) in row.cells.iter().enumerate() {
1993 let width = width(index);
1994 if cell.paragraphs.is_empty() || !cell.unsupported.is_empty() {
1995 return Err(LayoutError::UnsupportedContent);
1996 }
1997 let mut child = Self::flow(
1998 edited_nodes(&cell.paragraphs, Some(cell.id), edit),
1999 &cell.indents,
2000 width,
2001 false,
2002 depth,
2003 edit,
2004 shape,
2005 )?;
2006 height = height.max(child.size[1]);
2007 for paragraph in &mut child.paragraphs {
2008 paragraph.parent.get_or_insert(cell.id);
2009 }
2010 let tables = child
2011 .tables
2012 .iter_mut()
2013 .filter_map(|table| table.tags.as_mut());
2014 let objects = child
2015 .objects
2016 .iter_mut()
2017 .filter_map(|object| object.tags.as_mut());
2018 for block in tables.chain(objects) {
2019 block.parent.get_or_insert(cell.id);
2020 }
2021 let paragraph_start = result.paragraphs.len();
2022 result.append(child, [x, y + 3.54]);
2023 result.tables[0].cells.push(CellLayout {
2024 id: cell.id,
2025 rect: [x - 3.6, y + 1.86, x + width + 1.38, 0.0],
2026 paragraphs: paragraph_start..result.paragraphs.len(),
2027 });
2028 x += width + 4.98;
2029 }
2030 y += height + 4.98;
2031 for cell in &mut result.tables[0].cells[start..] {
2032 cell.rect[3] = y + 1.86;
2033 }
2034 }
2035 result.size[1] += y;
2036 if result.size.iter().any(|v| !v.is_finite()) {
2037 return Err(LayoutError::InvalidSpacing);
2038 }
2039 Ok(result)
2040 }
2041}
2042
2043/// Stored column widths extend 1.77pt past the final cell border.
2044fn table_width<'a>(tables: impl IntoIterator<Item = &'a TableLayout>) -> f32 {
2045 tables
2046 .into_iter()
2047 .filter_map(|table| table.cells.last())
2048 .map(|cell| cell.rect[2] + 1.77)
2049 .fold(0.0, f32::max)
2050}
2051
2052/// Shapes a page object into positioned paragraph layouts.
2053pub trait Arrange {
2054 type Output;
2055 fn layout(
2056 &self,
2057 engine: &mut TextEngine,
2058 definitions: &BTreeMap<ExGuid, Definition>,
2059 ) -> Result<Self::Output, LayoutError>;
2060}
2061
2062impl Arrange for Outline {
2063 type Output = OutlineLayout;
2064
2065 fn layout(
2066 &self,
2067 engine: &mut TextEngine,
2068 definitions: &BTreeMap<ExGuid, Definition>,
2069 ) -> Result<OutlineLayout, LayoutError> {
2070 let width = self
2071 .layout
2072 .reserved_width
2073 .or(self.layout.max_width)
2074 .ok_or(LayoutError::InvalidWidth)?;
2075 outline_layout(self, engine, definitions, width)
2076 }
2077}
2078
2079pub(crate) fn outline_layout(
2080 outline: &Outline,
2081 engine: &mut TextEngine,
2082 definitions: &BTreeMap<ExGuid, Definition>,
2083 width: f32,
2084) -> Result<OutlineLayout, LayoutError> {
2085 if !outline.unsupported.is_empty() {
2086 return Err(LayoutError::UnsupportedContent);
2087 }
2088 OutlineLayout::flow(
2089 outline.paragraphs.iter(),
2090 &outline.indents,
2091 width,
2092 outline.layout.width_set_by_user == Some(true),
2093 0,
2094 None,
2095 &mut |node, previous, width, indents| {
2096 ParagraphLayout::shape(engine, node, previous, width, indents, definitions)
2097 },
2098 )
2099}
2100
2101impl Arrange for Title {
2102 type Output = Vec<([f32; 2], OutlineLayout)>;
2103
2104 fn layout(
2105 &self,
2106 engine: &mut TextEngine,
2107 definitions: &BTreeMap<ExGuid, Definition>,
2108 ) -> Result<Vec<([f32; 2], OutlineLayout)>, LayoutError> {
2109 if [self.layout.x, self.layout.y]
2110 .into_iter()
2111 .flatten()
2112 .any(|v| !v.is_finite())
2113 {
2114 return Err(LayoutError::InvalidSpacing);
2115 }
2116 let mut layouts = Vec::new();
2117 let mut bottom = 0.0_f32;
2118 for outline in &self.outlines {
2119 let width = outline
2120 .layout
2121 .reserved_width
2122 .or(outline.layout.max_width)
2123 .unwrap_or(TITLE_WIDTH);
2124 let layout = outline_layout(outline, engine, definitions, width)?;
2125 let origin = [
2126 outline.layout.x.unwrap_or(0.0),
2127 bottom + outline.layout.y.unwrap_or(0.0),
2128 ];
2129 let height = outline.layout.max_height.unwrap_or(0.0);
2130 if origin.iter().any(|v| !v.is_finite()) || !height.is_finite() || height < 0.0 {
2131 return Err(LayoutError::InvalidSpacing);
2132 }
2133 bottom = origin[1] + layout.size[1].max(height) + if outline.title { 3.6 } else { 0.0 };
2134 if !bottom.is_finite() {
2135 return Err(LayoutError::InvalidSpacing);
2136 }
2137 layouts.push((origin, layout));
2138 }
2139 Ok(layouts)
2140 }
2141}
2142
2143#[cfg(test)]
2144mod tests {
2145 use super::*;
2146 use onestore::document::Layout;
2147 use onestore::page::{PageParagraph, TextObject};
2148
2149 fn paragraph(n: u32, text: &str, level: u32, parent: Option<u32>) -> PageParagraph {
2150 PageParagraph {
2151 id: ExGuid {
2152 n,
2153 ..ExGuid::default()
2154 },
2155 parent: parent.map(|n| ExGuid {
2156 n,
2157 ..ExGuid::default()
2158 }),
2159 level,
2160 format: Format::default(),
2161 content: onestore::page::ParagraphContent::Text(TextObject {
2162 date_field: None,
2163 id: ExGuid {
2164 n: n + 100,
2165 ..ExGuid::default()
2166 },
2167 text: Paragraph::new(text.into(), Format::default()),
2168 tags: Vec::new(),
2169 }),
2170 lists: Vec::new(),
2171 tags: Vec::new(),
2172 media: Default::default(),
2173 collapsed: false,
2174 style: None,
2175 }
2176 }
2177
2178 fn table(rows: &[&[&str]], widths: &[f32], mut n: u32) -> PageParagraph {
2179 use onestore::page::{TableCell, TableColumn, TableRow};
2180 let mut id = || {
2181 n += 1;
2182 ExGuid {
2183 n,
2184 ..ExGuid::default()
2185 }
2186 };
2187 let mut node = paragraph(id().n, "", 1, None);
2188 node.content = ParagraphContent::Table(Table {
2189 id: id(),
2190 columns: widths
2191 .iter()
2192 .map(|width| TableColumn {
2193 width: *width,
2194 locked: false,
2195 })
2196 .collect(),
2197 rows: rows
2198 .iter()
2199 .map(|row| TableRow {
2200 id: id(),
2201 cells: row
2202 .iter()
2203 .map(|text| TableCell {
2204 id: id(),
2205 layout: Layout::default(),
2206 indents: vec![18.0, 0.0, 27.0],
2207 shading: None,
2208 paragraphs: vec![paragraph(id().n, text, 1, None)],
2209 unsupported: Vec::new(),
2210 })
2211 .collect(),
2212 })
2213 .collect(),
2214 borders: Some(true),
2215 layout: Layout::default(),
2216 tags: Vec::new(),
2217 });
2218 node
2219 }
2220
2221 #[test]
2222 fn table_rows_align_cells_and_expand_for_wrapped_text() {
2223 let mut engine = TextEngine::default();
2224 let mut outline = Outline {
2225 id: ExGuid::default(),
2226 title: false,
2227 min_width: None,
2228 layout: Layout {
2229 max_width: Some(300.0),
2230 ..Layout::default()
2231 },
2232 indents: vec![18.0, 0.0, 27.0],
2233 paragraphs: vec![
2234 paragraph(1, "Before", 1, None),
2235 table(
2236 &[
2237 &[
2238 "A long paragraph that wraps inside a single table cell",
2239 "B",
2240 ],
2241 &["C", "D"],
2242 ],
2243 &[72.0, 48.0],
2244 1000,
2245 ),
2246 paragraph(2, "After", 1, None),
2247 ],
2248 unsupported: Vec::new(),
2249 };
2250 let definitions = BTreeMap::new();
2251 let layout = outline.layout(&mut engine, &definitions).unwrap();
2252 assert_eq!(layout.paragraphs.len(), 6);
2253 assert_eq!(layout.tables.len(), 1);
2254 let cells = &layout.tables[0].cells;
2255 assert_eq!(cells.len(), 4);
2256 assert_eq!(
2257 cells
2258 .iter()
2259 .map(|cell| cell.paragraphs.clone())
2260 .collect::<Vec<_>>(),
2261 [1..2, 2..3, 3..4, 4..5]
2262 );
2263 assert!(layout.paragraph_cell(0).is_none());
2264 assert_eq!(layout.paragraph_cell(4).unwrap().id, cells[3].id);
2265 assert!(layout.paragraph_cell(5).is_none());
2266 let paragraphs = &layout.paragraphs;
2267 assert!(paragraphs[1].text.lines().count() > 1);
2268 assert_eq!(paragraphs[2].text.lines().count(), 1);
2269 assert_eq!(paragraphs[1].origin[1], paragraphs[2].origin[1]);
2270 assert_eq!(paragraphs[3].origin[1], paragraphs[4].origin[1]);
2271 assert_eq!(cells[0].rect[3], cells[1].rect[3]);
2272 assert_eq!(cells[0].rect[3], cells[2].rect[1]);
2273 assert!((cells[0].rect[2] - cells[1].rect[0]).abs() < 0.00001);
2274 assert_eq!(paragraphs[1].origin[0], 0.0);
2275 assert_eq!(paragraphs[2].origin[0], 76.98);
2276 assert!(paragraphs[3].origin[1] > paragraphs[1].origin[1] + paragraphs[1].text.height());
2277 assert!(paragraphs[5].origin[1] > cells[3].rect[3]);
2278 assert_eq!(
2279 layout.size[1],
2280 paragraphs[5].origin[1] + paragraphs[5].text.height()
2281 );
2282 let ParagraphContent::Table(source) = &outline.paragraphs[1].content else {
2283 panic!()
2284 };
2285 assert_eq!(layout.tables[0].id, source.id);
2286 assert_eq!(
2287 cells.iter().map(|c| c.id).collect::<Vec<_>>(),
2288 source
2289 .rows
2290 .iter()
2291 .flat_map(|row| row.cells.iter().map(|c| c.id))
2292 .collect::<Vec<_>>()
2293 );
2294
2295 outline.layout.width_set_by_user = Some(true);
2296 let fixed = outline.layout(&mut engine, &definitions).unwrap();
2297 assert_eq!(fixed.size, [300.0, layout.size[1]]);
2298 assert_eq!(fixed.paragraphs[2].origin, paragraphs[2].origin);
2299 let ParagraphContent::Table(source) = &mut outline.paragraphs[1].content else {
2300 panic!()
2301 };
2302 source.columns[0].width = 160.0;
2303 let widened = outline.layout(&mut engine, &definitions).unwrap();
2304 assert!(widened.size[1] < fixed.size[1]);
2305 assert_eq!(widened.paragraphs[2].origin[0], 164.98);
2306 }
2307
2308 #[test]
2309 fn nested_table_layout_translates_cells_and_respects_collapsed_children() {
2310 let mut outer = table(&[&["Left", "Right"]], &[160.0, 72.0], 1000);
2311 let mut inner = table(&[&["Nested", "Cell"]], &[48.0, 48.0], 2000);
2312 inner.level = 2;
2313 let ParagraphContent::Table(source) = &mut outer.content else {
2314 panic!()
2315 };
2316 let hidden = paragraph(
2317 42,
2318 "Hidden descendant",
2319 2,
2320 Some(source.rows[0].cells[0].paragraphs[0].id.n),
2321 );
2322 source.rows[0].cells[0].paragraphs[0].collapsed = true;
2323 source.rows[0].cells[0].paragraphs.push(hidden);
2324 source.rows[0].cells[0].paragraphs.push(inner);
2325 let mut engine = TextEngine::default();
2326 let layout = OutlineLayout::flow(
2327 [&outer].into_iter(),
2328 &[18.0, 0.0, 27.0],
2329 300.0,
2330 false,
2331 0,
2332 None,
2333 &mut |node, previous, width, indents| {
2334 ParagraphLayout::shape(
2335 &mut engine,
2336 node,
2337 previous,
2338 width,
2339 indents,
2340 &BTreeMap::new(),
2341 )
2342 },
2343 )
2344 .unwrap();
2345 assert_eq!(layout.tables.len(), 2);
2346 assert_eq!(layout.tables[0].cells[0].paragraphs, 0..3);
2347 assert_eq!(layout.tables[0].cells[1].paragraphs, 3..4);
2348 assert_eq!(layout.tables[1].cells[0].paragraphs, 1..2);
2349 assert_eq!(layout.tables[1].cells[1].paragraphs, 2..3);
2350 assert_eq!(
2351 layout.paragraph_cell(1).unwrap().id,
2352 layout.tables[1].cells[0].id
2353 );
2354 assert_eq!(
2355 layout
2356 .paragraphs
2357 .iter()
2358 .map(|p| p.projection.text().text())
2359 .collect::<Vec<_>>(),
2360 ["Left", "Nested", "Cell", "Right"]
2361 );
2362 assert_eq!(layout.paragraphs[1].origin[0], 27.0);
2363 assert_eq!(layout.tables[1].cells[0].rect[0], 27.0 - 3.6);
2364 assert!(layout.tables[1].cells[0].rect[1] > layout.tables[0].cells[0].rect[1]);
2365 assert!(layout.tables[1].cells[0].rect[3] < layout.tables[0].cells[0].rect[3]);
2366 assert_eq!(
2367 layout.paragraphs[0].origin[1],
2368 layout.paragraphs[3].origin[1]
2369 );
2370 }
2371
2372 #[test]
2373 #[ignore = "requires CANVAS_TEST_SECTION native Tab capture"]
2374 fn native_table_layout() {
2375 use onestore::page::{Page, PageObject};
2376 use onestore::{RevisionIndex, Store, document::Document};
2377 let bytes = std::fs::read(std::env::var_os("CANVAS_TEST_SECTION").unwrap()).unwrap();
2378 let store = Store::parse(&bytes).unwrap();
2379 let index = RevisionIndex::parse(&store).unwrap();
2380 let document = Document::parse(&index).unwrap();
2381 let mut engine = TextEngine::default();
2382 let page = Page::from_document(&document, "rows").unwrap();
2383 let outline = page
2384 .objects
2385 .iter()
2386 .find_map(|object| match object {
2387 PageObject::Outline(outline) => Some(outline),
2388 _ => None,
2389 })
2390 .unwrap();
2391 let layout = outline.layout(&mut engine, &page.definitions).unwrap();
2392 assert!((layout.size[0] - 84.6).abs() < 0.001);
2393 assert!((layout.size[1] - 58.76315).abs() < 0.001);
2394 for (paragraph, expected) in layout.paragraphs.iter().zip([
2395 [0.0, 3.54],
2396 [44.34, 3.54],
2397 [0.0, 21.947714],
2398 [44.34, 21.947714],
2399 [0.0, 40.355427],
2400 [44.34, 40.355427],
2401 ]) {
2402 assert_eq!(paragraph.text.lines().count(), 1);
2403 for (actual, expected) in paragraph.origin.into_iter().zip(expected) {
2404 assert!((actual - expected).abs() < 0.001);
2405 }
2406 }
2407 assert_eq!(layout.tables.len(), 1);
2408 assert_eq!(layout.tables[0].cells.len(), 6);
2409 for (title, size) in [
2410 ("soft-break", [82.350006, 35.375435]),
2411 ("fixed", [180.0, 21.947721]),
2412 ] {
2413 let page = Page::from_document(&document, title).unwrap();
2414 let outline = page
2415 .objects
2416 .iter()
2417 .find_map(|object| match object {
2418 PageObject::Outline(outline) => Some(outline),
2419 _ => None,
2420 })
2421 .unwrap();
2422 let layout = outline.layout(&mut engine, &page.definitions).unwrap();
2423 for (actual, expected) in layout.size.into_iter().zip(size) {
2424 assert!(
2425 (actual - expected).abs() < 0.001,
2426 "{title}: {actual} != {expected}"
2427 );
2428 }
2429 assert_eq!(layout.tables.len(), 1);
2430 assert_eq!(layout.tables[0].cells.len(), 2);
2431 assert_eq!(
2432 layout
2433 .paragraphs
2434 .iter()
2435 .map(|p| p.text.lines().count())
2436 .max(),
2437 Some(if title == "soft-break" { 2 } else { 1 })
2438 );
2439 }
2440 }
2441
2442 #[test]
2443 fn tags_preserve_line_geometry_and_follow_list_indentation() {
2444 use onestore::document::Tag;
2445 let id = ExGuid {
2446 n: 500,
2447 ..ExGuid::default()
2448 };
2449 let mut node = paragraph(1, "Text that wraps across several lines", 2, None);
2450 let mut engine = TextEngine::default();
2451 let mut definitions = BTreeMap::new();
2452 let plain = ParagraphLayout::shape(
2453 &mut engine,
2454 &node,
2455 None,
2456 120.0,
2457 &[18.0, 0.0, 27.0],
2458 &definitions,
2459 )
2460 .unwrap();
2461 node.text_mut().unwrap().tags.push(Tag {
2462 definition: Some(id),
2463 status: 3,
2464 action_type: None,
2465 shape: None,
2466 property_status: None,
2467 created: None,
2468 completed: None,
2469 start: None,
2470 due: None,
2471 task_id: None,
2472 extra_set: 0,
2473 });
2474 for shape in [3, 13, 15, 17, 18, 23, 118, 136, 100, 101, 102, 121] {
2475 definitions.insert(
2476 id,
2477 Definition {
2478 kind: Kind::TagDefinition {
2479 shape: Some(shape),
2480 label: Some("Label".into()),
2481 action_type: None,
2482 color: None,
2483 highlight: None,
2484 },
2485 format: Format::default(),
2486 },
2487 );
2488 let tagged = ParagraphLayout::shape(
2489 &mut engine,
2490 &node,
2491 None,
2492 120.0,
2493 &[18.0, 0.0, 27.0],
2494 &definitions,
2495 )
2496 .unwrap();
2497 assert_eq!(
2498 tagged.tags[0].icon,
2499 TagIcon::Symbol {
2500 shape,
2501 checked: shape == 3
2502 }
2503 );
2504 let baseline = tagged.text.lines().next().unwrap().1.baseline;
2505 assert_eq!(
2506 tagged.tags[0].origin,
2507 [6.75, baseline - 0.357 * 11.0 + 0.2 - 6.0]
2508 );
2509 assert_eq!(tagged.tags[0].label, "Label");
2510 assert!(tagged.tags[0].disabled);
2511 assert_eq!(tagged.text.height(), plain.text.height());
2512 assert_eq!(
2513 tagged
2514 .text
2515 .lines()
2516 .map(|(_, b)| (&b.source, b.baseline))
2517 .collect::<Vec<_>>(),
2518 plain
2519 .text
2520 .lines()
2521 .map(|(_, b)| (&b.source, b.baseline))
2522 .collect::<Vec<_>>()
2523 );
2524 }
2525 let list = ExGuid {
2526 n: 501,
2527 ..ExGuid::default()
2528 };
2529 definitions.insert(
2530 list,
2531 Definition {
2532 kind: Kind::List {
2533 font: Some("Arial".into()),
2534 format: Some("•".into()),
2535 bullet: None,
2536 restart: None,
2537 },
2538 format: Format::default(),
2539 },
2540 );
2541 node.lists.push(list);
2542 let tagged = ParagraphLayout::shape(
2543 &mut engine,
2544 &node,
2545 None,
2546 120.0,
2547 &[18.0, 0.0, 27.0],
2548 &definitions,
2549 )
2550 .unwrap();
2551 assert_eq!(tagged.tags[0].origin[0], tagged.markers[0].1[0] - 12.9);
2552 let baseline = tagged.text.lines().next().unwrap().1.baseline;
2553 assert_eq!(
2554 tagged.tags[0].origin[1],
2555 baseline - 0.357 * 11.0 + 0.2 - 6.0
2556 );
2557 let Kind::TagDefinition { shape, .. } = &mut definitions.get_mut(&id).unwrap().kind else {
2558 unreachable!()
2559 };
2560 *shape = Some(999);
2561 let mut shaped = |node: &PageParagraph, definitions| {
2562 ParagraphLayout::shape(
2563 &mut engine,
2564 node,
2565 None,
2566 120.0,
2567 &[18.0, 0.0, 27.0],
2568 definitions,
2569 )
2570 .unwrap()
2571 };
2572 // A symbol MS-ONE does not list keeps its number, an Outlook task shows its flag, and
2573 // a tag whose definition is missing shows nothing.
2574 assert_eq!(
2575 shaped(&node, &definitions).tags[0].icon,
2576 TagIcon::Symbol {
2577 shape: 999,
2578 checked: false
2579 }
2580 );
2581 let mut task = node.clone();
2582 let stored = &mut task.text_mut().unwrap().tags[0];
2583 stored.status |= 4;
2584 stored.shape = Some(89);
2585 assert_eq!(
2586 shaped(&task, &definitions).tags[0].icon,
2587 TagIcon::Task { shape: 89 }
2588 );
2589 let mut untagged = definitions.clone();
2590 untagged.remove(&id);
2591 assert!(shaped(&node, &untagged).tags.is_empty());
2592 }
2593
2594 /// OneNote 2010 at 400% (Calibri bullets and numbers from 8 to 24 pt, default list
2595 /// spacing): a marker's advance ends 11.1 pt before its text, and a tag's 12 pt slot ends
2596 /// 0.9 pt before the leftmost marker among its paragraph's siblings, or 8.25 pt before its
2597 /// text when none has one.
2598 #[test]
2599 fn markers_and_tags_sit_where_onenote_draws_them() {
2600 use onestore::document::Tag;
2601 let id = |n| ExGuid {
2602 n,
2603 ..ExGuid::default()
2604 };
2605 let list = |format: &str| Definition {
2606 kind: Kind::List {
2607 font: None,
2608 format: Some(format.into()),
2609 bullet: None,
2610 restart: None,
2611 },
2612 format: Format::default(),
2613 };
2614 let definitions = BTreeMap::from([
2615 (id(900), list("\u{2022}")),
2616 (id(901), list("\u{fffd}\u{0}.")),
2617 (
2618 id(902),
2619 Definition {
2620 kind: Kind::TagDefinition {
2621 shape: Some(3),
2622 label: None,
2623 action_type: None,
2624 color: None,
2625 highlight: None,
2626 },
2627 format: Format::default(),
2628 },
2629 ),
2630 ]);
2631 let tag = Tag {
2632 definition: Some(id(902)),
2633 action_type: None,
2634 shape: None,
2635 property_status: None,
2636 status: 0,
2637 created: None,
2638 completed: None,
2639 start: None,
2640 due: None,
2641 task_id: None,
2642 extra_set: 0,
2643 };
2644 let tagged = |n, level, parent| {
2645 let mut node = paragraph(n, "Tag", level, parent);
2646 node.text_mut().unwrap().tags.push(tag.clone());
2647 node
2648 };
2649 let mut number = paragraph(1, "Number", 1, None);
2650 number.lists.push(id(901));
2651 let mut bullet = paragraph(5, "Bullet", 2, Some(3));
2652 bullet.lists.push(id(900));
2653 let nodes = [
2654 number,
2655 tagged(2, 1, None),
2656 paragraph(3, "Plain", 1, None),
2657 tagged(4, 2, Some(3)),
2658 bullet,
2659 paragraph(6, "Plain", 2, Some(3)),
2660 ];
2661 let mut engine = TextEngine::default();
2662 let layout = OutlineLayout::flow(
2663 nodes.iter(),
2664 &[18.0, 0.0, 27.0, 27.0],
2665 400.0,
2666 false,
2667 0,
2668 None,
2669 &mut |node, previous, width, indents| {
2670 ParagraphLayout::shape(&mut engine, node, previous, width, indents, &definitions)
2671 },
2672 )
2673 .unwrap();
2674 let [number, first, _, second, bullet, _] = &layout.paragraphs[..] else {
2675 panic!()
2676 };
2677 for paragraph in [number, bullet] {
2678 let (marker, [x, _]) = &paragraph.markers[0];
2679 let advance = marker.lines().next().unwrap().0.metrics().advance;
2680 assert!((x + advance - (paragraph.origin[0] - 11.1)).abs() < 1e-4);
2681 }
2682 // A numbered sibling pushes the level-1 tag left; the level-2 tag clears the bullet
2683 // that follows it rather than its own text.
2684 assert_eq!(first.tags[0].origin[0], number.markers[0].1[0] - 0.9 - 12.0);
2685 assert_eq!(
2686 second.tags[0].origin[0],
2687 bullet.markers[0].1[0] - 0.9 - 12.0
2688 );
2689 assert!(first.tags[0].origin[0] < first.origin[0] - 20.25);
2690 let alone = OutlineLayout::flow(
2691 [tagged(7, 1, None)].iter(),
2692 &[18.0, 0.0, 27.0, 27.0],
2693 400.0,
2694 false,
2695 0,
2696 None,
2697 &mut |node, previous, width, indents| {
2698 ParagraphLayout::shape(&mut engine, node, previous, width, indents, &definitions)
2699 },
2700 )
2701 .unwrap();
2702 assert_eq!(alone.paragraphs[0].tags[0].origin[0], -20.25);
2703 }
2704
2705 /// OneNote 2010 at 400%: the first run's size picks the tag icon (9 pt below 10 pt text,
2706 /// 12 pt to 17.5, 18 pt to 23.5, then 24 pt up to at least 60), whose right edge stays
2707 /// 8.25 pt before the text and whose centre sits 0.357 of the run's size less 0.2 pt above
2708 /// the first baseline.
2709 #[test]
2710 fn tag_icons_follow_the_first_run() {
2711 use onestore::document::Tag;
2712 let id = |n| ExGuid {
2713 n,
2714 ..ExGuid::default()
2715 };
2716 let definitions = BTreeMap::from([(
2717 id(902),
2718 Definition {
2719 kind: Kind::TagDefinition {
2720 shape: Some(3),
2721 label: None,
2722 action_type: None,
2723 color: None,
2724 highlight: None,
2725 },
2726 format: Format::default(),
2727 },
2728 )]);
2729 let tag = Tag {
2730 definition: Some(id(902)),
2731 action_type: None,
2732 shape: None,
2733 property_status: None,
2734 status: 0,
2735 created: None,
2736 completed: None,
2737 start: None,
2738 due: None,
2739 task_id: None,
2740 extra_set: 0,
2741 };
2742 let tagged = |sizes: &[f32], tags: usize| {
2743 let mut node = paragraph(1, "", 1, None);
2744 let text = node.text_mut().unwrap();
2745 text.text = Paragraph::from_runs(sizes.iter().map(|size| {
2746 (
2747 "Tag ".to_string(),
2748 Format {
2749 font_size: Some(*size),
2750 ..Format::default()
2751 },
2752 )
2753 }));
2754 text.tags = vec![tag.clone(); tags];
2755 node
2756 };
2757 let mut engine = TextEngine::default();
2758 let mut lay = |nodes: &[PageParagraph]| {
2759 OutlineLayout::flow(
2760 nodes.iter(),
2761 &[18.0, 0.0, 27.0, 27.0],
2762 400.0,
2763 false,
2764 0,
2765 None,
2766 &mut |node, previous, width, indents| {
2767 ParagraphLayout::shape(
2768 &mut engine,
2769 node,
2770 previous,
2771 width,
2772 indents,
2773 &definitions,
2774 )
2775 },
2776 )
2777 .unwrap()
2778 };
2779 for (sizes, side) in [
2780 (&[9.5][..], 9.0),
2781 (&[10.0], 12.0),
2782 (&[17.5], 12.0),
2783 (&[18.0], 18.0),
2784 (&[23.5], 18.0),
2785 (&[24.0], 24.0),
2786 (&[60.0], 24.0),
2787 (&[11.0, 24.0], 12.0),
2788 (&[24.0, 11.0], 24.0),
2789 ] {
2790 let layout = lay(&[tagged(sizes, 1)]);
2791 let icon = &layout.paragraphs[0].tags[0];
2792 assert_eq!((icon.size, icon.origin[0] + icon.size), (side, -8.25));
2793 let baseline = layout.paragraphs[0].text.lines().next().unwrap().1.baseline;
2794 let centre = icon.origin[1] + side / 2.0;
2795 assert!((centre - (baseline - 0.357 * sizes[0] + 0.2)).abs() < 1e-4);
2796 }
2797 // A second icon extends the column left by its own side.
2798 let layout = lay(&[tagged(&[20.0], 2)]);
2799 assert_eq!(layout.tag_column_offset(), -18.0);
2800 }
2801
2802 #[test]
2803 fn files_and_ink_take_their_own_paragraph_in_the_flow() {
2804 use onestore::page::{Attachment, Ink, InkStroke};
2805 let before = paragraph(1, "Before", 1, None);
2806 let mut file = paragraph(2, "", 1, None);
2807 file.content = ParagraphContent::Attachment(Attachment {
2808 id: ExGuid {
2809 n: 20,
2810 ..ExGuid::default()
2811 },
2812 filename: "notes 🦀.txt".into(),
2813 source_path: None,
2814 size: Some([24.0, 24.0]),
2815 layout: Default::default(),
2816 bytes: None,
2817 preview: None,
2818 recording: None,
2819 tags: Vec::new(),
2820 });
2821 let mut ink = paragraph(3, "", 1, None);
2822 ink.content = ParagraphContent::Ink(Ink {
2823 id: ExGuid {
2824 n: 30,
2825 ..ExGuid::default()
2826 },
2827 layout: Default::default(),
2828 strokes: vec![InkStroke {
2829 id: ExGuid::default(),
2830 points: vec![[300.0, 120.0], [360.0, 180.0]],
2831 width: 1.0,
2832 height: 1.0,
2833 color: None,
2834 transparency: None,
2835 pen_tip: None,
2836 raster_operation: None,
2837 pressure: Vec::new(),
2838 }],
2839 groups: Vec::new(),
2840 shape: None,
2841 });
2842 let after = paragraph(4, "After", 1, None);
2843 let mut engine = TextEngine::default();
2844 let layout = OutlineLayout::flow(
2845 [&before, &file, &ink, &after].into_iter(),
2846 &[0.0, 0.0],
2847 468.0,
2848 false,
2849 0,
2850 None,
2851 &mut |node, previous, width, indents| {
2852 ParagraphLayout::shape(
2853 &mut engine,
2854 node,
2855 previous,
2856 width,
2857 indents,
2858 &BTreeMap::new(),
2859 )
2860 },
2861 )
2862 .unwrap();
2863 let top = layout.paragraphs[0].text.height();
2864 let [icon, handwriting] = [&layout.objects[0], &layout.objects[1]];
2865 assert_eq!(icon.rect, [15.0, top + 6.0, 39.0, top + 30.0]);
2866 let label = icon.label().unwrap();
2867 assert_eq!(label.projection.text().text(), "notes 🦀");
2868 assert_eq!(label.origin, [0.0, top + 40.5]);
2869 assert_eq!(icon.bottom, label.origin[1] + label.text.height() + 9.0);
2870 assert_eq!(
2871 handwriting.rect,
2872 [0.0, icon.bottom, 360.0, icon.bottom + 180.0]
2873 );
2874 assert_eq!(layout.paragraphs[1].origin[1], handwriting.bottom);
2875 assert_eq!(layout.size[0], 360.0);
2876 }
2877
2878 #[test]
2879 fn tags_paint_oldest_first_and_the_newest_colour_wins() {
2880 use onestore::document::Tag;
2881 let mut definitions = BTreeMap::new();
2882 let mut tag = |n, shape, color| {
2883 let id = ExGuid {
2884 n,
2885 ..ExGuid::default()
2886 };
2887 definitions.insert(
2888 id,
2889 Definition {
2890 kind: Kind::TagDefinition {
2891 shape: Some(shape),
2892 label: None,
2893 action_type: None,
2894 color,
2895 highlight: None,
2896 },
2897 format: Format::default(),
2898 },
2899 );
2900 Tag {
2901 definition: Some(id),
2902 status: 1,
2903 action_type: None,
2904 shape: None,
2905 property_status: None,
2906 created: None,
2907 completed: None,
2908 start: None,
2909 due: None,
2910 task_id: None,
2911 extra_set: 0,
2912 }
2913 };
2914 let [action, mood, project, question] = [
2915 tag(1, 0, Some(0x0080_0080)),
2916 tag(2, 0, Some(0x0080_8000)),
2917 tag(3, 100, None),
2918 tag(4, 15, None),
2919 ];
2920 let mut node = paragraph(1, "Lyric", 1, None);
2921 // As stored: newest first.
2922 node.text_mut().unwrap().tags = vec![question, project, mood, action];
2923 let mut engine = TextEngine::default();
2924 let shaped =
2925 ParagraphLayout::shape(&mut engine, &node, None, 200.0, &[0.0, 0.0], &definitions)
2926 .unwrap();
2927 assert_eq!(
2928 shaped
2929 .tags
2930 .iter()
2931 .map(|tag| (tag.icon, tag.origin[0]))
2932 .collect::<Vec<_>>(),
2933 [
2934 (TagIcon::of(100, false).unwrap(), -20.25),
2935 (TagIcon::of(15, false).unwrap(), -8.25)
2936 ]
2937 );
2938 let colors: Vec<_> = shaped
2939 .text
2940 .lines()
2941 .flat_map(|(line, _)| line.items().collect::<Vec<_>>())
2942 .filter_map(|item| match item {
2943 parley::PositionedLayoutItem::GlyphRun(run) => Some(run.style().brush.color),
2944 _ => None,
2945 })
2946 .collect();
2947 assert_eq!(colors, [Some(0x0080_8000)]);
2948 assert_eq!(shaped.projection.text().spans()[0].format.color, None);
2949 let outline = OutlineLayout {
2950 paragraphs: vec![shaped],
2951 ..OutlineLayout::default()
2952 };
2953 assert_eq!(outline.tag_column_offset(), -12.0);
2954 }
2955
2956 #[test]
2957 fn title_uses_a_default_wrap_limit_and_keeps_date_after_wrapped_title() {
2958 let mut title = Title {
2959 date: None,
2960 id: ExGuid::default(),
2961 layout: Layout::default(),
2962 outlines: ["A title with enough words to wrap", "A date"]
2963 .into_iter()
2964 .enumerate()
2965 .map(|(index, text)| Outline {
2966 title: index == 0,
2967 min_width: None,
2968 id: ExGuid {
2969 n: index as u32,
2970 ..ExGuid::default()
2971 },
2972 layout: Layout {
2973 max_height: Some(21.6),
2974 ..Layout::default()
2975 },
2976 indents: vec![18.0, 0.0],
2977 paragraphs: vec![paragraph(index as u32, text, 1, None)],
2978 unsupported: Vec::new(),
2979 })
2980 .collect(),
2981 };
2982 let mut engine = TextEngine::default();
2983 let definitions = BTreeMap::new();
2984 assert!(matches!(
2985 title.outlines[0].layout(&mut engine, &definitions),
2986 Err(LayoutError::InvalidWidth)
2987 ));
2988 let layouts = title.layout(&mut engine, &definitions).unwrap();
2989 assert_eq!(layouts[0].1.paragraphs[0].text.lines().count(), 1);
2990 assert_eq!(layouts[1].0, [0.0, 21.6 + 3.6]);
2991 title.outlines[0].paragraphs[0].text_mut().unwrap().text = Paragraph::new(
2992 "A title with enough words to wrap ".repeat(12),
2993 Format::default(),
2994 );
2995 let layouts = title.layout(&mut engine, &definitions).unwrap();
2996 assert!(layouts[0].1.paragraphs[0].text.lines().count() > 1);
2997 assert!(layouts[0].1.size[0] <= 468.0);
2998 assert_eq!(layouts[1].0[1], layouts[0].1.size[1] + 3.6);
2999 title.outlines[0].layout.max_width = Some(70.0);
3000 let layouts = title.layout(&mut engine, &definitions).unwrap();
3001 assert!(layouts[0].1.paragraphs[0].text.lines().count() > 1);
3002 assert_eq!(layouts[1].0[1], layouts[0].1.size[1] + 3.6);
3003 for value in [f32::NAN, f32::INFINITY, -1.0] {
3004 title.outlines[0].layout.max_height = Some(value);
3005 assert!(matches!(
3006 title.layout(&mut engine, &definitions),
3007 Err(LayoutError::InvalidSpacing)
3008 ));
3009 }
3010 title.outlines[0].layout.max_height = Some(21.6);
3011 title.layout.x = Some(f32::NAN);
3012 assert!(matches!(
3013 title.layout(&mut engine, &definitions),
3014 Err(LayoutError::InvalidSpacing)
3015 ));
3016 }
3017
3018 #[test]
3019 fn collapses_descendants_and_uses_the_larger_adjacent_spacing() {
3020 let mut first = paragraph(1, "First", 1, None);
3021 first.text_mut().unwrap().text = Paragraph::new(
3022 "First".into(),
3023 Format {
3024 space_after: Some(4.0),
3025 ..Format::default()
3026 },
3027 );
3028 let mut second = paragraph(2, "Second", 2, Some(1));
3029 second.text_mut().unwrap().text = Paragraph::new(
3030 "Second".into(),
3031 Format {
3032 space_before: Some(7.0),
3033 space_after: Some(3.0),
3034 ..Format::default()
3035 },
3036 );
3037 second.collapsed = true;
3038 let mut outline = Outline {
3039 title: false,
3040 min_width: None,
3041 id: ExGuid::default(),
3042 layout: Layout {
3043 max_width: Some(300.0),
3044 ..Layout::default()
3045 },
3046 indents: vec![18.0, 0.0, 27.0],
3047 paragraphs: vec![
3048 first,
3049 second,
3050 paragraph(3, "Hidden", 6, Some(2)),
3051 paragraph(4, "Last", 1, None),
3052 ],
3053 unsupported: Vec::new(),
3054 };
3055 let mut engine = TextEngine::default();
3056 let layout = outline.layout(&mut engine, &BTreeMap::new()).unwrap();
3057 assert_eq!(
3058 layout.paragraphs.iter().map(|p| p.id.n).collect::<Vec<_>>(),
3059 [1, 2, 4]
3060 );
3061 assert_eq!(
3062 layout.paragraphs[1].origin,
3063 [27.0, layout.paragraphs[0].text.height() + 7.0]
3064 );
3065 assert_eq!(
3066 layout.paragraphs[2].origin[1],
3067 layout.paragraphs[1].origin[1] + layout.paragraphs[1].text.height() + 3.0
3068 );
3069 outline.paragraphs[1].collapsed = false;
3070 let expanded = outline.layout(&mut engine, &BTreeMap::new()).unwrap();
3071 assert_eq!(expanded.paragraphs[2].origin[0], 135.0);
3072 assert!(expanded.size[1] > layout.size[1]);
3073 outline.indents[1] = f32::NAN;
3074 assert!(matches!(
3075 outline.layout(&mut engine, &BTreeMap::new()),
3076 Err(LayoutError::InvalidIndentation)
3077 ));
3078 outline.paragraphs.truncate(1);
3079 for (indents, x) in [(vec![18.0, 0.0, 27.0, 27.0], 0.0), (vec![0.0], 27.0)] {
3080 outline.indents = indents;
3081 let single = outline.layout(&mut engine, &BTreeMap::new()).unwrap();
3082 assert_eq!(single.paragraphs[0].origin[0], x);
3083 }
3084 }
3085
3086 /// Text offsets of levels 1 through 5 as OneNote 2010 draws each table (cold reads of
3087 /// Rust-written outlines, measured to the pixel at 96 dpi).
3088 #[test]
3089 fn indentation_follows_onenote_for_short_and_unusual_tables() {
3090 for (indents, expected) in [
3091 (&[18.0, 0.0, 27.0, 27.0][..], [0.0, 27.0, 54.0, 81.0, 108.0]),
3092 (&[18.0, 0.0], [0.0, 27.0, 54.0, 81.0, 108.0]),
3093 (&[0.0, 0.0], [0.0, 27.0, 54.0, 81.0, 108.0]),
3094 (&[0.0], [27.0, 54.0, 81.0, 108.0, 135.0]),
3095 (&[18.0], [27.0, 54.0, 81.0, 108.0, 135.0]),
3096 (&[], [27.0, 54.0, 81.0, 108.0, 135.0]),
3097 (&[0.0, 5.0], [5.0, 32.0, 59.0, 86.0, 113.0]),
3098 (&[5.0, 10.0, 20.0, 40.0], [10.0, 30.0, 70.0, 97.0, 124.0]),
3099 (
3100 &[40.0, 0.0, 10.0, 20.0, 30.0, 50.0],
3101 [0.0, 10.0, 30.0, 60.0, 110.0],
3102 ),
3103 ] {
3104 for (level, x) in (1..).zip(expected) {
3105 assert_eq!(
3106 indentation(level, indents, 500.0).unwrap(),
3107 x,
3108 "{indents:?}"
3109 );
3110 }
3111 }
3112 }
3113
3114 #[test]
3115 fn marker_height_expands_the_paragraph_box_without_changing_text_line_advances() {
3116 let marker_id = ExGuid {
3117 n: 99,
3118 ..ExGuid::default()
3119 };
3120 let mut short = paragraph(1, "Short", 2, None);
3121 short.lists.push(marker_id);
3122 let mut long = paragraph(
3123 2,
3124 "A long paragraph wraps onto several separate lines of text.",
3125 2,
3126 None,
3127 );
3128 long.lists.push(marker_id);
3129 let outline = Outline {
3130 title: false,
3131 min_width: None,
3132 id: ExGuid::default(),
3133 layout: Layout {
3134 max_width: Some(110.0),
3135 width_set_by_user: Some(true),
3136 ..Layout::default()
3137 },
3138 indents: vec![18.0, 0.0, 27.0],
3139 paragraphs: vec![short, long, paragraph(3, "Last", 1, None)],
3140 unsupported: Vec::new(),
3141 };
3142 let definitions = BTreeMap::from([(
3143 marker_id,
3144 Definition {
3145 kind: Kind::List {
3146 font: Some("Courier New".into()),
3147 format: Some("○".into()),
3148 restart: None,
3149 bullet: Some(4),
3150 },
3151 format: Format {
3152 font_size: Some(22.0),
3153 ..Format::default()
3154 },
3155 },
3156 )]);
3157 let mut engine = TextEngine::default();
3158 let layout = outline.layout(&mut engine, &definitions).unwrap();
3159 let short = &layout.paragraphs[0];
3160 let long = &layout.paragraphs[1];
3161 assert!(short.markers[0].0.height() > short.text.height());
3162 assert!(long.text.height() > long.markers[0].0.height());
3163 assert_eq!(long.origin[1], short.markers[0].0.height());
3164 assert_eq!(
3165 layout.paragraphs[2].origin[1],
3166 long.origin[1] + long.text.height()
3167 );
3168 let plain = engine.layout(long.projection.text(), 83.0).unwrap();
3169 assert_eq!(
3170 long.text
3171 .lines()
3172 .map(|(_, l)| l.baseline)
3173 .collect::<Vec<_>>(),
3174 plain.lines().map(|(_, l)| l.baseline).collect::<Vec<_>>()
3175 );
3176 assert_eq!(
3177 short.origin[1]
3178 + short.markers[0].1[1]
3179 + short.markers[0].0.lines().next().unwrap().1.baseline,
3180 short.origin[1] + short.text.lines().next().unwrap().1.baseline
3181 );
3182 assert_eq!(layout.size[0], 110.0);
3183 }
3184
3185 #[test]
3186 fn symbol_fonts_show_what_windows_draws() {
3187 // OneNote's bullet library stores these (`BULLET_LIBRARY`).
3188 assert_eq!(symbol_text("Symbol", "\u{b7}"), "\u{2022}");
3189 assert_eq!(symbol_text("Symbol", "\u{de}"), "\u{21d2}");
3190 assert_eq!(symbol_text("Symbol", "ap\u{f0}"), "\u{3b1}\u{3c0}\u{f8ff}");
3191 assert_eq!(symbol_text("Wingdings", "l\u{ad}"), "\u{f06c}\u{f0ad}");
3192 assert_eq!(symbol_text("Wingdings 2", "\u{9d}"), "\u{f09d}");
3193 assert_eq!(symbol_text("Calibri", "\u{b7}"), "\u{b7}");
3194 }
3195
3196 #[test]
3197 fn numerals_follow_onenote_number_sequences() {
3198 assert_eq!(numeral(Some('\u{0}'), 12).unwrap(), "12");
3199 assert_eq!(numeral(Some('\u{1}'), 1994).unwrap(), "MCMXCIV");
3200 assert_eq!(numeral(Some('\u{2}'), 4).unwrap(), "iv");
3201 assert_eq!(numeral(Some('\u{3}'), 3).unwrap(), "C");
3202 assert_eq!(numeral(Some('\u{4}'), 26).unwrap(), "z");
3203 assert!(numeral(Some('\u{1}'), 0).is_err());
3204 // As OneNote 2010 renders them through COM: letters to 800, Roman numerals to 4010.
3205 assert_eq!(numeral(Some('\u{4}'), 27).unwrap(), "aa");
3206 assert_eq!(numeral(Some('\u{3}'), 105).unwrap(), "AAAAA");
3207 assert_eq!(numeral(Some('\u{3}'), 780).unwrap(), "Z".repeat(30));
3208 assert_eq!(numeral(Some('\u{3}'), 781).unwrap(), "A");
3209 assert_eq!(numeral(Some('\u{3}'), 800).unwrap(), "T");
3210 assert_eq!(numeral(Some('\u{1}'), 3999).unwrap(), "MMMCMXCIX");
3211 assert_eq!(numeral(Some('\u{1}'), 4009).unwrap(), "MMMMIX");
3212 assert_eq!(numeral(Some('\u{2}'), 4000).unwrap(), "mmmm");
3213 assert_eq!(numeral(Some('\u{16}'), 7).unwrap(), "07");
3214 assert_eq!(numeral(Some('\u{16}'), 106).unwrap(), "106");
3215 assert!(numeral(Some('\u{9}'), 1).is_err());
3216 // As OneNote 2010 renders them through COM, 1 to 130.
3217 let words = |sequence, numbers: &[u32]| {
3218 numbers
3219 .iter()
3220 .map(|number| numeral(Some(sequence), *number).unwrap())
3221 .collect::<Vec<_>>()
3222 };
3223 assert_eq!(
3224 words(
3225 '\u{5}',
3226 &[1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 111, 112, 121]
3227 ),
3228 [
3229 "1st", "2nd", "3rd", "4th", "11th", "12th", "13th", "21st", "22nd", "23rd",
3230 "101st", "111th", "112th", "121st"
3231 ]
3232 );
3233 assert_eq!(
3234 words('\u{6}', &[1, 12, 20, 21, 99, 100, 101, 130]),
3235 [
3236 "One",
3237 "Twelve",
3238 "Twenty",
3239 "Twenty-one",
3240 "Ninety-nine",
3241 "One hundred",
3242 "One hundred one",
3243 "One hundred thirty"
3244 ]
3245 );
3246 assert_eq!(
3247 words(
3248 '\u{7}',
3249 &[1, 2, 3, 5, 8, 9, 12, 20, 21, 40, 100, 101, 112, 130]
3250 ),
3251 [
3252 "First",
3253 "Second",
3254 "Third",
3255 "Fifth",
3256 "Eighth",
3257 "Ninth",
3258 "Twelfth",
3259 "Twentieth",
3260 "Twenty-first",
3261 "Fortieth",
3262 "One hundredth",
3263 "One hundred first",
3264 "One hundred twelfth",
3265 "One hundred thirtieth"
3266 ]
3267 );
3268 }
3269}