1use super::*;
2use library::{sb_library_set_offline, sb_library_sync_now};
3use notebook::session::SyncState;
4use std::path::{Path, PathBuf};
5
6#[path = "../../notebook/tests/support/vfs.rs"]
7mod vfs;
8
9const CORPUS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../corpus");
10
11fn corpus(path: &str) -> PathBuf {
12 Path::new(CORPUS).join(path)
13}
14
15/// A copy of the corpus section or notebook folder at `path` in a fresh directory, with a
16/// cache beside it.
17fn copy(path: &str) -> (tempfile::TempDir, PathBuf) {
18 let directory = tempfile::tempdir().unwrap();
19 let source = corpus(path);
20 let target = directory.path().join(source.file_name().unwrap());
21 let status = std::process::Command::new("cp")
22 .arg("-R")
23 .arg(&source)
24 .arg(&target)
25 .status()
26 .unwrap();
27 assert!(status.success());
28 (directory, target)
29}
30
31fn open(library: &Arc<Library>, path: &str) -> Section {
32 Section::open(Arc::clone(library), path, "Clover Test".into(), || {}).unwrap()
33}
34
35fn space(section: &Section, title: &str) -> ExGuid {
36 section
37 .shared
38 .section
39 .pages()
40 .unwrap()
41 .into_iter()
42 .find(|(_, heading, _)| heading == title)
43 .unwrap()
44 .0
45}
46
47/// A page of the Features section on a 402 × 874 point phone at 3 pixels per point, at
48/// 100% with the page origin at the view's corner.
49fn canvas(section: &Section, title: &str) -> Canvas {
50 let space = space(section, title);
51 let (page, _) = section.shared.page(space).unwrap();
52 let mut canvas = Canvas::new(space, page, [1206, 2622], 3.0).unwrap();
53 canvas.set_transform(1.0, [0.0; 2]);
54 canvas
55}
56
57fn features() -> (tempfile::TempDir, Section) {
58 let (directory, file) = copy("media-edit/candidate/Features.one");
59 let library = Arc::new(Library::open(&file, &directory.path().join("cache"), true).unwrap());
60 let section = open(&library, &file.to_string_lossy());
61 (directory, section)
62}
63
64/// A view point on the outline holding `text`, `fraction` of the way along its first line.
65fn point_on(canvas: &Canvas, text: &str, fraction: f32) -> [f32; 2] {
66 let outline = canvas
67 .page
68 .editor
69 .visible_outlines()
70 .find(|outline| outline.shown_text().contains(text))
71 .unwrap();
72 let bounds = outline.bounds();
73 let x = bounds.x0 as f32 + (bounds.x1 - bounds.x0) as f32 * fraction;
74 let y = bounds.y0 as f32 + 6.0;
75 [x * POINT, y * POINT]
76}
77
78/// Focuses the outline holding `text` with a tap, and hands the section the edit that took.
79fn focus(canvas: &mut Canvas, text: &str) {
80 let point = point_on(canvas, text, 0.1);
81 canvas.press(point).unwrap();
82 canvas.release().unwrap();
83}
84
85#[test]
86fn a_notebook_folder_lists_sections_in_order_with_groups_and_colours() {
87 let directory = tempfile::tempdir().unwrap();
88 let library = Library::open(
89 &corpus("m6/native-features-01/notebook"),
90 directory.path(),
91 true,
92 )
93 .unwrap();
94 let tabs = library.tabs().unwrap();
95 let names: Vec<_> = tabs
96 .iter()
97 .map(|tab| (tab.group.as_str(), tab.name.as_str()))
98 .collect();
99 assert!(names.contains(&("", "Features")), "{names:?}");
100 assert!(tabs.iter().any(|tab| !tab.group.is_empty()));
101 let lone = Library::open(
102 &corpus("media-edit/candidate/Features.one"),
103 directory.path(),
104 true,
105 )
106 .unwrap();
107 assert_eq!(lone.tabs().unwrap().len(), 1);
108}
109
110#[test]
111fn a_new_notebook_opens_with_one_section_in_its_colour_and_refuses_a_taken_name() {
112 let directory = tempfile::tempdir().unwrap();
113 let root = directory.path().join("Mine");
114 let cache = directory.path().join("cache");
115 std::fs::create_dir(&cache).unwrap();
116 let c = |path: &Path| CString::new(path.to_str().unwrap()).unwrap();
117 let create = |error: &mut *mut c_char| unsafe {
118 library::sb_notebook_create(
119 c(&root).as_ptr(),
120 c(&cache).as_ptr(),
121 c"Clover Test".as_ptr(),
122 c"Tuesday, September 29, 2026".as_ptr(),
123 c"9:41 AM".as_ptr(),
124 error,
125 )
126 };
127 let mut error = std::ptr::null_mut();
128 assert!(create(&mut error));
129 assert!(error.is_null());
130 let library = Library::open(&root, &cache, true).unwrap();
131 let tabs = library.tabs().unwrap();
132 assert_eq!(tabs.len(), 1);
133 assert!(tabs[0].readable);
134 assert_eq!(library::sb_library_color(&library), 0x91baae);
135 assert!(!create(&mut error));
136 assert!(!error.is_null());
137 unsafe { sb_string_free(error) };
138}
139
140#[test]
141fn touches_route_to_text_the_page_and_the_focused_outlines_grip() {
142 let (_directory, section) = features();
143 let mut canvas = canvas(&section, "Paragraph controls");
144 let text = point_on(&canvas, "Collapsed parent", 0.1);
145 let first = canvas.target(text);
146 assert!(
147 matches!(first, Target::ActiveText | Target::Text),
148 "{first:?}"
149 );
150 assert!(canvas.press(text).unwrap());
151 canvas.release().unwrap();
152 assert_eq!(canvas.target(text), Target::ActiveText);
153 // The grip strip sits above the text; a finger reaches it from 16 points higher still.
154 let bounds = canvas.active().bounds();
155 let above = [
156 (bounds.x0 as f32 + 40.0) * POINT,
157 (bounds.y0 as f32 - 12.0) * POINT - 10.0,
158 ];
159 assert_eq!(canvas.target(above), Target::Grip);
160 // Unfocused, the grips hide and a touch there reaches the page.
161 let _ = canvas.page.focus_changed(false).unwrap();
162 assert_eq!(canvas.target(above), Target::Page);
163}
164
165#[test]
166fn dragging_the_grip_moves_the_outline_onto_the_grid_as_an_edit() {
167 let (_directory, section) = features();
168 let mut canvas = canvas(&section, "Paragraph controls");
169 focus(&mut canvas, "Collapsed parent");
170 canvas.edit().unwrap();
171 let before = canvas.active().origin();
172 let grip = [(before[0] + 40.0) * POINT, (before[1] - 8.0) * POINT];
173 assert_eq!(canvas.target(grip), Target::Grip);
174 canvas.press(grip).unwrap();
175 for step in 1..=10 {
176 let step = step as f32;
177 canvas
178 .drag([grip[0] + step * 10.0, grip[1] + step * 7.0])
179 .unwrap();
180 }
181 canvas.release().unwrap();
182 let after = canvas.active().origin();
183 let margin = canvas.page.editor.margin_origin();
184 assert_ne!(after, before);
185 for axis in 0..2 {
186 let cells = (after[axis] - margin[axis]) / 18.0;
187 assert!(
188 (cells - cells.round()).abs() < 1e-3,
189 "{after:?} off the grid"
190 );
191 }
192 assert!(canvas.edit().unwrap().is_some());
193 assert!(canvas.page.editor.can_undo());
194}
195
196#[test]
197fn edits_leave_the_viewport_where_the_host_put_it() {
198 let (_directory, section) = features();
199 let mut canvas = canvas(&section, "Paragraph controls");
200 // Scrolled far past the content, where the canvas would clamp and reveal.
201 canvas.set_transform(1.0, [-2000.0, 5000.0]);
202 let origin = canvas.page.viewport.origin;
203 focus(&mut canvas, "Collapsed parent");
204 canvas.insert("typed".into()).unwrap();
205 assert_eq!(canvas.page.viewport.origin, origin);
206}
207
208#[test]
209fn the_text_model_skips_collapsed_paragraphs_and_round_trips_selection() {
210 let (_directory, section) = features();
211 let mut canvas = canvas(&section, "Paragraph controls");
212 focus(&mut canvas, "Collapsed parent");
213 let shown = canvas.active().shown_text();
214 let length = canvas.length();
215 assert_eq!(length as usize, shown.encode_utf16().count());
216 assert_eq!(canvas.text([0, length]), shown);
217 let start = shown.find("Collapsed").unwrap() as u32;
218 canvas.select([start, start + 9]).unwrap();
219 assert_eq!(canvas.selection().unwrap(), [start, start + 9]);
220 assert!(!canvas.range_rects([start, start + 9]).unwrap().is_empty());
221 let caret = canvas.caret_rect(start).unwrap();
222 let closest = canvas
223 .closest([caret[0] + 1.0, caret[1] + caret[3] / 2.0])
224 .unwrap();
225 assert!(closest.abs_diff(start) <= 1, "{closest} for {start}");
226 // Every offset has a caret, including those around the collapsed children.
227 for offset in 0..=length {
228 canvas.caret_rect(offset).unwrap();
229 }
230}
231
232#[test]
233fn select_more_widens_from_the_caret_paragraph_to_the_outline() {
234 let (_directory, section) = features();
235 let mut canvas = canvas(&section, "Paragraph controls");
236 focus(&mut canvas, "Collapsed parent");
237 let shown = canvas.active().shown_text();
238 let units = |text: &str| text.encode_utf16().count() as u32;
239 let start = units(&shown[..shown.find("Collapsed parent").unwrap()]);
240 let line = units(
241 shown
242 .split('\n')
243 .find(|line| line.contains("Collapsed parent"))
244 .unwrap(),
245 );
246 canvas.select([start + 2; 2]).unwrap();
247 canvas.page.editor.widen_selection().unwrap();
248 let [lo, hi] = canvas.selection().unwrap();
249 assert!(
250 lo == start && [start + line, start + line + 1].contains(&hi),
251 "{lo}..{hi}"
252 );
253 for _ in 0..8 {
254 canvas.page.editor.widen_selection().unwrap();
255 }
256 assert_eq!(canvas.selection().unwrap(), [0, canvas.length()]);
257}
258
259#[test]
260fn undo_restores_typing() {
261 let (_directory, section) = features();
262 let mut canvas = canvas(&section, "Paragraph controls");
263 focus(&mut canvas, "Collapsed parent");
264 let before = canvas.active().shown_text();
265 // UIKit's keystrokes, one call each, with the selection set again where it is: one run.
266 for text in ["h", "i", "x"] {
267 canvas.insert(text.into()).unwrap();
268 let selection = canvas.selection().unwrap();
269 canvas.select(selection).unwrap();
270 }
271 assert!(
272 canvas
273 .page
274 .key(&Key::Named(NamedKey::Backspace), None)
275 .unwrap()
276 .changed
277 );
278 canvas.insert("!".into()).unwrap();
279 assert_ne!(canvas.active().shown_text(), before);
280 assert!(moved(canvas.page.undo(false).unwrap()));
281 assert_eq!(canvas.active().shown_text(), before);
282 assert!(canvas.page.editor.can_redo());
283}
284
285/// The text of the page `space` of the section file `file`, read cold.
286fn stored_text(file: &Path, space: ExGuid) -> String {
287 let arena = onestore::Arena::default();
288 let section = onestore::Section::open(&arena, onestore::read_file(file).unwrap()).unwrap();
289 canvas::search::page_text(&section.page(space).unwrap())
290}
291
292#[test]
293fn typing_is_stored_in_the_cache_and_published_to_the_file() {
294 let (directory, file) = copy("media-edit/candidate/Features.one");
295 let cache = directory.path().join("cache");
296 let library = Arc::new(Library::open(&file, &cache, true).unwrap());
297 let section = open(&library, &file.to_string_lossy());
298 let mut canvas = canvas(&section, "Paragraph controls");
299 focus(&mut canvas, "Collapsed parent");
300 let shown = canvas.active().shown_text();
301 let at = shown[..shown.find("Collapsed parent").unwrap()]
302 .encode_utf16()
303 .count() as u32;
304 canvas.select([at, at]).unwrap();
305 canvas.insert("Saved ".into()).unwrap();
306 section
307 .shared
308 .apply(canvas.edit().unwrap().unwrap())
309 .unwrap();
310 assert!(section.flush(Duration::from_secs(20)));
311 let space = canvas.space;
312 assert!(stored_text(&file, space).contains("Saved Collapsed parent"));
313 // The replica reopens from the cache as the file now holds it.
314 let shared = Arc::clone(&section.shared);
315 drop((canvas, section));
316 Arc::into_inner(shared).unwrap().section.close().unwrap();
317 let reopened = open(&library, &file.to_string_lossy());
318 let (page, read_only) = reopened.shared.page(space).unwrap();
319 assert!(!read_only);
320 assert!(canvas::search::page_text(&page).contains("Saved Collapsed parent"));
321}
322
323#[test]
324fn cached_cloud_sections_reopen_with_offline_edits_after_eviction() {
325 let directory = tempfile::tempdir().unwrap();
326 let root = directory.path().join("notebook");
327 let cache = directory.path().join("cache");
328 let creation = onestore::PageCreation::new(None, Some("Kept offline"), "Fixture").unwrap();
329 let notebook =
330 notebook::session::Notebook::create(&root, &cache, 0x00f0_a0c0, &creation).unwrap();
331 let path = notebook.catalog().sections[0].path.clone();
332 drop(notebook);
333 let library = Arc::new(Library::open(&root, &cache, false).unwrap());
334 sb_library_set_offline(&library, true);
335 let section = open(&library, &path);
336 let space = space(&section, "Kept offline");
337 section
338 .shared
339 .apply(Edit {
340 at: library::filetime(),
341 ops: vec![Op::Page {
342 space,
343 op: PageOp::Color(Some(0x00ef_cdab)),
344 }],
345 })
346 .unwrap();
347 let shared = Arc::clone(&section.shared);
348 drop((section, library));
349 Arc::into_inner(shared).unwrap().section.close().unwrap();
350 let file = root.join(&path);
351 let held = directory.path().join("held.one");
352 std::fs::rename(&file, &held).unwrap();
353 let placeholder = root.join(format!(".{path}.icloud"));
354 std::fs::write(&placeholder, b"placeholder").unwrap();
355
356 let library = Arc::new(Library::open(&root, &cache, false).unwrap());
357 sb_library_set_offline(&library, true);
358 for _ in 0..2 {
359 let tabs = library.tabs().unwrap();
360 assert_eq!(tabs[0].path, path);
361 assert!(tabs[0].readable && !tabs[0].downloading);
362 }
363 let section = open(&library, &path);
364 assert_eq!(section.rows().unwrap()[0].title, "Kept offline");
365 assert_eq!(
366 section.shared.page(space).unwrap().0.color,
367 Some(0x00ef_cdab)
368 );
369 assert_eq!(section.shared.section.pending().unwrap().len(), 1);
370 assert!(!file.exists());
371
372 std::fs::rename(held, &file).unwrap();
373 std::fs::remove_file(placeholder).unwrap();
374 assert!(library.tabs().unwrap()[0].readable);
375 sb_library_set_offline(&library, false);
376 assert!(section.flush(Duration::from_secs(20)));
377 let arena = onestore::Arena::default();
378 let stored = onestore::Section::open(&arena, onestore::read_file(file).unwrap()).unwrap();
379 assert_eq!(stored.page(space).unwrap().color, Some(0x00ef_cdab));
380}
381
382#[test]
383fn reopening_a_reachable_source_while_offline_retains_its_original_queue() {
384 extern "C" fn wake(_: usize) {}
385
386 for lone in [false, true] {
387 let directory = tempfile::tempdir().unwrap();
388 let root = directory.path().join("notebook");
389 let cache = directory.path().join("cache");
390 let creation = onestore::PageCreation::new(None, Some("Original"), "Fixture").unwrap();
391 let notebook =
392 notebook::session::Notebook::create(&root, &cache, 0x00f0_a0c0, &creation).unwrap();
393 let path = notebook.catalog().sections[0].path.clone();
394 drop(notebook);
395 let file = root.join(&path);
396 let source = std::fs::read(&file).unwrap();
397 let (location, path) = if lone {
398 (file.clone(), file.to_string_lossy().into_owned())
399 } else {
400 (root, path)
401 };
402 let library = Arc::new(Library::open(&location, &cache, false).unwrap());
403 sb_library_set_offline(&library, true);
404 let section = open(&library, &path);
405 let creation =
406 onestore::PageCreation::new(None, Some("Mobile offline reopen marker"), "Fixture")
407 .unwrap();
408 section
409 .shared
410 .apply(Edit {
411 at: library::filetime(),
412 ops: vec![Op::Section(onestore::op::SectionOp::Create(creation))],
413 })
414 .unwrap();
415 section.shared.section.replica().written().unwrap();
416 let pending = section.shared.section.pending().unwrap();
417 assert_eq!(pending.len(), 1);
418 let shared = Arc::clone(&section.shared);
419 drop(section);
420 Arc::into_inner(shared).unwrap().section.close().unwrap();
421 let path = std::ffi::CString::new(path).unwrap();
422 for reopen in 0..2 {
423 let mut error = std::ptr::null_mut();
424 let raw = unsafe {
425 library::sb_section_open(
426 &library,
427 path.as_ptr(),
428 c"Fixture".as_ptr(),
429 wake,
430 0,
431 &mut error,
432 )
433 };
434 assert!(error.is_null());
435 assert!(!raw.is_null());
436 let section = unsafe { Box::from_raw(raw) };
437 for _ in 0..20 {
438 assert_eq!(section.shared.section.pending().unwrap(), pending);
439 assert_eq!(std::fs::read(&file).unwrap(), source);
440 std::thread::sleep(Duration::from_millis(10));
441 }
442 if reopen == 1 {
443 sb_library_sync_now(&library);
444 assert!(eventually(|| section
445 .shared
446 .section
447 .pending()
448 .unwrap()
449 .is_empty()));
450 let pages =
451 notebook::session::stored_pages(&std::fs::read(&file).unwrap()).unwrap();
452 assert_eq!(
453 pages
454 .iter()
455 .filter(|page| page.page.title == "Mobile offline reopen marker")
456 .count(),
457 1
458 );
459 }
460 let shared = Arc::clone(&section.shared);
461 drop(section);
462 Arc::into_inner(shared).unwrap().section.close().unwrap();
463 }
464 }
465}
466
467#[test]
468fn a_new_page_and_subpage_list_after_their_parent_and_delete_to_the_recycle_bin() {
469 let (directory, root) = copy("m6/native-features-01/notebook");
470 let library = Arc::new(Library::open(&root, &directory.path().join("cache"), true).unwrap());
471 let section = open(&library, "Features.one");
472 let first = section.rows().unwrap()[0].id.parse().unwrap();
473 let page = section
474 .new_page(None, "Sunday, September 27, 2026", "3:04 AM")
475 .unwrap();
476 let subpage = section
477 .new_page(Some(first), "Sunday, September 27, 2026", "3:05 AM")
478 .unwrap();
479 let rows = section.rows().unwrap();
480 assert_eq!(rows.last().unwrap().id, page.to_string());
481 assert_eq!(rows[1].id, subpage.to_string());
482 assert_eq!(rows[1].level, rows[0].level + 1);
483 let mut canvas = Canvas::new(
484 subpage,
485 section.shared.page(subpage).unwrap().0,
486 [1206, 2622],
487 3.0,
488 )
489 .unwrap();
490 assert!(canvas.focus_title().unwrap());
491 canvas.insert("Sketches".into()).unwrap();
492 assert_eq!(canvas.title().unwrap().shown_text(), "Sketches");
493 section
494 .shared
495 .apply(canvas.edit().unwrap().unwrap())
496 .unwrap();
497 section.shared.section.written().unwrap();
498 assert!(
499 section
500 .rows()
501 .unwrap()
502 .iter()
503 .any(|row| row.title == "Sketches")
504 );
505 let deleted = section.shared.section.page(subpage).unwrap();
506 assert!(deleted.identity.is_some());
507 section
508 .delete_page(subpage, "Sunday, September 27, 2026", "3:06 AM")
509 .unwrap();
510 section.shared.section.written().unwrap();
511 assert!(
512 section
513 .rows()
514 .unwrap()
515 .iter()
516 .all(|row| row.id != subpage.to_string())
517 );
518 let bytes = std::fs::read(root.join("OneNote_RecycleBin/OneNote_DeletedPages.one")).unwrap();
519 assert!(
520 notebook::session::stored_pages(&bytes)
521 .unwrap()
522 .iter()
523 .any(|stored| stored.page.identity == deleted.identity
524 && stored.page.title == "Sketches")
525 );
526}
527
528/// A page and a section deleted on iOS list in the recycle bin and leave it for places the
529/// reader picks: the page for another section, keeping its identity and content, and the
530/// section for a group; the files hold both on a cold reopen.
531#[test]
532fn deleted_pages_and_sections_restore_from_the_recycle_bin_to_where_they_are_put() {
533 const DELETED: &str = "OneNote_RecycleBin/OneNote_DeletedPages.one";
534 const TITLE: &str = "Image role background=false, printout=false";
535 let date = ["Friday, October 16, 2026", "9:00 AM"];
536 let (directory, root, library, features) = notebook_open("Features.one", false);
537 let deleted = space(&features, TITLE);
538 let page = features.shared.section.page(deleted).unwrap();
539 let text = canvas::search::page_text(&page);
540 assert!(text.contains("Foreground role control"));
541 features.delete_page(deleted, date[0], date[1]).unwrap();
542 drop(features);
543 library.delete("Empty.one").unwrap();
544 let binned: Vec<String> = (library.recycle_bin().unwrap().into_iter())
545 .map(|tab| tab.path)
546 .collect();
547 assert_eq!(binned, [DELETED, "OneNote_RecycleBin/Empty.one"]);
548 assert!(
549 library
550 .tabs()
551 .unwrap()
552 .iter()
553 .all(|tab| tab.path != "Empty.one")
554 );
555
556 let bin = open(&library, DELETED);
557 let recycled = space(&bin, TITLE);
558 drop(bin);
559 let restored = library
560 .move_page(
561 DELETED,
562 recycled,
563 "Group A/Duplicate.one",
564 None,
565 1,
566 None,
567 "Clover Test",
568 date,
569 )
570 .unwrap();
571 assert_eq!(restored.added, None, "the bin gains no placeholder page");
572 assert_eq!(restored.copied, None);
573 assert!(
574 open(&library, DELETED)
575 .shared
576 .section
577 .pages()
578 .unwrap()
579 .is_empty()
580 );
581 assert_eq!(
582 library
583 .place("OneNote_RecycleBin/Empty.one", "Group B", &[])
584 .unwrap(),
585 "Group B/Empty.one"
586 );
587 library.close(Duration::from_secs(20)).unwrap();
588 drop(library);
589
590 let cold = Library::open(&root, &directory.path().join("cold"), true).unwrap();
591 let paths: Vec<String> = cold
592 .tabs()
593 .unwrap()
594 .into_iter()
595 .map(|tab| tab.path)
596 .collect();
597 assert!(paths.contains(&"Group B/Empty.one".to_owned()));
598 let listed = take_json(library::sb_library_recycle_bin(&cold));
599 assert_eq!(listed[0]["path"], DELETED);
600 assert_eq!(listed.as_array().unwrap().len(), 1);
601 let arrived = restored.page.parse().unwrap();
602 let file = root.join("Group A/Duplicate.one");
603 assert_eq!(stored_text(&file, arrived), text);
604 let stored = notebook::session::stored_pages(&std::fs::read(&file).unwrap()).unwrap();
605 let back = stored
606 .iter()
607 .find(|stored| stored.space == arrived)
608 .unwrap();
609 assert_eq!(back.page.title, TITLE);
610 assert_eq!(
611 back.page.identity, page.identity,
612 "a restored page keeps its identity"
613 );
614 assert!(
615 notebook::session::stored_pages(&std::fs::read(root.join(DELETED)).unwrap())
616 .unwrap()
617 .is_empty()
618 );
619}
620
621/// A group deleted through the C surface takes its sections to the recycle bin, one with an
622/// edit not yet published keeping it there; and a page leaves Deleted Pages while the bin
623/// holds it open, as the iOS sheet does.
624#[test]
625fn a_group_with_an_unpublished_edit_goes_to_the_bin_and_an_open_bin_gives_up_its_page() {
626 const DELETED: &str = "OneNote_RecycleBin/OneNote_DeletedPages.one";
627 let date = ["Monday, October 19, 2026", "9:00 AM"];
628 let (_directory, root, library, features) = notebook_open("Features.one", true);
629 let duplicate = open(&library, "Group A/Duplicate.one");
630 let before = duplicate.rows().unwrap().len();
631 duplicate.new_page(None, date[0], date[1]).unwrap();
632 duplicate.shared.section.written().unwrap();
633 drop(duplicate);
634 let group = CString::new("Group A").unwrap();
635 assert!(unsafe { library::sb_library_delete(&library, group.as_ptr()) });
636 let binned = "OneNote_RecycleBin/Duplicate.one";
637 let listed = take_json(library::sb_library_recycle_bin(&library));
638 assert!(
639 listed
640 .as_array()
641 .unwrap()
642 .iter()
643 .any(|tab| tab["path"] == binned)
644 );
645 assert!(!root.join("Group A").exists());
646 sb_library_set_offline(&library, false);
647 sb_library_sync_now(&library);
648 let stored = || {
649 let bytes = std::fs::read(root.join(binned)).unwrap();
650 notebook::session::stored_pages(&bytes).unwrap().len()
651 };
652 assert!(
653 eventually(|| stored() == before + 1),
654 "the edit reached the binned section"
655 );
656
657 let space = features.rows().unwrap()[0].id.parse().unwrap();
658 features.delete_page(space, date[0], date[1]).unwrap();
659 drop(features);
660 let bin = open(&library, DELETED);
661 let recycled = bin.shared.section.pages().unwrap()[0].0;
662 let restored = library
663 .move_page(
664 DELETED,
665 recycled,
666 "Features.one",
667 None,
668 1,
669 None,
670 "Clover Test",
671 date,
672 )
673 .unwrap();
674 assert_eq!((restored.added, restored.copied), (None, None));
675 assert!(bin.shared.section.pages().unwrap().is_empty());
676}
677
678#[test]
679fn deleting_a_lone_section_page_still_creates_its_replacement_without_a_bin() {
680 let directory = tempfile::tempdir().unwrap();
681 let file = directory.path().join("Lone.one");
682 std::fs::write(
683 &file,
684 onestore::create_section("Lone.one", "Standalone page", "Fixture").unwrap(),
685 )
686 .unwrap();
687 let library = Arc::new(Library::open(&file, &directory.path().join("cache"), true).unwrap());
688 sb_library_set_offline(&library, true);
689 let section = open(&library, &file.to_string_lossy());
690 let space = section.shared.section.pages().unwrap()[0].0;
691 section
692 .delete_page(space, "Sunday, September 27, 2026", "3:06 AM")
693 .unwrap();
694 section.shared.section.written().unwrap();
695 let pages = section.shared.section.pages().unwrap();
696 assert_eq!(pages.len(), 1);
697 assert_ne!(pages[0].0, space);
698 assert!(section.shared.section.page(space).is_err());
699 assert!(!directory.path().join("OneNote_RecycleBin").exists());
700}
701
702#[test]
703fn conflict_pages_list_under_their_page_and_take_no_edits() {
704 let (directory, root) = copy("conflict-page/candidate");
705 let library = Arc::new(Library::open(&root, &directory.path().join("cache"), true).unwrap());
706 let section = open(&library, "synthetic.one");
707 let rows = section.rows().unwrap();
708 let version = rows
709 .iter()
710 .find_map(|row| row.versions.first())
711 .expect("a conflict page");
712 assert!(!version.user.is_empty());
713 let (page, read_only) = section.shared.page(version.id.parse().unwrap()).unwrap();
714 assert!(read_only);
715 // Conflicting paragraphs carry OneNote's highlight.
716 let highlighted = page.objects.iter().any(|object| match object {
717 onestore::page::PageObject::Outline(outline) => outline
718 .paragraphs
719 .iter()
720 .any(|paragraph| paragraph.format.highlight == Some(canvas::conflict::CONFLICTING)),
721 _ => false,
722 });
723 assert!(highlighted);
724}
725
726#[test]
727fn a_refused_edit_is_kept_as_a_conflict_page_or_a_copy() {
728 use onestore::page::PageObject;
729
730 let directory = tempfile::tempdir().unwrap();
731 let file = directory.path().join("Keep.one");
732 let cache = directory.path().join("cache");
733 std::fs::write(
734 &file,
735 onestore::create_section("Keep.one", "Original body", "Fixture").unwrap(),
736 )
737 .unwrap();
738 let library = Arc::new(Library::open(&file, &cache, true).unwrap());
739 let section = Section::open(
740 Arc::clone(&library),
741 file.to_str().unwrap(),
742 "Fixture".into(),
743 || {},
744 )
745 .unwrap();
746 let space = section.shared.section.pages().unwrap()[0].0;
747 let (page, read_only) = section.shared.page(space).unwrap();
748 let outline = page
749 .objects
750 .iter()
751 .find_map(|object| match object {
752 PageObject::Outline(outline) => Some(outline.id),
753 _ => None,
754 })
755 .unwrap();
756 let mut view = View {
757 canvas: ManuallyDrop::new(Canvas::new(space, page, [640, 960], 2.0).unwrap()),
758 presentation: None,
759 frame: Arc::default(),
760 section: Arc::clone(&section.shared),
761 read_only,
762 reload_pending: false,
763 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
764 };
765 focus(&mut view.canvas, "Original body");
766 assert!(sb_select(&mut view, 0, 0));
767 // Another writer deletes the outline the view still shows.
768 section
769 .shared
770 .section
771 .apply(
772 "Peer",
773 page_edit(space, vec![PageOp::Delete { object: outline }]),
774 )
775 .unwrap();
776 section.shared.section.written().unwrap();
777 if sb_view_format(&view) & 1 == 0 {
778 assert!(sb_view_apply(&mut view, 0));
779 }
780 assert!(unsafe { sb_insert(&mut view, c"Stale rich 😀 ".as_ptr()) });
781 let deadline = Instant::now() + Duration::from_secs(10);
782 while section.poll() & 4 == 0 {
783 assert!(Instant::now() < deadline);
784 std::thread::sleep(Duration::from_millis(10));
785 }
786 assert!(sb_view_keep(&view));
787 assert!(sb_view_reload(&mut view, true, None));
788 assert!(!sb_view_keep(&view));
789 section.shared.section.written().unwrap();
790 let kept = |conflicts: Vec<(ExGuid, Vec<onestore::ConflictPage>)>| {
791 let [(of, versions)] = conflicts.as_slice() else {
792 panic!("{conflicts:?}");
793 };
794 assert_eq!(*of, space);
795 let [version] = versions.as_slice() else {
796 panic!("{versions:?}");
797 };
798 assert_eq!(version.user, "Fixture");
799 version.space
800 };
801 let version = kept(section.shared.section.conflicts().unwrap());
802 let (page, read_only) = section.shared.page(version).unwrap();
803 assert!(read_only);
804 let stale = page.objects.iter().any(|object| match object {
805 PageObject::Outline(outline) => outline.paragraphs.iter().any(|paragraph| {
806 paragraph.format.highlight == Some(canvas::conflict::CONFLICTING)
807 && match &paragraph.content {
808 onestore::page::ParagraphContent::Text(text) => {
809 text.text.text().starts_with("Stale rich 😀 Original body")
810 && text.text.spans()[0].format.bold == Some(true)
811 }
812 _ => false,
813 }
814 }),
815 _ => false,
816 });
817 assert!(stale, "{page:?}");
818 let shared = Arc::clone(&section.shared);
819 drop((view, section, library));
820 Arc::into_inner(shared)
821 .expect("No other writer")
822 .section
823 .close()
824 .unwrap();
825 let library = Arc::new(Library::open(&file, &cache, true).unwrap());
826 let section = open(&library, "Keep.one");
827 assert_eq!(kept(section.shared.section.conflicts().unwrap()), version);
828
829 // A change outside the text, to a page deleted meanwhile, is kept as a copy of the page.
830 let (page, read_only) = section.shared.page(space).unwrap();
831 let title = page.title.clone();
832 let mut view = View {
833 canvas: ManuallyDrop::new(Canvas::new(space, page, [640, 960], 2.0).unwrap()),
834 presentation: None,
835 frame: Arc::default(),
836 section: Arc::clone(&section.shared),
837 read_only,
838 reload_pending: false,
839 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
840 };
841 section
842 .shared
843 .section
844 .apply(
845 "Peer",
846 Edit {
847 at: library::filetime(),
848 ops: vec![Op::Section(onestore::op::SectionOp::Delete(vec![space]))],
849 },
850 )
851 .unwrap();
852 section.shared.section.written().unwrap();
853 assert!(sb_view_set_paper(&mut view, 0x77, 0x88, 0x99, -1));
854 let deadline = Instant::now() + Duration::from_secs(10);
855 while section.poll() & 4 == 0 {
856 assert!(Instant::now() < deadline);
857 std::thread::sleep(Duration::from_millis(10));
858 }
859 assert!(sb_view_keep(&view));
860 let copies: Vec<_> = section
861 .shared
862 .section
863 .pages()
864 .unwrap()
865 .into_iter()
866 .filter(|(listed, _, _)| *listed != space)
867 .map(|(listed, _, _)| section.shared.section.page(listed).unwrap())
868 .collect();
869 let [copy] = copies.as_slice() else {
870 panic!("{copies:?}");
871 };
872 assert_eq!(copy.color, Some(0x0099_8877));
873 assert_eq!(copy.title, title);
874}
875
876#[test]
877fn search_finds_pages_by_title_and_text_across_sections() {
878 let directory = tempfile::tempdir().unwrap();
879 let library = Library::open(
880 &corpus("m6/native-features-01/notebook"),
881 directory.path(),
882 true,
883 )
884 .unwrap();
885 let found = library::search(&[&library], None, "collapsed PARENT").unwrap();
886 assert!(!found.is_empty());
887 assert!(found[0].snippet.to_lowercase().contains("collapsed parent"));
888 let [start, end] = found[0].snippet_hits[0];
889 let units: Vec<u16> = found[0].snippet.encode_utf16().collect();
890 assert_eq!(
891 String::from_utf16(&units[start..end])
892 .unwrap()
893 .to_lowercase(),
894 "collapsed"
895 );
896 assert!(
897 library::search(&[&library], None, "no such words anywhere")
898 .unwrap()
899 .is_empty()
900 );
901 let section = &found[0].section;
902 assert!(
903 library::search(&[&library], Some(section), "collapsed parent")
904 .unwrap()
905 .iter()
906 .all(|found| found.section == *section)
907 );
908}
909
910#[test]
911fn search_lists_title_matches_of_every_notebook_first() {
912 let directory = tempfile::tempdir().unwrap();
913 let personal = Library::open(
914 &corpus("search/notebook"),
915 &directory.path().join("a"),
916 true,
917 )
918 .unwrap();
919 let other = Library::open(
920 &corpus("m6/native-features-01/notebook"),
921 &directory.path().join("b"),
922 true,
923 )
924 .unwrap();
925 let found = library::search(&[&other, &personal], None, "tom").unwrap();
926 assert_eq!(found[0].title, "Tomatoes");
927 assert_eq!(found[0].notebook, 1);
928 assert_eq!(found[0].title_hits, [[0, 3]]);
929 assert!(found[1..].iter().all(|found| !found.in_title));
930 assert_eq!(found.len(), 5);
931}
932
933#[test]
934fn find_selects_the_match_and_formatting_reports_and_toggles() {
935 let (_directory, section) = features();
936 let mut canvas = canvas(&section, "Paragraph controls");
937 assert!(canvas.find("collapsed PARENT").unwrap());
938 let [start, end] = canvas.selection().unwrap();
939 assert_eq!(canvas.text([start, end]).to_lowercase(), "collapsed");
940 assert_eq!(canvas.format_bits().unwrap() & 1, 0);
941 assert!(canvas.format(0).unwrap());
942 assert_eq!(canvas.format_bits().unwrap() & 1, 1);
943 // To Do on the paragraph.
944 assert!(canvas.format(16).unwrap());
945 assert_ne!(canvas.format_bits().unwrap() & 1 << 16, 0);
946 assert!(canvas.edit().unwrap().is_some());
947}
948
949#[test]
950fn highlight_stores_any_colour_and_none_takes_it_away() {
951 let (_directory, section) = features();
952 let mut canvas = canvas(&section, "Paragraph controls");
953 assert!(canvas.find("collapsed PARENT").unwrap());
954 let stored = |canvas: &mut Canvas| {
955 section
956 .shared
957 .apply(canvas.edit().unwrap().unwrap())
958 .unwrap();
959 let (page, _) = section.shared.page(canvas.space).unwrap();
960 let mut highlights = Vec::new();
961 for object in &page.objects {
962 let onestore::page::PageObject::Outline(outline) = object else {
963 continue;
964 };
965 for paragraph in &outline.paragraphs {
966 if let onestore::page::ParagraphContent::Text(text) = &paragraph.content {
967 highlights.extend(
968 text.text
969 .spans()
970 .iter()
971 .filter_map(|span| span.format.highlight),
972 );
973 }
974 }
975 }
976 highlights
977 };
978 // Bright Green, which `sb_view_apply` has no number for.
979 assert!(canvas.highlight(Some(0x00ff00)).unwrap());
980 assert!(stored(&mut canvas).contains(&0x00ff00));
981 assert!(canvas.highlight(None).unwrap());
982 assert!(!stored(&mut canvas).contains(&0x00ff00));
983}
984
985#[test]
986fn a_picture_goes_in_at_the_caret_and_undoes() {
987 let (_directory, section) = features();
988 let mut canvas = canvas(&section, "Paragraph controls");
989 focus(&mut canvas, "Collapsed parent");
990 canvas.edit().unwrap();
991 let png = std::fs::read(corpus(
992 "../crates/snowbound/assets/icon/Snowbound-SnowLeopard.png",
993 ))
994 .unwrap();
995 assert!(canvas.insert_picture(&png, [64.0, 64.0]).unwrap());
996 let edit = canvas.edit().unwrap().unwrap();
997 assert!(edit.ops.iter().any(|op| matches!(
998 op,
999 Op::Page {
1000 op: onestore::op::PageOp::Insert { .. },
1001 ..
1002 }
1003 )));
1004 section.shared.apply(edit).unwrap();
1005 let pictures = |page: &Page| {
1006 page.objects
1007 .iter()
1008 .filter_map(|object| match object {
1009 onestore::page::PageObject::Outline(outline) => Some(
1010 outline
1011 .paragraphs
1012 .iter()
1013 .filter(|paragraph| {
1014 matches!(
1015 paragraph.content,
1016 onestore::page::ParagraphContent::Image(_)
1017 )
1018 })
1019 .count(),
1020 ),
1021 _ => None,
1022 })
1023 .sum::<usize>()
1024 };
1025 let before = pictures(&section.shared.page(canvas.space).unwrap().0);
1026 assert!(moved(canvas.page.undo(false).unwrap()));
1027 section
1028 .shared
1029 .apply(canvas.edit().unwrap().unwrap())
1030 .unwrap();
1031 assert_eq!(
1032 pictures(&section.shared.page(canvas.space).unwrap().0),
1033 before - 1
1034 );
1035}
1036
1037#[test]
1038fn to_do_marks_a_new_pages_body() {
1039 let (directory, root) = copy("m6/native-features-01/notebook");
1040 let library = Arc::new(Library::open(&root, &directory.path().join("cache"), true).unwrap());
1041 let section = open(&library, "Features.one");
1042 let page = section
1043 .new_page(None, "Sunday, September 27, 2026", "3:04 AM")
1044 .unwrap();
1045 let mut canvas = Canvas::new(
1046 page,
1047 section.shared.page(page).unwrap().0,
1048 [1206, 2622],
1049 3.0,
1050 )
1051 .unwrap();
1052 canvas.set_transform(1.0, [0.0; 2]);
1053 assert!(canvas.focus_title().unwrap());
1054 canvas.insert("Groceries".into()).unwrap();
1055 canvas.insert("\n".into()).unwrap();
1056 canvas.insert("Oat milk".into()).unwrap();
1057 canvas.insert("\n".into()).unwrap();
1058 canvas.insert("Pears".into()).unwrap();
1059 assert!(canvas.format(16).unwrap());
1060 section
1061 .shared
1062 .apply(canvas.edit().unwrap().unwrap())
1063 .unwrap();
1064 let stored = section.shared.page(page).unwrap().0;
1065 let tags: usize = stored
1066 .objects
1067 .iter()
1068 .map(|object| match object {
1069 onestore::page::PageObject::Outline(outline) => outline
1070 .paragraphs
1071 .iter()
1072 .filter_map(|paragraph| paragraph.text())
1073 .map(|text| text.tags.len())
1074 .sum(),
1075 _ => 0,
1076 })
1077 .sum();
1078 assert_eq!(tags, 1);
1079}
1080
1081/// Against a disposable share `agent` (`ONESTORE_SMB_LAB=HOST:PORT`, as
1082/// `SNOWBOUND_TEST_SMB_USER` with `SNOWBOUND_TEST_SMB_PASSWORD`, or a guest): a notebook
1083/// folder copied to the share lists, a section opens and publishes typing, and the listing
1084/// kept in the cache opens the section again while the server cannot be reached.
1085#[test]
1086#[ignore = "requires ONESTORE_SMB_LAB pointing to a disposable share"]
1087fn a_notebook_on_a_share_saves_and_opens_offline() {
1088 let address = std::env::var("ONESTORE_SMB_LAB").unwrap();
1089 let variable = |name| std::env::var(name).unwrap_or_default();
1090 let server = |address: &str| library::Server {
1091 address: address.into(),
1092 share: "agent".into(),
1093 user: variable("SNOWBOUND_TEST_SMB_USER"),
1094 password: variable("SNOWBOUND_TEST_SMB_PASSWORD"),
1095 domain: String::new(),
1096 };
1097 let client = server(&address).connect().unwrap();
1098 let root = format!("snowbound-test-mobile-{}", std::process::id());
1099 client.create_directory(&root).unwrap();
1100 let source = corpus("media-edit/candidate/Features.one");
1101 client
1102 .create(
1103 &format!("{root}/Features.one"),
1104 &std::fs::read(&source).unwrap(),
1105 )
1106 .unwrap();
1107 let cache = tempfile::tempdir().unwrap();
1108 let library = Arc::new(Library::server(server(&address), &root, cache.path()).unwrap());
1109 assert_eq!(library.tabs().unwrap()[0].path, "Features.one");
1110 let section = open(&library, "Features.one");
1111 let mut canvas = canvas(&section, "Paragraph controls");
1112 focus(&mut canvas, "Collapsed parent");
1113 canvas.insert("Shared ".into()).unwrap();
1114 section
1115 .shared
1116 .apply(canvas.edit().unwrap().unwrap())
1117 .unwrap();
1118 assert!(section.flush(Duration::from_secs(30)));
1119 let published = client
1120 .read(&format!("{root}/Features.one"), 1 << 26)
1121 .unwrap();
1122 let arena = onestore::Arena::default();
1123 let stored = onestore::Section::open(&arena, published).unwrap();
1124 assert!(canvas::search::page_text(&stored.page(canvas.space).unwrap()).contains("Shared "));
1125 sb_library_set_offline(&library, true);
1126 let source = client
1127 .read(&format!("{root}/Features.one"), 1 << 26)
1128 .unwrap();
1129 canvas.insert("Reachable offline marker ".into()).unwrap();
1130 section
1131 .shared
1132 .apply(canvas.edit().unwrap().unwrap())
1133 .unwrap();
1134 section.shared.section.replica().written().unwrap();
1135 let pending = section.shared.section.pending().unwrap();
1136 assert_eq!(pending.len(), 1);
1137 let page_space = canvas.space;
1138 let shared = Arc::clone(&section.shared);
1139 drop((canvas, section));
1140 Arc::into_inner(shared).unwrap().section.close().unwrap();
1141 let section = open(&library, "Features.one");
1142 for _ in 0..10 {
1143 assert_eq!(section.shared.section.pending().unwrap(), pending);
1144 assert_eq!(
1145 client
1146 .read(&format!("{root}/Features.one"), 1 << 26)
1147 .unwrap(),
1148 source
1149 );
1150 std::thread::sleep(Duration::from_millis(20));
1151 }
1152 sb_library_sync_now(&library);
1153 assert!(eventually(|| section
1154 .shared
1155 .section
1156 .pending()
1157 .unwrap()
1158 .is_empty()));
1159 let arena = onestore::Arena::default();
1160 let published = client
1161 .read(&format!("{root}/Features.one"), 1 << 26)
1162 .unwrap();
1163 let stored = onestore::Section::open(&arena, published).unwrap();
1164 assert_eq!(
1165 canvas::search::page_text(&stored.page(page_space).unwrap())
1166 .matches("Reachable offline marker ")
1167 .count(),
1168 1
1169 );
1170 let shared = Arc::clone(&section.shared);
1171 drop((section, library));
1172 Arc::into_inner(shared).unwrap().section.close().unwrap();
1173 // The same notebook while its server does not answer: a closed port on the lab's host.
1174 let host = address.split(':').next().unwrap();
1175 let mut unreachable = server(&format!("{host}:9"));
1176 unreachable.share = "agent".into();
1177 let listing = |address: &str| {
1178 cache.path().join("smb").join(format!(
1179 "{}.json",
1180 format!("{address}/agent/{root}").replace(|c: char| !c.is_alphanumeric(), "_")
1181 ))
1182 };
1183 std::fs::copy(listing(&address), listing(&format!("{host}:9"))).unwrap();
1184 notebook::location::moved(
1185 cache.path(),
1186 &notebook::location::smb(&address, "agent", &root),
1187 &notebook::location::smb(&format!("{host}:9"), "agent", &root),
1188 )
1189 .unwrap();
1190 let offline = Arc::new(Library::server(unreachable, &root, cache.path()).unwrap());
1191 assert_eq!(offline.tabs().unwrap()[0].path, "Features.one");
1192 let reopened = open(&offline, "Features.one");
1193 let page = reopened
1194 .shared
1195 .page(space(&reopened, "Paragraph controls"))
1196 .unwrap()
1197 .0;
1198 assert!(canvas::search::page_text(&page).contains("Shared "));
1199 sb_library_set_offline(&offline, true);
1200 let space = space(&reopened, "Paragraph controls");
1201 let pending = reopened.shared.section.pending().unwrap();
1202 assert!(
1203 reopened
1204 .delete_page(space, "Sunday, September 27, 2026", "3:06 AM")
1205 .is_err()
1206 );
1207 reopened.shared.section.written().unwrap();
1208 assert_eq!(reopened.shared.section.page(space).unwrap(), page);
1209 assert_eq!(reopened.shared.section.pending().unwrap(), pending);
1210 client.delete(&format!("{root}/Features.one")).unwrap();
1211 client.delete(&root).unwrap();
1212}
1213
1214/// Against a disposable share (as above): a section and a copy of it beside it, which holds
1215/// the same file identity, each edited offline, then synced: each file takes its own edit.
1216#[test]
1217#[ignore = "requires ONESTORE_SMB_LAB pointing to a disposable share"]
1218fn a_share_sections_copy_syncs_its_own_edits() {
1219 let address = std::env::var("ONESTORE_SMB_LAB").unwrap();
1220 let server = || library::Server {
1221 address: address.clone(),
1222 share: "agent".into(),
1223 user: std::env::var("SNOWBOUND_TEST_SMB_USER").unwrap_or_default(),
1224 password: std::env::var("SNOWBOUND_TEST_SMB_PASSWORD").unwrap_or_default(),
1225 domain: String::new(),
1226 };
1227 let client = server().connect().unwrap();
1228 let root = format!("snowbound-test-copy-{}", std::process::id());
1229 client.create_directory(&root).unwrap();
1230 let bytes = onestore::create_section("Notes.one", "Original text", "Fixture").unwrap();
1231 let names = ["Notes.one", "Notes - Copy.one"];
1232 for name in names {
1233 client.create(&format!("{root}/{name}"), &bytes).unwrap();
1234 }
1235 let cache = tempfile::tempdir().unwrap();
1236 let library = Arc::new(Library::server(server(), &root, cache.path()).unwrap());
1237 library.tabs().unwrap();
1238 sb_library_set_offline(&library, true);
1239 for (name, color) in names.into_iter().zip([0x0011_2233, 0x00ef_cdab]).rev() {
1240 let section = open(&library, name);
1241 let space = section.shared.section.pages().unwrap()[0].0;
1242 let op = Op::Page {
1243 space,
1244 op: PageOp::Color(Some(color)),
1245 };
1246 let at = library::filetime();
1247 section.shared.apply(Edit { at, ops: vec![op] }).unwrap();
1248 section.shared.section.written().unwrap();
1249 let shared = Arc::clone(&section.shared);
1250 drop(section);
1251 Arc::into_inner(shared).unwrap().section.close().unwrap();
1252 }
1253 sb_library_set_offline(&library, false);
1254 library.flush(Duration::from_secs(30)).unwrap();
1255 for (name, color) in names.into_iter().zip([0x0011_2233, 0x00ef_cdab]) {
1256 let stored = client.read(&format!("{root}/{name}"), 1 << 26).unwrap();
1257 let arena = onestore::Arena::default();
1258 let mut section = onestore::Section::open(&arena, stored).unwrap();
1259 let space = section.pages().unwrap()[0].0;
1260 assert_eq!(section.page(space).unwrap().color, Some(color), "{name}");
1261 client.delete(&format!("{root}/{name}")).unwrap();
1262 }
1263 client.delete(&root).unwrap();
1264}
1265
1266#[test]
1267fn a_share_notebook_syncs_only_its_readable_sections() {
1268 let (directory, root) = copy("native-encrypted/cold-encrypted-02/notebook");
1269 std::fs::copy(
1270 corpus("m6/native-features-01/notebook/Empty.one"),
1271 root.join("Empty.one"),
1272 )
1273 .unwrap();
1274 let notebook =
1275 notebook::session::Notebook::open(&root, directory.path().join("cache")).unwrap();
1276 let mut listed = library::Listed::default();
1277 library::files(notebook.catalog(), &mut listed);
1278 assert_eq!(listed.files.keys().collect::<Vec<_>>(), ["Empty.one"]);
1279}
1280
1281/// Paths the test coordinator was asked for, with whether to write.
1282static COORDINATED: Mutex<Vec<(String, bool)>> = Mutex::new(Vec::new());
1283
1284/// Files whose next coordinated access the test coordinator holds, as another app may: who
1285/// hears that each is held, and what lets it go. Tests running at once hold files of their own.
1286type Held = (
1287 String,
1288 std::sync::mpsc::Sender<()>,
1289 std::sync::mpsc::Receiver<()>,
1290);
1291static HELD: Mutex<Vec<Held>> = Mutex::new(Vec::new());
1292
1293extern "C" fn coordinator(
1294 path: *const c_char,
1295 write: bool,
1296 body: extern "C" fn(*mut c_void),
1297 context: *mut c_void,
1298) {
1299 let path = string(path);
1300 COORDINATED.lock().unwrap().push((path.clone(), write));
1301 let held = {
1302 let mut held = HELD.lock().unwrap();
1303 let at = held.iter().position(|(file, ..)| *file == path);
1304 at.map(|at| held.remove(at))
1305 };
1306 if let Some((_, entered, released)) = held {
1307 let _ = entered.send(());
1308 let _ = released.recv();
1309 }
1310 body(context);
1311}
1312
1313#[test]
1314fn a_local_sections_reads_and_publications_go_through_the_hosts_coordination() {
1315 library::sb_set_coordinator(coordinator);
1316 let (directory, root) = copy("m6/native-features-01/notebook");
1317 let library = Arc::new(Library::open(&root, &directory.path().join("cache"), true).unwrap());
1318 let section = open(&library, "Features.one");
1319 let mut canvas = canvas(&section, "Paragraph controls");
1320 focus(&mut canvas, "Collapsed parent");
1321 canvas.insert("Coordinated ".into()).unwrap();
1322 section
1323 .shared
1324 .apply(canvas.edit().unwrap().unwrap())
1325 .unwrap();
1326 assert!(section.flush(Duration::from_secs(20)));
1327 let file = root.canonicalize().unwrap().join("Features.one");
1328 let file = file.to_string_lossy();
1329 let coordinated = COORDINATED.lock().unwrap();
1330 assert!(
1331 coordinated
1332 .iter()
1333 .any(|(path, write)| path == &*file && !write)
1334 );
1335 assert!(
1336 coordinated
1337 .iter()
1338 .any(|(path, write)| path == &*file && *write)
1339 );
1340}
1341
1342#[test]
1343fn tapping_the_date_asks_for_it_and_a_new_date_is_stored() {
1344 let (_directory, section) = features();
1345 let mut canvas = canvas(&section, "Paragraph controls");
1346 // The first view point, scanning down the page, that lands on the date.
1347 let date = (0..400)
1348 .flat_map(|y| (0..130).map(move |x| [x as f32 * 3.0, y as f32 * 3.0]))
1349 .find(|point| {
1350 matches!(
1351 canvas.page.hit(canvas.device(*point)),
1352 Some(Hit::Date(DateField::Date))
1353 )
1354 })
1355 .expect("the page shows its date");
1356 canvas.press(date).unwrap();
1357 canvas.release().unwrap();
1358 assert_eq!(canvas.asked.take(), Some(DateField::Date));
1359 let before = canvas.page.editor.date().unwrap().timestamp();
1360 // 2 January 2026, 10:30 UTC.
1361 assert!(
1362 canvas
1363 .change_date(
1364 1_767_349_800,
1365 ["Friday, January 2, 2026".into(), "10:30 AM".into()]
1366 )
1367 .unwrap()
1368 );
1369 let edit = canvas.edit().unwrap().unwrap();
1370 assert!(edit.ops.iter().any(|op| matches!(
1371 op,
1372 Op::Page {
1373 op: PageOp::Date { .. },
1374 ..
1375 }
1376 )));
1377 section.shared.apply(edit).unwrap();
1378 let stored = section.shared.page(canvas.space).unwrap().0.date_text();
1379 assert_eq!(stored.unwrap()[0], "Friday, January 2, 2026");
1380 let after = canvas.page.editor.date().unwrap().timestamp();
1381 assert_ne!(after, before);
1382 // `sb_view_date_request` hands the host the date in its seconds.
1383 assert_eq!(library::unix(after), 1_767_349_800);
1384}
1385
1386#[test]
1387fn pages_open_with_the_snap_default_font_and_markdown_options_set() {
1388 // The defaults, so pages other tests open meanwhile see no change.
1389 sb_set_snap_to_grid(true);
1390 unsafe { sb_set_default_font(c"Calibri".as_ptr(), 11.0) };
1391 sb_set_markdown_shortcuts(true);
1392 assert_eq!(
1393 *options(),
1394 (true, canvas::editor::DefaultFont::default(), true)
1395 );
1396 let (_directory, section) = features();
1397 let canvas = canvas(&section, "Paragraph controls");
1398 assert!(canvas.page.snap_to_grid);
1399 assert_eq!(canvas.page.editor.default_font.face, "Calibri");
1400 assert!(canvas.page.editor.markdown.is_some());
1401}
1402
1403#[test]
1404fn a_share_notebook_names_its_files_from_the_share_s_top() {
1405 assert_eq!(library::on_share("", "Notes.one"), "Notes.one");
1406 assert_eq!(
1407 library::on_share("Team/Book", "Group/Notes.one"),
1408 "Team/Book/Group/Notes.one"
1409 );
1410}
1411
1412/// A notebook copy with its library, and a section of it open for editing. Working
1413/// `offline` from the start, no sync step can publish the section's edits.
1414fn notebook_open(path: &str, offline: bool) -> (tempfile::TempDir, PathBuf, Arc<Library>, Section) {
1415 let (directory, root) = copy("m6/native-features-01/notebook");
1416 let library = Arc::new(Library::open(&root, &directory.path().join("cache"), true).unwrap());
1417 if offline {
1418 sb_library_set_offline(&library, true);
1419 }
1420 let section = open(&library, path);
1421 (directory, root, library, section)
1422}
1423
1424/// Waits up to ten seconds for `ready`.
1425fn eventually(mut ready: impl FnMut() -> bool) -> bool {
1426 let deadline = Instant::now() + Duration::from_secs(10);
1427 while Instant::now() < deadline {
1428 if ready() {
1429 return true;
1430 }
1431 std::thread::sleep(Duration::from_millis(50));
1432 }
1433 false
1434}
1435
1436#[test]
1437fn sync_status_lists_every_section_and_work_offline_holds_edits_until_sync_now() {
1438 let (_directory, root, library, section) = notebook_open("Features.one", false);
1439 // Every readable section, the open one's from its session.
1440 assert!(eventually(|| {
1441 let status = library.sync_status();
1442 status.len()
1443 == library
1444 .tabs()
1445 .unwrap()
1446 .iter()
1447 .filter(|tab| tab.readable)
1448 .count()
1449 && status
1450 .iter()
1451 .all(|sync| sync.state == SyncState::UpToDate as u8)
1452 }));
1453 sb_library_set_offline(&library, true);
1454 let mut canvas = canvas(&section, "Paragraph controls");
1455 focus(&mut canvas, "Collapsed parent");
1456 canvas.insert("Offline ".into()).unwrap();
1457 section
1458 .shared
1459 .apply(canvas.edit().unwrap().unwrap())
1460 .unwrap();
1461 let file = root.join("Features.one");
1462 let queued = |library: &Library| {
1463 library
1464 .sync_status()
1465 .into_iter()
1466 .find(|sync| sync.path == "Features.one")
1467 .unwrap()
1468 .queued
1469 };
1470 assert!(eventually(|| queued(&library) == 1));
1471 std::thread::sleep(Duration::from_millis(500));
1472 assert!(!stored_text(&file, canvas.space).contains("Offline "));
1473 sb_library_sync_now(&library);
1474 assert!(eventually(|| queued(&library) == 0));
1475 assert!(stored_text(&file, canvas.space).contains("Offline "));
1476 sb_library_set_offline(&library, false);
1477}
1478
1479#[test]
1480fn sections_open_the_first_time_while_the_background_syncs() {
1481 let (directory, root) = copy("m6/native-features-01/notebook");
1482 let library = Arc::new(Library::open(&root, &directory.path().join("cache"), true).unwrap());
1483 let rounds = {
1484 let library = Arc::clone(&library);
1485 std::thread::spawn(move || {
1486 for _ in 0..200 {
1487 sb_library_sync_now(&library);
1488 std::thread::sleep(Duration::from_millis(2));
1489 }
1490 })
1491 };
1492 for tab in library
1493 .tabs()
1494 .unwrap()
1495 .into_iter()
1496 .filter(|tab| tab.readable)
1497 {
1498 open(&library, &tab.path);
1499 }
1500 rounds.join().unwrap();
1501 for tab in library
1502 .tabs()
1503 .unwrap()
1504 .into_iter()
1505 .filter(|tab| tab.readable)
1506 {
1507 open(&library, &tab.path);
1508 }
1509}
1510
1511#[test]
1512fn the_tags_summary_lists_tagged_paragraphs_and_opens_on_them() {
1513 let (directory, file) = copy("structural-probe/tag-gallery.one");
1514 let library = Arc::new(Library::open(&file, &directory.path().join("cache"), true).unwrap());
1515 let path = file.to_string_lossy().into_owned();
1516 let section = open(&library, &path);
1517 let tagged = library.tagged().unwrap();
1518 assert!(tagged.len() >= 9, "{}", tagged.len());
1519 assert!(
1520 tagged
1521 .iter()
1522 .any(|tag| tag.name == "To Do" && tag.shape == 3)
1523 );
1524 let first = &tagged[0];
1525 let space = first.page.parse().unwrap();
1526 let (page, _) = section.shared.page(space).unwrap();
1527 let mut canvas = Canvas::new(space, page, [1206, 2622], 3.0).unwrap();
1528 assert!(
1529 canvas
1530 .select_paragraph(first.paragraph.parse().unwrap())
1531 .unwrap()
1532 );
1533 let [start, end] = canvas.selection().unwrap();
1534 assert!(canvas.text([start, end]).contains(first.text.trim()));
1535}
1536
1537#[test]
1538fn every_tag_applies_and_reports_and_remove_tag_clears_them() {
1539 let (_directory, section) = features();
1540 let mut canvas = canvas(&section, "Paragraph controls");
1541 focus(&mut canvas, "Collapsed parent");
1542 for index in [0, 12, 28] {
1543 assert!(canvas.format(16 + index).unwrap());
1544 assert_ne!(canvas.format_bits().unwrap() & 1 << (16 + index), 0);
1545 }
1546 assert!(canvas.format(8).unwrap());
1547 assert_eq!(canvas.format_bits().unwrap() >> 16, 0);
1548 assert!(canvas.format(16 + NoteTag::defaults().len() as u8).is_err());
1549}
1550
1551#[test]
1552fn tag_icons_draw_their_art_and_highlighting_tags_have_none() {
1553 let mut rgba = vec![0; 32 * 32 * 4];
1554 for tag in NoteTag::defaults() {
1555 let drawn = unsafe { sb_tag_icon(tag.shape, true, 32, rgba.as_mut_ptr()) };
1556 assert_eq!(drawn, tag.shape != 0, "{tag:?}");
1557 if drawn {
1558 assert!(
1559 rgba.as_chunks::<4>().0.iter().any(|pixel| pixel[3] > 0),
1560 "{tag:?}"
1561 );
1562 }
1563 }
1564}
1565
1566#[test]
1567fn page_colour_rule_lines_and_art_are_stored_and_undo() {
1568 let (_directory, section) = features();
1569 let mut canvas = canvas(&section, "Paragraph controls");
1570 assert!(canvas.set_paper(Some(0xfef5ed), Some(1)).unwrap());
1571 assert!(canvas.set_art(Some("Bamboo")).unwrap());
1572 section
1573 .shared
1574 .apply(canvas.edit().unwrap().unwrap())
1575 .unwrap();
1576 let art = |page: &Page| {
1577 page.objects
1578 .iter()
1579 .filter(|object| {
1580 matches!(object, onestore::page::PageObject::Image(image) if image.background)
1581 })
1582 .count()
1583 };
1584 let stored = section.shared.page(canvas.space).unwrap().0;
1585 assert_eq!(stored.color, Some(0xfef5ed));
1586 assert_eq!(stored.rule_lines, Some(canvas::template::RULE_LINES[1].1));
1587 assert_eq!(art(&stored), 1);
1588 assert!(canvas.set_art(None).unwrap());
1589 assert!(moved(canvas.page.undo(false).unwrap()));
1590 assert!(moved(canvas.page.undo(false).unwrap()));
1591 section
1592 .shared
1593 .apply(canvas.edit().unwrap().unwrap())
1594 .unwrap();
1595 let stored = section.shared.page(canvas.space).unwrap().0;
1596 assert_eq!((stored.color, art(&stored)), (Some(0xfef5ed), 0));
1597}
1598
1599#[test]
1600fn insert_space_turns_the_next_touch_into_a_drag() {
1601 let (_directory, section) = features();
1602 let mut canvas = canvas(&section, "Paragraph controls");
1603 assert_eq!(canvas.target([300.0, 1500.0]), Target::Page);
1604 let _ = canvas.page.insert_space();
1605 assert_eq!(canvas.target([300.0, 1500.0]), Target::Grip);
1606}
1607
1608/// The page's drawings as the section stores them.
1609fn stored_ink(section: &Section, space: ExGuid) -> Vec<onestore::page::Ink> {
1610 let (page, _) = section.shared.page(space).unwrap();
1611 page.objects
1612 .into_iter()
1613 .filter_map(|object| match object {
1614 onestore::page::PageObject::Ink(ink) => Some(ink),
1615 _ => None,
1616 })
1617 .collect()
1618}
1619
1620/// A press, drags through `points` and a release, and the edit it made stored.
1621fn trace(canvas: &mut Canvas, section: &Section, points: &[[f32; 2]]) {
1622 canvas.press(points[0]).unwrap();
1623 for &point in &points[1..] {
1624 canvas.drag(point).unwrap();
1625 }
1626 canvas.release().unwrap();
1627 if let Some(edit) = canvas.edit().unwrap() {
1628 section.shared.apply(edit).unwrap();
1629 }
1630}
1631
1632fn line(from: [f32; 2], to: [f32; 2]) -> Vec<[f32; 2]> {
1633 (0..=20)
1634 .map(|step| {
1635 let t = step as f32 / 20.0;
1636 [
1637 from[0] + (to[0] - from[0]) * t,
1638 from[1] + (to[1] - from[1]) * t,
1639 ]
1640 })
1641 .collect()
1642}
1643
1644/// The tab colour of a section that stores none.
1645const SECTION: u32 = 0x00e4_a88a;
1646
1647#[test]
1648fn pencil_tools_draw_pick_move_delete_and_erase_drawings_as_edits() {
1649 let (_directory, section) = features();
1650 let mut canvas = canvas(&section, "Paragraph controls");
1651 let space = canvas.space;
1652 let before = stored_ink(&section, space).len();
1653 // The red pen, second in OneNote's gallery after the section's accent.
1654 canvas.set_tool(1, 2, SECTION).unwrap();
1655 trace(&mut canvas, &section, &line([100.0, 600.0], [300.0, 660.0]));
1656 let drawn = stored_ink(&section, space);
1657 assert_eq!(drawn.len(), before + 1);
1658 let stroke = &drawn.last().unwrap().strokes[0];
1659 assert_eq!(stroke.color, Some(0x241ced));
1660 assert!(stroke.points.len() > 2);
1661 // A highlighter stroke is a drawing of its own.
1662 canvas.set_tool(1, 6, SECTION).unwrap();
1663 trace(&mut canvas, &section, &line([100.0, 760.0], [300.0, 760.0]));
1664 assert_eq!(stored_ink(&section, space).len(), before + 2);
1665 assert!(stored_ink(&section, space).last().unwrap().strokes[0].raster_operation == Some(9));
1666
1667 // The lasso picks the pen stroke; a touch on it then drags it.
1668 canvas.set_tool(3, 0, SECTION).unwrap();
1669 let lasso = [
1670 [80.0, 580.0],
1671 [320.0, 580.0],
1672 [320.0, 700.0],
1673 [80.0, 700.0],
1674 [80.0, 582.0],
1675 ];
1676 trace(&mut canvas, &section, &lasso);
1677 let frame = canvas.ink_selection().unwrap();
1678 assert!(frame[2] > 150.0 && frame[3] > 40.0, "{frame:?}");
1679 let on = [200.0, 630.0];
1680 assert_eq!(canvas.target(on), Target::Grip);
1681 trace(&mut canvas, &section, &[on, [230.0, 645.0], [260.0, 660.0]]);
1682 let moved = stored_ink(&section, space);
1683 let layout = &moved[before].layout;
1684 assert!(layout.x.is_some_and(|x| x > 0.0), "{layout:?}");
1685 let _ = canvas
1686 .page
1687 .key(&Key::Named(NamedKey::Backspace), None)
1688 .unwrap();
1689 section
1690 .shared
1691 .apply(canvas.edit().unwrap().unwrap())
1692 .unwrap();
1693 assert_eq!(stored_ink(&section, space).len(), before + 1);
1694 assert!(canvas.ink_selection().is_none());
1695
1696 // The eraser takes the highlighter's stroke it crosses; undo brings it back.
1697 canvas.set_tool(2, 0, SECTION).unwrap();
1698 trace(&mut canvas, &section, &line([200.0, 720.0], [200.0, 800.0]));
1699 assert_eq!(stored_ink(&section, space).len(), before);
1700 let _ = canvas.page.undo(false).unwrap();
1701 section
1702 .shared
1703 .apply(canvas.edit().unwrap().unwrap())
1704 .unwrap();
1705 assert_eq!(stored_ink(&section, space).len(), before + 1);
1706}
1707
1708#[test]
1709fn the_accent_pen_and_shapes_draw_as_the_desktop_and_a_cancelled_sweep_stores_nothing() {
1710 let (_directory, section) = features();
1711 let mut canvas = canvas(&section, "Paragraph controls");
1712 let space = canvas.space;
1713 let before = stored_ink(&section, space).len();
1714 let accent = pens(canvas::gpu::colorref(SECTION))[0];
1715 canvas.set_tool(1, 0, SECTION).unwrap();
1716 trace(&mut canvas, &section, &line([100.0, 600.0], [300.0, 600.0]));
1717 let drawn = stored_ink(&section, space);
1718 assert_eq!(drawn.last().unwrap().strokes[0].color, accent.color);
1719 assert!(accent.color.is_some());
1720 // An oval dragged out is one drawing that keeps its shape.
1721 canvas.set_tool(4, 3, SECTION).unwrap();
1722 trace(&mut canvas, &section, &line([100.0, 700.0], [300.0, 800.0]));
1723 let drawn = stored_ink(&section, space);
1724 assert_eq!(drawn.len(), before + 2);
1725 assert!(drawn.last().unwrap().shape.is_some());
1726
1727 // An eraser sweep a second finger cancels gives back what it took and stores nothing.
1728 canvas.set_tool(2, 0, SECTION).unwrap();
1729 canvas.press([200.0, 580.0]).unwrap();
1730 canvas.drag([200.0, 620.0]).unwrap();
1731 assert!(canvas.page.editor.ink_extent(&[drawn[before].id]).is_none());
1732 let _ = canvas.page.cancel_ink().unwrap();
1733 assert!(canvas.edit().unwrap().is_none());
1734 assert!(canvas.page.editor.ink_extent(&[drawn[before].id]).is_some());
1735 assert!(!canvas.page.editor.can_redo());
1736 assert_eq!(stored_ink(&section, space).len(), before + 2);
1737}
1738
1739/// Queues an offline edit to Features.one and closes its session, leaving the edit to the
1740/// background; the replicas in the cache, and the text edited in.
1741fn unpublished_edit() -> (tempfile::TempDir, PathBuf, Arc<Library>, ExGuid) {
1742 let (directory, root, library, section) = notebook_open("Features.one", true);
1743 let mut canvas = canvas(&section, "Paragraph controls");
1744 focus(&mut canvas, "Collapsed parent");
1745 canvas.insert("Unpublished ".into()).unwrap();
1746 section
1747 .shared
1748 .apply(canvas.edit().unwrap().unwrap())
1749 .unwrap();
1750 assert!(eventually(|| !section
1751 .shared
1752 .section
1753 .pending()
1754 .unwrap()
1755 .is_empty()));
1756 let space = canvas.space;
1757 drop(canvas);
1758 drop(section);
1759 (directory, root, library, space)
1760}
1761
1762fn replicas(directory: &tempfile::TempDir) -> usize {
1763 let Ok(folders) = std::fs::read_dir(directory.path().join("cache/replicas")) else {
1764 return 0;
1765 };
1766 folders
1767 .filter_map(|folder| std::fs::read_dir(folder.ok()?.path()).ok())
1768 .flatten()
1769 .filter(|entry| {
1770 entry
1771 .as_ref()
1772 .is_ok_and(|entry| entry.path().extension() == Some("sqlite".as_ref()))
1773 })
1774 .count()
1775}
1776
1777#[test]
1778fn closing_publishes_a_pending_edit_so_the_notebook_renames_without_orphans() {
1779 let (directory, root, library, space) = unpublished_edit();
1780 library.close(Duration::from_secs(20)).unwrap();
1781 assert!(stored_text(&root.join("Features.one"), space).contains("Unpublished "));
1782 drop(library);
1783 assert!(eventually(|| replicas(&directory) == 0));
1784 let renamed = directory.path().join("Renamed");
1785 std::fs::rename(&root, &renamed).unwrap();
1786 let library = Arc::new(Library::open(&renamed, &directory.path().join("cache"), true).unwrap());
1787 let section = open(&library, "Features.one");
1788 let canvas = canvas(&section, "Paragraph controls");
1789 assert!(stored_text(&renamed.join("Features.one"), canvas.space).contains("Unpublished "));
1790}
1791
1792#[test]
1793fn closing_refuses_while_an_edit_cannot_publish_then_deletes_nothing_pending() {
1794 let (directory, root, library, space) = unpublished_edit();
1795 let away = directory.path().join("Away");
1796 std::fs::rename(&root, &away).unwrap();
1797 assert!(library.close(Duration::from_secs(2)).is_err());
1798 assert!(replicas(&directory) > 0);
1799 std::fs::rename(&away, &root).unwrap();
1800 library.close(Duration::from_secs(20)).unwrap();
1801 assert!(stored_text(&root.join("Features.one"), space).contains("Unpublished "));
1802 drop(library);
1803 std::fs::remove_dir_all(&root).unwrap();
1804 assert!(eventually(|| replicas(&directory) == 0));
1805}
1806
1807/// Print and Export as PDF make a PDF of the open page on the paper asked for.
1808#[test]
1809fn the_page_prints_as_a_pdf() {
1810 let (_directory, section) = features();
1811 let title = section.shared.section.pages().unwrap()[0].1.clone();
1812 let pdf = canvas(&section, &title)
1813 .pdf(canvas::print::A4, "Features")
1814 .unwrap();
1815 assert!(pdf.starts_with(b"%PDF"));
1816 let text = String::from_utf8_lossy(&pdf);
1817 assert!(
1818 text.contains("/MediaBox [0 0 595.276 841.89]"),
1819 "{}",
1820 &text[..400]
1821 );
1822}
1823
1824#[test]
1825fn a_recording_goes_in_as_the_desktop_stores_it_and_a_tap_plays_it() {
1826 use onestore::page::{PageObject, ParagraphContent};
1827 let (directory, section) = features();
1828 let mut canvas = canvas(&section, "Paragraph controls");
1829 focus(&mut canvas, "Collapsed parent");
1830 canvas.edit().unwrap();
1831 let date = ["Tuesday, September 29, 2026", "5:18 PM"];
1832 assert!(canvas.start_recording(false, date[0], date[1]).unwrap());
1833 canvas.insert("Linked note".into()).unwrap();
1834 let samples: Vec<i16> = (0..16_000).map(|n| (n % 64 * 256 - 8192) as i16).collect();
1835 let wav = canvas::recording::wave(canvas::recording::RATE, &samples);
1836 assert!(canvas.finish_recording(Some(wav), false).unwrap());
1837 section
1838 .shared
1839 .apply(canvas.edit().unwrap().unwrap())
1840 .unwrap();
1841
1842 let page = section.shared.page(canvas.space).unwrap().0;
1843 let paragraphs: Vec<_> = page
1844 .objects
1845 .iter()
1846 .filter_map(|object| match object {
1847 PageObject::Outline(outline) => Some(&outline.paragraphs),
1848 _ => None,
1849 })
1850 .flatten()
1851 .collect();
1852 let file = paragraphs
1853 .iter()
1854 .find_map(|paragraph| match &paragraph.content {
1855 ParagraphContent::Attachment(file) => Some(file),
1856 _ => None,
1857 })
1858 .unwrap();
1859 let recording = file.recording.unwrap();
1860 assert_eq!(file.filename, format!("{}.wav", page.title));
1861 assert_eq!((recording.kind, recording.duration_ms), (1, Some(1000)));
1862 // IMA ADPCM, as the desktop stores audio for OneNote (`corpus/recording`).
1863 let bytes = file.bytes.as_deref().unwrap();
1864 assert_eq!(u16::from_le_bytes([bytes[20], bytes[21]]), 0x11);
1865 let linked = |text: &str| {
1866 paragraphs
1867 .iter()
1868 .find(|paragraph| {
1869 paragraph
1870 .text()
1871 .is_some_and(|t| t.text.text().starts_with(text))
1872 })
1873 .map(|paragraph| (paragraph.media.recordings.clone(), paragraph.media.time_ms))
1874 .unwrap()
1875 };
1876 let line = linked("Audio recording started: 5:18 PM Tuesday, September 29, 2026");
1877 assert_eq!(line, (vec![recording.id], Some(0)));
1878 assert_eq!(linked("Linked note").0, [recording.id]);
1879
1880 // A tap on the recording plays it as PCM from the start.
1881 let tapped = (0..800)
1882 .flat_map(|y| (0..300).map(move |x| [x as f32 * 2.0, y as f32 * 2.0]))
1883 .find(|&point| {
1884 matches!(
1885 canvas.page.hit(canvas.device(point.map(|v| v * POINT))),
1886 Some(Hit::File(_))
1887 )
1888 })
1889 .unwrap()
1890 .map(|v| v * POINT);
1891 canvas.press(tapped).unwrap();
1892 canvas.release().unwrap();
1893 let folder = directory.path().join("playback");
1894 let request = canvas.take_play(&folder).unwrap().unwrap();
1895 assert_eq!(request["at_ms"], 0);
1896 assert!(request["video"].is_null());
1897 let sound = std::fs::read(request["sound"].as_str().unwrap()).unwrap();
1898 assert_eq!(u16::from_le_bytes([sound[20], sound[21]]), 1);
1899 assert!(canvas.take_play(&folder).unwrap().is_none());
1900 canvas.played(Some(5_000)).unwrap();
1901 canvas.played(None).unwrap();
1902}
1903
1904#[test]
1905fn a_movie_from_the_camera_becomes_the_desktop_s_avi() {
1906 let movie = recording::sb_movie_new();
1907 let bgra: Vec<u8> = (0..480 * 640 * 4).map(|n| (n % 251) as u8).collect();
1908 for index in 0..20u64 {
1909 unsafe {
1910 recording::sb_movie_picture(
1911 &mut *movie,
1912 index * 50_000,
1913 bgra.as_ptr(),
1914 640,
1915 480,
1916 640 * 4,
1917 )
1918 };
1919 }
1920 let pcm = vec![0u8; canvas::recording::RATE as usize * 2];
1921 unsafe { recording::sb_movie_sound(&mut *movie, pcm.as_ptr(), pcm.len()) };
1922 let mut length = 0;
1923 let avi = unsafe { recording::sb_movie_finish(movie, 1_000_000, &mut length) };
1924 let bytes = unsafe { std::slice::from_raw_parts(avi, length) }.to_vec();
1925 unsafe { sb_bytes_free(avi, length) };
1926 let parsed = canvas::recording::video::Movie::parse(&bytes).unwrap();
1927 assert_eq!((parsed.frames.len(), parsed.duration_ms()), (15, 1000));
1928 assert!(parsed.sound.is_some());
1929}
1930
1931fn levels(section: &Section) -> Vec<(ExGuid, u32)> {
1932 let pages = section.shared.section.pages().unwrap();
1933 pages
1934 .into_iter()
1935 .map(|(space, _, level)| (space, level))
1936 .collect()
1937}
1938
1939#[test]
1940fn pages_drag_indent_and_undo_as_one_edit_each() {
1941 let (_directory, _root, _library, section) = notebook_open("Features.one", true);
1942 let queued = || {
1943 section.shared.section.written().unwrap();
1944 section.shared.section.pending().unwrap().len()
1945 };
1946 let before = levels(&section);
1947 assert!(before.len() > 2);
1948 let last = before.last().unwrap().0;
1949 let mut dragged = before.clone();
1950 let moved = dragged.pop().unwrap();
1951 dragged.insert(0, moved);
1952 let mut edits = queued();
1953 let mut arrange = |order: &[(ExGuid, u32)], moved: ExGuid| {
1954 assert!(section.arrange(order, &[moved]).unwrap());
1955 assert_eq!(levels(&section), order);
1956 edits += 1;
1957 assert_eq!(queued(), edits);
1958 };
1959 arrange(&dragged, last);
1960 let second = dragged[1].0;
1961 let mut indented = dragged.clone();
1962 indented[1].1 = 2;
1963 arrange(&indented, second);
1964 arrange(&dragged, second);
1965 arrange(&before, last);
1966 assert!(!section.arrange(&before, &[ExGuid::default()]).unwrap());
1967 assert_eq!(queued(), edits);
1968}
1969
1970#[test]
1971fn a_page_moves_to_another_section_and_back_where_it_was() {
1972 let (_directory, root, library, features) = notebook_open("Features.one", false);
1973 let before = levels(&features);
1974 let (space, level) = before[1];
1975 let title = features.shared.section.page(space).unwrap().title;
1976 let date = ["Thursday, October 1, 2026", "9:00 AM"];
1977 let moved = library
1978 .move_page(
1979 "Features.one",
1980 space,
1981 "Empty.one",
1982 None,
1983 1,
1984 None,
1985 "Clover Test",
1986 date,
1987 )
1988 .unwrap();
1989 let arrived: ExGuid = moved.page.parse().unwrap();
1990 assert_eq!(moved.added, None);
1991 assert_eq!(moved.before, Some(before[2].0.to_string()));
1992 assert_eq!(moved.level, level);
1993 assert!(levels(&features).iter().all(|(page, _)| *page != space));
1994 let empty = open(&library, "Empty.one");
1995 let listed = empty.shared.section.pages().unwrap();
1996 assert_eq!(listed.last().unwrap(), &(arrived, title.clone(), 1));
1997 drop(empty);
1998 let back = library
1999 .move_page(
2000 "Empty.one",
2001 arrived,
2002 "Features.one",
2003 moved.before.map(|before| before.parse().unwrap()),
2004 moved.level,
2005 None,
2006 "Clover Test",
2007 date,
2008 )
2009 .unwrap()
2010 .page
2011 .parse()
2012 .unwrap();
2013 let mut returned = before.clone();
2014 returned[1].0 = back;
2015 assert_eq!(levels(&features), returned);
2016 assert_eq!(features.shared.section.page(back).unwrap().title, title);
2017 drop(features);
2018 library.close(Duration::from_secs(20)).unwrap();
2019 let arena = onestore::Arena::default();
2020 let file = onestore::read_file(root.join("Features.one")).unwrap();
2021 let stored = onestore::Section::open(&arena, file).unwrap();
2022 assert_eq!(stored.page(back).unwrap().title, title);
2023}
2024
2025/// A page edited while it moves stays, with the edit, beside the copy that arrived; a page added
2026/// meanwhile lets it go. The files hold both once the notebook closes.
2027#[test]
2028fn a_page_edited_while_it_moves_stays_with_its_edit() {
2029 library::sb_set_coordinator(coordinator);
2030 for edited in [true, false] {
2031 let (_directory, root, library, features) = notebook_open("Features.one", false);
2032 assert!(eventually(|| {
2033 let status = library.sync_status();
2034 !status.is_empty()
2035 && status
2036 .iter()
2037 .all(|sync| sync.state == SyncState::UpToDate as u8)
2038 }));
2039 let space = space(&features, "Task controls");
2040 // Empty.one is held for the move, which opens it, until the edit below is made.
2041 let (entered, holding) = std::sync::mpsc::channel();
2042 let (release, released) = std::sync::mpsc::channel();
2043 let empty = root.canonicalize().unwrap().join("Empty.one");
2044 HELD.lock()
2045 .unwrap()
2046 .push((empty.to_string_lossy().into_owned(), entered, released));
2047 let moving = Arc::clone(&library);
2048 let date = ["Thursday, October 1, 2026", "9:00 AM"];
2049 let move_page = std::thread::spawn(move || {
2050 moving
2051 .move_page(
2052 "Features.one",
2053 space,
2054 "Empty.one",
2055 None,
2056 1,
2057 None,
2058 "Clover Test",
2059 date,
2060 )
2061 .map(|moved| moved.copied)
2062 .map_err(|error| error.to_string())
2063 });
2064 holding.recv_timeout(Duration::from_secs(10)).unwrap();
2065 if edited {
2066 let mut canvas = canvas(&features, "Task controls");
2067 focus(&mut canvas, "Disabled standalone task");
2068 canvas.insert("Edited ".into()).unwrap();
2069 features
2070 .shared
2071 .apply(canvas.edit().unwrap().unwrap())
2072 .unwrap();
2073 } else {
2074 features.new_page(None, date[0], date[1]).unwrap();
2075 }
2076 features.shared.section.written().unwrap();
2077 drop(release);
2078 let copied = move_page.join().unwrap().unwrap();
2079 assert_eq!(copied.is_some(), edited, "{copied:?}");
2080 drop(features);
2081 library.close(Duration::from_secs(20)).unwrap();
2082 let arena = onestore::Arena::default();
2083 let stored = onestore::read_file(root.join("Features.one")).unwrap();
2084 let stayed = onestore::Section::open(&arena, stored).unwrap().page(space);
2085 assert_eq!(stayed.is_ok(), edited);
2086 if edited {
2087 assert!(canvas::search::page_text(&stayed.unwrap()).contains("Edited "));
2088 }
2089 let arena = onestore::Arena::default();
2090 let stored = onestore::read_file(root.join("Empty.one")).unwrap();
2091 let mut empty = onestore::Section::open(&arena, stored).unwrap();
2092 let copies: Vec<String> = (empty.pages().unwrap().into_iter())
2093 .filter(|(_, title, _)| title == "Task controls")
2094 .map(|(copy, ..)| canvas::search::page_text(&empty.page(copy).unwrap()))
2095 .collect();
2096 assert_eq!(copies.len(), 1);
2097 assert!(!copies[0].contains("Edited "));
2098 }
2099}
2100
2101/// A page whose section cannot write as it leaves stays there beside the copy that arrived,
2102/// and the move says so; both files hold it once the notebook closes.
2103#[test]
2104fn a_page_its_section_cannot_retire_stays_beside_its_copy() {
2105 vfs::install();
2106 let _exclusive = vfs::EXCLUSIVE
2107 .lock()
2108 .unwrap_or_else(std::sync::PoisonError::into_inner);
2109 let (directory, root, library, empty) = notebook_open("Empty.one", false);
2110 let features = open(&library, "Features.one");
2111 let space = space(&features, "Task controls");
2112 drop(features);
2113 let file = std::fs::read(root.join("Features.one")).unwrap();
2114 let identity = onestore::RevisionIndex::parse(&onestore::Store::parse(&file).unwrap())
2115 .unwrap()
2116 .root
2117 .guid;
2118 let location = notebook::location::local(&root).unwrap();
2119 let replica =
2120 notebook::location::folder(&directory.path().join("cache"), &location).join(format!(
2121 "{}.sqlite",
2122 (identity.iter())
2123 .map(|byte| format!("{byte:02x}"))
2124 .collect::<String>()
2125 ));
2126 *vfs::FAILING.lock().unwrap() = Some(replica.canonicalize().unwrap());
2127 let date = ["Thursday, October 1, 2026", "9:00 AM"];
2128 let moved = library.move_page(
2129 "Features.one",
2130 space,
2131 "Empty.one",
2132 None,
2133 1,
2134 None,
2135 "Clover Test",
2136 date,
2137 );
2138 *vfs::FAILING.lock().unwrap() = None;
2139 assert!(moved.unwrap().copied.is_some());
2140 drop(empty);
2141 library.close(Duration::from_secs(20)).unwrap();
2142 let titles = |name: &str| {
2143 let arena = onestore::Arena::default();
2144 let stored = onestore::read_file(root.join(name)).unwrap();
2145 let mut section = onestore::Section::open(&arena, stored).unwrap();
2146 (section.pages().unwrap().into_iter())
2147 .filter(|(_, title, _)| title == "Task controls")
2148 .count()
2149 };
2150 assert_eq!((titles("Features.one"), titles("Empty.one")), (1, 1));
2151}
2152
2153/// A page the section it moves to refuses stays where it was, and the move fails.
2154#[test]
2155fn a_page_the_other_section_refuses_stays() {
2156 let (_directory, _root, library, features) = notebook_open("Features.one", false);
2157 let before = levels(&features);
2158 let (space, _) = before[1];
2159 let page = features.shared.section.page(space).unwrap();
2160 let empty = open(&library, "Empty.one");
2161 let listed = levels(&empty);
2162 // A section's first page has level 1: Empty.one, holding none, refuses this one.
2163 assert!(
2164 library
2165 .move_page(
2166 "Features.one",
2167 space,
2168 "Empty.one",
2169 None,
2170 2,
2171 None,
2172 "Clover Test",
2173 ["Thursday, October 1, 2026", "9:00 AM"],
2174 )
2175 .is_err()
2176 );
2177 empty.shared.section.written().unwrap();
2178 features.shared.section.written().unwrap();
2179 assert_eq!(levels(&empty), listed);
2180 assert_eq!(levels(&features), before);
2181 assert_eq!(features.shared.section.page(space).unwrap(), page);
2182}
2183
2184#[test]
2185fn a_sections_last_page_moving_leaves_a_page_that_undo_takes_out() {
2186 let (_directory, _root, library, features) = notebook_open("Features.one", false);
2187 let date = ["Thursday, October 1, 2026", "9:02 AM"];
2188 let page = features.new_page(None, date[0], date[1]).unwrap();
2189 let arrived: ExGuid = library
2190 .move_page(
2191 "Features.one",
2192 page,
2193 "Empty.one",
2194 None,
2195 1,
2196 None,
2197 "Clover Test",
2198 date,
2199 )
2200 .unwrap()
2201 .page
2202 .parse()
2203 .unwrap();
2204 assert_eq!(levels(&open(&library, "Empty.one")), [(arrived, 1)]);
2205 let returned = library
2206 .move_page(
2207 "Empty.one",
2208 arrived,
2209 "Features.one",
2210 None,
2211 1,
2212 None,
2213 "Clover Test",
2214 date,
2215 )
2216 .unwrap();
2217 let back = returned.page.parse().unwrap();
2218 let added: ExGuid = returned.added.unwrap().parse().unwrap();
2219 assert_eq!(levels(&open(&library, "Empty.one")), [(added, 1)]);
2220 library
2221 .move_page(
2222 "Features.one",
2223 back,
2224 "Empty.one",
2225 None,
2226 1,
2227 Some(added),
2228 "Clover Test",
2229 date,
2230 )
2231 .unwrap();
2232 assert_eq!(levels(&open(&library, "Empty.one")).len(), 1);
2233}
2234
2235#[test]
2236fn sections_reorder_and_move_between_groups_and_back() {
2237 let (_directory, root, library, features) = notebook_open("Features.one", false);
2238 drop(features);
2239 let top = |library: &Library| -> Vec<String> {
2240 let tabs = library.tabs().unwrap();
2241 tabs.into_iter()
2242 .filter(|tab| tab.group.is_empty())
2243 .map(|tab| tab.path)
2244 .collect()
2245 };
2246 let before = top(&library);
2247 let mut reversed = before.clone();
2248 reversed.reverse();
2249 assert_eq!(
2250 library.place("Empty.one", "", &reversed).unwrap(),
2251 "Empty.one"
2252 );
2253 assert_eq!(top(&library), reversed);
2254 assert_eq!(
2255 library.place("Empty.one", "Group A", &[]).unwrap(),
2256 "Group A/Empty.one"
2257 );
2258 assert!(root.join("Group A/Empty.one").exists());
2259 let tabs = library.tabs().unwrap();
2260 let grouped: Vec<&str> = tabs
2261 .iter()
2262 .filter(|tab| tab.group == "Group A")
2263 .map(|tab| tab.path.as_str())
2264 .collect();
2265 assert_eq!(grouped.last(), Some(&"Group A/Empty.one"));
2266 assert_eq!(
2267 library.place("Group A/Empty.one", "", &before).unwrap(),
2268 "Empty.one"
2269 );
2270 assert_eq!(top(&library), before);
2271 assert!(root.join("Empty.one").exists());
2272 open(&library, "Empty.one");
2273}
2274
2275#[test]
2276fn dimensions_round_in_pixels_and_keep_subpixel_windows_nonempty() {
2277 assert_eq!(
2278 view_pixels([320.25, 480.75], 2.0, 8192).unwrap(),
2279 [641, 962]
2280 );
2281 assert_eq!(view_pixels([0.1, 0.2], 0.5, 8192).unwrap(), [1, 1]);
2282 assert_eq!(view_pixels([8192.0, 1.0], 1.0, 8192).unwrap(), [8192, 1]);
2283}
2284
2285#[test]
2286fn dimensions_reject_nonpositive_and_nonfinite_inputs() {
2287 for bad in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
2288 assert!(view_pixels([bad, 1.0], 1.0, 8192).is_err());
2289 assert!(view_pixels([1.0, bad], 1.0, 8192).is_err());
2290 assert!(view_pixels([1.0, 1.0], bad, 8192).is_err());
2291 }
2292}
2293
2294#[test]
2295fn dimensions_reject_overflow_and_the_device_texture_limit() {
2296 assert!(view_pixels([f32::MAX, 1.0], f32::MAX, u32::MAX).is_err());
2297 assert!(view_pixels([u32::MAX as f32, 1.0], 1.0, u32::MAX).is_err());
2298 assert!(view_pixels([8193.0, 1.0], 1.0, 8192).is_err());
2299 assert!(view_pixels([1.0, 4097.0], 2.0, 8192).is_err());
2300}
2301
2302#[test]
2303fn detached_editor_keeps_selection_and_undo_when_reattachment_fails() {
2304 let (_directory, section) = features();
2305 let space = section.shared.section.pages().unwrap()[0].0;
2306 let id = CString::new(space.to_string()).unwrap();
2307 assert!(
2308 unsafe {
2309 sb_view_new(
2310 std::ptr::null_mut(),
2311 &section,
2312 id.as_ptr(),
2313 320.0,
2314 480.0,
2315 2.0,
2316 )
2317 }
2318 .is_null()
2319 );
2320 let (page, read_only) = section.shared.page(space).unwrap();
2321 let mut view = View {
2322 canvas: ManuallyDrop::new(Canvas::new(space, page, [640, 960], 2.0).unwrap()),
2323 presentation: None,
2324 frame: Arc::default(),
2325 section: Arc::clone(&section.shared),
2326 read_only,
2327 reload_pending: false,
2328 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
2329 };
2330 assert!(sb_view_focus_title(&mut view));
2331 assert!(unsafe { sb_insert(&mut view, c" retained after surface loss".as_ptr()) });
2332 let text = view.canvas.active().shown_text();
2333 let history = view.canvas.page.editor.history_depth();
2334 let mut selection = [0; 2];
2335 sb_selection(&view, &mut selection);
2336 assert!(sb_view_can_undo(&view, false));
2337
2338 sb_view_detach_android(&mut view);
2339 sb_view_detach_android(&mut view);
2340 assert!(view.render().is_ok());
2341 assert!(!unsafe { sb_view_attach_android(&mut view, std::ptr::null_mut()) });
2342 let mut after = [0; 2];
2343 sb_selection(&view, &mut after);
2344 assert!(view.presentation.is_none());
2345 assert_eq!(view.canvas.page.viewport.size, [640, 960]);
2346 assert_eq!(view.canvas.scale, 2.0);
2347 assert_eq!(after, selection);
2348 assert_eq!(view.canvas.active().shown_text(), text);
2349 assert_eq!(view.canvas.page.editor.history_depth(), history);
2350 assert!(sb_view_undo(&mut view, false));
2351 assert!(
2352 !view
2353 .canvas
2354 .active()
2355 .shown_text()
2356 .contains("retained after surface loss")
2357 );
2358 assert!(sb_view_undo(&mut view, true));
2359 assert_eq!(view.canvas.active().shown_text(), text);
2360}
2361
2362struct LiveRelay(std::process::Child);
2363
2364impl LiveRelay {
2365 fn start(test: &str, root: &Path) -> (Self, String) {
2366 let receipt = root.join("relay-address");
2367 let child = std::process::Command::new(std::env::current_exe().unwrap())
2368 .args(["--exact", test, "--nocapture"])
2369 .env("SNOWBOUND_MOBILE_TEST_RELAY", &receipt)
2370 .stdout(std::process::Stdio::null())
2371 .spawn()
2372 .unwrap();
2373 let mut relay = Self(child);
2374 assert!(eventually(|| {
2375 assert!(relay.0.try_wait().unwrap().is_none());
2376 receipt.exists()
2377 }));
2378 (relay, std::fs::read_to_string(receipt).unwrap())
2379 }
2380}
2381
2382impl Drop for LiveRelay {
2383 fn drop(&mut self) {
2384 let _ = self.0.kill();
2385 let _ = self.0.wait();
2386 }
2387}
2388
2389fn live_relay_child() {
2390 if let Some(receipt) = std::env::var_os("SNOWBOUND_MOBILE_TEST_RELAY") {
2391 std::thread::spawn(|| {
2392 std::thread::sleep(Duration::from_secs(180));
2393 std::process::exit(124);
2394 });
2395 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2396 let receipt = PathBuf::from(receipt);
2397 let partial = receipt.with_extension("partial");
2398 std::fs::write(&partial, format!("ws://{}", listener.local_addr().unwrap())).unwrap();
2399 std::fs::rename(partial, receipt).unwrap();
2400 relay::server::serve(listener, Default::default()).unwrap();
2401 }
2402}
2403
2404fn live_host(
2405 root: &Path,
2406 cache: &Path,
2407 sharing: notebook::live::share::Sharing,
2408 relay: &str,
2409) -> notebook::live::share::Host {
2410 let kept = cache.join("sharing.json");
2411 let notebook = notebook::session::Notebook::open(root, cache).unwrap();
2412 notebook::live::share::Host::start(
2413 notebook.into_storage(),
2414 notebook::live::Hello::new("Host".into(), None).unwrap(),
2415 sharing,
2416 "Mobile fixture",
2417 None,
2418 Some(relay),
2419 || {},
2420 move |sharing| keep_live_fixture(&kept, sharing),
2421 )
2422 .unwrap()
2423}
2424
2425fn keep_live_fixture(path: &Path, value: &impl serde::Serialize) -> std::io::Result<()> {
2426 use std::io::Write;
2427 let mut options = std::fs::OpenOptions::new();
2428 options.write(true).create(true).truncate(true);
2429 #[cfg(unix)]
2430 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
2431 let partial = path.with_extension("partial");
2432 let mut output = options.open(&partial)?;
2433 output.write_all(&serde_json::to_vec(value)?)?;
2434 output.sync_all()?;
2435 std::fs::rename(partial, path)?;
2436 #[cfg(unix)]
2437 std::fs::File::open(path.parent().unwrap())?.sync_all()?;
2438 Ok(())
2439}
2440
2441struct JoinControl {
2442 deadline: Instant,
2443 cancelled: AtomicBool,
2444 approving: AtomicBool,
2445}
2446
2447impl JoinControl {
2448 fn new() -> Self {
2449 Self {
2450 deadline: Instant::now() + Duration::from_secs(30),
2451 cancelled: AtomicBool::new(false),
2452 approving: AtomicBool::new(false),
2453 }
2454 }
2455}
2456
2457extern "C" fn live_join_wait(token: usize, approving: bool) -> bool {
2458 // SAFETY: join_live keeps its borrowed JoinControl alive until sb_live_join returns.
2459 let control = unsafe { &*(token as *const JoinControl) };
2460 control.approving.store(approving, Ordering::Release);
2461 !control.cancelled.load(Ordering::Acquire) && Instant::now() < control.deadline
2462}
2463
2464fn take_json(raw: *mut c_char) -> serde_json::Value {
2465 assert!(!raw.is_null());
2466 let text = unsafe { CString::from_raw(raw) };
2467 serde_json::from_slice(text.as_bytes()).unwrap()
2468}
2469
2470fn join_live(code: &str, password: &str, relay: &str, control: &JoinControl) -> serde_json::Value {
2471 let code = CString::new(code).unwrap();
2472 let password = CString::new(password).unwrap();
2473 let relay = CString::new(relay).unwrap();
2474 take_json(unsafe {
2475 library::sb_live_join(
2476 c"Mobile guest".as_ptr(),
2477 c"Owned test device".as_ptr(),
2478 code.as_ptr(),
2479 password.as_ptr(),
2480 relay.as_ptr(),
2481 false,
2482 live_join_wait,
2483 control as *const JoinControl as usize,
2484 )
2485 })
2486}
2487
2488fn hosted_c(
2489 credential: &serde_json::Value,
2490 relay: &str,
2491 offline: bool,
2492 cache: &Path,
2493) -> Arc<Library> {
2494 let credential = CString::new(serde_json::to_vec(credential).unwrap()).unwrap();
2495 let relay = CString::new(relay).unwrap();
2496 let cache = CString::new(cache.to_str().unwrap()).unwrap();
2497 let mut error = std::ptr::null_mut();
2498 let raw = unsafe {
2499 library::sb_library_hosted(
2500 credential.as_ptr(),
2501 c"Mobile guest".as_ptr(),
2502 c"Owned test device".as_ptr(),
2503 relay.as_ptr(),
2504 false,
2505 offline,
2506 cache.as_ptr(),
2507 &mut error,
2508 )
2509 };
2510 if !error.is_null() {
2511 let error = unsafe { CString::from_raw(error) };
2512 panic!("hosted open: {}", error.to_string_lossy());
2513 }
2514 assert!(!raw.is_null());
2515 // SAFETY: sb_library_hosted hands the caller one owned Arc reference.
2516 unsafe { Arc::from_raw(raw) }
2517}
2518
2519#[test]
2520fn live_join_cancels_approval_and_returns_private_per_device_credentials() {
2521 live_relay_child();
2522 let directory = tempfile::tempdir().unwrap();
2523 let (_relay, url) = LiveRelay::start(
2524 "tests::live_join_cancels_approval_and_returns_private_per_device_credentials",
2525 directory.path(),
2526 );
2527 let root = directory.path().join("notebook");
2528 let cache = directory.path().join("host-cache");
2529 let creation = onestore::PageCreation::new(None, Some("Mobile fixture"), "Fixture").unwrap();
2530 drop(notebook::session::Notebook::create(&root, &cache, 0, &creation).unwrap());
2531 let mut sharing = notebook::live::share::Sharing::new("join password").unwrap();
2532 sharing.approve = true;
2533 let host = live_host(&root, &cache, sharing, &url);
2534 assert!(eventually(|| host.code().is_some()));
2535 let code = host.code().unwrap();
2536 assert_eq!(
2537 join_live("malformed", "", &url, &JoinControl::new())["refusal"],
2538 "malformed"
2539 );
2540 assert_eq!(
2541 join_live(&code, "wrong password", &url, &JoinControl::new())["refusal"],
2542 "wrong"
2543 );
2544 assert!(host.devices().is_empty());
2545 for decision in ["cancel", "decline", "allow"] {
2546 let control = JoinControl::new();
2547 let reply = std::thread::scope(|scope| {
2548 let joined = scope.spawn(|| join_live(&code, "join password", &url, &control));
2549 assert!(eventually(
2550 || control.approving.load(Ordering::Acquire) && host.requests().len() == 1
2551 ));
2552 match decision {
2553 "cancel" => control.cancelled.store(true, Ordering::Release),
2554 "decline" => host.decline(&host.requests()[0].peer),
2555 "allow" => host.allow(&host.requests()[0].peer).unwrap(),
2556 _ => unreachable!(),
2557 }
2558 joined.join().unwrap()
2559 });
2560 match decision {
2561 "allow" => {
2562 let credential = &reply["credential"];
2563 assert!(credential.is_object());
2564 let persisted: notebook::live::share::Sharing =
2565 serde_json::from_slice(&std::fs::read(cache.join("sharing.json")).unwrap())
2566 .unwrap();
2567 assert!(credential["secret"] == serde_json::json!(persisted.members[0].secret));
2568 assert!(credential["secret"] != serde_json::json!(persisted.secret));
2569 assert!(credential.get("room").is_none());
2570 assert!(credential.get("code").is_none());
2571 assert!(credential.get("password").is_none());
2572 assert_eq!(credential["protocol"], notebook::live::wire::VERSION);
2573 let kept = directory.path().join("joined.json");
2574 keep_live_fixture(&kept, credential).unwrap();
2575 let credential: serde_json::Value =
2576 serde_json::from_slice(&std::fs::read(kept).unwrap()).unwrap();
2577 let library = hosted_c(
2578 &credential,
2579 &url,
2580 false,
2581 &directory.path().join("guest-cache"),
2582 );
2583 assert!(eventually(|| take_json(library::sb_library_live_status(
2584 &library
2585 ))["state"]
2586 == "connected"));
2587 assert_eq!(library.tabs().unwrap().len(), 1);
2588 }
2589 _ => {
2590 assert_eq!(
2591 reply["refusal"],
2592 if decision == "cancel" {
2593 "cancelled"
2594 } else {
2595 "declined"
2596 }
2597 );
2598 assert!(reply.get("credential").is_none());
2599 assert!(host.devices().is_empty());
2600 assert!(eventually(|| host.requests().is_empty()));
2601 }
2602 }
2603 }
2604}
2605
2606#[test]
2607fn live_guests_reopen_original_offline_edits_search_and_resume_closed_sections() {
2608 live_relay_child();
2609 let directory = tempfile::tempdir().unwrap();
2610 let (_relay, url) = LiveRelay::start(
2611 "tests::live_guests_reopen_original_offline_edits_search_and_resume_closed_sections",
2612 directory.path(),
2613 );
2614 let root = directory.path().join("notebook");
2615 std::fs::create_dir_all(&root).unwrap();
2616 for (file, text) in [
2617 ("Read.one", "Original mobile text"),
2618 ("Other.one", "Closed section text"),
2619 ] {
2620 std::fs::write(
2621 root.join(file),
2622 onestore::create_section(file, text, "Fixture").unwrap(),
2623 )
2624 .unwrap();
2625 }
2626 let sealed = onestore::create_section("Sealed.one", "Protected fixture", "Fixture").unwrap();
2627 std::fs::write(
2628 root.join("Sealed.one"),
2629 onestore::protected::rekey(
2630 &sealed,
2631 None,
2632 Some(&onestore::protected::Key::new("section password").unwrap()),
2633 )
2634 .unwrap(),
2635 )
2636 .unwrap();
2637 let sealed = std::fs::read(root.join("Sealed.one")).unwrap();
2638 let host_cache = directory.path().join("host-cache");
2639 let host = live_host(
2640 &root,
2641 &host_cache,
2642 notebook::live::share::Sharing::new("").unwrap(),
2643 &url,
2644 );
2645 assert!(eventually(|| host.code().is_some()));
2646 let joined = join_live(&host.code().unwrap(), "", &url, &JoinControl::new());
2647 let kept = directory.path().join("joined.json");
2648 assert!(joined["credential"].is_object());
2649 keep_live_fixture(&kept, &joined["credential"]).unwrap();
2650 let credential: serde_json::Value =
2651 serde_json::from_slice(&std::fs::read(&kept).unwrap()).unwrap();
2652 let credential = &credential;
2653 let cache = directory.path().join("guest-cache");
2654 let library = hosted_c(credential, &url, false, &cache);
2655 let tabs = library.tabs().unwrap();
2656 assert!(
2657 tabs.iter()
2658 .any(|tab| tab.path == "Sealed.one" && tab.locked && !tab.readable)
2659 );
2660 let share: [u8; 16] = serde_json::from_value(credential["share"].clone()).unwrap();
2661 let copies = notebook::location::folder(&cache, &notebook::live::share::location(&share));
2662 let replicas = || {
2663 let mut paths: Vec<_> = std::fs::read_dir(&copies)
2664 .unwrap()
2665 .map(|entry| entry.unwrap().path())
2666 .filter(|path| {
2667 path.extension()
2668 .is_some_and(|extension| extension == "sqlite")
2669 })
2670 .collect();
2671 paths.sort();
2672 paths
2673 };
2674 assert!(eventually(|| copies.exists() && replicas().len() == 2));
2675 let original_replicas = replicas();
2676 assert!(eventually(|| library
2677 .sync_status()
2678 .iter()
2679 .filter(|sync| sync.state == SyncState::UpToDate as u8)
2680 .count()
2681 == 2));
2682 let sharing = host.sharing();
2683 drop(host);
2684 assert!(eventually(|| take_json(library::sb_library_live_status(
2685 &library
2686 ))["state"]
2687 != "connected"));
2688 sb_library_set_offline(&library, true);
2689 let section = open(&library, "Read.one");
2690 let space = section.shared.section.pages().unwrap()[0].0;
2691 let page = section.shared.section.page(space).unwrap();
2692 let text = page
2693 .objects
2694 .iter()
2695 .find_map(|object| match object {
2696 onestore::page::PageObject::Outline(outline) => {
2697 outline.paragraphs.iter().find_map(|paragraph| {
2698 paragraph
2699 .text()
2700 .filter(|text| text.text.text().contains("Original mobile text"))
2701 .map(|text| text.id)
2702 })
2703 }
2704 _ => None,
2705 })
2706 .unwrap();
2707 section
2708 .shared
2709 .apply(Edit {
2710 at: library::filetime(),
2711 ops: vec![Op::Page {
2712 space,
2713 op: PageOp::Text {
2714 text,
2715 range: 0..0,
2716 with: "OFFLINE_GUEST_TOKEN ".into(),
2717 },
2718 }],
2719 })
2720 .unwrap();
2721 section.shared.section.written().unwrap();
2722 let pending = section.shared.section.pending().unwrap();
2723 assert_eq!(pending.len(), 1);
2724 let identity = section.shared.section.replica().identity().unwrap();
2725 let shared = Arc::clone(&section.shared);
2726 drop((section, library));
2727 Arc::into_inner(shared).unwrap().section.close().unwrap();
2728
2729 let reopened: serde_json::Value =
2730 serde_json::from_slice(&std::fs::read(&kept).unwrap()).unwrap();
2731 let library = hosted_c(&reopened, &url, true, &cache);
2732 assert!(
2733 library
2734 .tabs()
2735 .unwrap()
2736 .iter()
2737 .any(|tab| tab.path == "Read.one" && tab.readable)
2738 );
2739 assert_eq!(replicas(), original_replicas);
2740 let section = open(&library, "Read.one");
2741 assert_eq!(
2742 section.shared.section.replica().identity().unwrap(),
2743 identity
2744 );
2745 assert_eq!(section.shared.section.pending().unwrap(), pending);
2746 assert!(
2747 canvas::search::page_text(&section.shared.section.page(space).unwrap())
2748 .contains("OFFLINE_GUEST_TOKEN")
2749 );
2750 let shared = Arc::clone(&section.shared);
2751 drop(section);
2752 Arc::into_inner(shared).unwrap().section.close().unwrap();
2753 assert_eq!(
2754 library::search(&[&library], None, "OFFLINE_GUEST_TOKEN")
2755 .unwrap()
2756 .len(),
2757 1
2758 );
2759 assert_eq!(std::fs::read(root.join("Sealed.one")).unwrap(), sealed);
2760 assert!(!stored_text(&root.join("Read.one"), space).contains("OFFLINE_GUEST_TOKEN"));
2761 let host = live_host(&root, &host_cache, sharing, &url);
2762 assert!(eventually(|| take_json(library::sb_library_live_status(
2763 &library
2764 ))["state"]
2765 == "connected"));
2766 let original = std::fs::read(root.join("Read.one")).unwrap();
2767 drop(library);
2768 let library = hosted_c(&reopened, &url, true, &cache);
2769 assert!(eventually(|| take_json(library::sb_library_live_status(
2770 &library
2771 ))["state"]
2772 == "connected"));
2773 assert_eq!(replicas(), original_replicas);
2774 for _ in 0..10 {
2775 let retained: Vec<_> = original_replicas
2776 .iter()
2777 .flat_map(|path| notebook::Replica::open(path).unwrap().pending().unwrap())
2778 .collect();
2779 assert_eq!(retained, pending);
2780 assert_eq!(std::fs::read(root.join("Read.one")).unwrap(), original);
2781 std::thread::sleep(Duration::from_millis(20));
2782 }
2783 // Closed-section search cannot override Work Offline while the host is reachable.
2784 for _ in 0..32 {
2785 assert_eq!(
2786 library::search(&[&library], None, "OFFLINE_GUEST_TOKEN")
2787 .unwrap()
2788 .len(),
2789 1
2790 );
2791 assert_eq!(std::fs::read(root.join("Read.one")).unwrap(), original);
2792 }
2793 let retained: Vec<_> = original_replicas
2794 .iter()
2795 .flat_map(|path| notebook::Replica::open(path).unwrap().pending().unwrap())
2796 .collect();
2797 assert_eq!(retained, pending);
2798 let section = open(&library, "Read.one");
2799 assert_eq!(
2800 section.shared.section.replica().identity().unwrap(),
2801 identity
2802 );
2803 for _ in 0..10 {
2804 assert_eq!(section.shared.section.pending().unwrap(), pending);
2805 assert_eq!(std::fs::read(root.join("Read.one")).unwrap(), original);
2806 std::thread::sleep(Duration::from_millis(20));
2807 }
2808 assert!(library.sync_status().iter().any(|sync| sync.queued == 1));
2809 sb_library_sync_now(&library);
2810 assert!(eventually(|| library
2811 .sync_status()
2812 .iter()
2813 .all(|sync| sync.queued == 0)));
2814 assert_eq!(
2815 stored_text(&root.join("Read.one"), space)
2816 .matches("OFFLINE_GUEST_TOKEN")
2817 .count(),
2818 1
2819 );
2820 assert_eq!(std::fs::read(root.join("Sealed.one")).unwrap(), sealed);
2821 assert!(section.shared.section.pending().unwrap().is_empty());
2822 let shared = Arc::clone(&section.shared);
2823 drop(section);
2824 Arc::into_inner(shared).unwrap().section.close().unwrap();
2825 sb_library_set_offline(&library, false);
2826 let other_join = join_live(&host.code().unwrap(), "", &url, &JoinControl::new());
2827 let other_kept = directory.path().join("other-joined.json");
2828 keep_live_fixture(&other_kept, &other_join["credential"]).unwrap();
2829 let other_credential: serde_json::Value =
2830 serde_json::from_slice(&std::fs::read(other_kept).unwrap()).unwrap();
2831 let other = hosted_c(
2832 &other_credential,
2833 &url,
2834 false,
2835 &directory.path().join("other-guest-cache"),
2836 );
2837 let secret: [u8; 16] = serde_json::from_value(credential["secret"].clone()).unwrap();
2838 host.remove(&secret).unwrap();
2839 assert!(eventually(|| take_json(library::sb_library_live_status(
2840 &library
2841 ))["state"]
2842 == "removed"));
2843 let unaffected = open(&other, "Read.one");
2844 unaffected
2845 .shared
2846 .apply(Edit {
2847 at: library::filetime(),
2848 ops: vec![Op::Page {
2849 space,
2850 op: PageOp::Text {
2851 text,
2852 range: 0..0,
2853 with: "OTHER_GUEST_TOKEN ".into(),
2854 },
2855 }],
2856 })
2857 .unwrap();
2858 assert!(unaffected.flush(Duration::from_secs(20)));
2859 assert_eq!(
2860 stored_text(&root.join("Read.one"), space)
2861 .matches("OTHER_GUEST_TOKEN")
2862 .count(),
2863 1
2864 );
2865 sb_library_set_offline(&library, true);
2866 let section = open(&library, "Read.one");
2867 section
2868 .shared
2869 .apply(Edit {
2870 at: library::filetime(),
2871 ops: vec![Op::Page {
2872 space,
2873 op: PageOp::Text {
2874 text,
2875 range: 0..0,
2876 with: "REMOVED_GUEST_TOKEN ".into(),
2877 },
2878 }],
2879 })
2880 .unwrap();
2881 section.shared.section.written().unwrap();
2882 let pending = section.shared.section.pending().unwrap();
2883 sb_library_sync_now(&library);
2884 assert!(eventually(|| library.sync_status().iter().any(|sync| sync
2885 .path
2886 == "Read.one"
2887 && sync.state == SyncState::NotConnected as u8
2888 && sync.queued == 1)));
2889 assert_eq!(section.shared.section.pending().unwrap(), pending);
2890 let shared = Arc::clone(&section.shared);
2891 drop((section, library));
2892 Arc::into_inner(shared).unwrap().section.close().unwrap();
2893 let reopened: serde_json::Value =
2894 serde_json::from_slice(&std::fs::read(&kept).unwrap()).unwrap();
2895 let library = hosted_c(&reopened, &url, true, &cache);
2896 let section = open(&library, "Read.one");
2897 assert_eq!(section.shared.section.pending().unwrap(), pending);
2898 assert!(
2899 canvas::search::page_text(&section.shared.section.page(space).unwrap())
2900 .contains("REMOVED_GUEST_TOKEN")
2901 );
2902 assert!(!stored_text(&root.join("Read.one"), space).contains("REMOVED_GUEST_TOKEN"));
2903 assert_eq!(std::fs::read(root.join("Sealed.one")).unwrap(), sealed);
2904}
2905
2906#[test]
2907fn hosted_credentials_reject_unknown_versions_without_echoing_secret_input() {
2908 let directory = tempfile::tempdir().unwrap();
2909 let cache = directory.path().join("must-not-be-created");
2910 let cache = CString::new(cache.to_str().unwrap()).unwrap();
2911 let wrong_version = serde_json::json!({
2912 "share": ([1u8; 16]), "secret": ([2u8; 16]),
2913 "protocol": notebook::live::wire::VERSION + 1,
2914 "notebook": "Fixture", "host": "Host",
2915 })
2916 .to_string();
2917 for input in ["{SECRET_MUST_NOT_BE_ECHOED", wrong_version.as_str()] {
2918 let input = CString::new(input).unwrap();
2919 let mut error = std::ptr::null_mut();
2920 let opened = unsafe {
2921 library::sb_library_hosted(
2922 input.as_ptr(),
2923 c"Guest".as_ptr(),
2924 std::ptr::null(),
2925 std::ptr::null(),
2926 false,
2927 true,
2928 cache.as_ptr(),
2929 &mut error,
2930 )
2931 };
2932 assert!(opened.is_null());
2933 assert!(!error.is_null());
2934 let error = unsafe { CString::from_raw(error) };
2935 assert!(
2936 !error
2937 .to_bytes()
2938 .windows(b"SECRET_MUST_NOT_BE_ECHOED".len())
2939 .any(|bytes| bytes == b"SECRET_MUST_NOT_BE_ECHOED")
2940 );
2941 }
2942 assert!(!Path::new(cache.to_str().unwrap()).exists());
2943}
2944
2945#[test]
2946fn reader_native_selection_commits_marked_ops_and_keeps_the_original_offline_editor() {
2947 let (directory, section) = features();
2948 sb_library_set_offline(&section.library, true);
2949 let file = directory.path().join("Features.one");
2950 let canonical = std::fs::read(&file).unwrap();
2951 let space = section.new_page(None, "Mon", "6:14 AM").unwrap();
2952 let (page, read_only) = section.shared.page(space).unwrap();
2953 let mut view = View {
2954 canvas: ManuallyDrop::new(Canvas::new(space, page, [720, 1280], 2.0).unwrap()),
2955 presentation: None,
2956 frame: Arc::default(),
2957 section: Arc::clone(&section.shared),
2958 read_only,
2959 reload_pending: false,
2960 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
2961 };
2962 view.canvas.set_transform(1.0, [0.0; 2]);
2963 let reading = |view: &View| {
2964 let query = sb_view_reading(view, 240.0);
2965 let status = serde_json::from_str::<serde_json::Value>(&string(query)).unwrap();
2966 unsafe { sb_string_free(query) };
2967 status
2968 };
2969 assert_eq!(reading(&view)["offered"], true);
2970 assert_eq!(reading(&view)["shown"], false);
2971 assert!(sb_view_focus_title(&mut view));
2972 assert!(unsafe { sb_insert(&mut view, c"A title that wraps on a narrow phone".as_ptr()) });
2973 let title = view.canvas.active().id;
2974 view.canvas.set_transform(1.5, [0.0; 2]);
2975 let before = view
2976 .canvas
2977 .page
2978 .caret_at(
2979 title,
2980 TextPosition {
2981 paragraph: 0,
2982 offset: 0,
2983 },
2984 Affinity::Downstream,
2985 0.0,
2986 )
2987 .unwrap();
2988 let mut anchor = [
2989 before.x0 as f32 * POINT - 4.0,
2990 before.y0 as f32 * POINT - 7.0,
2991 ];
2992 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
2993 let after = view
2994 .canvas
2995 .page
2996 .caret_at(
2997 title,
2998 TextPosition {
2999 paragraph: 0,
3000 offset: 0,
3001 },
3002 Affinity::Downstream,
3003 0.0,
3004 )
3005 .unwrap();
3006 for (axis, caret) in [after.x0, after.y0].into_iter().enumerate() {
3007 assert!(
3008 (caret * f64::from(POINT) - f64::from(anchor[axis]) - [4.0, 7.0][axis] * 1.5).abs()
3009 < 0.001
3010 );
3011 }
3012 view.canvas.set_transform(1.0, [0.0; 2]);
3013 assert!(!sb_view_read_only(&view));
3014 assert_eq!(reading(&view)["offered"], true);
3015 assert_eq!(reading(&view)["shown"], true);
3016 assert!(unsafe { sb_insert(&mut view, c"\n".as_ptr()) });
3017 assert!(unsafe {
3018 sb_insert(
3019 &mut view,
3020 c"Body 😀 with several wrapped words before the last line".as_ptr(),
3021 )
3022 });
3023 let body = view.canvas.active().id;
3024 let original = view.canvas.page.editor.page().unwrap();
3025 let history = view.canvas.page.editor.history_depth();
3026 let mut anchored_moved = false;
3027 for (source, offset) in [(title, 0), (body, 35)] {
3028 for width in [320.0, 240.0] {
3029 let before = view
3030 .canvas
3031 .page
3032 .caret_at(
3033 source,
3034 TextPosition {
3035 paragraph: 0,
3036 offset,
3037 },
3038 Affinity::Downstream,
3039 0.0,
3040 )
3041 .unwrap();
3042 anchor = [
3043 before.x0 as f32 * POINT,
3044 (before.y0 + (before.y1 - before.y0) / 2.0) as f32 * POINT,
3045 ];
3046 let old_anchor = anchor;
3047 assert!(sb_view_set_reading(&mut view, width, &mut anchor));
3048 let after = view
3049 .canvas
3050 .page
3051 .caret_at(
3052 source,
3053 TextPosition {
3054 paragraph: 0,
3055 offset,
3056 },
3057 Affinity::Downstream,
3058 0.0,
3059 )
3060 .unwrap();
3061 assert!(
3062 (f64::from(anchor[1] - old_anchor[1]) - (after.y0 - before.y0) * f64::from(POINT))
3063 .abs()
3064 < 0.001
3065 );
3066 eprintln!(
3067 "Reader anchor source={source} utf16={offset} width={width} before=({},{}) after=({},{}) anchor_delta_y={}",
3068 before.x0,
3069 before.y0,
3070 after.x0,
3071 after.y0,
3072 anchor[1] - old_anchor[1]
3073 );
3074 anchored_moved |= (after.y0 - before.y0).abs() > 0.1;
3075 for offset in [0, 8, 24] {
3076 let mut rect = [0.0; 4];
3077 assert!(sb_caret_rect(&view, offset, &mut rect));
3078 assert_eq!(
3079 view.canvas
3080 .closest([rect[0], rect[1] + rect[3] / 2.0])
3081 .unwrap(),
3082 offset
3083 );
3084 assert_eq!(
3085 view.canvas.target([rect[0] + 1.0, rect[1] + rect[3] / 2.0]),
3086 Target::ActiveText
3087 );
3088 }
3089 assert!(
3090 view.canvas
3091 .range_rects([0, view.canvas.length()])
3092 .unwrap()
3093 .len()
3094 > 1
3095 );
3096 assert_eq!(view.canvas.page.editor.page().unwrap(), original);
3097 assert_eq!(view.canvas.page.editor.history_depth(), history);
3098 assert_eq!(view.canvas.active().id, body);
3099 }
3100 }
3101 assert!(anchored_moved);
3102 assert!(sb_select(&mut view, 0, 0));
3103 assert!(unsafe { sb_set_marked(&mut view, c"marked 😀 ".as_ptr(), 10, 10) });
3104 let mut marked = [0; 2];
3105 assert!(sb_marked(&view, &mut marked));
3106 let preview = view.canvas.page.editor.page().unwrap();
3107 let selection = view.canvas.page.editor.selection();
3108 let history = view.canvas.page.editor.history_depth();
3109 for width in [320.0, 0.0, 240.0] {
3110 assert_eq!(
3111 sb_view_set_reading(&mut view, width, &mut anchor),
3112 width > 0.0
3113 );
3114 let mut unchanged = [0; 2];
3115 assert!(sb_marked(&view, &mut unchanged));
3116 assert_eq!(unchanged, marked);
3117 assert_eq!(view.canvas.page.editor.selection(), selection);
3118 assert_eq!(view.canvas.page.editor.history_depth(), history);
3119 assert_eq!(view.canvas.page.editor.page().unwrap(), preview);
3120 assert_eq!(view.canvas.active().id, body);
3121 assert!(!sb_view_reload(&mut view, false, Some(&mut anchor)));
3122 assert!(sb_marked(&view, &mut unchanged));
3123 assert_eq!(unchanged, marked);
3124 assert_eq!(view.canvas.page.editor.selection(), selection);
3125 assert_eq!(view.canvas.page.editor.history_depth(), history);
3126 assert_eq!(view.canvas.page.editor.page().unwrap(), preview);
3127 assert!(view.canvas.page.editor.take_ops().unwrap().is_empty());
3128 }
3129 assert!(sb_select(&mut view, 0, 0));
3130 assert!(!sb_marked(&view, &mut marked));
3131 assert!(view.canvas.page.editor.take_ops().unwrap().is_empty());
3132 let stored = section.shared.page(space).unwrap().0;
3133 let mut engine = pooled_engine();
3134 let stored = canvas::editor::CanvasEditor::from_page(stored, &mut engine).unwrap();
3135 pool_engine(engine);
3136 assert!(
3137 stored
3138 .outlines()
3139 .iter()
3140 .any(|outline| outline.id == body && outline.shown_text().contains("marked 😀"))
3141 );
3142 assert!(sb_view_undo(&mut view, false));
3143 assert!(!view.canvas.active().shown_text().contains("marked 😀"));
3144 assert!(sb_view_undo(&mut view, true));
3145 assert!(view.canvas.active().shown_text().contains("marked 😀"));
3146 for route in 0..6 {
3147 assert!(unsafe { sb_view_find(&mut view, c"Body".as_ptr()) });
3148 assert!(sb_select(&mut view, 0, 0));
3149 let paragraph = CString::new(
3150 view.canvas
3151 .active()
3152 .document()
3153 .text_nodes()
3154 .next()
3155 .unwrap()
3156 .id
3157 .to_string(),
3158 )
3159 .unwrap();
3160 if route == 5 {
3161 let mut rect = [0.0; 4];
3162 assert!(sb_caret_rect(&view, 0, &mut rect));
3163 assert!(sb_view_press(&mut view, rect[0], rect[1] + rect[3] / 2.0));
3164 }
3165 let text = format!("route{route} 😀 ");
3166 let marked_text = CString::new(text.clone()).unwrap();
3167 let end = u32::try_from(text.encode_utf16().count()).unwrap();
3168 assert!(unsafe { sb_set_marked(&mut view, marked_text.as_ptr(), end, end) });
3169 assert!(sb_marked(&view, &mut marked));
3170 match route {
3171 0 => assert!(sb_view_focus_title(&mut view)),
3172 1 => assert!(unsafe { sb_view_find(&mut view, c"Body".as_ptr()) }),
3173 2 => assert!(unsafe { sb_view_select_paragraph(&mut view, paragraph.as_ptr()) }),
3174 3 => assert!(sb_select_more(&mut view)),
3175 4 => sb_unmark(&mut view),
3176 _ => {
3177 let mut rect = [0.0; 4];
3178 assert!(sb_caret_rect(&view, end, &mut rect));
3179 assert!(sb_view_drag(&mut view, rect[0], rect[1] + rect[3] / 2.0));
3180 sb_view_release(&mut view);
3181 }
3182 }
3183 assert!(!sb_marked(&view, &mut marked));
3184 assert!(view.canvas.page.editor.take_ops().unwrap().is_empty());
3185 let mut rect = [0.0; 4];
3186 assert!(sb_caret_rect(&view, 0, &mut rect));
3187 let mut engine = pooled_engine();
3188 let stored = canvas::editor::CanvasEditor::from_page(
3189 section.shared.page(space).unwrap().0,
3190 &mut engine,
3191 )
3192 .unwrap();
3193 pool_engine(engine);
3194 assert!(
3195 stored
3196 .outlines()
3197 .iter()
3198 .any(|outline| outline.id == body && outline.shown_text().contains(text.trim()))
3199 );
3200 assert_eq!(reading(&view)["shown"], true);
3201 }
3202 let title_text = view
3203 .canvas
3204 .page
3205 .editor
3206 .visible_outlines()
3207 .find(|outline| outline.title)
3208 .unwrap()
3209 .document()
3210 .text_nodes()
3211 .next()
3212 .unwrap()
3213 .text()
3214 .unwrap()
3215 .id;
3216 for shown in [true, false] {
3217 for select in [true, false] {
3218 assert!(unsafe { sb_view_find(&mut view, c"Body".as_ptr()) });
3219 assert!(sb_select(&mut view, 0, 0));
3220 assert_eq!(
3221 sb_view_set_reading(&mut view, if shown { 240.0 } else { 0.0 }, &mut anchor),
3222 shown
3223 );
3224 if sb_view_format(&view) & 1 == 0 {
3225 assert!(sb_view_apply(&mut view, 0));
3226 }
3227 assert_ne!(sb_view_format(&view) & 1, 0);
3228 let local_before = view.canvas.active().shown_text();
3229 let text = view
3230 .canvas
3231 .active()
3232 .document()
3233 .text_nodes()
3234 .next()
3235 .unwrap()
3236 .text()
3237 .unwrap()
3238 .id;
3239 let history = view.canvas.page.editor.history_depth();
3240 let local = format!("retained {shown} {select} 😀 ");
3241 let local_text = CString::new(local.clone()).unwrap();
3242 let end = u32::try_from(local.encode_utf16().count()).unwrap();
3243 assert!(unsafe { sb_set_marked(&mut view, local_text.as_ptr(), end, end) });
3244 let preview = view.canvas.page.editor.page().unwrap();
3245 assert_eq!(
3246 view.canvas.active().shown_text(),
3247 format!("{local}{local_before}")
3248 );
3249 let local_nodes = view.canvas.active().document().nodes().to_vec();
3250 let selection = view.canvas.page.editor.selection();
3251 let peer = format!("peer {shown} {select} ");
3252 section
3253 .shared
3254 .section
3255 .apply(
3256 "Reader peer",
3257 page_edit(
3258 space,
3259 vec![PageOp::Text {
3260 text: title_text,
3261 range: 0..0,
3262 with: peer.clone(),
3263 }],
3264 ),
3265 )
3266 .unwrap();
3267 section.shared.section.written().unwrap();
3268 let pending_before = section.shared.section.pending().unwrap();
3269 let mut predicted = section.shared.page(space).unwrap().0;
3270 assert!(!sb_view_reload(&mut view, false, Some(&mut anchor)));
3271 assert!(view.reload_pending);
3272 assert!(sb_marked(&view, &mut marked));
3273 assert_eq!(view.canvas.page.editor.page().unwrap(), preview);
3274 assert_eq!(view.canvas.page.editor.selection(), selection);
3275 assert_eq!(view.canvas.page.editor.history_depth(), history);
3276 if select {
3277 assert!(sb_select(&mut view, 0, 0));
3278 } else {
3279 sb_unmark(&mut view);
3280 }
3281 assert!(!sb_marked(&view, &mut marked));
3282 let deadline = Instant::now() + Duration::from_secs(10);
3283 while view.reload_pending && !sb_view_reload_ready(&view) {
3284 let _ = section.poll();
3285 assert!(Instant::now() < deadline, "Original apply did not complete");
3286 std::thread::sleep(Duration::from_millis(10));
3287 }
3288 if sb_view_reload_ready(&view) {
3289 sb_view_reload(&mut view, false, Some(&mut anchor));
3290 }
3291 assert!(!view.reload_pending);
3292 assert_eq!(reading(&view)["shown"], shown);
3293 assert_eq!(view.canvas.active().id, body);
3294 assert!(view.canvas.page.editor.history_depth()[0] <= history[0] + 1);
3295 let expected_selection = if select {
3296 Selection::from(
3297 [TextPosition {
3298 paragraph: 0,
3299 offset: 0,
3300 }; 2],
3301 )
3302 } else {
3303 selection
3304 };
3305 assert_eq!(view.canvas.page.editor.selection(), expected_selection);
3306 assert!(
3307 view.canvas.page.editor.visible_outlines().any(|outline| {
3308 outline.id == title && outline.shown_text().starts_with(&peer)
3309 })
3310 );
3311 section.shared.section.written().unwrap();
3312 let pending = section.shared.section.pending().unwrap();
3313 assert_eq!(pending.len(), pending_before.len() + 1);
3314 assert_eq!(&pending[..pending_before.len()], pending_before.as_slice());
3315 let row = pending.last().unwrap();
3316 assert_eq!(row.author, "Clover Test");
3317 let edit = &row.edit;
3318 assert!(edit.ops.iter().any(|op| matches!(op,
3319 Op::Page { space: target, op: PageOp::Text { text: target_text, .. } }
3320 if *target == space && *target_text == text
3321 )));
3322 for op in &edit.ops {
3323 let Op::Page { space: target, op } = op else {
3324 panic!("Composition changed the section")
3325 };
3326 assert_eq!(*target, space);
3327 onestore::op::predict(&mut predicted, op).unwrap();
3328 }
3329 let mut normalized = preview.clone();
3330 for node in &local_nodes {
3331 let text = node.text().unwrap();
3332 onestore::op::predict(
3333 &mut normalized,
3334 &PageOp::Format {
3335 text: text.id,
3336 range: 0..text.text.utf16_offset(text.text.text().len()).unwrap(),
3337 set: Vec::new(),
3338 clear: Vec::new(),
3339 },
3340 )
3341 .unwrap();
3342 }
3343 let [stored_body, marked_body] = [&predicted, &normalized].map(|page| {
3344 page.objects
3345 .iter()
3346 .find_map(|object| match object {
3347 onestore::page::PageObject::Outline(outline) if outline.id == body => {
3348 Some(&outline.paragraphs)
3349 }
3350 _ => None,
3351 })
3352 .unwrap()
3353 });
3354 assert_eq!(stored_body, marked_body);
3355 assert_eq!(section.shared.page(space).unwrap().0, predicted);
3356 assert_eq!(view.canvas.active().document().nodes(), local_nodes);
3357 assert!(view.canvas.page.editor.take_ops().unwrap().is_empty());
3358 assert!(sb_view_undo(&mut view, false));
3359 assert_eq!(view.canvas.active().shown_text(), local_before);
3360 assert!(
3361 view.canvas.page.editor.visible_outlines().any(|outline| {
3362 outline.id == title && outline.shown_text().starts_with(&peer)
3363 })
3364 );
3365 assert!(sb_view_undo(&mut view, true));
3366 assert_eq!(
3367 view.canvas.active().shown_text(),
3368 format!("{local}{local_before}")
3369 );
3370 assert_eq!(reading(&view)["shown"], shown);
3371 }
3372 }
3373 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
3374 let before = view
3375 .canvas
3376 .page
3377 .caret_at(
3378 body,
3379 TextPosition {
3380 paragraph: 0,
3381 offset: 8,
3382 },
3383 Affinity::Downstream,
3384 0.0,
3385 )
3386 .unwrap();
3387 anchor = [
3388 before.x0 as f32 * POINT,
3389 (before.y0 + (before.y1 - before.y0) / 2.0) as f32 * POINT,
3390 ];
3391 let old_anchor = anchor;
3392 let selection = view.canvas.page.editor.selection();
3393 let history = view.canvas.page.editor.history_depth();
3394 section
3395 .shared
3396 .section
3397 .apply(
3398 "Reader peer",
3399 page_edit(
3400 space,
3401 vec![PageOp::Text {
3402 text: title_text,
3403 range: 0..0,
3404 with: "Peer title text before the original title ".into(),
3405 }],
3406 ),
3407 )
3408 .unwrap();
3409 section.shared.section.written().unwrap();
3410 let pending_before_reload = section.shared.section.pending().unwrap();
3411 assert!(sb_view_reload(&mut view, false, Some(&mut anchor)));
3412 let after = view
3413 .canvas
3414 .page
3415 .caret_at(
3416 body,
3417 TextPosition {
3418 paragraph: 0,
3419 offset: 8,
3420 },
3421 Affinity::Downstream,
3422 0.0,
3423 )
3424 .unwrap();
3425 assert!((after.y0 - before.y0).abs() > 0.1);
3426 assert!(
3427 (f64::from(anchor[1] - old_anchor[1]) - (after.y0 - before.y0) * f64::from(POINT)).abs()
3428 < 0.001
3429 );
3430 assert_eq!(view.canvas.page.editor.selection(), selection);
3431 assert!(view.canvas.page.editor.history_depth()[0] <= history[0]);
3432 assert_eq!(view.canvas.active().id, body);
3433 assert_eq!(reading(&view)["shown"], true);
3434 assert_eq!(
3435 section.shared.section.pending().unwrap(),
3436 pending_before_reload
3437 );
3438 assert!(view.canvas.page.editor.take_ops().unwrap().is_empty());
3439 let page = view.canvas.page.editor.page().unwrap();
3440 let created = page.created.unwrap();
3441 let fields: Vec<_> = view
3442 .canvas
3443 .page
3444 .editor
3445 .date()
3446 .unwrap()
3447 .source()
3448 .paragraphs
3449 .iter()
3450 .map(|node| {
3451 let text = node.text().unwrap();
3452 (text.id, text.text.text().to_owned())
3453 })
3454 .collect();
3455 for overwide in [true, false] {
3456 let mut next = fields.clone();
3457 if overwide {
3458 next[0].1 = "W".repeat(80);
3459 }
3460 section
3461 .shared
3462 .section
3463 .apply(
3464 "Reader peer",
3465 page_edit(
3466 space,
3467 vec![PageOp::Date {
3468 created,
3469 fields: next,
3470 }],
3471 ),
3472 )
3473 .unwrap();
3474 section.shared.section.written().unwrap();
3475 let pending_before_reload = section.shared.section.pending().unwrap();
3476 let history = view.canvas.page.editor.history_depth();
3477 assert!(sb_view_reload(&mut view, false, Some(&mut anchor)));
3478 assert_eq!(reading(&view)["shown"], false);
3479 assert_eq!(reading(&view)["offered"], !overwide);
3480 assert_eq!(view.canvas.page.editor.selection(), selection);
3481 assert_eq!(view.canvas.page.editor.history_depth(), history);
3482 assert_eq!(view.canvas.active().id, body);
3483 assert_eq!(
3484 section.shared.section.pending().unwrap(),
3485 pending_before_reload
3486 );
3487 assert!(view.canvas.page.editor.take_ops().unwrap().is_empty());
3488 }
3489 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
3490 assert!(unsafe { sb_view_find(&mut view, c"Body".as_ptr()) });
3491 assert!(!sb_view_set_reading(&mut view, 0.0, &mut anchor));
3492 assert_eq!(reading(&view)["shown"], false);
3493 assert_eq!(view.canvas.active().id, body);
3494 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
3495 sb_view_set_tool(&mut view, 1, 0, 0);
3496 assert_eq!(reading(&view)["shown"], false);
3497 assert_eq!(reading(&view)["offered"], true);
3498 sb_view_set_tool(&mut view, 0, 0, 0);
3499 assert_eq!(reading(&view)["shown"], false);
3500 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
3501 section.shared.section.written().unwrap();
3502 let mut predicted = section.shared.page(space).unwrap().0;
3503 let pending_before = section.shared.section.pending().unwrap();
3504 let result = view.canvas.page.insert_table(2, 2).map(moved);
3505 assert!(view.stored(result));
3506 assert_eq!(reading(&view)["shown"], false);
3507 assert_eq!(reading(&view)["offered"], false);
3508 assert!(!sb_view_read_only(&view));
3509 assert!(view.canvas.page.editor.take_ops().unwrap().is_empty());
3510 section.shared.section.written().unwrap();
3511 let pending = section.shared.section.pending().unwrap();
3512 assert_eq!(pending.len(), pending_before.len() + 1);
3513 assert_eq!(&pending[..pending_before.len()], pending_before.as_slice());
3514 let table = view
3515 .canvas
3516 .active()
3517 .document()
3518 .nodes()
3519 .iter()
3520 .find(|node| matches!(node.content, onestore::page::ParagraphContent::Table(_)))
3521 .unwrap();
3522 let edit = &pending.last().unwrap().edit;
3523 assert!(edit.ops.iter().any(|op| matches!(op, Op::Page { space: target, op: PageOp::Insert { container, paragraphs, .. } }
3524 if *target == space && *container == body && paragraphs.iter().any(|node| node.id == table.id))));
3525 let mut normalized = predicted.clone();
3526 let definitions = &view.canvas.page.editor.page().unwrap().definitions;
3527 for op in
3528 onestore::op::lower(body, &[], std::slice::from_ref(table), None, definitions).unwrap()
3529 {
3530 onestore::op::predict(&mut normalized, &op).unwrap();
3531 }
3532 for op in &edit.ops {
3533 let Op::Page { space: target, op } = op else {
3534 panic!("Table insertion changed the section")
3535 };
3536 assert_eq!(*target, space);
3537 onestore::op::predict(&mut predicted, op).unwrap();
3538 }
3539 let tables = [&normalized, &predicted].map(|page| {
3540 page.objects
3541 .iter()
3542 .find_map(|object| match object {
3543 onestore::page::PageObject::Outline(outline) if outline.id == body => {
3544 outline.paragraphs.iter().find(|node| node.id == table.id)
3545 }
3546 _ => None,
3547 })
3548 .unwrap()
3549 });
3550 assert_eq!(tables[0], tables[1]);
3551 assert_eq!(section.shared.page(space).unwrap().0, predicted);
3552 assert!(pending.iter().all(|edit| {
3553 section.shared.section.status(edit.id).unwrap() == Some(notebook::EditStatus::Pending)
3554 }));
3555 assert_eq!(std::fs::read(file).unwrap(), canonical);
3556}
3557
3558#[test]
3559fn reader_stacks_text_boxes_and_stores_an_edit_in_the_second_one() {
3560 let (directory, section) = features();
3561 let file = directory.path().join("Features.one");
3562 let space = section.new_page(None, "Mon", "6:14 AM").unwrap();
3563 let (page, read_only) = section.shared.page(space).unwrap();
3564 let mut view = View {
3565 canvas: ManuallyDrop::new(Canvas::new(space, page, [720, 1280], 2.0).unwrap()),
3566 presentation: None,
3567 frame: Arc::default(),
3568 section: Arc::clone(&section.shared),
3569 read_only,
3570 reload_pending: false,
3571 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
3572 };
3573 view.canvas.set_transform(1.0, [0.0; 2]);
3574 assert!(sb_view_focus_title(&mut view));
3575 assert!(unsafe { sb_insert(&mut view, c"Two boxes".as_ptr()) });
3576 let mut boxes = Vec::new();
3577 for (text, at) in [(c"Lower box", [72.0, 360.0]), (c"Upper box", [72.0, 200.0])] {
3578 assert!(sb_view_press(&mut view, at[0] * POINT, at[1] * POINT));
3579 assert!(sb_view_release(&mut view));
3580 assert!(unsafe { sb_insert(&mut view, text.as_ptr()) });
3581 boxes.push(view.canvas.active().id);
3582 }
3583 let [lower, upper] = boxes[..] else {
3584 unreachable!()
3585 };
3586 assert_ne!(lower, upper);
3587 let mut anchor = [0.0; 2];
3588 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
3589 let start = |view: &View, id| {
3590 view.canvas
3591 .page
3592 .caret_at(
3593 id,
3594 TextPosition {
3595 paragraph: 0,
3596 offset: 0,
3597 },
3598 Affinity::Downstream,
3599 0.0,
3600 )
3601 .unwrap()
3602 };
3603 let [first, second] = [start(&view, upper), start(&view, lower)];
3604 assert_eq!(first.x0, second.x0);
3605 assert!(first.y1 < second.y0);
3606 assert!(sb_view_press(
3607 &mut view,
3608 second.x0 as f32 * POINT + 1.0,
3609 (second.y0 + second.y1) as f32 / 2.0 * POINT
3610 ));
3611 assert!(sb_view_release(&mut view));
3612 assert_eq!(view.canvas.active().id, lower);
3613 let end = view.canvas.length();
3614 assert!(sb_select(&mut view, end, end));
3615 assert!(unsafe { sb_insert(&mut view, c", edited in reading 😀".as_ptr()) });
3616 assert_eq!(
3617 view.canvas.active().shown_text(),
3618 "Lower box, edited in reading 😀"
3619 );
3620 let mut status = sb_view_reading(&view, 240.0);
3621 let json = serde_json::from_str::<serde_json::Value>(&string(status)).unwrap();
3622 unsafe { sb_string_free(status) };
3623 assert_eq!(json["shown"], true);
3624 assert!(section.flush(Duration::from_secs(20)));
3625 let stored = stored_text(&file, space);
3626 assert!(stored.contains("Upper box"));
3627 assert!(stored.contains("Lower box, edited in reading 😀"));
3628 assert!(sb_view_undo(&mut view, false));
3629 assert_eq!(view.canvas.active().shown_text(), "Lower box");
3630 assert!(sb_view_undo(&mut view, true));
3631 assert!(!sb_view_set_reading(&mut view, 0.0, &mut anchor));
3632 status = sb_view_reading(&view, 240.0);
3633 let json = serde_json::from_str::<serde_json::Value>(&string(status)).unwrap();
3634 unsafe { sb_string_free(status) };
3635 assert_eq!(
3636 json,
3637 serde_json::json!({ "offered": true, "shown": false, "verdict": "Reflows" })
3638 );
3639 assert!(section.flush(Duration::from_secs(20)));
3640 let shared = Arc::clone(&view.section);
3641 drop(view);
3642 drop(section);
3643 Arc::into_inner(shared).unwrap().section.close().unwrap();
3644 let arena = onestore::Arena::default();
3645 let cold = onestore::Section::open(&arena, onestore::read_file(&file).unwrap()).unwrap();
3646 let mut engine = pooled_engine();
3647 let cold =
3648 canvas::editor::CanvasEditor::from_page(cold.page(space).unwrap(), &mut engine).unwrap();
3649 pool_engine(engine);
3650 let texts: Vec<_> = cold
3651 .outlines()
3652 .iter()
3653 .filter(|outline| !outline.title)
3654 .map(|outline| outline.shown_text())
3655 .collect();
3656 assert!(texts.contains(&"Upper box".to_string()));
3657 assert!(texts.contains(&"Lower box, edited in reading 😀".to_string()));
3658}
3659
3660/// A view of the page `title` of the corpus section `path`, copied, at 100%.
3661fn reader_corpus_view(path: &str, title: &str) -> (tempfile::TempDir, Section, View) {
3662 let (directory, file) = copy(path);
3663 let library = Arc::new(Library::open(&file, &directory.path().join("cache"), true).unwrap());
3664 let section = open(&library, &file.to_string_lossy());
3665 let space = space(&section, title);
3666 let (page, read_only) = section.shared.page(space).unwrap();
3667 let mut view = View {
3668 canvas: ManuallyDrop::new(Canvas::new(space, page, [720, 1280], 2.0).unwrap()),
3669 presentation: None,
3670 frame: Arc::default(),
3671 section: Arc::clone(&section.shared),
3672 read_only,
3673 reload_pending: false,
3674 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
3675 };
3676 view.canvas.set_transform(1.0, [0.0; 2]);
3677 (directory, section, view)
3678}
3679
3680#[test]
3681fn reader_shows_a_corpus_pages_picture_no_wider_than_the_column() {
3682 let (_directory, _section, mut view) =
3683 reader_corpus_view("print/native/Print.one", "Printing test");
3684 let query = sb_view_reading(&view, 240.0);
3685 let status = serde_json::from_str::<serde_json::Value>(&string(query)).unwrap();
3686 unsafe { sb_string_free(query) };
3687 assert_eq!(status["offered"], true);
3688 let mut page = [0.0; 4];
3689 sb_view_content(&mut view, &mut page);
3690 let mut anchor = [0.0; 2];
3691 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
3692 let mut column = [0.0; 4];
3693 sb_view_content(&mut view, &mut column);
3694 assert!(column[2] < page[2]);
3695 // The picture follows the long outline: the whole column in view.
3696 view.canvas.set_transform(0.05, [0.0; 2]);
3697 let paper = view.canvas.page_paper();
3698 let deadline = std::time::Instant::now() + Duration::from_secs(20);
3699 let pictures = loop {
3700 view.canvas
3701 .page
3702 .update_pictures(paper, std::task::Waker::noop());
3703 let pictures: Vec<[f32; 4]> = view
3704 .canvas
3705 .page
3706 .primitives(view.canvas.colors())
3707 .unwrap()
3708 .iter()
3709 .filter_map(|primitive| match primitive {
3710 draw::Primitive::Image { rect, .. } => Some(*rect),
3711 _ => None,
3712 })
3713 .collect();
3714 if !pictures.is_empty() || std::time::Instant::now() > deadline {
3715 break pictures;
3716 }
3717 std::thread::sleep(Duration::from_millis(10));
3718 };
3719 assert_eq!(pictures.len(), 1);
3720 assert!(pictures[0][2] - pictures[0][0] <= 240.0 / POINT + 0.01);
3721}
3722
3723#[test]
3724fn reader_leaves_a_small_drawing_out_and_refuses_a_mostly_drawn_page() {
3725 let reading = |view: &View| {
3726 let query = sb_view_reading(view, 240.0);
3727 let status = serde_json::from_str::<serde_json::Value>(&string(query)).unwrap();
3728 unsafe { sb_string_free(query) };
3729 status
3730 };
3731 let (_directory, _section, drawn) =
3732 reader_corpus_view("ink-edit/drawing/candidate/ink.one", "Beside the drawing");
3733 assert_eq!(reading(&drawn)["offered"], false);
3734 let (directory, section) = features();
3735 let space = section.new_page(None, "Mon", "6:14 AM").unwrap();
3736 let (page, read_only) = section.shared.page(space).unwrap();
3737 let mut view = View {
3738 canvas: ManuallyDrop::new(Canvas::new(space, page, [720, 1280], 2.0).unwrap()),
3739 presentation: None,
3740 frame: Arc::default(),
3741 section: Arc::clone(&section.shared),
3742 read_only,
3743 reload_pending: false,
3744 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
3745 };
3746 view.canvas.set_transform(1.0, [0.0; 2]);
3747 assert!(sb_view_focus_title(&mut view));
3748 assert!(unsafe { sb_insert(&mut view, c"Notes with a doodle".as_ptr()) });
3749 assert!(unsafe { sb_insert(&mut view, c"\n".as_ptr()) });
3750 assert!(unsafe {
3751 sb_insert(
3752 &mut view,
3753 c"A paragraph long enough to fill several lines of the column on a phone, with a small drawing beside it."
3754 .as_ptr(),
3755 )
3756 });
3757 sb_view_set_tool(&mut view, 1, 0, 0);
3758 let stroke =
3759 [[300.0, 400.0], [320.0, 410.0], [340.0, 400.0]].map(|[x, y]| [x * POINT, y * POINT]);
3760 assert!(sb_view_press(&mut view, stroke[0][0], stroke[0][1]));
3761 for [x, y] in &stroke[1..] {
3762 sb_view_drag(&mut view, *x, *y);
3763 }
3764 sb_view_release(&mut view);
3765 sb_view_set_tool(&mut view, 0, 0, 0);
3766 let strokes = |view: &View| {
3767 view.canvas
3768 .page
3769 .primitives(view.canvas.colors())
3770 .unwrap()
3771 .iter()
3772 .filter(|primitive| {
3773 matches!(
3774 primitive,
3775 draw::Primitive::Segment { .. } | draw::Primitive::Taper { .. }
3776 )
3777 })
3778 .count()
3779 };
3780 assert!(strokes(&view) > 0);
3781 assert_eq!(reading(&view)["offered"], true);
3782 let mut anchor = [0.0; 2];
3783 assert!(sb_view_set_reading(&mut view, 240.0, &mut anchor));
3784 assert_eq!(strokes(&view), 0);
3785 // A tap where the drawing lies on the page picks nothing to delete.
3786 assert!(sb_view_press(&mut view, stroke[1][0], stroke[1][1]));
3787 sb_view_release(&mut view);
3788 let mut rect = [0.0; 4];
3789 assert!(!sb_view_ink_selection(&view, &mut rect));
3790 assert!(!sb_view_set_reading(&mut view, 0.0, &mut anchor));
3791 assert!(strokes(&view) > 0);
3792 assert!(section.flush(Duration::from_secs(20)));
3793 let arena = onestore::Arena::default();
3794 let file = directory.path().join("Features.one");
3795 let stored = onestore::Section::open(&arena, onestore::read_file(file).unwrap()).unwrap();
3796 assert!(
3797 stored
3798 .page(space)
3799 .unwrap()
3800 .objects
3801 .iter()
3802 .any(|object| matches!(object, onestore::page::PageObject::Ink(_)))
3803 );
3804}
3805
3806#[test]
3807fn reader_local_apply_fence_tracks_overlapping_replies_and_view_lifetime() {
3808 use std::sync::mpsc;
3809
3810 let (directory, file) = copy("media-edit/candidate/Features.one");
3811 let library = Arc::new(Library::open(&file, &directory.path().join("cache"), true).unwrap());
3812 sb_library_set_offline(&library, true);
3813 let section = open(&library, file.to_str().unwrap());
3814 let space = space(&section, "Paragraph controls");
3815 let (page, read_only) = section.shared.page(space).unwrap();
3816 let mut view = View {
3817 canvas: ManuallyDrop::new(Canvas::new(space, page, [640, 960], 2.0).unwrap()),
3818 presentation: None,
3819 frame: Arc::default(),
3820 section: Arc::clone(&section.shared),
3821 read_only,
3822 reload_pending: true,
3823 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
3824 };
3825 focus(&mut view.canvas, "Collapsed parent");
3826 assert!(sb_view_reload_ready(&view));
3827 let before = section.shared.section.pending().unwrap();
3828 let (started, start) = mpsc::channel();
3829 let (release, released) = mpsc::channel();
3830 assert!(view.canvas.insert("first 🦀 ".into()).unwrap());
3831 let first = view.canvas.edit().unwrap().unwrap();
3832 let expected_first = first.clone();
3833 let first_reply = ApplyReply::new(&view.local_edits);
3834 section
3835 .shared
3836 .apply_with(first, move |result| {
3837 started.send(()).unwrap();
3838 released.recv_timeout(Duration::from_secs(10)).unwrap();
3839 first_reply.complete(result);
3840 })
3841 .unwrap();
3842 start.recv_timeout(Duration::from_secs(10)).unwrap();
3843 assert!(!sb_view_reload_ready(&view));
3844 assert!(view.canvas.insert("second 😀 ".into()).unwrap());
3845 let second = view.canvas.edit().unwrap().unwrap();
3846 let expected_second = second.clone();
3847 let second_reply = ApplyReply::new(&view.local_edits);
3848 let (started, start) = mpsc::channel();
3849 let (release_second, released_second) = mpsc::channel();
3850 section
3851 .shared
3852 .apply_with(second, move |result| {
3853 started.send(()).unwrap();
3854 released_second
3855 .recv_timeout(Duration::from_secs(10))
3856 .unwrap();
3857 second_reply.complete(result);
3858 })
3859 .unwrap();
3860 assert_eq!(view.local_edits.lock().unwrap().pending, 2);
3861 release.send(()).unwrap();
3862 start.recv_timeout(Duration::from_secs(10)).unwrap();
3863 assert_eq!(view.local_edits.lock().unwrap().pending, 1);
3864 assert!(!sb_view_reload_ready(&view));
3865 release_second.send(()).unwrap();
3866 let deadline = Instant::now() + Duration::from_secs(10);
3867 while !sb_view_reload_ready(&view) {
3868 assert!(Instant::now() < deadline);
3869 std::thread::sleep(Duration::from_millis(10));
3870 }
3871 sb_view_reload(&mut view, false, None);
3872 assert!(!view.reload_pending);
3873 assert!(!sb_view_reload_ready(&view));
3874 let pending = section.shared.section.pending().unwrap();
3875 assert_eq!(pending.len(), before.len() + 2);
3876 assert_eq!(&pending[..before.len()], before.as_slice());
3877 assert_eq!(pending[before.len()].edit, expected_first);
3878 assert_eq!(pending[before.len() + 1].edit, expected_second);
3879 assert!(pending[before.len()].id < pending[before.len() + 1].id);
3880 assert!(view.canvas.active().shown_text().contains("first 🦀"));
3881 assert!(view.canvas.active().shown_text().contains("second 😀"));
3882
3883 let (started, start) = mpsc::channel();
3884 let (release, released) = mpsc::channel();
3885 let (finished, finish) = mpsc::channel();
3886 assert!(view.canvas.insert("late reply ".into()).unwrap());
3887 let third = view.canvas.edit().unwrap().unwrap();
3888 let third_reply = ApplyReply::new(&view.local_edits);
3889 let weak = Arc::downgrade(&view.local_edits);
3890 section
3891 .shared
3892 .apply_with(third, move |result| {
3893 started.send(()).unwrap();
3894 released.recv_timeout(Duration::from_secs(10)).unwrap();
3895 third_reply.complete(result);
3896 finished.send(()).unwrap();
3897 })
3898 .unwrap();
3899 start.recv_timeout(Duration::from_secs(10)).unwrap();
3900 drop(view);
3901 assert!(weak.upgrade().is_some());
3902 release.send(()).unwrap();
3903 finish.recv_timeout(Duration::from_secs(10)).unwrap();
3904 assert!(weak.upgrade().is_none());
3905 section.shared.section.written().unwrap();
3906 assert_eq!(
3907 section.shared.section.pending().unwrap().len(),
3908 before.len() + 3
3909 );
3910 drop((section, directory));
3911}
3912
3913#[test]
3914fn reader_dropped_and_synchronous_failed_apply_callbacks_never_release_the_reload_fence() {
3915 for synchronous in [false, true] {
3916 let edits = Arc::new(Mutex::new(LocalEdits::default()));
3917 let reply = ApplyReply::new(&edits);
3918 let callback: Box<dyn FnOnce(std::result::Result<u64, notebook::Error>)> =
3919 Box::new(move |result| reply.complete(result));
3920 if synchronous {
3921 callback(Err(
3922 std::io::Error::other("Disposable ingress failure").into()
3923 ));
3924 } else {
3925 drop(callback);
3926 }
3927 assert_eq!(edits.lock().unwrap().pending, 0);
3928 assert!(edits.lock().unwrap().failed);
3929 }
3930}
3931
3932#[test]
3933fn reader_deferred_reload_preserves_rich_composition_after_real_local_write_failure() {
3934 let _exclusive = vfs::EXCLUSIVE
3935 .lock()
3936 .unwrap_or_else(std::sync::PoisonError::into_inner);
3937 for select in [false, true] {
3938 let directory = tempfile::tempdir().unwrap();
3939 let file = directory.path().join("Reader fault.one");
3940 let cache = directory.path().join("cache");
3941 let original =
3942 onestore::create_section("Reader fault.one", "Original body", "Fixture").unwrap();
3943 std::fs::write(&file, &original).unwrap();
3944 let library = Arc::new(Library::open(&file, &cache, true).unwrap());
3945 sb_library_set_offline(&library, true);
3946 let section = Section::open(
3947 Arc::clone(&library),
3948 file.to_str().unwrap(),
3949 "Fixture".into(),
3950 || {},
3951 )
3952 .unwrap();
3953 let identity = section.shared.section.identity().unwrap();
3954 let space = section.shared.section.pages().unwrap()[0].0;
3955 let (page, read_only) = section.shared.page(space).unwrap();
3956 let mut view = View {
3957 canvas: ManuallyDrop::new(Canvas::new(space, page, [640, 960], 2.0).unwrap()),
3958 presentation: None,
3959 frame: Arc::default(),
3960 section: Arc::clone(&section.shared),
3961 read_only,
3962 reload_pending: false,
3963 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
3964 };
3965 focus(&mut view.canvas, "Original body");
3966 assert!(sb_select(&mut view, 0, 0));
3967 if sb_view_format(&view) & 1 == 0 {
3968 assert!(sb_view_apply(&mut view, 0));
3969 }
3970 assert!(unsafe { sb_insert(&mut view, c"SEED ".as_ptr()) });
3971 section.shared.section.written().unwrap();
3972 assert_eq!(view.local_edits.lock().unwrap().pending, 0);
3973 assert!(!view.local_edits.lock().unwrap().failed);
3974 let seed = section.shared.section.pending().unwrap();
3975 assert_eq!(seed.len(), 1);
3976 let location = notebook::location::local(&file).unwrap();
3977 let root = onestore::RevisionIndex::parse(&onestore::Store::parse(&original).unwrap())
3978 .unwrap()
3979 .root
3980 .guid;
3981 let database = notebook::location::folder(&cache, &location).join(format!(
3982 "{}.sqlite",
3983 root.iter()
3984 .map(|byte| format!("{byte:02x}"))
3985 .collect::<String>(),
3986 ));
3987 assert!(database.is_file());
3988 let shared = Arc::clone(&section.shared);
3989 drop((view, section, library));
3990 Arc::into_inner(shared)
3991 .expect("No other seed writer")
3992 .section
3993 .close()
3994 .unwrap();
3995 // The cache's WAL takes no writes until the test has seen the edits wait.
3996 vfs::install();
3997 *vfs::FAILING.lock().unwrap() = Some(database.canonicalize().unwrap());
3998
3999 let library = Arc::new(Library::open(&file, &cache, true).unwrap());
4000 sb_library_set_offline(&library, true);
4001 let section = Section::open(
4002 Arc::clone(&library),
4003 file.to_str().unwrap(),
4004 "Fixture".into(),
4005 || {},
4006 )
4007 .unwrap();
4008 assert_eq!(section.shared.section.pending().unwrap(), seed);
4009 let (page, read_only) = section.shared.page(space).unwrap();
4010 let mut view = View {
4011 canvas: ManuallyDrop::new(Canvas::new(space, page, [640, 960], 2.0).unwrap()),
4012 presentation: None,
4013 frame: Arc::default(),
4014 section: Arc::clone(&section.shared),
4015 read_only,
4016 reload_pending: false,
4017 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
4018 };
4019 focus(&mut view.canvas, "Original body");
4020 assert!(sb_select(&mut view, 0, 0));
4021 let mut anchor = [0.0; 2];
4022 assert_eq!(
4023 sb_view_set_reading(&mut view, if select { 0.0 } else { 240.0 }, &mut anchor),
4024 !select
4025 );
4026 assert_ne!(sb_view_format(&view) & 1, 0);
4027 assert!(unsafe { sb_set_marked(&mut view, c"FAILED rich 😀 ".as_ptr(), 15, 15) });
4028 if select {
4029 assert!(sb_select(&mut view, 0, 0));
4030 } else {
4031 sb_unmark(&mut view);
4032 }
4033 assert!(sb_view_set_paper(&mut view, 0x77, 0x88, 0x99, -1));
4034 let preview = view.canvas.page.editor.page().unwrap();
4035 let deadline = Instant::now() + Duration::from_secs(10);
4036 let mut flags = 0;
4037 while section.shared.status.load(Ordering::Relaxed) != library::Status::NotSaving as u8 {
4038 flags |= section.poll();
4039 assert!(Instant::now() < deadline);
4040 std::thread::sleep(Duration::from_millis(10));
4041 }
4042 flags |= section.poll();
4043 assert_eq!(flags & 4, 0);
4044 assert_eq!(section.shared.section.pending().unwrap(), seed);
4045 let (waiting, _) = section.shared.page(space).unwrap();
4046 assert!(canvas::search::page_text(&waiting).contains("FAILED rich 😀"));
4047 assert_eq!(waiting.color, Some(0x0099_8877));
4048 assert_eq!(view.local_edits.lock().unwrap().pending, 2);
4049 assert!(!view.local_edits.lock().unwrap().failed);
4050 assert!(library.close(Duration::from_millis(100)).is_err());
4051 *vfs::FAILING.lock().unwrap() = None;
4052
4053 let deadline = Instant::now() + Duration::from_secs(10);
4054 while view.local_edits.lock().unwrap().pending > 0 {
4055 assert!(Instant::now() < deadline);
4056 std::thread::sleep(Duration::from_millis(10));
4057 }
4058 assert!(!view.local_edits.lock().unwrap().failed);
4059 let pending = section.shared.section.pending().unwrap();
4060 assert_eq!(pending.len(), seed.len() + 2);
4061 assert_eq!(&pending[..seed.len()], seed.as_slice());
4062 sb_view_reload(&mut view, false, None);
4063 assert!(!view.reload_pending);
4064 assert_eq!(view.canvas.page.editor.page().unwrap(), preview);
4065 let shared = Arc::clone(&section.shared);
4066 drop((view, section, library));
4067 Arc::into_inner(shared)
4068 .expect("No other writer")
4069 .section
4070 .close()
4071 .unwrap();
4072 let cold = notebook::Replica::open(&database).unwrap();
4073 assert_eq!(cold.identity().unwrap(), identity);
4074 assert_eq!(cold.pending().unwrap(), pending);
4075 let page = cold.page(space).unwrap();
4076 assert_eq!(
4077 canvas::search::page_text(&page)
4078 .matches("FAILED rich 😀")
4079 .count(),
4080 1
4081 );
4082 assert_eq!(page.color, Some(0x0099_8877));
4083 }
4084}
4085
4086/// A document provider over real folders, documents named by their paths, failing as the code
4087/// `fail` set for a folder says.
4088mod provider_fake {
4089 use crate::provider::{Found, Table, sb_set_provider};
4090 use crate::string;
4091 use std::{
4092 ffi::{CString, c_char, c_void},
4093 os::fd::IntoRawFd,
4094 path::{Path, PathBuf},
4095 sync::Mutex,
4096 };
4097
4098 static FAILING: Mutex<Vec<(PathBuf, i32)>> = Mutex::new(Vec::new());
4099 /// Folders whose documents list but don't open, as a cloud provider's offline.
4100 static UNOPENABLE: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
4101
4102 pub(super) fn unopenable(root: &Path, unopenable: bool) {
4103 let mut roots = UNOPENABLE.lock().unwrap();
4104 roots.retain(|held| held != root);
4105 roots.extend(unopenable.then(|| root.to_owned()));
4106 }
4107
4108 /// Has every call on documents in `root` fail with `code`, or none.
4109 pub(super) fn fail(root: &Path, code: Option<i32>) {
4110 let mut failing = FAILING.lock().unwrap();
4111 failing.retain(|(failed, _)| failed != root);
4112 failing.extend(code.map(|code| (root.to_owned(), code)));
4113 }
4114
4115 fn failing(id: *const c_char) -> Result<PathBuf, i32> {
4116 let path = PathBuf::from(string(id));
4117 let failing = FAILING.lock().unwrap();
4118 match failing.iter().find(|(root, _)| path.starts_with(root)) {
4119 Some((_, code)) => Err(*code),
4120 None => Ok(path),
4121 }
4122 }
4123
4124 fn describe(path: &Path, found: Found, context: *mut c_void) -> i32 {
4125 let Ok(metadata) = std::fs::metadata(path) else {
4126 return 3;
4127 };
4128 let id = CString::new(path.to_str().unwrap()).unwrap();
4129 let name = CString::new(path.file_name().unwrap().to_str().unwrap()).unwrap();
4130 let modified = metadata.modified().unwrap();
4131 let modified = modified.duration_since(std::time::UNIX_EPOCH).unwrap();
4132 let (size, modified) = (metadata.len() as i64, modified.as_millis() as i64);
4133 found(
4134 context,
4135 id.as_ptr(),
4136 name.as_ptr(),
4137 metadata.is_dir(),
4138 size,
4139 modified,
4140 true,
4141 );
4142 0
4143 }
4144
4145 extern "C" fn document(id: *const c_char, found: Found, context: *mut c_void) -> i32 {
4146 failing(id).map_or_else(|code| code, |path| describe(&path, found, context))
4147 }
4148
4149 extern "C" fn children(id: *const c_char, found: Found, context: *mut c_void) -> i32 {
4150 let path = match failing(id) {
4151 Ok(path) => path,
4152 Err(code) => return code,
4153 };
4154 let Ok(entries) = std::fs::read_dir(path) else {
4155 return 3;
4156 };
4157 for entry in entries {
4158 describe(&entry.unwrap().path(), found, context);
4159 }
4160 0
4161 }
4162
4163 extern "C" fn open(
4164 id: *const c_char,
4165 mode: *const c_char,
4166 fd: *mut i32,
4167 handle: *mut u64,
4168 ) -> i32 {
4169 let path = match failing(id) {
4170 Ok(path) => path,
4171 Err(code) => return code,
4172 };
4173 if UNOPENABLE
4174 .lock()
4175 .unwrap()
4176 .iter()
4177 .any(|root| path.starts_with(root))
4178 {
4179 return 1;
4180 }
4181 let write = string(mode) == "rw";
4182 match std::fs::File::options().read(true).write(write).open(path) {
4183 Ok(file) => {
4184 // SAFETY: the caller passes places for one descriptor and one handle.
4185 unsafe {
4186 fd.write(file.into_raw_fd());
4187 handle.write(1);
4188 }
4189 0
4190 }
4191 Err(_) => 3,
4192 }
4193 }
4194
4195 extern "C" fn close(handle: u64) -> i32 {
4196 assert_eq!(handle, 1);
4197 0
4198 }
4199
4200 extern "C" fn rename(
4201 id: *const c_char,
4202 name: *const c_char,
4203 renamed: extern "C" fn(*mut c_void, *const c_char),
4204 context: *mut c_void,
4205 ) -> i32 {
4206 let path = match failing(id) {
4207 Ok(path) => path,
4208 Err(code) => return code,
4209 };
4210 let new = path.with_file_name(string(name));
4211 if std::fs::rename(&path, &new).is_err() {
4212 return 3;
4213 }
4214 let new = CString::new(new.to_str().unwrap()).unwrap();
4215 renamed(context, new.as_ptr());
4216 0
4217 }
4218
4219 pub(super) fn register() {
4220 // SAFETY: every function keeps the header's contract; `open` hands over its own file.
4221 unsafe {
4222 sb_set_provider(&Table {
4223 document,
4224 children,
4225 open,
4226 close,
4227 rename,
4228 })
4229 };
4230 }
4231}
4232
4233/// The library `sb_library_provider` opens on `root`, or its error.
4234fn provided(root: &Path, folder: bool, cache: &Path) -> std::result::Result<Arc<Library>, String> {
4235 provider_fake::register();
4236 let (root, cache) = (
4237 CString::new(root.to_str().unwrap()).unwrap(),
4238 CString::new(cache.to_str().unwrap()).unwrap(),
4239 );
4240 let mut error = std::ptr::null_mut();
4241 // SAFETY: every string is NUL-terminated and `error` a place for one.
4242 let library = unsafe {
4243 library::sb_library_provider(
4244 root.as_ptr(),
4245 folder,
4246 true,
4247 c"Test".as_ptr(),
4248 cache.as_ptr(),
4249 &mut error,
4250 )
4251 };
4252 if library.is_null() {
4253 let message = string(error);
4254 // SAFETY: `error` came from the call above.
4255 unsafe { sb_string_free(error) };
4256 return Err(message);
4257 }
4258 // SAFETY: a library the call above made, freed when the Arc drops (`sb_library_free`).
4259 Ok(unsafe { Arc::from_raw(library) })
4260}
4261
4262/// Types `text` before "Collapsed parent" on Paragraph controls, returning the page.
4263fn typed(section: &Section, text: &str) -> ExGuid {
4264 let mut canvas = canvas(section, "Paragraph controls");
4265 focus(&mut canvas, "Collapsed parent");
4266 canvas.insert(text.into()).unwrap();
4267 section
4268 .shared
4269 .apply(canvas.edit().unwrap().unwrap())
4270 .unwrap();
4271 section.shared.section.replica().written().unwrap();
4272 canvas.space
4273}
4274
4275fn closed(section: Section) {
4276 let shared = Arc::clone(&section.shared);
4277 drop(section);
4278 Arc::into_inner(shared).unwrap().section.close().unwrap();
4279}
4280
4281fn flushed(library: &Library, seconds: f64) -> bool {
4282 // SAFETY: a null error is allowed.
4283 unsafe { library::sb_library_flush(library, seconds, std::ptr::null_mut()) }
4284}
4285
4286#[test]
4287fn a_provider_folder_opens_through_the_c_surface_and_publishes_in_place() {
4288 let (directory, root) = copy("m6/native-features-01/notebook");
4289 let library = provided(&root, true, &directory.path().join("cache")).unwrap();
4290 let tabs = library.tabs().unwrap();
4291 assert!(
4292 tabs.iter()
4293 .any(|tab| tab.path == "Features.one" && tab.readable)
4294 );
4295 let section = open(&library, "Features.one");
4296 let space = typed(&section, "Provided ");
4297 assert!(section.flush(Duration::from_secs(20)));
4298 assert!(stored_text(&root.join("Features.one"), space).contains("Provided "));
4299 closed(section);
4300}
4301
4302#[test]
4303fn a_provider_notebook_cold_opens_offline_as_last_listed_with_its_queued_edits() {
4304 let (directory, root) = copy("m6/native-features-01/notebook");
4305 let cache = directory.path().join("cache");
4306 let library = provided(&root, true, &cache).unwrap();
4307 let listed: Vec<String> = library
4308 .tabs()
4309 .unwrap()
4310 .into_iter()
4311 .map(|tab| tab.path)
4312 .collect();
4313 let section = open(&library, "Features.one");
4314 provider_fake::fail(&root, Some(1));
4315 let space = typed(&section, "Offline ");
4316 assert!(!flushed(&library, 0.5));
4317 closed(section);
4318 drop(library);
4319
4320 let library = provided(&root, true, &cache).unwrap();
4321 let tabs: Vec<String> = library
4322 .tabs()
4323 .unwrap()
4324 .into_iter()
4325 .map(|tab| tab.path)
4326 .collect();
4327 assert_eq!(tabs, listed);
4328 let section = open(&library, "Features.one");
4329 let (page, _) = section.shared.page(space).unwrap();
4330 assert!(canvas::search::page_text(&page).contains("Offline "));
4331 assert_eq!(section.shared.section.pending().unwrap().len(), 1);
4332 assert!(eventually(|| library.sync_status().iter().any(|sync| {
4333 sync.path == "Features.one" && sync.state == SyncState::NotConnected as u8
4334 })));
4335 assert!(!stored_text(&root.join("Features.one"), space).contains("Offline "));
4336 provider_fake::fail(&root, None);
4337 sb_library_sync_now(&library);
4338 assert!(section.flush(Duration::from_secs(20)));
4339 assert!(stored_text(&root.join("Features.one"), space).contains("Offline "));
4340 closed(section);
4341}
4342
4343#[test]
4344fn a_revoked_grant_refuses_to_open_and_keeps_the_queued_edits() {
4345 let (directory, root) = copy("m6/native-features-01/notebook");
4346 let cache = directory.path().join("cache");
4347 let library = provided(&root, true, &cache).unwrap();
4348 let section = open(&library, "Features.one");
4349 provider_fake::fail(&root, Some(2));
4350 let space = typed(&section, "Kept ");
4351 closed(section);
4352 drop(library);
4353 let refused = provided(&root, true, &cache).err().unwrap();
4354 assert!(refused.contains("no longer has access"), "{refused}");
4355 assert!(replicas(&directory) > 0);
4356
4357 provider_fake::fail(&root, None);
4358 let library = provided(&root, true, &cache).unwrap();
4359 let section = open(&library, "Features.one");
4360 assert_eq!(section.shared.section.pending().unwrap().len(), 1);
4361 assert!(section.flush(Duration::from_secs(20)));
4362 assert!(stored_text(&root.join("Features.one"), space).contains("Kept "));
4363 closed(section);
4364}
4365
4366#[test]
4367fn finishing_keeps_offline_copies_and_close_notebook_deletes_them() {
4368 let (directory, root) = copy("m6/native-features-01/notebook");
4369 let cache = directory.path().join("cache");
4370 let library = provided(&root, true, &cache).unwrap();
4371 let readable = library
4372 .tabs()
4373 .unwrap()
4374 .iter()
4375 .filter(|tab| tab.readable)
4376 .count();
4377 assert!(eventually(|| replicas(&directory) == readable));
4378 assert!(flushed(&library, 10.0));
4379 drop(library);
4380 std::thread::sleep(Duration::from_millis(200));
4381 assert_eq!(replicas(&directory), readable);
4382
4383 let library = provided(&root, true, &cache).unwrap();
4384 // SAFETY: a null error is allowed.
4385 assert!(unsafe { library::sb_library_close(&library, 10.0, std::ptr::null_mut()) });
4386 drop(library);
4387 assert!(eventually(|| replicas(&directory) == 0));
4388}
4389
4390#[test]
4391fn a_lone_provider_document_opens_and_publishes() {
4392 let (directory, file) = copy("media-edit/candidate/Features.one");
4393 let library = provided(&file, false, &directory.path().join("cache")).unwrap();
4394 let tabs = library.tabs().unwrap();
4395 assert_eq!(
4396 (tabs[0].name.as_str(), tabs[0].path.as_str()),
4397 ("Features", "")
4398 );
4399 let section = open(&library, "");
4400 let space = typed(&section, "Alone ");
4401 // As finishing flushes: the library, its open section and no background.
4402 assert!(flushed(&library, 20.0));
4403 assert!(stored_text(&file, space).contains("Alone "));
4404 closed(section);
4405}
4406
4407#[test]
4408fn a_provider_that_lists_but_cannot_open_opens_from_the_offline_copies() {
4409 let (directory, root) = copy("m6/native-features-01/notebook");
4410 let cache = directory.path().join("cache");
4411 let library = provided(&root, true, &cache).unwrap();
4412 let section = open(&library, "Features.one");
4413 let space = typed(&section, "Before ");
4414 assert!(flushed(&library, 20.0));
4415 closed(section);
4416 drop(library);
4417 // Listed otherwise than when last read, so discovery would read it again.
4418 let file = root.join("Features.one");
4419 let touched = std::fs::metadata(&file).unwrap().modified().unwrap() + Duration::from_secs(5);
4420 std::fs::File::options()
4421 .write(true)
4422 .open(&file)
4423 .unwrap()
4424 .set_modified(touched)
4425 .unwrap();
4426 provider_fake::unopenable(&root, true);
4427
4428 let library = provided(&root, true, &cache).unwrap();
4429 assert!(
4430 library
4431 .tabs()
4432 .unwrap()
4433 .iter()
4434 .any(|tab| tab.path == "Features.one" && tab.readable)
4435 );
4436 let section = open(&library, "Features.one");
4437 let (page, _) = section.shared.page(space).unwrap();
4438 assert!(canvas::search::page_text(&page).contains("Before "));
4439 typed(&section, "Offline");
4440 let (page, _) = section.shared.page(space).unwrap();
4441 assert!(canvas::search::page_text(&page).contains("Offline"));
4442 assert!(eventually(|| library.sync_status().iter().any(|sync| {
4443 sync.path == "Features.one"
4444 && sync.state == SyncState::NotConnected as u8
4445 && sync.queued == 1
4446 })));
4447 provider_fake::unopenable(&root, false);
4448 sb_library_sync_now(&library);
4449 assert!(flushed(&library, 20.0));
4450 assert!(stored_text(&file, space).contains("Offline"));
4451 closed(section);
4452}
4453
4454/// A page restored from a share's recycle bin while working offline waits in the cache and
4455/// publishes once online: a cold reopen finds it, content and identity kept, in the section
4456/// it was restored to, and Deleted Pages empty. `ONESTORE_SMB_LAB=HOST:PORT` names a guest
4457/// share `agent` (`tools/w7/linux_vm.py up NAME`); the notebook goes in a fresh folder.
4458#[test]
4459#[ignore = "requires an owned Samba share at ONESTORE_SMB_LAB"]
4460fn a_page_restored_offline_on_a_share_publishes_once_online() {
4461 const DELETED: &str = "OneNote_RecycleBin/OneNote_DeletedPages.one";
4462 let date = ["Monday, October 19, 2026", "9:00 AM"];
4463 let server = || library::Server {
4464 address: std::env::var("ONESTORE_SMB_LAB").unwrap(),
4465 share: "agent".into(),
4466 user: String::new(),
4467 password: String::new(),
4468 domain: String::new(),
4469 };
4470 let root = format!("snowbound-recycle-{}", std::process::id());
4471 let directory = tempfile::tempdir().unwrap();
4472 let client = Arc::new(server().connect().unwrap());
4473 client.create_directory(&root).unwrap();
4474 let mut notebook = notebook::session::Notebook::open_smb(
4475 Arc::clone(&client),
4476 &root,
4477 directory.path().join("made"),
4478 )
4479 .unwrap();
4480 for (name, title) in [("Kept", "Restored over SMB"), ("Target", "Already there")] {
4481 let page = onestore::PageCreation::new(None, Some(title), "Clover Test").unwrap();
4482 notebook.create_section("", name, &page).unwrap();
4483 }
4484 drop(notebook);
4485
4486 let library =
4487 Arc::new(Library::server(server(), &root, &directory.path().join("cache")).unwrap());
4488 library.tabs().unwrap();
4489 let kept = open(&library, "Kept.one");
4490 let deleted = space(&kept, "Restored over SMB");
4491 let page = kept.shared.section.page(deleted).unwrap();
4492 kept.delete_page(deleted, date[0], date[1]).unwrap();
4493 drop(kept);
4494 // As the iOS sheet lists the bin, then opens Deleted Pages.
4495 assert_eq!(library.recycle_bin().unwrap()[0].path, DELETED);
4496 let bin = open(&library, DELETED);
4497 let recycled = bin.shared.section.pages().unwrap()[0].0;
4498
4499 sb_library_set_offline(&library, true);
4500 let restored = library
4501 .move_page(
4502 DELETED,
4503 recycled,
4504 "Target.one",
4505 None,
4506 1,
4507 None,
4508 "Clover Test",
4509 date,
4510 )
4511 .unwrap();
4512 assert_eq!((restored.added, restored.copied), (None, None));
4513 assert!(
4514 !bin.shared.section.pending().unwrap().is_empty(),
4515 "the bin's edit waits offline"
4516 );
4517 drop(bin);
4518 sb_library_set_offline(&library, false);
4519 sb_library_sync_now(&library);
4520 library.close(Duration::from_secs(60)).unwrap();
4521 drop(library);
4522
4523 let cold = Arc::new(Library::server(server(), &root, &directory.path().join("cold")).unwrap());
4524 cold.tabs().unwrap();
4525 let target = open(&cold, "Target.one");
4526 let arrived = space(&target, "Restored over SMB");
4527 assert_eq!(
4528 target.shared.section.page(arrived).unwrap().identity,
4529 page.identity
4530 );
4531 drop(target);
4532 assert!(
4533 open(&cold, DELETED)
4534 .shared
4535 .section
4536 .pages()
4537 .unwrap()
4538 .is_empty()
4539 );
4540}
4541
4542/// iCloud Drive's conflict versions as the iOS host lists them (`NSFileVersion`): the file
4543/// each is of, where its contents are, and the device that saved it.
4544static CLOUD_VERSIONS: Mutex<Vec<(PathBuf, PathBuf, String)>> = Mutex::new(Vec::new());
4545
4546extern "C" fn cloud_versions(
4547 path: *const c_char,
4548 found: extern "C" fn(*mut c_void, *const c_char, *const c_char),
4549 context: *mut c_void,
4550) {
4551 let Ok(path) = std::fs::canonicalize(string(path)) else {
4552 return;
4553 };
4554 for (file, version, device) in CLOUD_VERSIONS.lock().unwrap().iter() {
4555 if *file == path {
4556 let id = std::ffi::CString::new(version.as_os_str().as_encoded_bytes()).unwrap();
4557 let device = std::ffi::CString::new(device.as_str()).unwrap();
4558 found(context, id.as_ptr(), device.as_ptr());
4559 }
4560 }
4561}
4562
4563/// Retires a version as ICloud.swift does, first keeping it beside the file when asked.
4564extern "C" fn cloud_retire(path: *const c_char, id: *const c_char, keep: bool) -> bool {
4565 let (path, id) = (PathBuf::from(string(path)), PathBuf::from(string(id)));
4566 let mut held = CLOUD_VERSIONS.lock().unwrap();
4567 let Some(at) = held.iter().position(|(_, version, _)| *version == id) else {
4568 return true;
4569 };
4570 let (_, version, device) = held.remove(at);
4571 if keep {
4572 let stem = path.file_stem().unwrap().to_string_lossy();
4573 std::fs::copy(
4574 version,
4575 path.with_file_name(format!("{stem} ({device}).one")),
4576 )
4577 .unwrap();
4578 }
4579 true
4580}
4581
4582/// A notebook opened as `Notebook.open` opens one in iCloud Drive.
4583fn cloud_library(root: &Path, cache: &Path) -> Arc<Library> {
4584 let text = |path: &Path| std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
4585 let mut error = std::ptr::null_mut();
4586 let raw = unsafe {
4587 library::sb_library_open(text(root).as_ptr(), text(cache).as_ptr(), false, &mut error)
4588 };
4589 assert!(error.is_null() && !raw.is_null());
4590 // SAFETY: `sb_library_open` hands over one reference.
4591 unsafe { Arc::from_raw(raw) }
4592}
4593
4594/// The section at `path`, opened as `Section.open` opens it.
4595fn cloud_section(library: &Library, path: &str) -> Box<Section> {
4596 extern "C" fn wake(_: usize) {}
4597 let path = std::ffi::CString::new(path).unwrap();
4598 let mut error = std::ptr::null_mut();
4599 let raw = unsafe {
4600 library::sb_section_open(
4601 library,
4602 path.as_ptr(),
4603 c"Clover".as_ptr(),
4604 wake,
4605 0,
4606 &mut error,
4607 )
4608 };
4609 assert!(error.is_null() && !raw.is_null());
4610 unsafe { Box::from_raw(raw) }
4611}
4612
4613/// The page ids `sb_section_pages` lists, conflict pages after their page.
4614fn listed_ids(section: &Section) -> Vec<ExGuid> {
4615 let json = library::sb_section_pages(section);
4616 let rows: Vec<serde_json::Value> =
4617 serde_json::from_str(unsafe { std::ffi::CStr::from_ptr(json) }.to_str().unwrap()).unwrap();
4618 unsafe { sb_string_free(json) };
4619 rows.iter()
4620 .flat_map(|row| {
4621 std::iter::once(&row["id"])
4622 .chain(row["versions"].as_array().unwrap().iter().map(|v| &v["id"]))
4623 })
4624 .map(|id| id.as_str().unwrap().parse().unwrap())
4625 .collect()
4626}
4627
4628/// A view on page `space`, as `sb_view_new` makes one, in the Reading View.
4629fn reading_view(section: &Section, space: ExGuid) -> Option<View> {
4630 let (page, read_only) = section.shared.page(space).ok()?;
4631 let mut view = View {
4632 canvas: ManuallyDrop::new(Canvas::new(space, page, [1206, 2622], 3.0).unwrap()),
4633 presentation: None,
4634 frame: Arc::default(),
4635 section: Arc::clone(&section.shared),
4636 read_only,
4637 reload_pending: false,
4638 local_edits: Arc::new(Mutex::new(LocalEdits::default())),
4639 };
4640 let _ = view.canvas.focus_title();
4641 sb_view_set_reading(&mut view, 402.0, &mut [0.0; 2]);
4642 Some(view)
4643}
4644
4645/// Types `text` on page `space`: below its title in a new outline, or in its first line.
4646fn type_on(section: &Section, space: ExGuid, text: &str) {
4647 let mut canvas = Canvas::new(
4648 space,
4649 section.shared.page(space).unwrap().0,
4650 [1206, 2622],
4651 3.0,
4652 )
4653 .unwrap();
4654 canvas.press([300.0, 600.0]).unwrap();
4655 canvas.release().unwrap();
4656 if let Some(edit) = canvas.edit().unwrap() {
4657 section.shared.apply(edit).unwrap();
4658 }
4659 canvas.insert(text.into()).unwrap();
4660 section
4661 .shared
4662 .apply(canvas.edit().unwrap().unwrap())
4663 .unwrap();
4664}
4665
4666fn titled(section: &Section, title: &str) -> ExGuid {
4667 let space = section
4668 .new_page(None, "Friday, October 16, 2026", "1:45 AM")
4669 .unwrap();
4670 let mut canvas = Canvas::new(
4671 space,
4672 section.shared.page(space).unwrap().0,
4673 [1206, 2622],
4674 3.0,
4675 )
4676 .unwrap();
4677 canvas.focus_title().unwrap();
4678 canvas.insert(title.into()).unwrap();
4679 section
4680 .shared
4681 .apply(canvas.edit().unwrap().unwrap())
4682 .unwrap();
4683 space
4684}
4685
4686fn close_section(section: Box<Section>) {
4687 assert!(section.flush(Duration::from_secs(20)));
4688 let shared = Arc::clone(&section.shared);
4689 drop(section);
4690 Arc::into_inner(shared).unwrap().section.close().unwrap();
4691}
4692
4693/// Every page and conflict page of every section of the notebook at `root`, as text,
4694/// each opened in the page view and the Reading View on the way.
4695fn every_page(root: &Path, cache: &Path) -> String {
4696 let library = cloud_library(root, cache);
4697 let mut shown = String::new();
4698 for tab in library.tabs().unwrap() {
4699 let section = cloud_section(&library, &tab.path);
4700 for space in listed_ids(&section) {
4701 let (page, _) = section.shared.page(space).unwrap();
4702 shown += &format!("{}\n{}\n", page.title, canvas::search::page_text(&page));
4703 drop(reading_view(&section, space).unwrap());
4704 }
4705 close_section(section);
4706 }
4707 shown
4708}
4709
4710/// The images the cache keeps of this device's publications.
4711fn kept(cache: &Path) -> Vec<Vec<u8>> {
4712 let folders = std::fs::read_dir(cache.join("replicas"))
4713 .into_iter()
4714 .flatten();
4715 folders
4716 .filter_map(|folder| std::fs::read_dir(folder.ok()?.path()).ok())
4717 .flatten()
4718 .filter_map(|entry| {
4719 let path = entry.ok()?.path();
4720 (path.extension()? == "published").then_some(path)
4721 })
4722 .filter_map(|store| std::fs::read_dir(store).ok())
4723 .flatten()
4724 .map(|image| std::fs::read(image.unwrap().path()).unwrap())
4725 .collect()
4726}
4727
4728/// How many versions of a section are kept beside it in `root`, as "Name (iPhone).one".
4729fn beside(root: &Path) -> usize {
4730 std::fs::read_dir(root)
4731 .unwrap()
4732 .filter(|entry| {
4733 let name = entry.as_ref().unwrap().file_name();
4734 name.to_string_lossy().contains("(iPhone")
4735 })
4736 .count()
4737}
4738
4739/// The titles and text of every page and conflict page each section file in `root` stores.
4740fn stored(root: &Path) -> String {
4741 let mut text = String::new();
4742 for entry in std::fs::read_dir(root).unwrap() {
4743 let path = entry.unwrap().path();
4744 if path.extension().is_some_and(|extension| extension == "one") {
4745 let arena = onestore::Arena::default();
4746 let mut section =
4747 onestore::Section::open(&arena, std::fs::read(path).unwrap()).unwrap();
4748 let conflicts = section.conflicts().unwrap().into_iter();
4749 let spaces = (section
4750 .pages()
4751 .unwrap()
4752 .into_iter()
4753 .map(|(space, ..)| space))
4754 .chain(
4755 conflicts
4756 .flat_map(|(_, pages)| pages)
4757 .map(|page| page.space),
4758 );
4759 for space in spaces.collect::<Vec<_>>() {
4760 let page = section.page(space).unwrap();
4761 text += &format!("{}\n{}\n", page.title, canvas::search::page_text(&page));
4762 }
4763 }
4764 }
4765 text
4766}
4767
4768/// The phone and the Mac edit one iCloud Drive notebook Snowbound made, each in its own copy:
4769/// the same page, a page each adds and moves to the top, a page the Mac deletes as the phone
4770/// types on it, and a section the phone adds. The Mac's upload wins: iCloud Drive keeps the
4771/// phone's file as a conflict version, or loses it. The phone's next launch opens, lists and
4772/// merges it back through the C surface as iOS does, its pages open and typed on in the
4773/// Reading View all the while. Nothing either device typed goes missing, and nothing is kept
4774/// beside the file twice.
4775#[test]
4776fn an_icloud_notebook_merges_the_phones_upload_back_at_launch() {
4777 unsafe { library::sb_set_versions(cloud_versions, cloud_retire, c"iPhone".as_ptr()) };
4778 // Whether the devices' copies already share an edit of the page both type on, and
4779 // whether iCloud Drive lost the phone's upload rather than keep it as a version.
4780 for (shared, lost) in [(false, false), (true, false), (false, true), (true, true)] {
4781 let directory = tempfile::tempdir().unwrap();
4782 let folder = |name: &str| directory.path().join(name);
4783 let (phone, mac) = (folder("phone"), folder("mac"));
4784 let creation = onestore::PageCreation::new(None, Some("Shared page"), "Clover").unwrap();
4785 let notebook = notebook::session::Notebook::create(
4786 &phone,
4787 folder("phone-cache"),
4788 0x00f0_a0c0,
4789 &creation,
4790 )
4791 .unwrap();
4792 let path = notebook.catalog().sections[0].path.clone();
4793 drop(notebook);
4794 let library = cloud_library(&phone, &folder("phone-cache"));
4795 let section = cloud_section(&library, &path);
4796 let first = listed_ids(&section)[0];
4797 let doomed = titled(&section, "Doomed page");
4798 if shared {
4799 type_on(&section, first, "Typed on both ");
4800 }
4801 close_section(section);
4802 drop(library);
4803 let copied = std::process::Command::new("cp")
4804 .arg("-R")
4805 .arg(&phone)
4806 .arg(&mac)
4807 .status();
4808 assert!(copied.unwrap().success());
4809
4810 for device in ["Phone", "Mac"] {
4811 let (root, cache) = (
4812 folder(&device.to_lowercase()),
4813 folder(&format!("{}-cache", device.to_lowercase())),
4814 );
4815 let library = cloud_library(&root, &cache);
4816 let section = cloud_section(&library, &path);
4817 type_on(&section, first, &format!("{device} first words "));
4818 type_on(&section, doomed, &format!("{device} on the doomed page "));
4819 let added = titled(&section, &format!("{device} page"));
4820 let moved = onestore::PageEdit::move_to(added, Some(first), 1).unwrap();
4821 section
4822 .shared
4823 .apply(Edit {
4824 at: library::filetime(),
4825 ops: vec![Op::Section(onestore::op::SectionOp::Pages(vec![moved]))],
4826 })
4827 .unwrap();
4828 if device == "Mac" {
4829 section
4830 .delete_page(doomed, "Friday, October 16, 2026", "8:00 AM")
4831 .unwrap();
4832 } else {
4833 let made = unsafe {
4834 library::sb_library_new_section(
4835 &library,
4836 c"".as_ptr(),
4837 c"Phone section".as_ptr(),
4838 c"Clover".as_ptr(),
4839 c"Friday, October 16, 2026".as_ptr(),
4840 c"1:46 AM".as_ptr(),
4841 )
4842 };
4843 assert!(!made.is_null());
4844 unsafe { sb_string_free(made) };
4845 }
4846 close_section(section);
4847 library.flush(Duration::from_secs(20)).unwrap();
4848 }
4849
4850 let file = phone.join(&path);
4851 let version = folder("version.one");
4852 std::fs::rename(&file, &version).unwrap();
4853 std::fs::copy(mac.join(&path), &file).unwrap();
4854 if !lost {
4855 let device = "iPhone".to_owned();
4856 let file = std::fs::canonicalize(&file).unwrap();
4857 CLOUD_VERSIONS.lock().unwrap().push((file, version, device));
4858 }
4859
4860 // The launch: the notebook opens and lists, the page shown last opens, and the
4861 // background merges the version meanwhile.
4862 let library = cloud_library(&phone, &folder("phone-cache"));
4863 sb_library_set_offline(&library, false);
4864 let tabs = library::sb_library_sections(&library);
4865 assert!(!tabs.is_null());
4866 unsafe { sb_string_free(tabs) };
4867 library::sb_library_color(&library);
4868 let section = cloud_section(&library, &path);
4869 let mut views: Vec<View> = listed_ids(&section)
4870 .into_iter()
4871 .filter_map(|space| reading_view(&section, space))
4872 .collect();
4873 sb_library_sync_now(&library);
4874 let deadline = Instant::now() + Duration::from_secs(10);
4875 while !CLOUD_VERSIONS.lock().unwrap().is_empty()
4876 || !stored(&phone).contains("Phone first words")
4877 {
4878 assert!(Instant::now() < deadline, "the phone's upload never merged");
4879 library::sb_section_poll(&section, &mut 0);
4880 for view in &mut views {
4881 unsafe { sb_insert(view, c"Launch ".as_ptr()) };
4882 sb_view_reload(view, false, Some(&mut [0.0; 2]));
4883 }
4884 std::thread::sleep(Duration::from_millis(20));
4885 }
4886 library::sb_section_poll(&section, &mut 0);
4887 for mut view in views {
4888 sb_view_reload(&mut view, false, Some(&mut [0.0; 2]));
4889 sb_view_reload(&mut view, true, Some(&mut [0.0; 2]));
4890 sb_view_set_reading(&mut view, 402.0, &mut [0.0; 2]);
4891 unsafe { sb_insert(&mut view, c"After ".as_ptr()) };
4892 sb_view_keep(&view);
4893 }
4894 // What the phone kept of its uploads goes once its file moves on, keeping them; only
4895 // what a file stands as stays kept.
4896 assert!(
4897 eventually(|| {
4898 section.shared.section.wake();
4899 let files: Vec<Vec<u8>> = (std::fs::read_dir(&phone).unwrap())
4900 .map(|entry| std::fs::read(entry.unwrap().path()).unwrap_or_default())
4901 .collect();
4902 kept(&folder("phone-cache"))
4903 .iter()
4904 .all(|image| files.contains(image))
4905 }),
4906 "the phone's uploads stay kept (shared {shared}, lost {lost})"
4907 );
4908 close_section(section);
4909 library.flush(Duration::from_secs(20)).unwrap();
4910 drop(library);
4911 // Every upload merged: none is kept beside the file, nor twice.
4912 assert_eq!(beside(&phone), 0);
4913
4914 let shown = every_page(&phone, &folder("phone-cache"));
4915 for typed in [
4916 "Phone first words",
4917 "Mac first words",
4918 "Phone page",
4919 "Mac page",
4920 "Phone on the doomed page",
4921 ] {
4922 assert!(shown.contains(typed), "{typed} is gone:\n{shown}");
4923 }
4924 }
4925}
4926
4927/// A notebook Snowbound made in a scratch folder standing in for iCloud Drive's, opened as
4928/// the phone opens one there, and its one section.
4929fn cloud_notebook(directory: &Path) -> (PathBuf, PathBuf, String) {
4930 let (root, cache) = (directory.join("Notes"), directory.join("cache"));
4931 let creation = onestore::PageCreation::new(None, Some("Shared page"), "Clover").unwrap();
4932 let notebook =
4933 notebook::session::Notebook::create(&root, &cache, 0x00f0_a0c0, &creation).unwrap();
4934 let path = notebook.catalog().sections[0].path.clone();
4935 (root, cache, path)
4936}
4937
4938/// Ages the images the cache keeps past the time reads get to catch up with an upload.
4939fn aged(cache: &Path) {
4940 let folders = std::fs::read_dir(cache.join("replicas")).unwrap();
4941 for folder in folders {
4942 for entry in std::fs::read_dir(folder.unwrap().path()).unwrap() {
4943 let store = entry.unwrap().path();
4944 if store
4945 .extension()
4946 .is_none_or(|extension| extension != "published")
4947 {
4948 continue;
4949 }
4950 for image in std::fs::read_dir(store).unwrap() {
4951 let file = std::fs::File::options()
4952 .write(true)
4953 .open(image.unwrap().path())
4954 .unwrap();
4955 file.set_modified(std::time::SystemTime::now() - Duration::from_secs(61))
4956 .unwrap();
4957 }
4958 }
4959 }
4960}
4961
4962/// iCloud Drive puts back the file as it stood before the phone's upload, as when another
4963/// device's upload made on that state wins: the phone's edits merge back once reads have had a
4964/// minute to catch up with its upload, not before.
4965#[test]
4966fn an_upload_icloud_undid_merges_back_once_reads_have_caught_up() {
4967 unsafe { library::sb_set_versions(cloud_versions, cloud_retire, c"iPhone".as_ptr()) };
4968 let directory = tempfile::tempdir().unwrap();
4969 let (root, cache, path) = cloud_notebook(directory.path());
4970 let library = cloud_library(&root, &cache);
4971 let section = cloud_section(&library, &path);
4972 let page = listed_ids(&section)[0];
4973 type_on(&section, page, "Before ");
4974 assert!(section.flush(Duration::from_secs(20)));
4975 let before = std::fs::read(root.join(&path)).unwrap();
4976 type_on(&section, page, "Phone words ");
4977 assert!(section.flush(Duration::from_secs(20)));
4978 std::fs::write(root.join(&path), before).unwrap();
4979 for _ in 0..20 {
4980 section.shared.section.wake();
4981 std::thread::sleep(Duration::from_millis(50));
4982 }
4983 assert!(!stored(&root).contains("Phone words"));
4984 aged(&cache);
4985 assert!(eventually(|| {
4986 section.shared.section.wake();
4987 stored(&root).contains("Phone words")
4988 }));
4989 close_section(section);
4990}
4991
4992/// A notebook on this device alone loses no upload, and keeps nothing of its publications.
4993#[test]
4994fn a_notebook_on_the_phone_alone_keeps_no_uploads() {
4995 unsafe { library::sb_set_versions(cloud_versions, cloud_retire, c"iPhone".as_ptr()) };
4996 let directory = tempfile::tempdir().unwrap();
4997 let (root, cache, path) = cloud_notebook(directory.path());
4998 let library = Arc::new(Library::open(&root, &cache, true).unwrap());
4999 let section = cloud_section(&library, &path);
5000 type_on(&section, listed_ids(&section)[0], "Phone words ");
5001 assert!(section.flush(Duration::from_secs(20)));
5002 assert!(stored(&root).contains("Phone words"));
5003 assert!(kept(&cache).is_empty());
5004 close_section(section);
5005}
5006
5007/// Another device sets a password on the section: the file is written anew under a new
5008/// identity, and the plaintext the phone kept of its uploads goes with the replica it backed.
5009#[test]
5010fn a_password_set_elsewhere_takes_the_plaintext_kept() {
5011 unsafe { library::sb_set_versions(cloud_versions, cloud_retire, c"iPhone".as_ptr()) };
5012 let directory = tempfile::tempdir().unwrap();
5013 let (root, cache, path) = cloud_notebook(directory.path());
5014 let library = cloud_library(&root, &cache);
5015 let section = cloud_section(&library, &path);
5016 type_on(&section, listed_ids(&section)[0], "Secret words ");
5017 close_section(section);
5018 assert!(!kept(&cache).is_empty());
5019
5020 let other = directory.path().join("other");
5021 let copied = std::process::Command::new("cp")
5022 .arg("-R")
5023 .arg(&root)
5024 .arg(&other)
5025 .status();
5026 assert!(copied.unwrap().success());
5027 let mut notebook =
5028 notebook::session::Notebook::open(&other, directory.path().join("other-cache")).unwrap();
5029 notebook
5030 .set_password(&path, None, Some("password"))
5031 .unwrap();
5032 drop(notebook);
5033 for entry in std::fs::read_dir(&other).unwrap() {
5034 let entry = entry.unwrap();
5035 if entry.path().is_file() {
5036 std::fs::copy(entry.path(), root.join(entry.file_name())).unwrap();
5037 }
5038 }
5039 let tabs = library.tabs().unwrap();
5040 assert!(tabs.iter().any(|tab| tab.path == path && tab.locked));
5041 assert!(kept(&cache).is_empty());
5042}
5043
5044/// A copy of a section made while the notebook is open keeps what it publishes of its own,
5045/// beside its own replica, never in place of the original's.
5046#[test]
5047fn a_copy_found_while_open_keeps_its_own_uploads() {
5048 unsafe { library::sb_set_versions(cloud_versions, cloud_retire, c"iPhone".as_ptr()) };
5049 let directory = tempfile::tempdir().unwrap();
5050 let (root, cache, path) = cloud_notebook(directory.path());
5051 let library = cloud_library(&root, &cache);
5052 let section = cloud_section(&library, &path);
5053 type_on(&section, listed_ids(&section)[0], "Original words ");
5054 close_section(section);
5055 let original = kept(&cache);
5056 assert_eq!(original.len(), 1);
5057 std::fs::copy(root.join(&path), root.join("Copy.one")).unwrap();
5058 assert!(
5059 library
5060 .tabs()
5061 .unwrap()
5062 .iter()
5063 .any(|tab| tab.path == "Copy.one")
5064 );
5065 let copy = cloud_section(&library, "Copy.one");
5066 type_on(&copy, listed_ids(&copy)[0], "Copy words ");
5067 close_section(copy);
5068 let images = kept(&cache);
5069 assert_eq!(images.len(), 2);
5070 assert!(images.contains(&original[0]));
5071 assert!(images.contains(&std::fs::read(root.join("Copy.one")).unwrap()));
5072}
5073
5074/// The phone's upload to an iCloud Drive notebook is lost after the phone renamed the
5075/// notebook: the images its publications keep move with it, and the next launch merges it back.
5076#[test]
5077fn an_upload_lost_after_the_notebook_is_renamed_merges_back() {
5078 unsafe { library::sb_set_versions(cloud_versions, cloud_retire, c"iPhone".as_ptr()) };
5079 let directory = tempfile::tempdir().unwrap();
5080 let folder = |name: &str| directory.path().join(name);
5081 let (phone, mac, cache) = (folder("Notes"), folder("mac"), folder("phone-cache"));
5082 let creation = onestore::PageCreation::new(None, Some("Shared page"), "Clover").unwrap();
5083 let notebook =
5084 notebook::session::Notebook::create(&phone, &cache, 0x00f0_a0c0, &creation).unwrap();
5085 let path = notebook.catalog().sections[0].path.clone();
5086 drop(notebook);
5087 let library = cloud_library(&phone, &cache);
5088 let section = cloud_section(&library, &path);
5089 let page = listed_ids(&section)[0];
5090 type_on(&section, page, "Typed on both ");
5091 close_section(section);
5092 drop(library);
5093 let copied = std::process::Command::new("cp")
5094 .arg("-R")
5095 .arg(&phone)
5096 .arg(&mac)
5097 .status();
5098 assert!(copied.unwrap().success());
5099 for (root, cache, typed) in [
5100 (&phone, &cache, "Phone words "),
5101 (&mac, &folder("mac-cache"), "Mac words "),
5102 ] {
5103 let library = cloud_library(root, cache);
5104 let section = cloud_section(&library, &path);
5105 type_on(&section, page, typed);
5106 close_section(section);
5107 // As the app closes a notebook before renaming it (Lists.swift).
5108 library.close(Duration::from_secs(20)).unwrap();
5109 }
5110
5111 // Renamed in the app, as Arranging.swift renames a notebook's folder.
5112 let renamed = folder("Renamed Notes");
5113 std::fs::rename(&phone, &renamed).unwrap();
5114 let text = |path: &Path| std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
5115 let mut error = std::ptr::null_mut();
5116 let moved = unsafe {
5117 library::sb_notebook_moved(
5118 text(&cache).as_ptr(),
5119 text(&phone).as_ptr(),
5120 text(&renamed).as_ptr(),
5121 &mut error,
5122 )
5123 };
5124 assert!(moved && error.is_null());
5125 // iCloud Drive: the Mac's upload lands over the phone's, and no version is kept.
5126 std::fs::copy(mac.join(&path), renamed.join(&path)).unwrap();
5127
5128 let library = cloud_library(&renamed, &cache);
5129 let section = cloud_section(&library, &path);
5130 sb_library_sync_now(&library);
5131 assert!(
5132 eventually(|| {
5133 section.shared.section.wake();
5134 stored(&renamed).contains("Phone words")
5135 }),
5136 "the phone's upload never merged back:\n{}",
5137 stored(&renamed)
5138 );
5139 assert!(stored(&renamed).contains("Mac words"));
5140 close_section(section);
5141}
5142
5143/// A copy of a section beside it keeps a replica of its own; renaming the notebook in the app
5144/// carries the copy's along with the rest, its edits still waiting in it.
5145#[test]
5146fn renaming_a_notebook_keeps_a_copys_waiting_edits() {
5147 let directory = tempfile::tempdir().unwrap();
5148 let (root, cache) = (
5149 directory.path().join("Notes"),
5150 directory.path().join("cache"),
5151 );
5152 std::fs::create_dir(&root).unwrap();
5153 let bytes = onestore::create_section("Notes.one", "Original text", "Fixture").unwrap();
5154 for name in ["Notes.one", "Notes - Copy.one"] {
5155 std::fs::write(root.join(name), &bytes).unwrap();
5156 }
5157 let open_copy = |root: &Path| {
5158 let library = Arc::new(Library::open(root, &cache, true).unwrap());
5159 sb_library_set_offline(&library, true);
5160 open(&library, "Notes - Copy.one")
5161 };
5162 let copy = open_copy(&root);
5163 let space = copy.shared.section.pages().unwrap()[0].0;
5164 let op = Op::Page {
5165 space,
5166 op: PageOp::Color(Some(0x00ef_cdab)),
5167 };
5168 let at = library::filetime();
5169 copy.shared.apply(Edit { at, ops: vec![op] }).unwrap();
5170 copy.shared.section.written().unwrap();
5171 let pending = copy.shared.section.pending().unwrap();
5172 assert_eq!(pending.len(), 1);
5173 let shared = Arc::clone(&copy.shared);
5174 drop(copy);
5175 Arc::into_inner(shared).unwrap().section.close().unwrap();
5176
5177 let renamed = directory.path().join("Renamed Notes");
5178 std::fs::rename(&root, &renamed).unwrap();
5179 let text = |path: &Path| std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
5180 let mut error = std::ptr::null_mut();
5181 let moved = unsafe {
5182 library::sb_notebook_moved(
5183 text(&cache).as_ptr(),
5184 text(&root).as_ptr(),
5185 text(&renamed).as_ptr(),
5186 &mut error,
5187 )
5188 };
5189 assert!(moved && error.is_null());
5190 let copy = open_copy(&renamed);
5191 assert_eq!(copy.shared.section.pending().unwrap(), pending);
5192 assert_eq!(copy.shared.page(space).unwrap().0.color, Some(0x00ef_cdab));
5193}
5194
5195/// What the iOS host calls on the main thread as a launch restores a page returns while the
5196/// background waits on a coordinated read of the section, as iCloud Drive holds one until the
5197/// file downloads: a main thread that waited would have the system end the app.
5198#[test]
5199fn main_thread_calls_return_while_icloud_holds_the_section_file() {
5200 library::sb_set_coordinator(coordinator);
5201 let directory = tempfile::tempdir().unwrap();
5202 let (root, cache) = (
5203 directory.path().join("notebook"),
5204 directory.path().join("cache"),
5205 );
5206 let creation = onestore::PageCreation::new(None, Some("Waiting"), "Clover").unwrap();
5207 let notebook =
5208 notebook::session::Notebook::create(&root, &cache, 0x00f0_a0c0, &creation).unwrap();
5209 let path = notebook.catalog().sections[0].path.clone();
5210 drop(notebook);
5211 let library = cloud_library(&root, &cache);
5212 let section: Arc<Section> = Arc::from(cloud_section(&library, &path));
5213 let space = listed_ids(&section)[0];
5214 let file = root.canonicalize().unwrap().join(&path);
5215 let (entered, held) = std::sync::mpsc::channel();
5216 let (release, released) = std::sync::mpsc::channel();
5217 HELD.lock()
5218 .unwrap()
5219 .push((file.to_string_lossy().into_owned(), entered, released));
5220 type_on(&section, space, "Typed while iCloud downloads ");
5221 sb_library_sync_now(&library);
5222 held.recv_timeout(Duration::from_secs(10)).unwrap();
5223 type Call = Box<dyn FnOnce(&Library, Arc<Section>) + Send>;
5224 let calls: Vec<(&str, Call)> = vec![
5225 (
5226 "sb_section_poll",
5227 Box::new(|_, section| _ = library::sb_section_poll(&section, &mut 0)),
5228 ),
5229 (
5230 "sb_view_new",
5231 Box::new(move |_, section| _ = section.shared.page(space).unwrap()),
5232 ),
5233 (
5234 "sb_insert",
5235 Box::new(move |_, section| type_on(&section, space, "More ")),
5236 ),
5237 (
5238 "sb_library_set_offline",
5239 Box::new(|library, _| sb_library_set_offline(library, false)),
5240 ),
5241 ("sb_section_free", Box::new(|_, section| drop(section))),
5242 ];
5243 let mut section = Some(section);
5244 for (name, call) in calls {
5245 let (done, finished) = std::sync::mpsc::channel();
5246 let (library, section) = (
5247 Arc::clone(&library),
5248 match name {
5249 "sb_section_free" => section.take().unwrap(),
5250 _ => Arc::clone(section.as_ref().unwrap()),
5251 },
5252 );
5253 std::thread::spawn(move || {
5254 call(&library, section);
5255 let _ = done.send(());
5256 });
5257 assert!(
5258 finished.recv_timeout(Duration::from_secs(4)).is_ok(),
5259 "{name} waited on iCloud"
5260 );
5261 }
5262 release.send(()).unwrap();
5263}