1//! An editable page model: outlines, paragraphs, tables and images with their stored
2//! identities, plus everything else on the page retained as `Unsupported`.
3
4use crate::{
5 Error, ExGuid,
6 document::{Document, Element, FieldValue, Format, Kind, Layout, Revision, Tag},
7};
8use std::{
9 collections::{BTreeMap, BTreeSet},
10 sync::Arc,
11};
12
13pub mod ink;
14mod linear;
15pub mod link;
16pub mod math;
17pub mod text;
18
19pub use ink::{Ink, InkStroke};
20pub use math::Math;
21
22/// Picture and attachment payloads travel with the model (queued intents replay them),
23/// as base64 text.
24mod payload {
25 use base64::{Engine, display::Base64Display, engine::general_purpose::STANDARD};
26 use std::sync::Arc;
27
28 struct Encoded<'a>(&'a [u8]);
29
30 impl serde::Serialize for Encoded<'_> {
31 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
32 serializer.collect_str(&Base64Display::new(self.0, &STANDARD))
33 }
34 }
35
36 pub fn serialize<S: serde::Serializer>(
37 bytes: &Option<Arc<[u8]>>,
38 serializer: S,
39 ) -> Result<S::Ok, S::Error> {
40 match bytes {
41 Some(bytes) => serializer.serialize_some(&Encoded(bytes)),
42 None => serializer.serialize_none(),
43 }
44 }
45
46 pub fn deserialize<'de, D: serde::Deserializer<'de>>(
47 deserializer: D,
48 ) -> Result<Option<Arc<[u8]>>, D::Error> {
49 let text: Option<String> = serde::Deserialize::deserialize(deserializer)?;
50 text.map(|text| {
51 STANDARD
52 .decode(text)
53 .map(Arc::from)
54 .map_err(serde::de::Error::custom)
55 })
56 .transpose()
57 }
58}
59pub use text::Paragraph;
60
61/// The page node's colour (View, Page Color) as COLORREF, absent for "No color"; not in
62/// MS-ONE, observed in OneNote 2010's pages (`corpus/notebook-management/native/page-color`).
63pub(crate) const PAGE_COLOR: u32 = 0x14001d2a;
64
65/// The page node's rule lines (View, Rule Lines), as OneNote 2010 orders them; not in MS-ONE,
66/// observed in its pages (`corpus/rule-lines/native`). Each direction stores a kind (1 grid,
67/// 2 ruled, 3 margin line), a spacing in half inches and a colour as 0xAARRGGBB.
68pub(crate) const RULE_LINES: [u32; 6] = [
69 HORIZONTAL_COLOR,
70 HORIZONTAL_KIND,
71 HORIZONTAL_SPACING,
72 VERTICAL_KIND,
73 VERTICAL_SPACING,
74 VERTICAL_COLOR,
75];
76const HORIZONTAL_KIND: u32 = 0x14001cd3;
77const HORIZONTAL_SPACING: u32 = 0x14001cd4;
78const HORIZONTAL_COLOR: u32 = 0x14001cd5;
79const VERTICAL_KIND: u32 = 0x14001cd6;
80const VERTICAL_SPACING: u32 = 0x14001cd7;
81const VERTICAL_COLOR: u32 = 0x14001cd8;
82
83/// A page's rule lines (View, Rule Lines): horizontal lines every `spacing` from the margin
84/// origin down, crossed by a margin line or a grid's vertical lines. Spacings are in half
85/// inches, as stored, so OneNote's presets survive exactly.
86#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
87pub struct RuleLines {
88 pub spacing: f32,
89 /// COLORREF.
90 pub color: u32,
91 pub vertical: VerticalRule,
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
95pub enum VerticalRule {
96 /// One line just left of the margin origin, COLORREF.
97 Margin(u32),
98 /// Lines every `spacing` either side of the margin origin.
99 Grid { spacing: f32, color: u32 },
100}
101
102impl RuleLines {
103 /// The page node's properties for these lines, in `RULE_LINES` order.
104 pub(crate) fn properties(&self) -> [(u32, [u8; 4]); 6] {
105 let argb = |color: u32| {
106 let [red, green, blue, _] = color.to_le_bytes();
107 [blue, green, red, 0xff]
108 };
109 let (kinds, spacing, color) = match self.vertical {
110 VerticalRule::Margin(color) => ([2, 3], 0.0, color),
111 VerticalRule::Grid { spacing, color } => ([1, 1], spacing, color),
112 };
113 [
114 (HORIZONTAL_COLOR, argb(self.color)),
115 (HORIZONTAL_KIND, u32::to_le_bytes(kinds[0])),
116 (HORIZONTAL_SPACING, self.spacing.to_le_bytes()),
117 (VERTICAL_KIND, u32::to_le_bytes(kinds[1])),
118 (VERTICAL_SPACING, spacing.to_le_bytes()),
119 (VERTICAL_COLOR, argb(color)),
120 ]
121 }
122
123 /// The lines a page node's `fields` store, if any are whole enough to draw.
124 fn read(fields: &[crate::document::Field<'_>]) -> Option<Self> {
125 let value = |id: u32| {
126 fields
127 .iter()
128 .find(|field| field.id == id)
129 .and_then(|field| match field.value {
130 FieldValue::Bytes(&[a, b, c, d]) => Some([a, b, c, d]),
131 _ => None,
132 })
133 };
134 let spacing = |id| value(id).map(f32::from_le_bytes);
135 let color =
136 |id| value(id).map(|[blue, green, red, _]| u32::from_le_bytes([red, green, blue, 0]));
137 value(HORIZONTAL_KIND)?;
138 let vertical = match value(VERTICAL_KIND).map(u32::from_le_bytes) {
139 Some(1) => VerticalRule::Grid {
140 spacing: spacing(VERTICAL_SPACING)?,
141 color: color(VERTICAL_COLOR)?,
142 },
143 _ => VerticalRule::Margin(color(VERTICAL_COLOR)?),
144 };
145 Some(Self {
146 spacing: spacing(HORIZONTAL_SPACING).filter(|spacing| *spacing > 0.0)?,
147 color: color(HORIZONTAL_COLOR)?,
148 vertical,
149 })
150 }
151}
152
153/// The role of a title-outline paragraph that displays the page's creation date or time.
154#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
155pub enum DateField {
156 Date = 0,
157 Time = 1,
158}
159
160#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
161pub struct Page {
162 pub title: String,
163 /// The page's notebook-management identity, which internal links name as `page-id`.
164 pub identity: Option<[u8; 16]>,
165 /// FILETIME ticks from the page's TopologyCreationTimeStamp.
166 pub created: Option<u64>,
167 pub margin_origin: [f32; 2],
168 /// Right-to-left page direction, whose positions keep the left-to-right frame.
169 #[serde(default)]
170 pub rtl: bool,
171 /// The page's colour (View, Page Color), COLORREF; `None` is OneNote's "No color".
172 #[serde(default)]
173 pub color: Option<u32>,
174 #[serde(default)]
175 pub rule_lines: Option<RuleLines>,
176 pub objects: Vec<PageObject>,
177 pub definitions: BTreeMap<ExGuid, Definition>,
178}
179
180#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
181pub struct Definition {
182 pub kind: Kind<'static>,
183 pub format: Format,
184}
185
186#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
187pub enum PageObject {
188 Outline(Outline),
189 Title(Title),
190 Image(Image),
191 /// A file on a blank part of the page, as OneNote places one attached or dropped there.
192 Attachment(Attachment),
193 Ink(Ink),
194 Unsupported(Unsupported),
195}
196
197impl PageObject {
198 pub fn id(&self) -> ExGuid {
199 match self {
200 Self::Outline(value) => value.id,
201 Self::Title(value) => value.id,
202 Self::Image(value) => value.id,
203 Self::Attachment(value) => value.id,
204 Self::Ink(value) => value.id,
205 Self::Unsupported(value) => value.id,
206 }
207 }
208 pub fn layout(&self) -> &Layout {
209 match self {
210 Self::Outline(value) => &value.layout,
211 Self::Title(value) => &value.layout,
212 Self::Image(value) => &value.layout,
213 Self::Attachment(value) => &value.layout,
214 Self::Ink(value) => &value.layout,
215 Self::Unsupported(value) => &value.layout,
216 }
217 }
218
219 pub fn layout_mut(&mut self) -> &mut Layout {
220 match self {
221 Self::Outline(value) => &mut value.layout,
222 Self::Title(value) => &mut value.layout,
223 Self::Image(value) => &mut value.layout,
224 Self::Attachment(value) => &mut value.layout,
225 Self::Ink(value) => &mut value.layout,
226 Self::Unsupported(value) => &mut value.layout,
227 }
228 }
229}
230
231#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
232pub struct Title {
233 pub id: ExGuid,
234 pub date: Option<ExGuid>,
235 pub layout: Layout,
236 pub outlines: Vec<Outline>,
237}
238
239#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
240pub struct Outline {
241 pub id: ExGuid,
242 pub title: bool,
243 pub min_width: Option<f32>,
244 pub layout: Layout,
245 pub indents: Vec<f32>,
246 pub paragraphs: Vec<PageParagraph>,
247 pub unsupported: Vec<Unsupported>,
248}
249
250#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
251pub struct PageParagraph {
252 pub id: ExGuid,
253 pub parent: Option<ExGuid>,
254 pub level: u32,
255 pub style: Option<ExGuid>,
256 pub format: Format,
257 pub content: ParagraphContent,
258 pub lists: Vec<ExGuid>,
259 pub tags: Vec<Tag>,
260 pub media: MediaIndex,
261 pub collapsed: bool,
262}
263
264#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
265pub enum ParagraphContent {
266 Text(TextObject),
267 Table(Table),
268 /// A picture inside the paragraph, as OneNote inserts pictures into outlines.
269 Image(Image),
270 /// An embedded file, as OneNote inserts attachments into outlines.
271 Attachment(Attachment),
272 /// Handwriting held by the paragraph.
273 Ink(Ink),
274 Unsupported(Unsupported),
275}
276
277/// Payload bytes are identified by `id`, so equality and serialization leave them out.
278#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
279pub struct Attachment {
280 pub id: ExGuid,
281 /// The name OneNote shows and saves the file under.
282 pub filename: String,
283 /// Where the file was inserted from, when recorded.
284 pub source_path: Option<String>,
285 /// The icon's size in points.
286 pub size: Option<[f32; 2]>,
287 /// On the page, where the file's column sits and its extent; a paragraph's file has none.
288 #[serde(default)]
289 pub layout: Layout,
290 #[serde(with = "payload")]
291 pub bytes: Option<Arc<[u8]>>,
292 #[serde(with = "payload")]
293 pub preview: Option<Arc<[u8]>>,
294 /// Set when the file is audio or video OneNote plays; notes on the page refer to it by
295 /// identity (`PageParagraph::media`).
296 pub recording: Option<Recording>,
297 /// Note tags on the file itself, where OneNote stores a tagged file's, in a paragraph or
298 /// on the page.
299 #[serde(default)]
300 pub tags: Vec<Tag>,
301}
302
303/// A recording's identity, whether it is audio (1) or video (2), and its length.
304#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
305pub struct Recording {
306 pub id: [u8; 16],
307 pub kind: u32,
308 pub duration_ms: Option<u32>,
309}
310
311impl Recording {
312 /// The kind of recording MS-ONE requires a file named `filename` to be, if any: audio
313 /// for .wma, .mp3 and .wav, video for .wmv, .avi and .mpg.
314 pub fn kind_of(filename: &str) -> Option<u32> {
315 let extension = filename.rsplit_once('.')?.1.to_ascii_lowercase();
316 match extension.as_str() {
317 "wma" | "mp3" | "wav" => Some(1),
318 "wmv" | "avi" | "mpg" => Some(2),
319 _ => None,
320 }
321 }
322}
323
324/// A paragraph's link to a moment in recordings on the page: OneNote plays from
325/// `time_ms` when the paragraph is chosen, and links what is written while it records.
326#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
327pub struct MediaIndex {
328 pub recordings: Vec<[u8; 16]>,
329 pub time_ms: Option<u32>,
330}
331
332impl PartialEq for Attachment {
333 fn eq(&self, other: &Self) -> bool {
334 self.id == other.id
335 && self.filename == other.filename
336 && self.source_path == other.source_path
337 && self.size == other.size
338 && self.layout == other.layout
339 && self.recording == other.recording
340 && self.tags == other.tags
341 }
342}
343
344impl Attachment {
345 pub(crate) fn read(
346 revision: &Revision<'_>,
347 id: ExGuid,
348 node: &crate::document::Element<'_>,
349 ) -> Result<Self, Error> {
350 let invalid = |message| Error { offset: 0, message };
351 let Kind::Attachment {
352 container,
353 preview,
354 filename,
355 source_path,
356 recording_id,
357 recording_type,
358 recording_duration,
359 icon_width,
360 icon_height,
361 } = &node.kind
362 else {
363 unreachable!()
364 };
365 let payload = |target: &Option<ExGuid>| -> Result<Option<Arc<[u8]>>, Error> {
366 let Some(target) = target else {
367 return Ok(None);
368 };
369 let data = revision
370 .nodes
371 .get(target)
372 .ok_or_else(|| invalid("Missing canvas attachment data"))?;
373 match &data.kind {
374 Kind::File { payload, .. } => Ok(payload.map(Arc::from)),
375 _ => Err(invalid("Canvas attachment data has the wrong type")),
376 }
377 };
378 Ok(Self {
379 id,
380 filename: filename.clone().unwrap_or_default(),
381 source_path: source_path.clone(),
382 size: icon_width.zip(*icon_height).map(|(w, h)| [w, h]),
383 layout: node.layout.clone(),
384 bytes: payload(container)?,
385 preview: payload(preview)?,
386 recording: recording_id.map(|id| Recording {
387 id,
388 kind: recording_type
389 .or_else(|| Recording::kind_of(filename.as_deref().unwrap_or_default()))
390 .unwrap_or(1),
391 duration_ms: *recording_duration,
392 }),
393 tags: node.tags.clone(),
394 })
395 }
396}
397
398#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
399pub struct Table {
400 pub id: ExGuid,
401 pub columns: Vec<TableColumn>,
402 pub rows: Vec<TableRow>,
403 pub borders: Option<bool>,
404 pub layout: Layout,
405 pub tags: Vec<Tag>,
406}
407
408#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
409pub struct TableColumn {
410 pub width: f32,
411 pub locked: bool,
412}
413
414#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
415pub struct TableRow {
416 pub id: ExGuid,
417 pub cells: Vec<TableCell>,
418}
419
420#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
421pub struct TableCell {
422 pub id: ExGuid,
423 pub layout: Layout,
424 pub indents: Vec<f32>,
425 pub shading: Option<u32>,
426 pub paragraphs: Vec<PageParagraph>,
427 pub unsupported: Vec<Unsupported>,
428}
429
430#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
431pub struct TextObject {
432 pub id: ExGuid,
433 pub date_field: Option<DateField>,
434 pub text: Paragraph,
435 pub tags: Vec<Tag>,
436}
437
438/// Payload bytes are identified by `id`, so equality and serialization leave them out.
439#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
440pub struct Image {
441 pub id: ExGuid,
442 pub layout: Layout,
443 /// Displayed picture width and height in points.
444 pub size: Option<[f32; 2]>,
445 #[serde(with = "payload")]
446 pub bytes: Option<Arc<[u8]>>,
447 /// The raster OneNote shows for a picture stored in a format it draws itself, a
448 /// printout's XPS page or a metafile (WebPictureContainer14).
449 #[serde(default, with = "payload")]
450 pub display: Option<Arc<[u8]>>,
451 pub alt: Option<String>,
452 pub background: bool,
453 /// Set when the picture is a page of a file printout, which OneNote frames.
454 #[serde(default)]
455 pub printout: Option<Printout>,
456 /// Note tags on the picture itself, where OneNote stores a tagged picture's, in a
457 /// paragraph or on the page.
458 #[serde(default)]
459 pub tags: Vec<Tag>,
460 /// The address the picture links to (WzHyperlinkUrl).
461 #[serde(default)]
462 pub link: Option<String>,
463 /// Text OneNote recognised in the picture, or a printout page's text; OneNote searches
464 /// it.
465 #[serde(default)]
466 pub text: Option<Recognized>,
467}
468
469/// Text a picture holds (RichEditTextUnicode).
470#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
471pub struct Recognized {
472 pub text: String,
473 /// Its language (RichEditTextLangID) and the undocumented layout of its words,
474 /// `RECOGNIZED_PROPERTIES`, written back as read.
475 pub stored: Vec<(u32, Vec<u8>)>,
476}
477
478/// RichEditTextLangID, and where OneNote 2010 found each word of a picture's text
479/// (`corpus/object-tags`), not in MS-ONE.
480pub(crate) const RECOGNIZED_PROPERTIES: [u32; 2] = [0x10001cfe, 0x1c001d61];
481
482/// A page of a file printout.
483#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
484pub struct Printout {
485 /// The page shown, zero-based (DisplayedPageNumber).
486 pub page: u32,
487 /// The undocumented properties tying the page to its XPS package, `PRINTOUT_PROPERTIES`,
488 /// written back as read; without them OneNote does not draw a page it reads back.
489 pub stored: Vec<(u32, Vec<u8>)>,
490}
491
492/// The printout's identity, its file's index and the page's place in it, as OneNote 2010
493/// stores them on a printout page (`corpus/printout`), not in MS-ONE; with the picture's
494/// file name (ImageFilename) and the package's description and hash, also undocumented.
495pub(crate) const PRINTOUT_PROPERTIES: [u32; 6] = [
496 0x1c001d84, 0x14003480, 0x14003481, 0x1c001dd7, 0x1c001dfb, 0x1c001dfc,
497];
498
499impl PartialEq for Image {
500 fn eq(&self, other: &Self) -> bool {
501 self.id == other.id
502 && self.layout == other.layout
503 && self.size == other.size
504 && self.alt == other.alt
505 && self.background == other.background
506 && self.printout == other.printout
507 && self.tags == other.tags
508 && self.link == other.link
509 && self.text == other.text
510 }
511}
512
513impl Image {
514 pub(crate) fn read(
515 revision: &Revision<'_>,
516 id: ExGuid,
517 node: &crate::document::Element<'_>,
518 ) -> Result<Self, Error> {
519 let invalid = |message| Error { offset: 0, message };
520 let Kind::Image {
521 container,
522 alt,
523 background,
524 printout,
525 picture_width,
526 picture_height,
527 link,
528 filename,
529 ..
530 } = &node.kind
531 else {
532 unreachable!()
533 };
534 let payload = |container: Option<&ExGuid>| -> Result<Option<Arc<[u8]>>, Error> {
535 let Some(container) = container else {
536 return Ok(None);
537 };
538 let data = revision
539 .nodes
540 .get(container)
541 .ok_or_else(|| invalid("Missing canvas image data"))?;
542 match &data.kind {
543 Kind::File { payload, .. } => Ok(payload.map(Arc::from)),
544 _ => Err(invalid("Canvas image data has the wrong type")),
545 }
546 };
547 let bytes = payload(container.as_ref())?;
548 let fields = node.extra.first().map(Vec::as_slice).unwrap_or_default();
549 let web = fields.iter().find_map(|field| match &field.value {
550 FieldValue::Objects(ids) if field.id == 0x200034c8 => ids.first(),
551 _ => None,
552 });
553 Ok(Self {
554 id,
555 layout: node.layout.clone(),
556 size: picture_width.zip(*picture_height).map(|(w, h)| [w, h]),
557 bytes,
558 display: payload(web)?,
559 alt: alt.clone(),
560 background: background.unwrap_or(false),
561 printout: printout.unwrap_or(false).then(|| Printout {
562 page: fields
563 .iter()
564 .find_map(|field| match field.value {
565 FieldValue::Bytes(&[a, b, c, d]) if field.id == 0x14001df9 => {
566 Some(u32::from_le_bytes([a, b, c, d]))
567 }
568 _ => None,
569 })
570 .unwrap_or(0),
571 stored: filename
572 .iter()
573 .map(|name| (0x1c001dd7, crate::create::string(name)))
574 .chain(fields.iter().filter_map(|field| match field.value {
575 FieldValue::Bytes(bytes) if PRINTOUT_PROPERTIES.contains(&field.id) => {
576 Some((field.id, bytes.to_vec()))
577 }
578 _ => None,
579 }))
580 .collect(),
581 }),
582 tags: node.tags.clone(),
583 link: link.clone(),
584 text: fields
585 .iter()
586 .find_map(|field| match field.value {
587 FieldValue::Bytes(bytes) if field.id == 0x1c001c22 => Some(bytes),
588 _ => None,
589 })
590 .map(|bytes| {
591 let units: Vec<u16> = bytes
592 .as_chunks::<2>()
593 .0
594 .iter()
595 .map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
596 .collect();
597 String::from_utf16_lossy(&units)
598 .trim_end_matches('\0')
599 .to_owned()
600 })
601 .filter(|text| !text.trim().is_empty())
602 .map(|text| Recognized {
603 text,
604 stored: fields
605 .iter()
606 .filter_map(|field| match field.value {
607 FieldValue::Bytes(bytes)
608 if RECOGNIZED_PROPERTIES.contains(&field.id) =>
609 {
610 Some((field.id, bytes.to_vec()))
611 }
612 _ => None,
613 })
614 .collect(),
615 }),
616 })
617 }
618}
619
620#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
621pub struct Unsupported {
622 pub id: ExGuid,
623 pub jcid: u32,
624 pub layout: Layout,
625}
626
627impl Page {
628 pub fn from_document(document: &Document<'_>, title: &str) -> Result<Self, Error> {
629 let mut selected = None;
630 for (space, id) in document.pages()? {
631 let revision = document.active(space)?;
632 if page_title(revision, id)
633 .map(crate::edit::without_fields)
634 .as_deref()
635 == Some(title)
636 {
637 if selected.is_some() {
638 return Err(Error {
639 offset: 0,
640 message: "More than one active page has the requested title",
641 });
642 }
643 selected = Some((revision, id));
644 }
645 }
646 let (revision, id) = selected.ok_or(Error {
647 offset: 0,
648 message: "No active page has the requested title",
649 })?;
650 Self::from_revision(revision, id)
651 }
652
653 /// The page's content under fresh identities, for a copy into this or another section:
654 /// OneNote gives a copied page and every object on it new identities, and stored
655 /// links keep naming the original. Content outside the model has no copy, so an
656 /// `Unsupported` object is an error.
657 pub fn copy(&self) -> Result<Self, Error> {
658 self.copy_with(&mut [])
659 }
660
661 /// `copy`, renaming `ids`, identities on this page, to theirs on the copy.
662 pub fn copy_with(&self, ids: &mut [ExGuid]) -> Result<Self, Error> {
663 let invalid = |message| Error { offset: 0, message };
664 let mut value =
665 serde_json::to_value((self, &*ids)).map_err(|_| invalid("Page is not serializable"))?;
666 let mut fresh: BTreeMap<String, String> = BTreeMap::new();
667 fn walk(
668 value: &mut serde_json::Value,
669 fresh: &mut BTreeMap<String, String>,
670 ) -> Result<(), Error> {
671 match value {
672 serde_json::Value::String(text) if text.starts_with('{') => {
673 if text.parse::<ExGuid>().is_ok() {
674 if !fresh.contains_key(text) {
675 fresh.insert(text.clone(), text::new_id()?.to_string());
676 }
677 *text = fresh[text].clone();
678 }
679 }
680 serde_json::Value::Array(items) => {
681 for item in items {
682 walk(item, fresh)?;
683 }
684 }
685 serde_json::Value::Object(fields) => {
686 if fields.contains_key("Unsupported") {
687 return Err(Error {
688 offset: 0,
689 message: "Content outside the page model cannot be copied",
690 });
691 }
692 let keys: Vec<String> = fields.keys().cloned().collect();
693 for key in keys {
694 let mut item = fields.remove(&key).unwrap();
695 walk(&mut item, fresh)?;
696 let key = match key.parse::<ExGuid>() {
697 Ok(_) => {
698 if !fresh.contains_key(&key) {
699 fresh.insert(key.clone(), text::new_id()?.to_string());
700 }
701 fresh[&key].clone()
702 }
703 Err(_) => key,
704 };
705 fields.insert(key, item);
706 }
707 }
708 _ => {}
709 }
710 Ok(())
711 }
712 walk(&mut value, &mut fresh)?;
713 let (mut copy, renamed): (Self, Vec<ExGuid>) =
714 serde_json::from_value(value).map_err(|_| invalid("Page copy does not deserialize"))?;
715 ids.copy_from_slice(&renamed);
716 copy.identity = Some(crate::write::fresh_guid()?);
717 // A paragraph's indent level follows its parent chain; a level beyond that comes
718 // from an outline group, which the model does not hold.
719 fn levels(paragraphs: &[PageParagraph]) -> bool {
720 let by_id: BTreeMap<ExGuid, u32> = paragraphs.iter().map(|p| (p.id, p.level)).collect();
721 paragraphs.iter().all(|paragraph| {
722 let expected = match paragraph.parent {
723 Some(parent) => by_id.get(&parent).map_or(0, |level| level + 1),
724 None => 1,
725 };
726 paragraph.level == expected
727 && match &paragraph.content {
728 ParagraphContent::Table(table) => table
729 .rows
730 .iter()
731 .flat_map(|row| &row.cells)
732 .all(|cell| levels(&cell.paragraphs)),
733 _ => true,
734 }
735 })
736 }
737 let expressible = copy.objects.iter().all(|object| match object {
738 PageObject::Outline(outline) => levels(&outline.paragraphs),
739 _ => true,
740 });
741 if !expressible {
742 return Err(invalid("Outline groups cannot be copied"));
743 }
744 Ok(copy)
745 }
746
747 /// The date and time the title's date fields show, when it has both.
748 pub fn date_text(&self) -> Option<[String; 2]> {
749 let title = self.objects.iter().find_map(|object| match object {
750 PageObject::Title(title) => Some(title),
751 _ => None,
752 })?;
753 let outline = title
754 .outlines
755 .iter()
756 .find(|outline| Some(outline.id) == title.date)?;
757 let [first, second] = &outline.paragraphs[..] else {
758 return None;
759 };
760 let [first, second] = [first.text()?, second.text()?];
761 let text = |object: &TextObject| object.text.text().to_owned();
762 // OneNote writes the date first; a field marked as the other role says otherwise.
763 Some(
764 if first.date_field == Some(DateField::Time)
765 || second.date_field == Some(DateField::Date)
766 {
767 [text(second), text(first)]
768 } else {
769 [text(first), text(second)]
770 },
771 )
772 }
773
774 /// The notebook-management identity of the page in an active page revision, which
775 /// internal links name.
776 pub fn identity_of(revision: &Revision<'_>) -> Option<[u8; 16]> {
777 revision
778 .roots
779 .get(&2)
780 .and_then(|id| revision.nodes.get(id))
781 .and_then(Self::metadata_identity)
782 }
783
784 /// The identity page metadata element `metadata` holds.
785 pub(crate) fn metadata_identity(metadata: &Element<'_>) -> Option<[u8; 16]> {
786 Some(metadata)
787 .filter(|node| matches!(node.kind, Kind::Metadata { .. }))
788 .and_then(|node| node.extra.first())
789 .and_then(|fields| fields.iter().find(|field| field.id == 0x1c001c30))
790 .and_then(|field| match field.value {
791 FieldValue::Bytes(bytes) => bytes.try_into().ok(),
792 _ => None,
793 })
794 }
795
796 /// The title and outline level (1 at the top) a section's page list shows, read from
797 /// the page's metadata without building its content.
798 pub fn heading(revision: &Revision<'_>, id: ExGuid) -> (String, u32) {
799 let level = revision
800 .roots
801 .get(&2)
802 .and_then(|id| revision.nodes.get(id))
803 .and_then(|node| match node.kind {
804 Kind::Metadata { level, .. } => level,
805 _ => None,
806 });
807 (
808 crate::edit::without_fields(page_title(revision, id).unwrap_or_default()),
809 level.unwrap_or(1),
810 )
811 }
812
813 /// The single active page declared in one page object space.
814 pub fn from_space(document: &Document<'_>, space: ExGuid) -> Result<Self, Error> {
815 let pages = document.pages_in(space)?;
816 let [id] = pages.as_slice() else {
817 return Err(Error {
818 offset: 0,
819 message: "Choose an object space containing one active page",
820 });
821 };
822 Self::from_revision(document.active(space)?, *id)
823 }
824
825 pub fn from_revision(revision: &Revision<'_>, id: ExGuid) -> Result<Self, Error> {
826 let invalid = |message| Error { offset: 0, message };
827 let root = revision
828 .nodes
829 .get(&id)
830 .ok_or_else(|| invalid("Missing canvas page"))?;
831 let Kind::Page {
832 margin_origin_x,
833 margin_origin_y,
834 rtl,
835 ..
836 } = &root.kind
837 else {
838 return Err(invalid("Canvas root is not a page"));
839 };
840 let metadata = revision
841 .roots
842 .get(&2)
843 .and_then(|id| revision.nodes.get(id))
844 .filter(|node| matches!(node.kind, Kind::Metadata { .. }))
845 .and_then(|node| node.extra.first());
846 let mut page = Self {
847 title: crate::edit::without_fields(page_title(revision, id).unwrap_or_default()),
848 identity: Self::identity_of(revision),
849 created: metadata
850 .and_then(|fields| fields.iter().find(|field| field.id == 0x18001c65))
851 .map(|field| {
852 let FieldValue::Bytes(bytes) = field.value else {
853 return Err(invalid("The page creation date is damaged"));
854 };
855 Ok(u64::from_le_bytes(bytes.try_into().map_err(|_| {
856 invalid("The page creation date is damaged")
857 })?))
858 })
859 .transpose()?,
860 // OneNote 2010 snaps to, and on the first move writes, (36, 14.4) when unset: 1.0
861 // and 0.4 half inches, read as stored ones are.
862 margin_origin: [
863 margin_origin_x.unwrap_or(1.0_f32 * 36.0),
864 margin_origin_y.unwrap_or(0.4_f32 * 36.0),
865 ],
866 rtl: rtl.unwrap_or(false),
867 color: root
868 .extra
869 .first()
870 .and_then(|fields| fields.iter().find(|field| field.id == PAGE_COLOR))
871 .map(|field| match field.value {
872 FieldValue::Bytes(&[red, green, blue, alpha]) => {
873 Ok(u32::from_le_bytes([red, green, blue, alpha]))
874 }
875 _ => Err(invalid("The page color is damaged")),
876 })
877 .transpose()?,
878 rule_lines: root
879 .extra
880 .first()
881 .and_then(|fields| RuleLines::read(fields)),
882 objects: Vec::new(),
883 definitions: BTreeMap::new(),
884 };
885 let mut roots: Vec<_> = root
886 .children
887 .iter()
888 .chain(&root.structure)
889 .rev()
890 .map(|id| (*id, None))
891 .collect();
892 let mut seen = BTreeSet::new();
893 while let Some((id, title_index)) = roots.pop() {
894 if !seen.insert(id) {
895 return Err(invalid("Repeated canvas page object"));
896 }
897 let node = revision
898 .nodes
899 .get(&id)
900 .ok_or_else(|| invalid("Missing canvas page object"))?;
901 if title_index.is_some() && !matches!(node.kind, Kind::Outline { .. }) {
902 return Err(invalid("Canvas title child is not an outline"));
903 }
904 match &node.kind {
905 Kind::Title => {
906 let index = page.objects.len();
907 page.objects.push(PageObject::Title(Title {
908 id,
909 date: None,
910 layout: node.layout.clone(),
911 outlines: Vec::new(),
912 }));
913 roots.extend(node.children.iter().rev().map(|id| (*id, Some(index))));
914 }
915 Kind::Outline { indents } => {
916 let fields = node.extra.first().map(Vec::as_slice).unwrap_or_default();
917 if let Some(index) = title_index
918 && fields.iter().any(|field| {
919 field.id == 0x88001cb5 && matches!(field.value, FieldValue::NoData)
920 })
921 {
922 let PageObject::Title(title) = &mut page.objects[index] else {
923 unreachable!()
924 };
925 if title.date.replace(id).is_some() {
926 return Err(invalid("The page has more than one date field"));
927 }
928 }
929 let min_width = fields
930 .iter()
931 .find(|field| field.id == 0x14001cec)
932 .map(|field| {
933 let FieldValue::Bytes(bytes) = field.value else {
934 return Err(invalid("Invalid canvas minimum outline width"));
935 };
936 let width =
937 f32::from_le_bytes(bytes.try_into().map_err(|_| {
938 invalid("Invalid canvas minimum outline width")
939 })?) * 36.0;
940 if !width.is_finite() || width <= 0.0 {
941 return Err(invalid("Invalid canvas minimum outline width"));
942 }
943 Ok(width)
944 })
945 .transpose()?;
946 let title_text = |node: &Element<'_>| {
947 node.extra.first().is_some_and(|fields| {
948 fields.iter().any(|field| {
949 field.id == 0x88001cb4 && matches!(field.value, FieldValue::NoData)
950 })
951 })
952 };
953 let mut outline = Outline {
954 id,
955 // OneNote flags the outline and its paragraph, and still shows an outline
956 // whose paragraph alone is flagged as the title.
957 title: title_text(node)
958 || node
959 .children
960 .iter()
961 .any(|id| revision.nodes.get(id).is_some_and(title_text)),
962 min_width,
963 layout: node.layout.clone(),
964 indents: indents.clone(),
965 paragraphs: Vec::new(),
966 unsupported: Vec::new(),
967 };
968 (outline.paragraphs, outline.unsupported) = read_paragraphs(
969 revision,
970 node,
971 &node.format,
972 &mut page.definitions,
973 &mut seen,
974 0,
975 )?;
976 if let Some(index) = title_index {
977 let PageObject::Title(title) = &mut page.objects[index] else {
978 unreachable!()
979 };
980 title.outlines.push(outline);
981 } else {
982 page.objects.push(PageObject::Outline(outline));
983 }
984 }
985 Kind::Image { .. } | Kind::Attachment { .. } => {
986 for tag in node.tags.iter().filter_map(|tag| tag.definition) {
987 define(revision, tag, false, &mut page.definitions)?;
988 }
989 page.objects.push(match node.kind {
990 Kind::Image { .. } => PageObject::Image(Image::read(revision, id, node)?),
991 _ => PageObject::Attachment(Attachment::read(revision, id, node)?),
992 });
993 }
994 Kind::Ink { .. } => {
995 page.objects
996 .push(PageObject::Ink(Ink::read(revision, id, node)?));
997 }
998 _ => page.objects.push(PageObject::Unsupported(Unsupported {
999 id,
1000 jcid: node.jcid,
1001 layout: node.layout.clone(),
1002 })),
1003 }
1004 }
1005 Ok(page)
1006 }
1007}
1008
1009/// The format `container` passes to its children, as reading its page inherits it.
1010fn inherited_by(
1011 revision: &Revision<'_>,
1012 parents: &BTreeMap<ExGuid, Vec<ExGuid>>,
1013 container: ExGuid,
1014) -> Result<Format, Error> {
1015 let invalid = |message| Error { offset: 0, message };
1016 let node = revision
1017 .nodes
1018 .get(&container)
1019 .ok_or_else(|| invalid("Missing canvas outline object"))?;
1020 let parent = || -> Result<ExGuid, Error> {
1021 match parents.get(&container).map(Vec::as_slice) {
1022 Some([parent]) => Ok(*parent),
1023 _ => Err(invalid("Page content must have one parent")),
1024 }
1025 };
1026 Ok(match &node.kind {
1027 Kind::Outline { .. } => node.format.clone(),
1028 Kind::OutlineGroup => node
1029 .format
1030 .inherit(&inherited_by(revision, parents, parent()?)?),
1031 Kind::Paragraph {
1032 paragraph_style, ..
1033 } => {
1034 let style = match paragraph_style {
1035 Some(id) => revision
1036 .nodes
1037 .get(id)
1038 .map(|n| n.format.clone())
1039 .unwrap_or_default(),
1040 None => Format::default(),
1041 };
1042 node.format
1043 .inherit(&style)
1044 .inherit(&inherited_by(revision, parents, parent()?)?)
1045 }
1046 Kind::Cell { .. } => {
1047 let row = parent()?;
1048 let [table] = parents.get(&row).map(Vec::as_slice).unwrap_or_default() else {
1049 return Err(invalid("A table row must have one table"));
1050 };
1051 let [holder] = parents.get(table).map(Vec::as_slice).unwrap_or_default() else {
1052 return Err(invalid("A table must have one paragraph"));
1053 };
1054 node.format.inherit(
1055 &revision.nodes[table]
1056 .format
1057 .inherit(&inherited_by(revision, parents, *holder)?),
1058 )
1059 }
1060 _ => Format::default(),
1061 })
1062}
1063
1064/// The text of rich-text object `text` as its page model shows it, read from its ancestors
1065/// alone.
1066pub(crate) fn text_of(
1067 revision: &Revision<'_>,
1068 parents: &BTreeMap<ExGuid, Vec<ExGuid>>,
1069 text: ExGuid,
1070) -> Result<Paragraph, Error> {
1071 let invalid = |message| Error { offset: 0, message };
1072 let [paragraph] = parents.get(&text).map(Vec::as_slice).unwrap_or_default() else {
1073 return Err(invalid("Select text belonging to one paragraph"));
1074 };
1075 let format = inherited_by(revision, parents, *paragraph)?;
1076 let node = revision
1077 .nodes
1078 .get(&text)
1079 .ok_or_else(|| invalid("Missing text object"))?;
1080 let Kind::RichText {
1081 paragraph_style, ..
1082 } = &node.kind
1083 else {
1084 return Err(invalid("Select a rich-text object"));
1085 };
1086 let runs = revision.text_runs(text)?;
1087 Ok(if runs.is_empty() {
1088 let style = match paragraph_style {
1089 Some(id) => revision
1090 .nodes
1091 .get(id)
1092 .map(|n| n.format.clone())
1093 .unwrap_or_default(),
1094 None => Format::default(),
1095 };
1096 Paragraph::new(String::new(), node.format.inherit(&style).inherit(&format))
1097 } else {
1098 Paragraph::from_runs(
1099 runs.into_iter()
1100 .map(|run| (run.text.to_owned(), run.format.inherit(&format))),
1101 )
1102 })
1103}
1104
1105/// Adds list or tag definition `id` to `definitions`.
1106fn define(
1107 revision: &Revision<'_>,
1108 id: ExGuid,
1109 is_list: bool,
1110 definitions: &mut BTreeMap<ExGuid, Definition>,
1111) -> Result<(), Error> {
1112 let invalid = |message| Error { offset: 0, message };
1113 let definition = revision
1114 .nodes
1115 .get(&id)
1116 .ok_or_else(|| invalid("Missing canvas list or tag definition"))?;
1117 let kind = match &definition.kind {
1118 Kind::List {
1119 font,
1120 format,
1121 restart,
1122 bullet,
1123 } if is_list => Kind::List {
1124 font: font.clone(),
1125 format: format.clone(),
1126 restart: *restart,
1127 bullet: *bullet,
1128 },
1129 Kind::TagDefinition {
1130 label,
1131 action_type,
1132 shape,
1133 color,
1134 highlight,
1135 } if !is_list => Kind::TagDefinition {
1136 label: label.clone(),
1137 action_type: *action_type,
1138 shape: *shape,
1139 color: *color,
1140 highlight: *highlight,
1141 },
1142 _ => return Err(invalid("Canvas list or tag definition has the wrong type")),
1143 };
1144 definitions.insert(
1145 id,
1146 Definition {
1147 kind,
1148 format: definition.format.clone(),
1149 },
1150 );
1151 Ok(())
1152}
1153
1154fn read_paragraphs(
1155 revision: &Revision<'_>,
1156 container: &Element<'_>,
1157 inherited: &Format,
1158 definitions: &mut BTreeMap<ExGuid, Definition>,
1159 seen: &mut BTreeSet<ExGuid>,
1160 depth: usize,
1161) -> Result<(Vec<PageParagraph>, Vec<Unsupported>), Error> {
1162 let invalid = |message| Error { offset: 0, message };
1163 let default_format = Format::default();
1164 let style = |id: Option<ExGuid>| -> Result<&Format, Error> {
1165 let Some(id) = id else {
1166 return Ok(&default_format);
1167 };
1168 let node = revision
1169 .nodes
1170 .get(&id)
1171 .ok_or_else(|| invalid("Missing canvas paragraph style"))?;
1172 if !matches!(node.kind, Kind::Style { .. }) {
1173 return Err(invalid("Canvas paragraph style has the wrong type"));
1174 }
1175 Ok(&node.format)
1176 };
1177
1178 let mut paragraphs = Vec::new();
1179 let mut unsupported = Vec::new();
1180 let mut pending: Vec<_> = container
1181 .children
1182 .iter()
1183 .rev()
1184 .map(|id| {
1185 (
1186 *id,
1187 None,
1188 u32::from(container.child_level.unwrap_or(0)),
1189 inherited.clone(),
1190 )
1191 })
1192 .collect();
1193 while let Some((id, parent, level, inherited)) = pending.pop() {
1194 if !seen.insert(id) {
1195 return Err(invalid("Repeated canvas outline object"));
1196 }
1197 let node = revision
1198 .nodes
1199 .get(&id)
1200 .ok_or_else(|| invalid("Missing canvas outline object"))?;
1201 let next_level = level
1202 .checked_add(u32::from(node.child_level.unwrap_or(0)))
1203 .ok_or_else(|| invalid("Canvas outline level overflow"))?;
1204 match &node.kind {
1205 Kind::Paragraph {
1206 lists,
1207 paragraph_style,
1208 collapse_state,
1209 } => {
1210 let format = node
1211 .format
1212 .inherit(style(*paragraph_style)?)
1213 .inherit(&inherited);
1214 let mut base_style = *paragraph_style;
1215 let [content_id] = node.content.as_slice() else {
1216 return Err(invalid("A paragraph must contain one content object"));
1217 };
1218 if !seen.insert(*content_id) {
1219 return Err(invalid("Repeated canvas paragraph content"));
1220 }
1221 let content = revision
1222 .nodes
1223 .get(content_id)
1224 .ok_or_else(|| invalid("Missing canvas paragraph content"))?;
1225 let media = MediaIndex {
1226 recordings: content.media_ids.clone(),
1227 time_ms: content.media_time_ms,
1228 };
1229 let content = if let Kind::RichText {
1230 paragraph_style, ..
1231 } = &content.kind
1232 {
1233 base_style = paragraph_style.or(base_style);
1234 let runs = revision.text_runs(*content_id)?;
1235 let text_content = if runs.is_empty() {
1236 Paragraph::new(
1237 String::new(),
1238 content
1239 .format
1240 .inherit(style(*paragraph_style)?)
1241 .inherit(&format),
1242 )
1243 } else {
1244 Paragraph::from_runs(
1245 runs.into_iter()
1246 .map(|run| (run.text.to_owned(), run.format.inherit(&format))),
1247 )
1248 };
1249 ParagraphContent::Text(TextObject {
1250 id: *content_id,
1251 date_field: content
1252 .extra
1253 .first()
1254 .map(Vec::as_slice)
1255 .unwrap_or_default()
1256 .iter()
1257 .filter(|field| matches!(field.value, FieldValue::NoData))
1258 .filter_map(|field| match field.id {
1259 0x88001cb5 => Some(DateField::Date),
1260 0x88001c87 => Some(DateField::Time),
1261 _ => None,
1262 })
1263 .try_fold(None, |previous, field| {
1264 if previous.is_some() {
1265 Err(invalid("The page date field has conflicting roles"))
1266 } else {
1267 Ok(Some(field))
1268 }
1269 })?,
1270 text: text_content,
1271 tags: content.tags.clone(),
1272 })
1273 } else if matches!(content.kind, Kind::Image { .. }) {
1274 ParagraphContent::Image(Image::read(revision, *content_id, content)?)
1275 } else if matches!(content.kind, Kind::Attachment { .. }) {
1276 ParagraphContent::Attachment(Attachment::read(revision, *content_id, content)?)
1277 } else if matches!(content.kind, Kind::Ink { .. }) {
1278 ParagraphContent::Ink(Ink::read(revision, *content_id, content)?)
1279 } else if matches!(content.kind, Kind::Table { .. }) {
1280 ParagraphContent::Table(read_table(
1281 revision,
1282 *content_id,
1283 &content.format.inherit(&format),
1284 definitions,
1285 seen,
1286 depth + 1,
1287 )?)
1288 } else {
1289 ParagraphContent::Unsupported(Unsupported {
1290 id: *content_id,
1291 jcid: content.jcid,
1292 layout: content.layout.clone(),
1293 })
1294 };
1295 for (id, is_list) in lists.iter().map(|id| (id, true)).chain(
1296 node.tags
1297 .iter()
1298 .chain(match &content {
1299 ParagraphContent::Text(text) => text.tags.as_slice(),
1300 ParagraphContent::Table(table) => table.tags.as_slice(),
1301 ParagraphContent::Image(image) => image.tags.as_slice(),
1302 ParagraphContent::Attachment(file) => file.tags.as_slice(),
1303 ParagraphContent::Ink(_) | ParagraphContent::Unsupported(_) => &[],
1304 })
1305 .filter_map(|tag| tag.definition.as_ref())
1306 .map(|id| (id, false)),
1307 ) {
1308 define(revision, *id, is_list, definitions)?;
1309 }
1310 if let Some(id) = base_style {
1311 let definition = revision
1312 .nodes
1313 .get(&id)
1314 .ok_or_else(|| invalid("Missing canvas paragraph style"))?;
1315 let Kind::Style { name, next } = &definition.kind else {
1316 return Err(invalid("Canvas paragraph style has the wrong type"));
1317 };
1318 definitions.entry(id).or_insert_with(|| Definition {
1319 kind: Kind::Style {
1320 name: name.clone(),
1321 next: next.clone(),
1322 },
1323 format: definition.format.clone(),
1324 });
1325 }
1326 paragraphs.push(PageParagraph {
1327 id,
1328 parent,
1329 level,
1330 style: base_style,
1331 format: format.clone(),
1332 content,
1333 lists: lists.clone(),
1334 tags: node.tags.clone(),
1335 media,
1336 collapsed: *collapse_state == Some(1),
1337 });
1338 pending.extend(
1339 node.children
1340 .iter()
1341 .rev()
1342 .map(|child| (*child, Some(id), next_level, format.clone())),
1343 );
1344 }
1345 Kind::OutlineGroup => pending.extend(
1346 node.children
1347 .iter()
1348 .rev()
1349 .map(|child| (*child, parent, next_level, node.format.inherit(&inherited))),
1350 ),
1351 _ => unsupported.push(Unsupported {
1352 id,
1353 jcid: node.jcid,
1354 layout: node.layout.clone(),
1355 }),
1356 }
1357 }
1358 Ok((paragraphs, unsupported))
1359}
1360
1361fn read_table(
1362 revision: &Revision<'_>,
1363 id: ExGuid,
1364 inherited: &Format,
1365 definitions: &mut BTreeMap<ExGuid, Definition>,
1366 seen: &mut BTreeSet<ExGuid>,
1367 depth: usize,
1368) -> Result<Table, Error> {
1369 let invalid = |message| Error { offset: 0, message };
1370 if depth > 64 {
1371 return Err(invalid("Tables are nested too deeply"));
1372 }
1373 let node = &revision.nodes[&id];
1374 let Kind::Table {
1375 rows,
1376 columns,
1377 widths,
1378 locked,
1379 borders,
1380 } = &node.kind
1381 else {
1382 unreachable!()
1383 };
1384 if rows.map(|n| n as usize) != Some(node.children.len())
1385 || node.children.is_empty()
1386 || columns.map(|n| n as usize) != Some(widths.len())
1387 || widths.is_empty()
1388 || (!locked.is_empty() && locked.len() != widths.len())
1389 || widths.iter().any(|w| !w.is_finite() || *w < 36.0)
1390 {
1391 return Err(invalid("Table dimensions are inconsistent"));
1392 }
1393 let mut table_rows = Vec::new();
1394 for row_id in &node.children {
1395 if !seen.insert(*row_id) {
1396 return Err(invalid("Repeated canvas table row"));
1397 }
1398 let row = revision
1399 .nodes
1400 .get(row_id)
1401 .ok_or_else(|| invalid("Missing canvas table row"))?;
1402 if !matches!(row.kind, Kind::Row) || row.children.len() != widths.len() {
1403 return Err(invalid("Table row dimensions are inconsistent"));
1404 }
1405 let mut cells = Vec::new();
1406 for cell_id in &row.children {
1407 if !seen.insert(*cell_id) {
1408 return Err(invalid("Repeated canvas table cell"));
1409 }
1410 let cell = revision
1411 .nodes
1412 .get(cell_id)
1413 .ok_or_else(|| invalid("Missing canvas table cell"))?;
1414 if cell.children.is_empty() {
1415 return Err(invalid("A table cell has no paragraphs"));
1416 }
1417 let Kind::Cell { shading, indents } = &cell.kind else {
1418 return Err(invalid("A table row contains an invalid cell"));
1419 };
1420 let (paragraphs, unsupported) = read_paragraphs(
1421 revision,
1422 cell,
1423 &cell.format.inherit(inherited),
1424 definitions,
1425 seen,
1426 depth,
1427 )?;
1428 cells.push(TableCell {
1429 id: *cell_id,
1430 layout: cell.layout.clone(),
1431 indents: indents.clone(),
1432 shading: *shading,
1433 paragraphs,
1434 unsupported,
1435 });
1436 }
1437 table_rows.push(TableRow { id: *row_id, cells });
1438 }
1439 Ok(Table {
1440 id,
1441 columns: widths
1442 .iter()
1443 .enumerate()
1444 .map(|(index, &width)| TableColumn {
1445 width,
1446 locked: locked.get(index).copied().unwrap_or(false),
1447 })
1448 .collect(),
1449 rows: table_rows,
1450 borders: *borders,
1451 layout: node.layout.clone(),
1452 tags: node.tags.clone(),
1453 })
1454}
1455
1456fn page_title<'a>(revision: &'a Revision<'_>, id: ExGuid) -> Option<&'a str> {
1457 revision
1458 .roots
1459 .get(&2)
1460 .and_then(|id| revision.nodes.get(id))
1461 .and_then(|node| {
1462 if let Kind::Metadata { title, .. } = &node.kind {
1463 title.as_deref()
1464 } else {
1465 None
1466 }
1467 })
1468 .or_else(|| {
1469 if let Kind::Page {
1470 alternate_title, ..
1471 } = &revision.nodes.get(&id)?.kind
1472 {
1473 alternate_title.as_deref()
1474 } else {
1475 None
1476 }
1477 })
1478}
1479
1480impl PageParagraph {
1481 pub fn text(&self) -> Option<&TextObject> {
1482 match &self.content {
1483 ParagraphContent::Text(text) => Some(text),
1484 _ => None,
1485 }
1486 }
1487 pub fn text_mut(&mut self) -> Option<&mut TextObject> {
1488 match &mut self.content {
1489 ParagraphContent::Text(text) => Some(text),
1490 _ => None,
1491 }
1492 }
1493}
1494
1495#[cfg(test)]
1496mod tests {
1497 use super::*;
1498 use crate::document::{Element, Field, FieldValue, TextRun};
1499
1500 fn id(n: u32) -> ExGuid {
1501 ExGuid {
1502 n,
1503 ..ExGuid::default()
1504 }
1505 }
1506
1507 const IDENTITY: [u8; 16] = [7; 16];
1508
1509 fn element(kind: Kind<'_>) -> Element<'_> {
1510 Element {
1511 jcid: 0,
1512 children: Vec::new(),
1513 content: Vec::new(),
1514 structure: Vec::new(),
1515 spaces: Vec::new(),
1516 child_level: None,
1517 layout: Layout::default(),
1518 format: Format::default(),
1519 created: None,
1520 modified: None,
1521 original_author: None,
1522 latest_author: None,
1523 media_ids: Vec::new(),
1524 media_time_ms: None,
1525 tags: Vec::new(),
1526 kind,
1527 extra: Vec::new(),
1528 }
1529 }
1530
1531 fn revision() -> Revision<'static> {
1532 let mut page = element(Kind::Page {
1533 alternate_title: Some("Fallback".into()),
1534 level: None,
1535 width: None,
1536 height: None,
1537 margin_origin_x: Some(36.0),
1538 margin_origin_y: Some(12.0),
1539 rtl: None,
1540 recordings: Vec::new(),
1541 });
1542 page.children.push(id(2));
1543 let mut outline = element(Kind::Outline {
1544 indents: vec![18.0, 0.0, 36.0],
1545 });
1546 outline.children.push(id(3));
1547 outline.child_level = Some(1);
1548 outline.format.font_size = Some(9.0);
1549 outline.format.bold = Some(true);
1550 let mut paragraph = element(Kind::Paragraph {
1551 lists: Vec::new(),
1552 paragraph_style: Some(id(5)),
1553 collapse_state: Some(1),
1554 });
1555 paragraph.content.push(id(4));
1556 paragraph.format.bold = Some(false);
1557 let text = element(Kind::RichText {
1558 text: "ab".into(),
1559 runs: vec![TextRun {
1560 start: 0,
1561 end: 2,
1562 format: None,
1563 extra_set: None,
1564 }],
1565 paragraph_style: None,
1566 boilerplate: false,
1567 });
1568 let mut style = element(Kind::Style {
1569 name: Some("Body".into()),
1570 next: None,
1571 });
1572 style.format.font_size = Some(12.0);
1573 let mut metadata = element(Kind::Metadata {
1574 title: Some("Page title".into()),
1575 level: None,
1576 });
1577 metadata.extra = vec![vec![Field {
1578 id: 0x1c001c30,
1579 value: FieldValue::Bytes(&IDENTITY),
1580 }]];
1581 Revision {
1582 roots: BTreeMap::from([(2, id(6))]),
1583 nodes: BTreeMap::from([
1584 (id(1), page),
1585 (id(2), outline),
1586 (id(3), paragraph),
1587 (id(4), text),
1588 (id(5), style),
1589 (id(6), metadata),
1590 ]),
1591 }
1592 }
1593
1594 fn table_revision() -> Revision<'static> {
1595 let mut source = revision();
1596 source.nodes.get_mut(&id(3)).unwrap().content = vec![id(7)];
1597 let mut table = element(Kind::Table {
1598 rows: Some(1),
1599 columns: Some(2),
1600 widths: vec![37.11, 99.0],
1601 locked: vec![false, true],
1602 borders: Some(false),
1603 });
1604 table.children = vec![id(8)];
1605 let mut row = element(Kind::Row);
1606 row.children = vec![id(9), id(10)];
1607 source.nodes.insert(id(7), table);
1608 source.nodes.insert(id(8), row);
1609 for (cell, paragraph, text) in [(9, 11, 4), (10, 12, 13)] {
1610 let mut node = element(Kind::Cell {
1611 shading: Some(0x00ffff),
1612 indents: vec![18.0, 0.0, 27.0, 27.0],
1613 });
1614 node.child_level = Some(1);
1615 node.layout.max_width = Some(268.8);
1616 node.children = vec![id(paragraph)];
1617 if cell == 10 {
1618 node.format.font_size = Some(13.0);
1619 }
1620 source.nodes.insert(id(cell), node);
1621 let mut node = element(Kind::Paragraph {
1622 lists: Vec::new(),
1623 paragraph_style: None,
1624 collapse_state: None,
1625 });
1626 node.content = vec![id(text)];
1627 source.nodes.insert(id(paragraph), node);
1628 }
1629 source.nodes.insert(
1630 id(13),
1631 element(Kind::RichText {
1632 text: "cd".into(),
1633 runs: vec![TextRun {
1634 start: 0,
1635 end: 2,
1636 format: None,
1637 extra_set: None,
1638 }],
1639 paragraph_style: None,
1640 boilerplate: false,
1641 }),
1642 );
1643 source
1644 }
1645
1646 #[test]
1647 fn table_import_owns_cells_and_inherits_format_across_containers() {
1648 let page = {
1649 let source = table_revision();
1650 let before = serde_json::to_vec(&source).unwrap();
1651 let page = Page::from_revision(&source, id(1)).unwrap();
1652 assert_eq!(serde_json::to_vec(&source).unwrap(), before);
1653 page
1654 };
1655 let PageObject::Outline(outline) = &page.objects[0] else {
1656 panic!()
1657 };
1658 let ParagraphContent::Table(table) = &outline.paragraphs[0].content else {
1659 panic!()
1660 };
1661 assert_eq!(table.id, id(7));
1662 assert_eq!(table.borders, Some(false));
1663 assert_eq!(
1664 table.columns,
1665 [
1666 TableColumn {
1667 width: 37.11,
1668 locked: false
1669 },
1670 TableColumn {
1671 width: 99.0,
1672 locked: true
1673 }
1674 ]
1675 );
1676 assert_eq!(table.rows[0].id, id(8));
1677 for (index, cell) in table.rows[0].cells.iter().enumerate() {
1678 assert_eq!(cell.id, id(9 + index as u32));
1679 assert_eq!(cell.layout.max_width, Some(268.8));
1680 assert_eq!(cell.indents, [18.0, 0.0, 27.0, 27.0]);
1681 assert_eq!(cell.shading, Some(0x00ffff));
1682 let paragraph = &cell.paragraphs[0];
1683 assert_eq!(paragraph.parent, None);
1684 assert_eq!(paragraph.level, 1);
1685 assert_eq!(paragraph.id, id(11 + index as u32));
1686 let text = paragraph.text().unwrap();
1687 assert_eq!(text.id, if index == 0 { id(4) } else { id(13) });
1688 assert_eq!(text.text.text(), if index == 0 { "ab" } else { "cd" });
1689 assert_eq!(
1690 text.text.spans()[0].format.font_size,
1691 Some(if index == 0 { 12.0 } else { 13.0 })
1692 );
1693 assert_eq!(text.text.spans()[0].format.bold, Some(false));
1694 }
1695 }
1696
1697 #[test]
1698 fn absent_column_locks_use_the_specified_unlocked_default() {
1699 let mut source = table_revision();
1700 let Kind::Table { locked, .. } = &mut source.nodes.get_mut(&id(7)).unwrap().kind else {
1701 panic!()
1702 };
1703 locked.clear();
1704 let page = Page::from_revision(&source, id(1)).unwrap();
1705 let PageObject::Outline(outline) = &page.objects[0] else {
1706 panic!()
1707 };
1708 let ParagraphContent::Table(table) = &outline.paragraphs[0].content else {
1709 panic!()
1710 };
1711 assert!(table.columns.iter().all(|column| !column.locked));
1712 }
1713
1714 #[test]
1715 fn table_import_rejects_aliases_cycles_and_inconsistent_dimensions() {
1716 for case in 0..7 {
1717 let mut source = table_revision();
1718 match case {
1719 0 => source.nodes.get_mut(&id(8)).unwrap().children[1] = id(9),
1720 1 => source.nodes.get_mut(&id(11)).unwrap().content = vec![id(7)],
1721 2 => source.nodes.get_mut(&id(12)).unwrap().content = vec![id(4)],
1722 3 => source.nodes.get_mut(&id(3)).unwrap().content.push(id(4)),
1723 4 => source.nodes.get_mut(&id(9)).unwrap().children.clear(),
1724 5 => {
1725 let Kind::Table { columns, .. } =
1726 &mut source.nodes.get_mut(&id(7)).unwrap().kind
1727 else {
1728 panic!()
1729 };
1730 *columns = Some(3);
1731 }
1732 _ => {
1733 let Kind::Table { widths, .. } =
1734 &mut source.nodes.get_mut(&id(7)).unwrap().kind
1735 else {
1736 panic!()
1737 };
1738 widths[0] = f32::INFINITY;
1739 }
1740 }
1741 assert!(Page::from_revision(&source, id(1)).is_err(), "case {case}");
1742 }
1743 }
1744
1745 #[test]
1746 fn nested_tables_import_with_a_bounded_depth() {
1747 for levels in [1, 62, 65] {
1748 let mut source = table_revision();
1749 let mut paragraph = id(11);
1750 for depth in 0..levels {
1751 let base = 20 + depth * 4;
1752 source.nodes.get_mut(&paragraph).unwrap().content = vec![id(base)];
1753 let mut table = element(Kind::Table {
1754 rows: Some(1),
1755 columns: Some(1),
1756 widths: vec![72.0],
1757 locked: vec![true],
1758 borders: Some(true),
1759 });
1760 table.children = vec![id(base + 1)];
1761 let mut row = element(Kind::Row);
1762 row.children = vec![id(base + 2)];
1763 let mut cell = element(Kind::Cell {
1764 shading: None,
1765 indents: vec![18.0, 0.0, 27.0, 27.0],
1766 });
1767 cell.child_level = Some(1);
1768 cell.children = vec![id(base + 3)];
1769 let mut child = element(Kind::Paragraph {
1770 lists: Vec::new(),
1771 paragraph_style: None,
1772 collapse_state: None,
1773 });
1774 child.content = vec![id(4)];
1775 source.nodes.extend([
1776 (id(base), table),
1777 (id(base + 1), row),
1778 (id(base + 2), cell),
1779 (id(base + 3), child),
1780 ]);
1781 paragraph = id(base + 3);
1782 }
1783 assert_eq!(Page::from_revision(&source, id(1)).is_ok(), levels < 64);
1784 }
1785 }
1786
1787 #[test]
1788 fn owns_page_content_and_resolves_style_before_ancestor_defaults() {
1789 let page = {
1790 let mut source = revision();
1791 source.nodes.get_mut(&id(4)).unwrap().tags.push(Tag {
1792 definition: Some(id(7)),
1793 action_type: None,
1794 shape: None,
1795 property_status: None,
1796 status: 0,
1797 created: Some(123),
1798 completed: None,
1799 start: None,
1800 due: None,
1801 task_id: None,
1802 extra_set: 0,
1803 });
1804 source.nodes.insert(
1805 id(7),
1806 element(Kind::TagDefinition {
1807 label: Some("To Do".into()),
1808 action_type: Some(0),
1809 shape: Some(3),
1810 color: None,
1811 highlight: None,
1812 }),
1813 );
1814 let before = serde_json::to_vec(&source).unwrap();
1815 let page = Page::from_revision(&source, id(1)).unwrap();
1816 assert_eq!(before, serde_json::to_vec(&source).unwrap());
1817 page
1818 };
1819 assert_eq!(page.title, "Page title");
1820 assert_eq!(page.margin_origin, [36.0, 12.0]);
1821 let PageObject::Outline(outline) = &page.objects[0] else {
1822 panic!()
1823 };
1824 assert_eq!(outline.paragraphs.len(), 1);
1825 let paragraph = &outline.paragraphs[0];
1826 assert!(paragraph.collapsed);
1827 assert_eq!(paragraph.level, 1);
1828 assert_eq!(paragraph.parent, None);
1829 assert_eq!(paragraph.style, Some(id(5)));
1830 assert!(matches!(&page.definitions[&id(5)].kind,
1831 Kind::Style { name: Some(name), .. } if name == "Body"));
1832 assert_eq!(page.definitions[&id(5)].format.font_size, Some(12.0));
1833 let text = &paragraph.text().unwrap().text;
1834 assert_eq!(text.text(), "ab");
1835 assert_eq!(text.spans()[0].format.font_size, Some(12.0));
1836 assert_eq!(text.spans()[0].format.bold, Some(false));
1837 assert_eq!(paragraph.text().unwrap().tags[0].created, Some(123));
1838 assert!(matches!(&page.definitions[&id(7)].kind,
1839 Kind::TagDefinition { label: Some(label), shape: Some(3), .. } if label == "To Do"));
1840 }
1841
1842 #[test]
1843 fn creation_time_comes_from_page_metadata_and_date_role_from_the_title_child() {
1844 let mut source = revision();
1845 source.nodes.get_mut(&id(1)).unwrap().created = Some(7);
1846 let bytes = 134_333_468_649_123_456_u64.to_le_bytes();
1847 source.nodes.get_mut(&id(6)).unwrap().extra = vec![vec![
1848 Field {
1849 id: 0x18001c65,
1850 value: FieldValue::Bytes(&bytes),
1851 },
1852 Field {
1853 id: 0x1c001c30,
1854 value: FieldValue::Bytes(&IDENTITY),
1855 },
1856 ]];
1857 source.nodes.get_mut(&id(1)).unwrap().children.clear();
1858 source.nodes.get_mut(&id(1)).unwrap().structure.push(id(7));
1859 let mut title = element(Kind::Title);
1860 title.children.push(id(2));
1861 source.nodes.insert(id(7), title);
1862 source.nodes.get_mut(&id(2)).unwrap().extra = vec![vec![Field {
1863 id: 0x88001cb5,
1864 value: FieldValue::NoData,
1865 }]];
1866 source.nodes.get_mut(&id(4)).unwrap().extra = vec![vec![Field {
1867 id: 0x88001c87,
1868 value: FieldValue::NoData,
1869 }]];
1870 let page = Page::from_revision(&source, id(1)).unwrap();
1871 assert_eq!(page.created, Some(134_333_468_649_123_456));
1872 let PageObject::Title(title) = &page.objects[0] else {
1873 panic!()
1874 };
1875 assert_eq!(title.date, Some(id(2)));
1876 assert_eq!(
1877 title.outlines[0].paragraphs[0].text().unwrap().date_field,
1878 Some(DateField::Time)
1879 );
1880 source.nodes.get_mut(&id(6)).unwrap().extra[0][0].value = FieldValue::Bytes(&bytes[..7]);
1881 assert!(Page::from_revision(&source, id(1)).is_err());
1882 source.nodes.get_mut(&id(6)).unwrap().extra.clear();
1883 let bare = Page::from_revision(&source, id(1)).unwrap();
1884 assert_eq!((bare.created, bare.identity), (None, None));
1885 }
1886
1887 #[test]
1888 fn title_role_and_minimum_width_come_from_root_properties() {
1889 let mut source = revision();
1890 source.nodes.get_mut(&id(1)).unwrap().children.clear();
1891 source.nodes.get_mut(&id(1)).unwrap().structure.push(id(7));
1892 let mut title = element(Kind::Title);
1893 title.children.push(id(2));
1894 source.nodes.insert(id(7), title);
1895 source.nodes.get_mut(&id(2)).unwrap().extra = vec![vec![
1896 Field {
1897 id: 0x88001cb4,
1898 value: FieldValue::NoData,
1899 },
1900 Field {
1901 id: 0x14001cec,
1902 value: FieldValue::Bytes(&[0, 0, 0x90, 0x40]),
1903 },
1904 ]];
1905 let page = Page::from_revision(&source, id(1)).unwrap();
1906 let PageObject::Title(title) = &page.objects[0] else {
1907 panic!()
1908 };
1909 assert!(title.outlines[0].title);
1910 assert_eq!(title.outlines[0].min_width, Some(162.0));
1911 source.nodes.get_mut(&id(2)).unwrap().extra[0][1].value =
1912 FieldValue::Bytes(&[0, 0, 0x80, 0x7f]);
1913 assert!(Page::from_revision(&source, id(1)).is_err());
1914 source.nodes.get_mut(&id(2)).unwrap().extra = vec![
1915 vec![Field {
1916 id: 0x08001cb4,
1917 value: FieldValue::NoData,
1918 }],
1919 vec![Field {
1920 id: 0x88001cb4,
1921 value: FieldValue::NoData,
1922 }],
1923 ];
1924 let page = Page::from_revision(&source, id(1)).unwrap();
1925 let PageObject::Title(title) = &page.objects[0] else {
1926 panic!()
1927 };
1928 assert!(!title.outlines[0].title);
1929 assert_eq!(title.outlines[0].min_width, None);
1930 }
1931
1932 #[test]
1933 fn preserves_paint_order_nested_parents_and_owned_image_payloads() {
1934 let bytes = vec![1, 2, 3, 4];
1935 let mut source = revision();
1936 let image = element(Kind::Image {
1937 container: Some(id(8)),
1938 filename: None,
1939 alt: Some("Image".into()),
1940 picture_width: None,
1941 picture_height: None,
1942 background: Some(true),
1943 printout: None,
1944 link: None,
1945 });
1946 let file = element(Kind::File {
1947 reference: crate::FileDataReference::Internal([0; 16]),
1948 extension: "png".into(),
1949 payload: Some(bytes.as_slice()),
1950 });
1951 let mut title = element(Kind::Title);
1952 title.layout.x = Some(12.0);
1953 title.layout.y = Some(24.0);
1954 title.children.push(id(10));
1955 let title_outline = element(Kind::Outline {
1956 indents: Vec::new(),
1957 });
1958 let mut group = element(Kind::OutlineGroup);
1959 group.children.push(id(12));
1960 group.child_level = Some(1);
1961 let mut child = element(Kind::Paragraph {
1962 lists: Vec::new(),
1963 paragraph_style: None,
1964 collapse_state: None,
1965 });
1966 child.content.push(id(13));
1967 source.nodes.insert(
1968 id(13),
1969 element(Kind::RichText {
1970 text: "".into(),
1971 runs: Vec::new(),
1972 paragraph_style: None,
1973 boilerplate: false,
1974 }),
1975 );
1976 source.nodes.extend([
1977 (id(7), image),
1978 (id(8), file),
1979 (id(9), title),
1980 (id(10), title_outline),
1981 (id(11), group),
1982 (id(12), child),
1983 ]);
1984 source
1985 .nodes
1986 .get_mut(&id(1))
1987 .unwrap()
1988 .children
1989 .insert(0, id(7));
1990 source.nodes.get_mut(&id(1)).unwrap().structure.push(id(9));
1991 source.nodes.get_mut(&id(3)).unwrap().children.push(id(11));
1992 source.nodes.get_mut(&id(3)).unwrap().child_level = Some(1);
1993 let page = Page::from_revision(&source, id(1)).unwrap();
1994 drop(source);
1995 drop(bytes);
1996 assert_eq!(page.objects.len(), 3);
1997 let PageObject::Image(image) = &page.objects[0] else {
1998 panic!()
1999 };
2000 assert_eq!(image.bytes.as_deref(), Some([1, 2, 3, 4].as_slice()));
2001 let PageObject::Outline(outline) = &page.objects[1] else {
2002 panic!()
2003 };
2004 assert_eq!(outline.paragraphs[1].id, id(12));
2005 assert_eq!(outline.paragraphs[1].parent, Some(id(3)));
2006 assert_eq!(outline.paragraphs[1].level, 3);
2007 let PageObject::Title(title) = &page.objects[2] else {
2008 panic!()
2009 };
2010 assert_eq!(title.id, id(9));
2011 assert_eq!([title.layout.x, title.layout.y], [Some(12.0), Some(24.0)]);
2012 assert_eq!(title.outlines[0].id, id(10));
2013 assert_eq!(title.outlines[0].layout.x, None);
2014 }
2015
2016 #[test]
2017 fn rejects_title_children_that_are_not_outlines() {
2018 let mut source = revision();
2019 let mut title = element(Kind::Title);
2020 title.children.push(id(8));
2021 source.nodes.insert(id(7), title);
2022 source.nodes.insert(id(8), element(Kind::Title));
2023 source.nodes.get_mut(&id(1)).unwrap().structure.push(id(7));
2024 assert_eq!(
2025 Page::from_revision(&source, id(1)).err().unwrap().message,
2026 "Canvas title child is not an outline"
2027 );
2028 }
2029
2030 #[test]
2031 fn validates_empty_text_styles_missing_references_and_cycles() {
2032 let mut source = revision();
2033 source.nodes.get_mut(&id(4)).unwrap().kind = Kind::RichText {
2034 text: String::new(),
2035 runs: Vec::new(),
2036 paragraph_style: Some(id(5)),
2037 boilerplate: false,
2038 };
2039 source.nodes.get_mut(&id(3)).unwrap().format.font_size = Some(10.0);
2040 let page = Page::from_revision(&source, id(1)).unwrap();
2041 let PageObject::Outline(outline) = &page.objects[0] else {
2042 panic!()
2043 };
2044 assert_eq!(
2045 outline.paragraphs[0].text().unwrap().text.spans()[0]
2046 .format
2047 .font_size,
2048 Some(12.0)
2049 );
2050 source.nodes.get_mut(&id(3)).unwrap().children.push(id(2));
2051 assert!(Page::from_revision(&source, id(1)).is_err());
2052 source.nodes.get_mut(&id(3)).unwrap().children.clear();
2053 source.nodes.remove(&id(5));
2054 assert!(Page::from_revision(&source, id(1)).is_err());
2055 }
2056}