1//! Reading view: a page's content in reading order, reflowed into one column as wide as a
2//! phone's screen. The reflowed page is only shown; nothing of it is stored.
3//!
4//! Blocks are the page's outlines, pictures, files and drawings, as laid out. Blocks whose
5//! lines or pictures overlap, ink over text, and strokes within reach of each other join
6//! into one piece moved whole. Reading order is a recursive XY cut: rows split by horizontal
7//! gaps, then columns by vertical gaps, left column first. Notes beside one long outline are
8//! asides: the outline splits after the paragraph each note sits beside, and the note follows
9//! it. Text rewraps to the column, pictures shrink to it, and everything else keeps its size.
10
11use crate::{
12 editor::{CanvasEditor, EditorError, TextOutline, page::Content},
13 layout::TextEngine,
14};
15use onestore::{
16 ExGuid,
17 page::{Outline, Page, PageObject, ParagraphContent},
18};
19use std::{collections::BTreeMap, ops::Range};
20
21#[cfg(feature = "gpu")]
22pub(crate) struct Column {
23 #[cfg(feature = "interaction")]
24 pub(crate) width: f32,
25 pub(crate) outlines: Vec<(ExGuid, [f32; 2], crate::outline::OutlineLayout)>,
26 /// Page pictures as the column shows them, `[x0, y0, x1, y1]` in page points.
27 pub(crate) pictures: Vec<(ExGuid, [f32; 4])>,
28 /// Where the note that the page has drawings, which the column leaves out, starts.
29 pub(crate) drawings: Option<([f32; 2], crate::layout::TextLayout)>,
30}
31
32#[cfg(feature = "gpu")]
33impl Column {
34 /// The note's `[x0, y0, x1, y1]` in page points.
35 pub(crate) fn drawings_rect(&self) -> Option<[f32; 4]> {
36 let ([x, y], note) = self.drawings.as_ref()?;
37 Some([*x, *y, x + note.shaped.width(), y + note.height()])
38 }
39
40 /// Where the column shows page picture `id`; None for one it leaves out.
41 pub(crate) fn picture(&self, id: ExGuid) -> Option<[f32; 4]> {
42 self.pictures
43 .iter()
44 .find_map(|(picture, rect)| (*picture == id).then_some(*rect))
45 }
46}
47
48#[cfg(feature = "gpu")]
49pub(crate) fn geometry<'a>(
50 source: &'a TextOutline,
51 column: Option<&'a Column>,
52) -> (crate::editor::OutlineGeometry<'a>, [f32; 2]) {
53 let (shaped, origin) = match column {
54 Some(column) => {
55 let (_, origin, shaped) = column
56 .outlines
57 .iter()
58 .find(|(id, _, _)| *id == source.id)
59 .expect("active column contains every current outline");
60 (shaped, *origin)
61 }
62 None => (source.shaped(), source.origin()),
63 };
64 (crate::editor::OutlineGeometry { source, shaped }, origin)
65}
66
67#[cfg(feature = "interaction")]
68impl Column {
69 /// The page's editable outlines and pictures stacked in reading order, title and its
70 /// header first, or None where something on the page would not reflow.
71 pub(crate) fn build(
72 editor: &CanvasEditor,
73 scene: Option<&crate::gpu::page::PageScene>,
74 width: f32,
75 engine: &mut TextEngine,
76 ) -> Result<Option<Self>, crate::layout::LayoutError> {
77 if !width.is_finite() || width <= 0.0 {
78 return Err(crate::layout::LayoutError::InvalidWidth);
79 }
80 if editor.rtl() {
81 return Ok(None);
82 }
83 let (titles, body): (Vec<_>, Vec<_>) = editor
84 .visible_outlines()
85 .chain(editor.caret_outline())
86 .partition(|outline| outline.title);
87 let title = match titles[..] {
88 [] => None,
89 [title] => Some(title),
90 _ => return Ok(None),
91 };
92 if editor.objects.iter().any(|object| {
93 if let Content::Date { below_title } | Content::Outline { below_title, .. } = object
94 && (below_title.is_none() || *below_title != title.map(|title| title.id))
95 {
96 return true;
97 }
98 if let Content::Outline { source, .. } = object
99 && source
100 .paragraphs
101 .iter()
102 .any(|paragraph| !matches!(paragraph.content, ParagraphContent::Text(_)))
103 {
104 return true;
105 }
106 !matches!(
107 object,
108 Content::Editable(_)
109 | Content::Date { .. }
110 | Content::Outline {
111 below_title: Some(_),
112 ..
113 }
114 | Content::Image(_)
115 | Content::Ink(_)
116 )
117 }) {
118 return Ok(None);
119 }
120 if scene.is_none()
121 && editor
122 .objects
123 .iter()
124 .any(|object| !matches!(object, Content::Editable(_)))
125 {
126 return Ok(None);
127 }
128 let tops = editor
129 .outlines()
130 .iter()
131 .map(|outline| (outline.id, root_tops(outline)))
132 .collect();
133 // Emptied outlines, and one being started, keep their place while typing.
134 let blocks = blocks(
135 editor,
136 editor.visible_outlines().chain(editor.caret_outline()),
137 );
138 if drawn_or_arranged(&blocks).is_some() {
139 return Ok(None);
140 }
141 let ordered = order(blocks, &tops, &mut Vec::new());
142 let rank = |id: ExGuid| {
143 ordered
144 .iter()
145 .position(|block| block.members.contains(&id))
146 .unwrap_or(ordered.len())
147 };
148 enum Piece<'a> {
149 Text(&'a TextOutline),
150 Picture(ExGuid, [f32; 2], [f32; 2]),
151 }
152 let pictures = editor.objects.iter().filter_map(|object| match object {
153 Content::Image(image) if !image.background => Some(Piece::Picture(
154 image.id,
155 crate::origin(&image.layout),
156 crate::outline::image_size(image)?,
157 )),
158 _ => None,
159 });
160 let mut pieces: Vec<_> = body
161 .into_iter()
162 .map(Piece::Text)
163 .chain(pictures)
164 .map(|piece| {
165 let (id, origin) = match piece {
166 Piece::Text(outline) => (outline.id, outline.origin()),
167 Piece::Picture(id, origin, _) => (id, origin),
168 };
169 ((rank(id), origin), piece)
170 })
171 .collect();
172 pieces.sort_by(|((a_rank, [ax, ay]), _), ((b_rank, [bx, by]), _)| {
173 a_rank
174 .cmp(b_rank)
175 .then(ay.total_cmp(by))
176 .then(ax.total_cmp(bx))
177 });
178 let mut column = Self {
179 width,
180 outlines: Vec::new(),
181 pictures: Vec::new(),
182 drawings: None,
183 };
184 let mut top = 14.4;
185 if let Some(title) = title {
186 let Some(layout) = column_layout(title, editor, width, engine)? else {
187 return Ok(None);
188 };
189 top += layout.size[1] + GAP;
190 column.outlines.push((title.id, [36.0, 14.4], layout));
191 }
192 if let Some(scene) = scene {
193 for (rect, _) in scene.content_bounds(editor, Some(&column)) {
194 if rect[0] < 36.0 || rect[2] > 36.0 + width + 1.0 {
195 return Ok(None);
196 }
197 top = top.max(rect[3] + GAP);
198 }
199 }
200 for (_, piece) in pieces {
201 let height = match piece {
202 Piece::Text(source) => {
203 let Some(layout) = column_layout(source, editor, width, engine)? else {
204 return Ok(None);
205 };
206 let height = layout.size[1];
207 column.outlines.push((source.id, [36.0, top], layout));
208 height
209 }
210 Piece::Picture(id, _, [w, h]) => {
211 let scale = (width / w).min(1.0);
212 column
213 .pictures
214 .push((id, [36.0, top, 36.0 + w * scale, top + h * scale]));
215 h * scale
216 }
217 };
218 top += height + GAP;
219 }
220 if editor
221 .objects
222 .iter()
223 .any(|object| matches!(object, Content::Ink(_)))
224 {
225 let note = engine.layout(
226 &onestore::page::text::Paragraph::new(
227 DRAWINGS_NOTE.into(),
228 onestore::document::Format {
229 font_size: Some(10.0),
230 ..Default::default()
231 },
232 ),
233 width,
234 )?;
235 column.drawings = Some(([36.0, top], note));
236 }
237 Ok(Some(column))
238 }
239}
240
241/// `source` wrapped to a column `width` points wide, or None where it would not fit.
242#[cfg(feature = "interaction")]
243fn column_layout(
244 source: &TextOutline,
245 editor: &CanvasEditor,
246 width: f32,
247 engine: &mut TextEngine,
248) -> Result<Option<crate::outline::OutlineLayout>, crate::layout::LayoutError> {
249 use crate::outline::{OutlineLayout, ParagraphLayout};
250 if source.document().paragraphs().any(|text| {
251 text.spans()
252 .iter()
253 .any(|span| span.format.math == Some(true) || span.format.math_object.is_some())
254 }) {
255 return Ok(None);
256 }
257 // Pictures in the flow shrink to the room their level leaves.
258 let mut nodes = source.document().nodes().to_vec();
259 for node in &mut nodes {
260 match &mut node.content {
261 ParagraphContent::Text(_) | ParagraphContent::Ink(_) => {}
262 ParagraphContent::Image(image) => {
263 let indent = crate::outline::indentation(node.level, &source.indents, width)?;
264 shrink(image, width - indent);
265 }
266 _ => return Ok(None),
267 }
268 }
269 let layout = OutlineLayout::flow(
270 nodes.iter(),
271 &source.indents,
272 width,
273 false,
274 0,
275 None,
276 &mut |node, previous, width, indents| {
277 ParagraphLayout::shape(engine, node, previous, width, indents, &editor.definitions)
278 },
279 )?;
280 let fits = layout.size[0] <= width + 1.0
281 && layout.paragraphs.iter().all(|paragraph| {
282 paragraph.origin[0] >= 0.0
283 && paragraph.origin[0]
284 + paragraph
285 .text
286 .lines()
287 .map(|(line, _)| {
288 line.metrics().advance - line.metrics().trailing_whitespace
289 })
290 .fold(0.0_f32, f32::max)
291 <= width + 1.0
292 });
293 Ok(fits.then_some(layout))
294}
295
296/// Ends a column that leaves out the page's drawings.
297pub(crate) const DRAWINGS_NOTE: &str = "This page has drawings. Turn off Reading View to see them.";
298
299/// Points between blocks in the column: OneNote's grid row.
300const GAP: f32 = 18.0;
301/// Strokes this near one another are one drawing, as handwriting is many strokes.
302const INK_REACH: f32 = 9.0;
303/// The share of the content's area drawn, or kept as laid out, past which the page is a
304/// canvas rather than a document.
305const CANVAS_SHARE: f64 = 0.5;
306/// How far below a paragraph's top a note beside it may start and still follow it.
307const ASIDE_SLACK: f32 = 6.0;
308/// How far an aside sits in from the column's edge, and the room above and below it.
309const ASIDE_INDENT: f32 = 18.0;
310const ASIDE_GAP: f32 = 6.0;
311
312#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
313pub enum Kind {
314 Text,
315 Picture,
316 File,
317 Drawing,
318 /// Overlapping blocks or ink over text, moved as one piece.
319 Group,
320}
321
322#[derive(Clone, Debug, PartialEq)]
323pub struct Block {
324 pub kind: Kind,
325 /// The page objects it moves.
326 pub members: Vec<ExGuid>,
327 /// `[x0, y0, x1, y1]` in page points, as laid out on the page.
328 pub bounds: [f32; 4],
329 /// The outline's top-level paragraphs it shows, where asides split the outline.
330 pub part: Option<Range<usize>>,
331 /// A note beside an outline, read after the paragraph it sits by.
332 pub aside: bool,
333}
334
335#[derive(Clone, Debug, PartialEq, Eq)]
336pub enum Verdict {
337 /// No wider than the column already: shown as laid out.
338 Fits,
339 /// Every block flows into the column.
340 Reflows,
341 /// Flows, with what each `Kept` names read in an order or shape the page decides.
342 Partial(Vec<Kept>),
343 /// Not offered.
344 Refused(Refusal),
345}
346
347#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
348pub enum Kept {
349 /// Notes beside an outline, each placed after the paragraph it sits beside.
350 Asides,
351 /// Blocks side by side, or interlocked, read left column first.
352 SideBySide,
353 /// Overlapping blocks or ink over text, moved whole at their size.
354 Group,
355 /// Something still wider than the column: a table with set column widths, a drawing, a
356 /// group.
357 Wide,
358}
359
360#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
361pub enum Refusal {
362 /// Its positions read from the right; not yet reflowed.
363 RightToLeft,
364 /// Mostly ink.
365 Drawn,
366 /// Mostly overlapping blocks or ink over text.
367 Arranged,
368}
369
370pub struct Reading {
371 pub verdict: Verdict,
372 /// In reading order where the page reflows, else as found.
373 pub blocks: Vec<Block>,
374 /// The page reflowed, where it reflows.
375 pub page: Option<Page>,
376}
377
378impl Verdict {
379 /// Whether the page has a reading view.
380 pub fn offered(&self) -> bool {
381 matches!(self, Self::Reflows | Self::Partial(_))
382 }
383}
384
385/// `page` read into a column `column` points wide.
386pub fn read(page: &Page, column: f32, engine: &mut TextEngine) -> Result<Reading, EditorError> {
387 let editor = CanvasEditor::from_page(page.clone(), engine)?;
388 let blocks = blocks(
389 &editor,
390 editor
391 .outlines()
392 .iter()
393 .filter(|outline| !outline.is_empty()),
394 );
395 let refused = |refusal, blocks| Reading {
396 verdict: Verdict::Refused(refusal),
397 blocks,
398 page: None,
399 };
400 if page.rtl {
401 return Ok(refused(Refusal::RightToLeft, blocks));
402 }
403 let left = blocks
404 .iter()
405 .map(|b| b.bounds[0])
406 .fold(f32::INFINITY, f32::min);
407 let right = blocks
408 .iter()
409 .map(|b| b.bounds[2])
410 .fold(f32::NEG_INFINITY, f32::max);
411 if blocks.is_empty() || right - left <= column + 1.0 {
412 return Ok(Reading {
413 verdict: Verdict::Fits,
414 blocks,
415 page: None,
416 });
417 }
418 if let Some(refusal) = drawn_or_arranged(&blocks) {
419 return Ok(refused(refusal, blocks));
420 }
421 let mut kept = Vec::new();
422 if blocks.iter().any(|b| b.kind == Kind::Group) {
423 kept.push(Kept::Group);
424 }
425 let tops: BTreeMap<ExGuid, Vec<f32>> = editor
426 .outlines()
427 .iter()
428 .map(|outline| (outline.id, root_tops(outline)))
429 .collect();
430 let blocks = order(blocks, &tops, &mut kept);
431 let start = editor.body_start().unwrap_or([left, blocks[0].bounds[1]]);
432 let mut reflowed = page.clone();
433 let blocks = split(&mut reflowed, blocks);
434 reflow(
435 &mut reflowed,
436 &blocks,
437 [start[0].min(left), start[1]],
438 column,
439 engine,
440 &mut kept,
441 )?;
442 kept.sort();
443 kept.dedup();
444 Ok(Reading {
445 verdict: if kept.is_empty() {
446 Verdict::Reflows
447 } else {
448 Verdict::Partial(kept)
449 },
450 blocks,
451 page: Some(reflowed),
452 })
453}
454
455/// Why `blocks` make a canvas rather than a document: mostly ink, or mostly overlapping.
456fn drawn_or_arranged(blocks: &[Block]) -> Option<Refusal> {
457 let area = |kind: Option<Kind>| -> f64 {
458 blocks
459 .iter()
460 .filter(|b| kind.is_none_or(|kind| b.kind == kind))
461 .map(|b| f64::from(b.bounds[2] - b.bounds[0]) * f64::from(b.bounds[3] - b.bounds[1]))
462 .sum()
463 };
464 let total = area(None).max(1.0);
465 if area(Some(Kind::Drawing)) / total >= CANVAS_SHARE {
466 Some(Refusal::Drawn)
467 } else if area(Some(Kind::Group)) / total >= CANVAS_SHARE {
468 Some(Refusal::Arranged)
469 } else {
470 None
471 }
472}
473
474/// Where `outline`'s lines, table cells and pictures lie, in page points.
475fn marks(outline: &TextOutline) -> Vec<[f32; 4]> {
476 let [x, y] = outline.origin();
477 let shaped = outline.shaped();
478 let lines = outline.layouts().flat_map(|(_, paragraph)| {
479 let [px, py] = paragraph.origin;
480 paragraph.text.lines().map(move |(line, bounds)| {
481 let metrics = line.metrics();
482 let left = x + px + metrics.offset;
483 let top = y + py + bounds.top;
484 [
485 left,
486 top,
487 left + metrics.advance - metrics.trailing_whitespace,
488 top + bounds.height,
489 ]
490 })
491 });
492 let cells = shaped
493 .tables
494 .iter()
495 .flat_map(|table| &table.cells)
496 .map(|cell| cell.rect);
497 let objects = shaped.objects.iter().map(|object| object.rect);
498 lines
499 .chain(
500 cells
501 .chain(objects)
502 .map(|rect| crate::translated(rect, [x, y])),
503 )
504 .filter(|[x0, y0, x1, y1]| x1 > x0 && y1 > y0)
505 .collect()
506}
507
508/// The page top of each of `outline`'s top-level paragraphs: its own text's, or the first
509/// shown below it; the one before's where nothing below it shows.
510fn root_tops(outline: &TextOutline) -> Vec<f32> {
511 let source = outline.snapshot();
512 let mut root_of = BTreeMap::new();
513 let mut roots = 0;
514 for paragraph in &source.paragraphs {
515 if paragraph.parent.is_none() {
516 roots += 1;
517 }
518 root_of.insert(paragraph.id, roots - 1);
519 }
520 let y = outline.origin()[1];
521 let mut tops = vec![f32::INFINITY; roots];
522 for (_, paragraph) in outline.layouts() {
523 if let Some(&root) = root_of.get(&paragraph.id) {
524 tops[root] = tops[root].min(y + paragraph.origin[1]);
525 }
526 }
527 let mut last = y;
528 for top in &mut tops {
529 if top.is_finite() {
530 last = *top;
531 } else {
532 *top = last;
533 }
534 }
535 tops
536}
537
538/// A page object as laid out: its identity, kind, bounds, and where its lines and pictures
539/// lie within them.
540type Item = (ExGuid, Kind, [f32; 4], Vec<[f32; 4]>);
541
542/// The page's content as laid out, `outlines` among it, overlapping pieces and nearby
543/// strokes joined.
544fn blocks<'a>(
545 editor: &CanvasEditor,
546 outlines: impl Iterator<Item = &'a TextOutline>,
547) -> Vec<Block> {
548 let mut items: Vec<Item> = outlines
549 .filter(|outline| !outline.title)
550 .map(|outline| {
551 let b = outline.bounds();
552 let bounds = [b.x0, b.y0, b.x1, b.y1].map(|v| v as f32);
553 (outline.id, Kind::Text, bounds, marks(outline))
554 })
555 .collect();
556 for object in &editor.objects {
557 let item = match object {
558 Content::Outline {
559 source,
560 layout,
561 below_title: None,
562 } => {
563 let [x, y] = crate::origin(&source.layout);
564 Some((
565 source.id,
566 Kind::Text,
567 [x, y, x + layout.size[0], y + layout.size[1]],
568 ))
569 }
570 Content::Image(image) if !image.background => {
571 crate::outline::image_size(image).map(|[width, height]| {
572 let [x, y] = crate::origin(&image.layout);
573 (image.id, Kind::Picture, [x, y, x + width, y + height])
574 })
575 }
576 Content::File { source, .. } => object.file().map(|(_, b)| (source.id, Kind::File, b)),
577 Content::Ink(ink) => {
578 crate::editor::page::ink_bounds(ink).map(|b| (ink.id, Kind::Drawing, b))
579 }
580 Content::ReadOnly(object) if !matches!(object.source, PageObject::Title(_)) => {
581 Some((object.source.id(), Kind::Picture, object.rect()))
582 }
583 _ => None,
584 };
585 let item = item.filter(|(_, _, b)| b.iter().all(|v| v.is_finite()));
586 items.extend(item.map(|(id, kind, bounds)| (id, kind, bounds, vec![bounds])));
587 }
588 let mut parent: Vec<usize> = (0..items.len()).collect();
589 fn root(parent: &mut [usize], mut i: usize) -> usize {
590 while parent[i] != i {
591 parent[i] = parent[parent[i]];
592 i = parent[i];
593 }
594 i
595 }
596 let meets = |a: &[f32; 4], b: &[f32; 4], reach: f32| {
597 a[0] < b[2] + reach && b[0] < a[2] + reach && a[1] < b[3] + reach && b[1] < a[3] + reach
598 };
599 for i in 0..items.len() {
600 for j in i + 1..items.len() {
601 let (a, b) = (&items[i], &items[j]);
602 // Touching edges are not overlap.
603 let reach = if a.1 == Kind::Drawing && b.1 == Kind::Drawing {
604 INK_REACH
605 } else {
606 -1.0
607 };
608 if meets(&a.2, &b.2, reach)
609 && a.3.iter().any(|m| b.3.iter().any(|n| meets(m, n, reach)))
610 {
611 let (ra, rb) = (root(&mut parent, i), root(&mut parent, j));
612 parent[ra] = rb;
613 }
614 }
615 }
616 let mut joined: BTreeMap<usize, Block> = BTreeMap::new();
617 for (i, (id, kind, bounds, _)) in items.into_iter().enumerate() {
618 let r = root(&mut parent, i);
619 joined
620 .entry(r)
621 .and_modify(|block| {
622 block.members.push(id);
623 if !(block.kind == Kind::Drawing && kind == Kind::Drawing) {
624 block.kind = Kind::Group;
625 }
626 block.bounds = union(block.bounds, bounds);
627 })
628 .or_insert(Block {
629 kind,
630 members: vec![id],
631 bounds,
632 part: None,
633 aside: false,
634 });
635 }
636 joined.into_values().collect()
637}
638
639fn union(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
640 [
641 a[0].min(b[0]),
642 a[1].min(b[1]),
643 a[2].max(b[2]),
644 a[3].max(b[3]),
645 ]
646}
647
648/// `blocks` in reading order by recursive XY cut: rows first, then columns left to right,
649/// notes beside a single outline as its asides.
650fn order(
651 blocks: Vec<Block>,
652 tops: &BTreeMap<ExGuid, Vec<f32>>,
653 kept: &mut Vec<Kept>,
654) -> Vec<Block> {
655 if blocks.len() <= 1 {
656 return blocks;
657 }
658 let mut parts = cut(blocks, 1);
659 if let [row] = &mut parts[..] {
660 let row = std::mem::take(row);
661 if let Some(asides) = asides(&row, tops) {
662 kept.push(Kept::Asides);
663 return asides;
664 }
665 parts = cut(row, 0);
666 let texts = parts
667 .iter()
668 .filter(|part| part.iter().any(|b| b.kind == Kind::Text));
669 if texts.count() > 1 {
670 kept.push(Kept::SideBySide);
671 }
672 }
673 if let [interlocked] = &mut parts[..] {
674 // No gap runs across: top to bottom, then left to right.
675 kept.push(Kept::SideBySide);
676 let mut blocks = std::mem::take(interlocked);
677 blocks.sort_by(|a, b| {
678 a.bounds[1]
679 .total_cmp(&b.bounds[1])
680 .then(a.bounds[0].total_cmp(&b.bounds[0]))
681 });
682 return blocks;
683 }
684 parts
685 .into_iter()
686 .flat_map(|part| order(part, tops, kept))
687 .collect()
688}
689
690/// `row` as one outline split after each paragraph a note beside it sits by, where every
691/// other block is text no taller than the outline and clear of it across.
692fn asides(row: &[Block], tops: &BTreeMap<ExGuid, Vec<f32>>) -> Option<Vec<Block>> {
693 let height = |b: &Block| b.bounds[3] - b.bounds[1];
694 let main = row
695 .iter()
696 .filter(|b| b.kind == Kind::Text)
697 .max_by(|a, b| height(a).total_cmp(&height(b)))?;
698 let tops = tops.get(&main.members[0])?;
699 let mut notes: Vec<&Block> = row.iter().filter(|b| *b != main).collect();
700 let beside = |b: &Block| {
701 b.kind == Kind::Text
702 && height(b) < height(main)
703 && (b.bounds[0] >= main.bounds[0] + 72.0 || b.bounds[2] <= main.bounds[0])
704 };
705 if notes.is_empty() || tops.len() < 2 || !notes.iter().all(|b| beside(b)) {
706 return None;
707 }
708 notes.sort_by(|a, b| a.bounds[1].total_cmp(&b.bounds[1]));
709 let mut out = Vec::new();
710 let mut from = 0;
711 let slice = |range: Range<usize>| {
712 let mut bounds = main.bounds;
713 bounds[1] = tops[range.start];
714 bounds[3] = tops.get(range.end).copied().unwrap_or(main.bounds[3]);
715 Block {
716 part: Some(range),
717 bounds,
718 ..main.clone()
719 }
720 };
721 for note in notes {
722 let after = tops
723 .partition_point(|top| *top <= note.bounds[1] + ASIDE_SLACK)
724 .max(1);
725 if after > from {
726 out.push(slice(from..after));
727 from = after;
728 }
729 out.push(Block {
730 aside: true,
731 ..note.clone()
732 });
733 }
734 if from < tops.len() {
735 out.push(slice(from..tops.len()));
736 }
737 Some(out)
738}
739
740/// `blocks` split at each gap along `axis` (0 for x, 1 for y) that no block spans.
741fn cut(mut blocks: Vec<Block>, axis: usize) -> Vec<Vec<Block>> {
742 blocks.sort_by(|a, b| a.bounds[axis].total_cmp(&b.bounds[axis]));
743 let mut parts: Vec<Vec<Block>> = Vec::new();
744 let mut end = f32::NEG_INFINITY;
745 for block in blocks {
746 if parts.is_empty() || block.bounds[axis] >= end {
747 parts.push(Vec::new());
748 }
749 end = end.max(block.bounds[axis + 2]);
750 parts.last_mut().unwrap().push(block);
751 }
752 parts
753}
754
755/// Splits each outline asides cut into one outline per part, shown only: the first part
756/// keeps the outline's identity, the others take ones derived from it.
757fn split(page: &mut Page, mut blocks: Vec<Block>) -> Vec<Block> {
758 let mut whole: BTreeMap<ExGuid, Outline> = BTreeMap::new();
759 for block in &mut blocks {
760 let Some(range) = block.part.clone() else {
761 continue;
762 };
763 let id = block.members[0];
764 let source = match whole.get(&id) {
765 Some(source) => source.clone(),
766 None => {
767 let Some(PageObject::Outline(source)) = object_mut(page, id).cloned() else {
768 continue;
769 };
770 whole.insert(id, source.clone());
771 source
772 }
773 };
774 let mut root = 0;
775 let paragraphs = source
776 .paragraphs
777 .iter()
778 .filter(|paragraph| {
779 if paragraph.parent.is_none() {
780 root += 1;
781 }
782 range.contains(&(root - 1))
783 })
784 .cloned()
785 .collect();
786 let part = Outline {
787 id: if range.start == 0 {
788 id
789 } else {
790 ExGuid {
791 guid: id.guid,
792 n: id.n ^ (0x8000_0000 | range.start as u32),
793 }
794 },
795 paragraphs,
796 ..source
797 };
798 block.members[0] = part.id;
799 match object_mut(page, part.id) {
800 Some(object) => *object = PageObject::Outline(part),
801 None => page.objects.push(PageObject::Outline(part)),
802 }
803 }
804 blocks
805}
806
807/// Stacks `blocks` in order from `start` down a column `column` wide.
808fn reflow(
809 page: &mut Page,
810 blocks: &[Block],
811 start: [f32; 2],
812 column: f32,
813 engine: &mut TextEngine,
814 kept: &mut Vec<Kept>,
815) -> Result<(), EditorError> {
816 let [left, mut y] = start;
817 // Widths first: text rewraps, pictures shrink, the rest moves across whole.
818 let mut heights = Vec::with_capacity(blocks.len());
819 for block in blocks {
820 let [x0, y0, x1, y1] = block.bounds;
821 let mut height = y1 - y0;
822 let indent = if block.aside { ASIDE_INDENT } else { 0.0 };
823 match (block.kind, object_mut(page, block.members[0])) {
824 (Kind::Text, Some(PageObject::Outline(outline))) => {
825 outline.layout.x = Some(left + indent);
826 outline.layout.max_width = Some((x1 - x0).min(column - indent));
827 outline.layout.reserved_width = None;
828 outline.min_width = None;
829 collapse_blanks(outline);
830 for paragraph in &mut outline.paragraphs {
831 if let ParagraphContent::Image(image) = &mut paragraph.content {
832 shrink(image, column - 36.0);
833 }
834 }
835 }
836 (Kind::Picture, Some(PageObject::Image(image))) => {
837 image.layout.x = Some(left);
838 height = shrink(image, column).unwrap_or(height);
839 }
840 _ => {
841 for &id in &block.members {
842 if let Some(object) = object_mut(page, id) {
843 let layout = object.layout_mut();
844 layout.x = Some(layout.x.unwrap_or(0.0) + left - x0);
845 }
846 }
847 if x1 - x0 > column + 1.0 {
848 kept.push(Kept::Wide);
849 }
850 }
851 }
852 heights.push(height);
853 }
854 // Text heights at the new widths.
855 let laid = CanvasEditor::from_page(page.clone(), engine)?;
856 for (block, height) in blocks.iter().zip(&mut heights) {
857 if block.kind != Kind::Text {
858 continue;
859 }
860 if let Some(outline) = laid.outlines().iter().find(|o| o.id == block.members[0]) {
861 let b = outline.bounds();
862 *height = (b.y1 - b.y0) as f32;
863 if (b.x1 - b.x0) as f32 > column + 1.0 {
864 kept.push(Kept::Wide);
865 }
866 }
867 }
868 for (index, (block, height)) in blocks.iter().zip(&heights).enumerate() {
869 // Asides and the parts of the outline they split sit close.
870 let close = |block: &Block| block.aside || block.part.as_ref().is_some_and(|p| p.start > 0);
871 if index > 0 {
872 let previous = &blocks[index - 1];
873 y += if close(block) || previous.aside {
874 ASIDE_GAP
875 } else {
876 GAP
877 };
878 }
879 let dy = y - block.bounds[1];
880 for (index, &id) in block.members.iter().enumerate() {
881 if let Some(object) = object_mut(page, id) {
882 let layout = object.layout_mut();
883 layout.y = Some(
884 if index == 0 && matches!(block.kind, Kind::Text | Kind::Picture) {
885 y
886 } else {
887 layout.y.unwrap_or(0.0) + dy
888 },
889 );
890 }
891 }
892 y += height;
893 }
894 Ok(())
895}
896
897/// Drops each blank top-level paragraph that follows another, as spacing kept a side
898/// column level with the text beside it.
899fn collapse_blanks(outline: &mut Outline) {
900 let blank = |p: &onestore::page::PageParagraph| {
901 p.lists.is_empty()
902 && p.tags.is_empty()
903 && p.text()
904 .is_some_and(|t| t.tags.is_empty() && t.text.text().trim().is_empty())
905 };
906 let parents: std::collections::BTreeSet<ExGuid> =
907 outline.paragraphs.iter().filter_map(|p| p.parent).collect();
908 let mut previous_blank = false;
909 let mut root_kept = true;
910 outline.paragraphs.retain(|p| {
911 if p.parent.is_some() {
912 return root_kept;
913 }
914 let is_blank = blank(p) && !parents.contains(&p.id);
915 root_kept = !(is_blank && previous_blank);
916 previous_blank = is_blank;
917 root_kept
918 });
919}
920
921fn object_mut(page: &mut Page, id: ExGuid) -> Option<&mut PageObject> {
922 page.objects.iter_mut().find(|object| object.id() == id)
923}
924
925/// Scales `image` down to `width` points across, keeping its shape; its new height.
926fn shrink(image: &mut onestore::page::Image, width: f32) -> Option<f32> {
927 let [w, h] = crate::outline::image_size(image)?;
928 let scale = (width / w).min(1.0);
929 image.layout.max_width = Some(w * scale);
930 image.layout.max_height = Some(h * scale);
931 Some(h * scale)
932}