1//! Notebooks behind the C surface: a folder or lone section from Files, or a folder on an
2//! SMB share through the embedded client. A section opens through its replica in the app's
3//! cache, which stores each edit at once and publishes it in the background.
4
5use crate::{Result, owned, report, srgb, string};
6use canvas::search::{Entry, Index, Query, Tagged};
7use notebook::{
8 Remote, Replica,
9 discover::{Folder, Reason, SectionState},
10 live::{self, Hello, Reach, share::Guest},
11 provider::Documents,
12 published::{Published, Written},
13 session::{self, Background, Event, Known, Notebook, RECYCLE_BIN, SyncStatus},
14 smb::{Client, Credentials},
15};
16use onestore::{
17 CommitError, CommitState, ExGuid, PageCreation, PageEdit, Stamp, Transaction,
18 op::{Edit, Op, SectionOp},
19 page::Page,
20 protected::Key,
21};
22use std::{
23 collections::{BTreeMap, BTreeSet, HashMap},
24 ffi::{CString, c_char, c_void},
25 io,
26 path::{Path, PathBuf},
27 sync::{
28 Arc, Mutex, OnceLock, Weak,
29 atomic::{AtomicBool, AtomicU8, Ordering},
30 },
31 time::{Duration, Instant},
32};
33
34/// How long an SMB request may take before the share counts as unreachable.
35const TIMEOUT: Duration = Duration::from_secs(10);
36/// The largest section file read whole.
37const LIMIT: usize = 256 * 1024 * 1024;
38/// The tab colour OneNote gives a section that stores none, as the desktop shows it.
39const SECTION_COLOR: u32 = 0x00e4_a88a;
40
41/// Called on a background thread when a notebook's sync status may have changed.
42static SYNC_WAKE: OnceLock<extern "C" fn()> = OnceLock::new();
43
44/// Has the host call `wake` whenever a notebook's closed sections report; set once, before
45/// any library opens.
46#[unsafe(no_mangle)]
47pub extern "C" fn sb_set_sync_wake(wake: extern "C" fn()) {
48 let _ = SYNC_WAKE.set(wake);
49}
50
51fn sync_woken() {
52 if let Some(wake) = SYNC_WAKE.get() {
53 wake();
54 }
55}
56
57/// Runs `body(context)` within the host's coordinated reading or writing of `path`, as
58/// `NSFileCoordinator` has other processes (file providers) wait for it, or not at all when
59/// it cannot coordinate.
60pub type Coordinator = extern "C" fn(
61 path: *const c_char,
62 write: bool,
63 body: extern "C" fn(*mut c_void),
64 context: *mut c_void,
65);
66
67static COORDINATOR: OnceLock<Coordinator> = OnceLock::new();
68
69/// Coordinates every read and write of a local notebook's files through `coordinator` from
70/// now on; set once, before any library opens.
71#[unsafe(no_mangle)]
72pub extern "C" fn sb_set_coordinator(coordinator: Coordinator) {
73 let _ = COORDINATOR.set(coordinator);
74}
75
76/// `work` within the host's coordinated access to `path`, or directly when the host
77/// coordinates nothing.
78pub(crate) fn coordinated<F: FnOnce() -> T, T>(path: &Path, write: bool, work: F) -> io::Result<T> {
79 let Some(coordinator) = COORDINATOR.get() else {
80 return Ok(work());
81 };
82 extern "C" fn run<F: FnOnce() -> T, T>(context: *mut c_void) {
83 // SAFETY: `context` is the pair below, alive for the host's call.
84 let (work, result) = unsafe { &mut *context.cast::<(Option<F>, Option<T>)>() };
85 *result = work.take().map(|work| work());
86 }
87 let mut pair = (Some(work), None);
88 let path = CString::new(path.as_os_str().as_encoded_bytes())?;
89 coordinator(path.as_ptr(), write, run::<F, T>, (&raw mut pair).cast());
90 pair.1
91 .ok_or_else(|| io::Error::other("Another app is using the notebook's file; try again."))
92}
93
94/// Calls `found(context, id, device)` for each conflict version the host's file provider keeps
95/// beside the file at `path`, as iCloud Drive keeps another device's commit that lost:
96/// `id` is a file the version's contents read from, `device` who saved it or null.
97pub type Versions = extern "C" fn(
98 path: *const c_char,
99 found: extern "C" fn(*mut c_void, *const c_char, *const c_char),
100 context: *mut c_void,
101);
102
103/// Marks version `id` of the file at `path` resolved and removes it, first keeping a copy
104/// beside the file when `keep`; false when it could not.
105pub type Retire = extern "C" fn(path: *const c_char, id: *const c_char, keep: bool) -> bool;
106
107static VERSIONS: OnceLock<(Versions, Retire, String)> = OnceLock::new();
108
109/// Merges the conflict versions the host lists into their files from now on, then has the
110/// host retire them, and merges back this device's publications a file provider lost, which
111/// conflict pages name for `device`; set once, before any library opens.
112///
113/// # Safety
114/// `device` is NUL-terminated UTF-8.
115#[unsafe(no_mangle)]
116pub unsafe extern "C" fn sb_set_versions(
117 versions: Versions,
118 retire: Retire,
119 device: *const c_char,
120) {
121 let _ = VERSIONS.set((versions, retire, string(device)));
122}
123
124/// A local section file read and published under the host's file coordination. One a file
125/// provider keeps elsewhere, which syncs it whole with no lock, keeps each image this device
126/// publishes beside its replica until the file holds it, and merges one another device's
127/// upload replaced back (`notebook::published`).
128struct Coordinated {
129 file: PathBuf,
130 published: Option<Published>,
131}
132
133impl Coordinated {
134 /// The section file `file`, its replica at `replica` where it has one.
135 fn new(file: &Path, replica: Option<&Path>, elsewhere: bool) -> Self {
136 let device = VERSIONS
137 .get()
138 .filter(|_| elsewhere)
139 .map(|(.., device)| device);
140 Self {
141 file: file.to_owned(),
142 published: replica
143 .zip(device)
144 .map(|(replica, device)| Published::of(replica, device)),
145 }
146 }
147}
148
149/// The header and length of `file`, as the file remote's uncoordinated change detector reads
150/// them.
151fn stamp(file: &Path) -> io::Result<Stamp> {
152 coordinated(file, false, || {
153 use std::io::Read;
154 let mut opened = std::fs::File::open(file)?;
155 let mut header = [0; 1024];
156 opened.read_exact(&mut header)?;
157 Ok(Stamp {
158 header,
159 length: opened.metadata()?.len(),
160 })
161 })?
162}
163
164impl Remote for Coordinated {
165 fn read(&mut self) -> io::Result<Vec<u8>> {
166 coordinated(&self.file, false, || onestore::read_file(&self.file))?
167 }
168
169 fn stamp(&mut self) -> io::Result<Stamp> {
170 stamp(&self.file)
171 }
172
173 fn publish(&mut self, transaction: &Transaction) -> std::result::Result<(), CommitError> {
174 coordinated(&self.file, true, || {
175 transaction.commit_file(&self.file)?;
176 if let Some(published) = &self.published {
177 // A copy it could not keep only leaves the publication unprotected.
178 let _ = std::fs::File::open(&self.file)
179 .and_then(|mut file| published.keep(Written::InPlace(&mut file), transaction));
180 }
181 Ok(())
182 })
183 .map_err(uncommitted)?
184 }
185
186 fn confirm(&mut self, base: &Stamp) -> std::result::Result<(), CommitError> {
187 coordinated(&self.file, true, || {
188 onestore::confirm_file(&self.file, base)?;
189 if let Some(published) = &self.published {
190 let _ = std::fs::File::open(&self.file)
191 .and_then(|mut file| published.confirmed(Written::InPlace(&mut file), base));
192 }
193 Ok(())
194 })
195 .map_err(uncommitted)?
196 }
197
198 /// The host's conflict versions, then this device's publications the file lost.
199 fn versions(&mut self) -> io::Result<Vec<notebook::Version>> {
200 let mut listed: Vec<notebook::Version> = Vec::new();
201 if let Some((versions, ..)) = VERSIONS.get() {
202 extern "C" fn found(context: *mut c_void, id: *const c_char, device: *const c_char) {
203 // SAFETY: `context` is the list below, alive for the host's call.
204 let listed = unsafe { &mut *context.cast::<Vec<notebook::Version>>() };
205 listed.push(notebook::Version {
206 id: string(id),
207 device: (!device.is_null()).then(|| string(device)),
208 });
209 }
210 let path = CString::new(self.file.as_os_str().as_encoded_bytes())?;
211 versions(path.as_ptr(), found, (&raw mut listed).cast());
212 }
213 if let Some(published) = &self.published {
214 let lost = published.versions(|| stamp(&self.file), &listed)?;
215 listed.extend(lost);
216 }
217 Ok(listed)
218 }
219
220 /// A version's contents never change: they read without coordination.
221 fn version(&mut self, id: &str) -> io::Result<Vec<u8>> {
222 std::fs::read(id)
223 }
224
225 /// A publication of this device's that cannot merge is kept whole beside the file, as
226 /// the host keeps a conflict version: "Name (Device).one".
227 fn retire(&mut self, id: &str, keep: bool) -> io::Result<()> {
228 if let Some(published) = &self.published
229 && published.holds(id)
230 {
231 if keep {
232 let beside = notebook::published::beside(&self.file, published.device());
233 coordinated(&beside, true, || std::fs::copy(id, &beside))??;
234 }
235 return std::fs::remove_file(id);
236 }
237 if let Some(published) = &self.published {
238 let _ = published.retired(Path::new(id));
239 }
240 let Some((_, retire, _)) = VERSIONS.get() else {
241 return Ok(());
242 };
243 let path = CString::new(self.file.as_os_str().as_encoded_bytes())?;
244 let id = CString::new(id)?;
245 if retire(path.as_ptr(), id.as_ptr(), keep) {
246 Ok(())
247 } else {
248 Err(io::Error::other("The version could not be retired"))
249 }
250 }
251}
252
253fn uncommitted(error: io::Error) -> CommitError {
254 CommitError {
255 state: CommitState::NotCommitted,
256 error,
257 }
258}
259
260/// A server and share with the account that opens it, kept to reconnect.
261pub(crate) struct Server {
262 pub(crate) address: String,
263 pub(crate) share: String,
264 pub(crate) user: String,
265 pub(crate) password: String,
266 pub(crate) domain: String,
267}
268
269impl Server {
270 pub(crate) fn connect(&self) -> io::Result<Client> {
271 Client::connect(
272 &self.address,
273 &self.share,
274 Credentials {
275 username: &self.user,
276 password: &self.password,
277 domain: &self.domain,
278 },
279 TIMEOUT,
280 )
281 }
282}
283
284/// A connected share, for browsing to a notebook folder.
285pub struct Share(Client);
286
287enum Place {
288 Folder(PathBuf),
289 /// A section file opened on its own.
290 File(PathBuf),
291 /// A notebook folder at `root` on a share; no client while the server cannot be reached.
292 Share {
293 server: Arc<Server>,
294 client: Mutex<Option<Arc<Client>>>,
295 root: String,
296 },
297 Hosted(Arc<Guest>),
298 /// A notebook folder a document provider keeps.
299 Provider(Arc<Documents>),
300 /// A section a document provider keeps, opened on its own, with its name when it opened:
301 /// none while the provider can't be reached, the host keeping the name it was picked by.
302 Document(Arc<Documents>, Option<String>),
303}
304
305#[derive(serde::Serialize, serde::Deserialize)]
306#[serde(deny_unknown_fields)]
307struct Joined {
308 share: [u8; 16],
309 secret: [u8; 16],
310 protocol: u16,
311 notebook: String,
312 host: String,
313}
314
315/// A share notebook's sections as last listed, so they open from their replicas while the
316/// server cannot be reached.
317#[derive(serde::Serialize, serde::Deserialize, Default)]
318pub(crate) struct Listed {
319 tabs: Vec<Tab>,
320 /// Each readable section's file identity in hex, which names its replica, by catalog path.
321 pub(crate) files: BTreeMap<String, String>,
322 /// The sections that copy another, holding its identity, whose replicas are their own
323 /// (`session::replica_location`).
324 #[serde(default)]
325 pub(crate) copies: BTreeSet<String>,
326}
327
328fn hex(bytes: &[u8]) -> String {
329 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
330}
331
332/// Every readable section's file identity in `folder` and its groups, by catalog path, and
333/// the copies among them, as `Notebook::replicas` lists a local notebook's. `Client::read`
334/// answers a protected section as it does one mid-write (WouldBlock), so syncing one would
335/// show it in use for good.
336pub(crate) fn files(folder: &Folder, listed: &mut Listed) {
337 for section in &folder.sections {
338 if matches!(section.state, SectionState::Readable { .. }) {
339 listed
340 .files
341 .insert(section.path.clone(), hex(&section.file_id));
342 if section.copy {
343 listed.copies.insert(section.path.clone());
344 }
345 }
346 }
347 for group in &folder.groups {
348 self::files(group, listed);
349 }
350}
351
352/// Catalog `path` from the top of the share holding a notebook at `root`.
353pub(crate) fn on_share(root: &str, path: &str) -> String {
354 if root.is_empty() {
355 path.to_owned()
356 } else {
357 format!("{root}/{path}")
358 }
359}
360
361/// When a section's file was last checked for changes, and how it was then.
362struct Checked {
363 at: Instant,
364 stamp: Vec<u8>,
365}
366
367pub struct Library {
368 /// A share's catalog may be absent while cached sections remain available.
369 notebook: Mutex<Option<Notebook>>,
370 place: Place,
371 cache: PathBuf,
372 index: Mutex<(HashMap<String, Checked>, Index)>,
373 /// Syncs the sections no session holds; none for a lone section.
374 background: Option<Background>,
375 /// The sections open for editing, by catalog path, whose sessions sync them.
376 open: Mutex<Vec<(String, Weak<Shared>)>>,
377 /// Work Offline, which sections opened later follow too.
378 offline: AtomicBool,
379 /// Keys of the protected sections unlocked this run, by catalog path; in memory only.
380 keys: Mutex<HashMap<String, Key>>,
381 /// A file provider keeps the notebook elsewhere too, as iCloud Drive does: edits wait for a
382 /// pause in typing before they publish (`Section::set_pause`), as it uploads each
383 /// publication and makes one concurrent with another device's a conflict version.
384 elsewhere: bool,
385}
386
387/// The pause edits to a file a provider keeps elsewhere wait for.
388const PAUSE: Duration = Duration::from_secs(3);
389
390#[derive(serde::Serialize, serde::Deserialize)]
391pub(crate) struct Tab {
392 pub(crate) name: String,
393 /// The catalog path `sb_section_open` takes.
394 pub(crate) path: String,
395 /// The section group holding it, `/`-separated; empty at the notebook's top.
396 pub(crate) group: String,
397 /// The tab colour in sRGB.
398 pub(crate) color: [u8; 3],
399 /// Password-protected or unreadable sections list but do not open; a protected one opens
400 /// once unlocked.
401 pub(crate) readable: bool,
402 /// Password protected and not unlocked (`sb_library_unlock`).
403 #[serde(default)]
404 pub(crate) locked: bool,
405 /// Not on this device yet, as iCloud Drive keeps it elsewhere; the host downloads it.
406 #[serde(default)]
407 pub(crate) downloading: bool,
408 /// Why the file could not be read, where retrying or repair may help.
409 #[serde(default)]
410 pub(crate) problem: Option<String>,
411}
412
413/// Titles keep OneNote's line breaks, which a one-line list shows as spaces.
414fn one_line(title: &str) -> String {
415 title.replace(|char: char| char.is_control(), " ")
416}
417
418fn stem(path: &str) -> String {
419 Path::new(path)
420 .file_stem()
421 .map(|stem| stem.to_string_lossy().into_owned())
422 .unwrap_or_default()
423}
424
425/// A folder's sections, its groups' after them, leaving out the recycle bin OneNote keeps
426/// deleted sections and pages in.
427fn tabs(folder: &Folder, unlocked: &HashMap<String, Key>, tabs: &mut Vec<Tab>) {
428 crash_report::conceal(&folder.path);
429 for section in &folder.sections {
430 crash_report::conceal(&section.path);
431 let (name, color, readable) = match &section.state {
432 SectionState::Readable { name, color, .. } => (name.clone(), *color, true),
433 SectionState::Locked => (None, None, unlocked.contains_key(&section.path)),
434 SectionState::Unreadable(_) => (None, None, false),
435 };
436 if let Some(name) = &name {
437 crash_report::conceal(name);
438 }
439 let locked = matches!(section.state, SectionState::Locked) && !readable;
440 tabs.push(Tab {
441 name: name.unwrap_or_else(|| stem(&section.path)),
442 path: section.path.clone(),
443 group: folder.path.clone(),
444 color: srgb(color.unwrap_or(SECTION_COLOR)),
445 readable,
446 locked,
447 downloading: false,
448 problem: None,
449 });
450 }
451 for entry in folder.unavailable.iter().filter(|entry| !entry.group) {
452 tabs.push(Tab {
453 name: stem(&entry.path),
454 path: entry.path.clone(),
455 group: folder.path.clone(),
456 color: srgb(SECTION_COLOR),
457 readable: false,
458 locked: false,
459 downloading: entry.reason == Reason::Evicted,
460 problem: match entry.reason {
461 Reason::InUse => Some("Section in use".into()),
462 Reason::Unreadable => Some("Can’t read this section".into()),
463 _ => None,
464 },
465 });
466 }
467 for group in &folder.groups {
468 if !group.path.ends_with(RECYCLE_BIN) {
469 self::tabs(group, unlocked, tabs);
470 }
471 }
472}
473
474impl Library {
475 /// The notebook folder or lone section file at `path`. A folder `local` to this device
476 /// reports every change to `touched`; any other, as a file provider keeps it, gets offline
477 /// copies of its sections and is checked every few seconds.
478 pub(crate) fn open(path: &Path, cache: &Path, local: bool) -> Result<Self> {
479 crash_report::conceal(&path.to_string_lossy());
480 let (notebook, place, background) = if path.is_file() {
481 (None, Place::File(path.to_owned()), None)
482 } else {
483 let mut notebook = Notebook::open(path, cache)?;
484 let background = notebook.background_with(
485 local,
486 !local,
487 move |file, replica| Coordinated::new(file, replica, !local),
488 sync_woken,
489 )?;
490 background.watch(notebook.replicas());
491 (
492 Some(notebook),
493 Place::Folder(path.to_owned()),
494 Some(background),
495 )
496 };
497 Ok(Self {
498 notebook: Mutex::new(notebook),
499 place,
500 cache: cache.to_owned(),
501 index: Mutex::default(),
502 background,
503 open: Mutex::default(),
504 offline: AtomicBool::new(false),
505 keys: Default::default(),
506 elsewhere: !local,
507 })
508 }
509
510 /// The notebook folder `root` on `server`; while the server cannot be reached, its sections
511 /// as last listed, if it was listed before.
512 pub(crate) fn server(server: Server, root: &str, cache: &Path) -> Result<Self> {
513 let server = Arc::new(server);
514 let connect = Arc::clone(&server);
515 let background = Background::smb(root, LIMIT, move || connect.connect(), sync_woken)?;
516 let library = Self {
517 notebook: Mutex::default(),
518 place: Place::Share {
519 server,
520 client: Mutex::default(),
521 root: root.to_owned(),
522 },
523 cache: cache.to_owned(),
524 index: Mutex::default(),
525 background: Some(background),
526 open: Mutex::default(),
527 offline: AtomicBool::new(false),
528 keys: Default::default(),
529 elsewhere: false,
530 };
531 let reached = library.with_notebook(false, |_| Ok(()));
532 match library.listed() {
533 Some(listed) => library.watch(&listed),
534 None => reached?,
535 }
536 Ok(library)
537 }
538
539 fn hosted(
540 joined: Joined,
541 author: String,
542 device: Option<String>,
543 relay: Option<&str>,
544 local_network: bool,
545 offline: bool,
546 cache: &Path,
547 ) -> Result<Self> {
548 if joined.protocol != live::wire::VERSION {
549 return Err(io::Error::from(io::ErrorKind::Unsupported).into());
550 }
551 let mut hello = Hello::new(author, None)?;
552 hello.device = device;
553 let guest = Guest::start(
554 hello,
555 joined.share,
556 joined.secret,
557 local_network.then_some(Reach::Network),
558 relay,
559 sync_woken,
560 )?;
561 let mut notebook = match Notebook::open_hosted(Arc::clone(&guest), cache) {
562 Ok(notebook) => notebook,
563 Err(error) if guest.host().is_none() => {
564 let deadline = Instant::now() + TIMEOUT;
565 while guest.host().is_none() && guest.ended().is_none() && Instant::now() < deadline
566 {
567 std::thread::sleep(Duration::from_millis(50));
568 }
569 if guest.host().is_none() {
570 return Err(error.into());
571 }
572 Notebook::open_hosted(Arc::clone(&guest), cache)?
573 }
574 Err(error) => return Err(error.into()),
575 };
576 let background = Background::hosted(Arc::clone(&guest), sync_woken)?;
577 background.set_offline(offline);
578 background.watch(notebook.replicas());
579 Ok(Self {
580 notebook: Mutex::new(Some(notebook)),
581 place: Place::Hosted(guest),
582 cache: cache.to_owned(),
583 index: Mutex::default(),
584 background: Some(background),
585 open: Mutex::default(),
586 offline: AtomicBool::new(offline),
587 keys: Default::default(),
588 elsewhere: false,
589 })
590 }
591
592 /// The notebook folder, or with `folder` false the lone section, whose document `root` the
593 /// registered provider keeps (`sb_set_provider`). A provider `local` to this device
594 /// publishes each edit at once; any other waits for a pause in typing. While the provider
595 /// can't be reached, the folder opens as last listed and sections from their offline copies.
596 fn provider(root: &str, folder: bool, local: bool, device: &str, cache: &Path) -> Result<Self> {
597 let host = crate::provider::Host::default();
598 let name = (!folder)
599 .then(|| {
600 Some(
601 notebook::provider::Provider::document(&host, root)
602 .ok()?
603 .name,
604 )
605 })
606 .flatten();
607 let documents = Arc::new(Documents::new(host, root, cache, device));
608 let (notebook, place, background) = if folder {
609 let mut notebook = Notebook::open_provider(Arc::clone(&documents))?;
610 let background = Background::provider(Arc::clone(&documents), sync_woken)?;
611 background.watch(notebook.replicas());
612 (Some(notebook), Place::Provider(documents), Some(background))
613 } else {
614 (None, Place::Document(documents, name), None)
615 };
616 Ok(Self {
617 notebook: Mutex::new(notebook),
618 place,
619 cache: cache.to_owned(),
620 index: Mutex::default(),
621 background,
622 open: Mutex::default(),
623 offline: AtomicBool::new(false),
624 keys: Default::default(),
625 elsewhere: !local,
626 })
627 }
628
629 /// Has the background sync a share notebook's sections, as `listed` names them.
630 fn watch(&self, listed: &Listed) {
631 let Some(background) = &self.background else {
632 return;
633 };
634 background.watch(
635 listed
636 .files
637 .keys()
638 .map(|path| Known {
639 path: path.clone(),
640 replica: self.share_replica(listed, path),
641 found: None,
642 image: None,
643 })
644 .collect(),
645 );
646 }
647
648 /// The replica of the share section at catalog `path`, as `listed` names it: by its file
649 /// identity in the notebook's folder, a copy's in a folder of its own.
650 fn share_replica(&self, listed: &Listed, path: &str) -> Option<PathBuf> {
651 let Place::Share { server, root, .. } = &self.place else {
652 return None;
653 };
654 let notebook = notebook::location::smb(&server.address, &server.share, root);
655 let location = session::replica_location(&notebook, path, listed.copies.contains(path));
656 let folder = notebook::location::claimed(&self.cache, &location).ok()?;
657 Some(folder.join(format!("{}.sqlite", listed.files.get(path)?)))
658 }
659
660 /// Where a share notebook's last listing is kept.
661 fn listing(&self) -> Option<PathBuf> {
662 let Place::Share { server, root, .. } = &self.place else {
663 return None;
664 };
665 let name: String = format!("{}/{}/{root}", server.address, server.share)
666 .chars()
667 .map(|char| if char.is_alphanumeric() { char } else { '_' })
668 .collect();
669 Some(self.cache.join("smb").join(format!("{name}.json")))
670 }
671
672 fn listed(&self) -> Option<Listed> {
673 let bytes = std::fs::read(self.listing()?).ok()?;
674 serde_json::from_slice(&bytes).ok()
675 }
676
677 fn notebook(&self) -> std::sync::MutexGuard<'_, Option<Notebook>> {
678 self.notebook
679 .lock()
680 .unwrap_or_else(|error| error.into_inner())
681 }
682
683 fn client(&self) -> Option<Arc<Client>> {
684 match &self.place {
685 Place::Share { client, .. } => client
686 .lock()
687 .unwrap_or_else(|error| error.into_inner())
688 .clone(),
689 _ => None,
690 }
691 }
692
693 /// Runs `change`, which reads or with `write` changes the notebook's files, on the
694 /// notebook: a local folder under the host's file coordination; on a share not reached
695 /// yet or whose connection dropped, connecting again and retrying once.
696 fn with_notebook<T>(
697 &self,
698 write: bool,
699 mut change: impl FnMut(&mut Notebook) -> Result<T>,
700 ) -> Result<T> {
701 let mut notebook = self.notebook();
702 let Place::Share {
703 server,
704 client,
705 root,
706 } = &self.place
707 else {
708 let notebook = notebook.as_mut().ok_or("A lone section has no notebook")?;
709 return match &self.place {
710 Place::Folder(root) => coordinated(root, write, || change(notebook))?,
711 _ => change(notebook),
712 };
713 };
714 if let Some(current) = notebook.as_mut()
715 && let Ok(result) = change(current)
716 {
717 return Ok(result);
718 }
719 let fresh = Arc::new(server.connect()?);
720 *client.lock().unwrap_or_else(|error| error.into_inner()) = Some(Arc::clone(&fresh));
721 let reopened = notebook.insert(Notebook::open_smb(fresh, root, &self.cache)?);
722 change(reopened)
723 }
724
725 fn unlocked(&self) -> std::sync::MutexGuard<'_, HashMap<String, Key>> {
726 self.keys.lock().unwrap_or_else(|error| error.into_inner())
727 }
728
729 /// Unlocks the protected section at catalog `path` with `password`; whether it matched.
730 pub(crate) fn unlock(&self, path: &str, password: &str) -> Result<bool> {
731 let key = self.with_notebook(false, |notebook| match notebook.unlock(path, password) {
732 Ok(key) => Ok(Some(key)),
733 Err(notebook::Error::Protected(_)) => Ok(None),
734 Err(error) => Err(error.into()),
735 })?;
736 let unlocked = key.is_some();
737 if let Some(key) = key {
738 self.unlocked().insert(path.to_owned(), key);
739 }
740 Ok(unlocked)
741 }
742
743 /// The notebook's colour, COLORREF, as its table of contents held it when last read.
744 fn color(&self) -> Option<u32> {
745 self.notebook().as_ref()?.catalog().toc.as_ref()?.color
746 }
747
748 /// The notebook's sections, read again.
749 pub(crate) fn tabs(&self) -> Result<Vec<Tab>> {
750 let lone = match &self.place {
751 Place::File(file) => Some((stem(&file.to_string_lossy()), file.to_string_lossy())),
752 Place::Document(_, name) => {
753 Some((stem(name.as_deref().unwrap_or_default()), "".into()))
754 }
755 _ => None,
756 };
757 if let Some((name, path)) = lone {
758 return Ok(vec![Tab {
759 name,
760 path: path.into_owned(),
761 group: String::new(),
762 color: srgb(SECTION_COLOR),
763 readable: true,
764 locked: false,
765 downloading: false,
766 problem: None,
767 }]);
768 }
769 let listed = self.with_notebook(false, |notebook| {
770 notebook.refresh()?;
771 let mut listed = Listed::default();
772 tabs(notebook.catalog(), &self.unlocked(), &mut listed.tabs);
773 if matches!(self.place, Place::Share { .. }) {
774 files(notebook.catalog(), &mut listed);
775 }
776 if let (Place::Folder(_) | Place::Hosted(_) | Place::Provider(_), Some(background)) =
777 (&self.place, &self.background)
778 {
779 background.watch(notebook.replicas());
780 }
781 Ok(listed)
782 });
783 let Some(listing) = self.listing() else {
784 return Ok(listed?.tabs);
785 };
786 match listed {
787 Ok(listed) => {
788 std::fs::create_dir_all(listing.parent().ok_or("No cache")?)?;
789 std::fs::write(&listing, serde_json::to_vec(&listed)?)?;
790 self.watch(&listed);
791 Ok(listed.tabs)
792 }
793 Err(error) => Ok(self.listed().ok_or(error)?.tabs),
794 }
795 }
796
797 /// The sections of the notebook's recycle bin, Deleted Pages among them, as `tabs` lists
798 /// sections; none for a lone section.
799 pub(crate) fn recycle_bin(&self) -> Result<Vec<Tab>> {
800 if matches!(self.place, Place::File(_) | Place::Document(..)) {
801 return Ok(Vec::new());
802 }
803 // Listed again, a share's bin sections open by the identities the listing keeps.
804 self.tabs()?;
805 self.with_notebook(false, |notebook| {
806 let mut binned = Vec::new();
807 let catalog = notebook.catalog();
808 if let Some(bin) = catalog
809 .groups
810 .iter()
811 .find(|group| group.path == RECYCLE_BIN)
812 {
813 tabs(bin, &self.unlocked(), &mut binned);
814 }
815 Ok(binned)
816 })
817 }
818
819 /// Deletes for good what the recycle bin has held unchanged past OneNote's 60 days, as
820 /// OneNote 2010 prunes it after opening; a guest leaves that to its host's notebook, and a
821 /// share not reached is left for the next time.
822 pub(crate) fn purge_recycle_bin(&self) -> Result<usize> {
823 if matches!(self.place, Place::Hosted(_)) || self.notebook().is_none() {
824 return Ok(0);
825 }
826 // Time32 counts seconds from 1980; FILETIME, tenths of microseconds from 1601.
827 let now = (filetime() / 10_000_000).saturating_sub(11_960_006_400);
828 let now = u32::try_from(now).unwrap_or(u32::MAX);
829 self.with_notebook(true, |notebook| Ok(notebook.purge_recycle_bin(now)?))
830 }
831
832 /// Moves the section or group at catalog `path` into the recycle bin, as OneNote 2010
833 /// deletes one.
834 pub(crate) fn delete(&self, path: &str) -> Result<()> {
835 self.with_notebook(true, |notebook| {
836 notebook.refresh()?;
837 Ok(notebook.delete(path)?)
838 })?;
839 // Listed again, the background syncs the binned sections, edits waiting among them.
840 self.tabs().map(drop)
841 }
842
843 /// The section at catalog `path`, through a replica in the cache, following Work
844 /// Offline. The background may hold the replica for a step, which takes a network round
845 /// trip, so a busy replica is tried again for a while.
846 pub(crate) fn section(
847 &self,
848 path: &str,
849 notify: impl Fn() + Send + Sync + 'static,
850 ) -> Result<session::Section> {
851 let deadline = Instant::now() + TIMEOUT * 3;
852 let notify = Arc::new(notify);
853 let section = loop {
854 let notify = Arc::clone(&notify);
855 match self.section_once(path, move || notify()) {
856 Err(error)
857 if Instant::now() < deadline
858 && error
859 .downcast_ref::<notebook::Error>()
860 .is_some_and(notebook::Error::busy) =>
861 {
862 std::thread::sleep(Duration::from_millis(50));
863 }
864 opened => break opened?,
865 }
866 };
867 section.set_offline(self.offline.load(Ordering::Relaxed));
868 section.set_pause(if self.elsewhere {
869 PAUSE
870 } else {
871 Duration::ZERO
872 });
873 if let Some(background) = &self.background {
874 background.hold(path, &section);
875 }
876 Ok(section)
877 }
878
879 fn section_once(
880 &self,
881 path: &str,
882 notify: impl Fn() + Send + Sync + 'static,
883 ) -> Result<session::Section> {
884 let offline = self.offline.load(Ordering::Relaxed);
885 let elsewhere = self.elsewhere;
886 let connect = move |file: &Path, replica: Option<&Path>| {
887 Ok(Coordinated::new(file, replica, elsewhere))
888 };
889 match &self.place {
890 Place::File(file) => Ok(session::Section::open_with(
891 file,
892 &self.cache,
893 connect,
894 offline,
895 notify,
896 )?),
897 Place::Folder(_) => {
898 let notebook = self.notebook();
899 let notebook = notebook.as_ref().ok_or("A lone section has no notebook")?;
900 Ok(match self.unlocked().get(path) {
901 Some(key) => {
902 notebook.section_unlocked_with(path, key, connect, offline, notify)?
903 }
904 None => notebook.section_with(path, connect, offline, notify)?,
905 })
906 }
907 Place::Share { server, root, .. } => {
908 let file = on_share(root, path);
909 let key = self.unlocked().get(path).cloned();
910 // A protected section's replica is named by the identity its file holds.
911 let cache = match &key {
912 Some(_) => self
913 .notebook()
914 .as_ref()
915 .ok_or("The notebook hasn’t been read")?
916 .replica_path(path)?,
917 None => self
918 .listed()
919 .and_then(|listed| self.share_replica(&listed, path))
920 .ok_or("The notebook hasn’t listed this section")?,
921 };
922 std::fs::create_dir_all(cache.parent().ok_or("No cache")?)?;
923 let replica = Replica::open_or_create(&cache, key.as_ref(), || {
924 let client = self.client().ok_or_else(|| {
925 std::io::Error::new(
926 std::io::ErrorKind::NotConnected,
927 "The server can’t be reached, and this section hasn’t been opened here before.",
928 )
929 })?;
930 Ok(client.read_storage(&file, LIMIT)?)
931 })?;
932 let server = Arc::clone(server);
933 Ok(session::Section::resume_smb(
934 file,
935 replica,
936 LIMIT,
937 move || server.connect(),
938 offline,
939 notify,
940 )?)
941 }
942 Place::Hosted(guest) => Ok(session::Section::resume_hosted(
943 path.to_owned(),
944 self.served_replica(path)?,
945 Arc::clone(guest),
946 offline,
947 notify,
948 )?),
949 Place::Provider(documents) => Ok(session::Section::resume_provider(
950 path.to_owned(),
951 self.served_replica(path)?,
952 Arc::clone(documents),
953 offline,
954 notify,
955 )?),
956 Place::Document(documents, _) => Ok(session::Section::open_provider(
957 Arc::clone(documents),
958 offline,
959 notify,
960 )?),
961 }
962 }
963
964 /// The replica of the section at catalog `path` of a notebook another program serves,
965 /// made from the section where there is none.
966 fn served_replica(&self, path: &str) -> Result<Replica> {
967 let notebook = self.notebook();
968 let notebook = notebook
969 .as_ref()
970 .ok_or_else(|| io::Error::from(io::ErrorKind::NotConnected))?;
971 let cache = notebook.replica_path(path)?;
972 std::fs::create_dir_all(cache.parent().unwrap_or(&self.cache))?;
973 let key = self.unlocked().get(path).cloned();
974 Ok(Replica::open_or_create(&cache, key.as_ref(), || {
975 notebook.read_section(path)
976 })?)
977 }
978}
979
980/// What saving has come to, as the page shows it.
981#[repr(u8)]
982#[derive(Clone, Copy)]
983pub(crate) enum Status {
984 Saved = 1,
985 Saving = 2,
986 /// The file cannot be reached; edits wait in the cache.
987 Offline = 3,
988 /// An edit was refused or the replica failed.
989 NotSaving = 4,
990}
991
992/// An open section as its page views share it.
993pub(crate) struct Shared {
994 pub section: session::Section,
995 /// Who the edits name, as OneNote names the Office user.
996 pub author: Mutex<String>,
997 pub status: AtomicU8,
998}
999
1000impl Shared {
1001 pub fn author(&self) -> String {
1002 self.author
1003 .lock()
1004 .unwrap_or_else(|error| error.into_inner())
1005 .clone()
1006 }
1007
1008 pub fn apply(&self, edit: Edit) -> Result<()> {
1009 self.apply_with(edit, |_| {})
1010 }
1011
1012 pub fn apply_with(
1013 &self,
1014 edit: Edit,
1015 reply: impl FnOnce(std::result::Result<u64, notebook::Error>) + Send + 'static,
1016 ) -> Result<()> {
1017 self.status.store(Status::Saving as u8, Ordering::Relaxed);
1018 if let Err(error) = self.section.apply_with(&self.author(), edit, reply) {
1019 self.status
1020 .store(Status::NotSaving as u8, Ordering::Relaxed);
1021 return Err(error.into());
1022 }
1023 Ok(())
1024 }
1025
1026 /// The page in `space` as a view shows it: a conflict page highlighted and read-only.
1027 pub fn page(&self, space: ExGuid) -> Result<(Page, bool)> {
1028 let page = self.section.page(space)?;
1029 let conflict = self
1030 .section
1031 .conflicts()?
1032 .into_iter()
1033 .flat_map(|(_, versions)| versions)
1034 .find(|version| version.space == space);
1035 Ok(match conflict {
1036 Some(version) => (canvas::conflict::highlighted(page, &version.objects), true),
1037 None => (page, false),
1038 })
1039 }
1040}
1041
1042/// A section open for editing, with the notebook it belongs to.
1043pub struct Section {
1044 pub(crate) shared: Arc<Shared>,
1045 pub(crate) library: Arc<Library>,
1046}
1047
1048#[derive(serde::Serialize)]
1049pub(crate) struct Row {
1050 pub(crate) id: String,
1051 pub(crate) title: String,
1052 /// 1 at the top, 2 for a subpage and so on.
1053 pub(crate) level: u32,
1054 /// Conflict pages: versions with changes a merge could not take.
1055 pub(crate) versions: Vec<Version>,
1056}
1057
1058#[derive(serde::Serialize)]
1059pub(crate) struct Version {
1060 pub(crate) id: String,
1061 /// Whose version it is.
1062 pub(crate) user: String,
1063 /// When the merge made it, in seconds since 1970.
1064 pub(crate) created: Option<i64>,
1065}
1066
1067pub(crate) fn unix(filetime: u64) -> i64 {
1068 (filetime / 10_000_000) as i64 - 11_644_473_600
1069}
1070
1071/// FILETIME now: when an edit happened, which its modification times record.
1072pub(crate) fn filetime() -> u64 {
1073 let unix = std::time::SystemTime::now()
1074 .duration_since(std::time::UNIX_EPOCH)
1075 .unwrap_or_default();
1076 (unix.as_secs() + 11_644_473_600) * 10_000_000 + u64::from(unix.subsec_nanos() / 100)
1077}
1078
1079/// A page OneNote 2010 would create now, titled `date` and `time` as the host formats
1080/// them: the long date and the short time; titled in the Default font's face.
1081fn dated(author: &str, date: &str, time: &str) -> Result<PageCreation> {
1082 let font = crate::options().1.clone();
1083 Ok(PageCreation::new(None, Some(""), author)?
1084 .titled_in(&font.face, font.color)?
1085 .dated(date, time)?)
1086}
1087
1088impl Section {
1089 /// The notebook's themes; none for a lone section.
1090 pub(crate) fn themes(&self) -> notebook::sidecar::themes::Themes {
1091 self.library
1092 .notebook()
1093 .as_ref()
1094 .and_then(|notebook| crate::report(notebook.themes().map_err(Into::into)))
1095 .unwrap_or_default()
1096 }
1097
1098 /// Merges `change` into the notebook's themes.
1099 pub(crate) fn save_themes(&self, change: notebook::sidecar::themes::Themes) -> Result<()> {
1100 self.library
1101 .notebook()
1102 .as_ref()
1103 .ok_or("A section on its own keeps no themes")?
1104 .save_themes(change)?;
1105 Ok(())
1106 }
1107
1108 /// The theme scopes of page `id`: the page, its section and the notebook, where known.
1109 pub(crate) fn scopes(&self, id: &str) -> Result<[Option<notebook::sidecar::themes::Scope>; 3]> {
1110 use notebook::sidecar::themes::Scope;
1111 let (page, _) = self.shared.page(id.parse()?)?;
1112 Ok([
1113 page.identity.map(Scope::page),
1114 self.shared.section.identity().ok().map(Scope::section),
1115 Some(Scope::Notebook),
1116 ])
1117 }
1118
1119 /// The paragraph styles page `identity` of this section wears in its theme, in this
1120 /// section's colour; none where no scope names a theme.
1121 pub(crate) fn sheet(
1122 &self,
1123 identity: Option<[u8; 16]>,
1124 ) -> std::collections::BTreeMap<String, onestore::page::Definition> {
1125 let section = self.shared.section.identity().ok();
1126 let Some(theme) = self.themes().effective(section, identity) else {
1127 return Default::default();
1128 };
1129 let color = section.and_then(|section| {
1130 let notebook = self.library.notebook();
1131 let listed = notebook
1132 .as_ref()?
1133 .catalog()
1134 .sections()
1135 .find(|listed| listed.file_id == section)?;
1136 match listed.state {
1137 SectionState::Readable { color, .. } => color,
1138 _ => None,
1139 }
1140 });
1141 theme.sheet(color)
1142 }
1143
1144 /// The section at catalog `path` of `library`, its edits naming `author`.
1145 pub(crate) fn open(
1146 library: Arc<Library>,
1147 path: &str,
1148 author: String,
1149 notify: impl Fn() + Send + Sync + 'static,
1150 ) -> Result<Self> {
1151 let shared = Arc::new(Shared {
1152 section: library.section(path, notify)?,
1153 author: Mutex::new(author),
1154 status: AtomicU8::new(0),
1155 });
1156 let mut open = library
1157 .open
1158 .lock()
1159 .unwrap_or_else(|error| error.into_inner());
1160 shared
1161 .section
1162 .set_offline(library.offline.load(Ordering::Relaxed));
1163 open.push((path.to_owned(), Arc::downgrade(&shared)));
1164 drop(open);
1165 Ok(Self { shared, library })
1166 }
1167
1168 pub(crate) fn rows(&self) -> Result<Vec<Row>> {
1169 let section = &self.shared.section;
1170 let conflicts = section.conflicts()?;
1171 Ok(section
1172 .pages()?
1173 .into_iter()
1174 .map(|(space, title, level)| Row {
1175 id: space.to_string(),
1176 title: one_line(&title),
1177 level,
1178 versions: conflicts
1179 .iter()
1180 .find(|(page, _)| *page == space)
1181 .map(|(_, versions)| {
1182 versions
1183 .iter()
1184 .map(|version| Version {
1185 id: version.space.to_string(),
1186 user: version.user.clone(),
1187 created: version.created.map(unix),
1188 })
1189 .collect()
1190 })
1191 .unwrap_or_default(),
1192 })
1193 .collect())
1194 }
1195
1196 /// Adds a page at the end, or a subpage after `parent` and its subpages, as OneNote's
1197 /// New Page and New Subpage do; returns its space.
1198 pub(crate) fn new_page(
1199 &self,
1200 parent: Option<ExGuid>,
1201 date: &str,
1202 time: &str,
1203 ) -> Result<ExGuid> {
1204 let creation = dated(&self.shared.author(), date, time)?;
1205 let space = creation.space();
1206 let mut ops = vec![Op::Section(SectionOp::Create(creation))];
1207 if let Some(parent) = parent {
1208 let pages = self.shared.section.pages()?;
1209 let at = pages
1210 .iter()
1211 .position(|(space, ..)| *space == parent)
1212 .ok_or("The page is not listed")?;
1213 let level = pages[at].2;
1214 let next = pages[at + 1..]
1215 .iter()
1216 .find(|(.., below)| *below <= level)
1217 .map(|(space, ..)| *space);
1218 ops.push(Op::Section(SectionOp::Pages(vec![PageEdit::move_to(
1219 space,
1220 next,
1221 (level + 1).min(3),
1222 )?])));
1223 }
1224 self.shared.apply(Edit {
1225 at: filetime(),
1226 ops,
1227 })?;
1228 Ok(space)
1229 }
1230
1231 /// Recycles an ordinary notebook page before submitting its deletion; a lone section's
1232 /// page or a conflict page goes for good. A section left empty gets a new page.
1233 pub(crate) fn delete_page(&self, space: ExGuid, date: &str, time: &str) -> Result<()> {
1234 let section = &self.shared.section;
1235 let listed = section.pages()?;
1236 let mut ops = vec![Op::Section(SectionOp::Delete(vec![space]))];
1237 if listed.iter().any(|(page, ..)| *page == space) {
1238 if !matches!(self.library.place, Place::File(_) | Place::Document(..)) {
1239 let page = section.page(space)?;
1240 let author = self.shared.author();
1241 self.library.with_notebook(true, |notebook| {
1242 Ok(notebook.recycle_pages(std::slice::from_ref(&page), &author)?)
1243 })?;
1244 }
1245 if listed.len() == 1 {
1246 ops.push(Op::Section(SectionOp::Create(dated(
1247 &self.shared.author(),
1248 date,
1249 time,
1250 )?)));
1251 }
1252 }
1253 self.shared.apply(Edit {
1254 at: filetime(),
1255 ops,
1256 })
1257 }
1258
1259 /// Puts the pages `moved` where `order` lists them, at their levels, as one edit; false
1260 /// where none of them is listed any more.
1261 pub(crate) fn arrange(&self, order: &[(ExGuid, u32)], moved: &[ExGuid]) -> Result<bool> {
1262 let edits = session::arrange(&self.shared.section.pages()?, order, moved)?;
1263 if edits.is_empty() {
1264 return Ok(false);
1265 }
1266 self.shared.apply(Edit {
1267 at: filetime(),
1268 ops: vec![Op::Section(SectionOp::Pages(edits))],
1269 })?;
1270 Ok(true)
1271 }
1272
1273 /// Applies the events since the last poll to the shared status.
1274 pub(crate) fn poll(&self) -> u32 {
1275 let mut flags = 0;
1276 for event in self.shared.section.events() {
1277 let status = match event {
1278 Event::Changed(_) => {
1279 flags |= LISTED | CHANGED;
1280 continue;
1281 }
1282 Event::Rejected { error, .. } => {
1283 eprintln!("snowbound: saving failed: {error}");
1284 flags |= REJECTED;
1285 Status::NotSaving
1286 }
1287 Event::Attempt {
1288 status: notebook::EditStatus::Published { .. },
1289 ..
1290 } => Status::Saved,
1291 Event::Attempt { .. } => Status::Saving,
1292 Event::Unreachable(error) => {
1293 eprintln!("snowbound: the section cannot be reached: {error}");
1294 Status::Offline
1295 }
1296 Event::Failed(error) => {
1297 eprintln!("snowbound: not saving: {error}");
1298 Status::NotSaving
1299 }
1300 };
1301 self.shared.status.store(status as u8, Ordering::Relaxed);
1302 }
1303 flags
1304 }
1305
1306 /// Waits until every edit is in the cache, then publishes them within `limit`: true when
1307 /// nothing waits to be published.
1308 pub(crate) fn flush(&self, limit: Duration) -> bool {
1309 let section = &self.shared.section;
1310 if report(section.written().map_err(Into::into)).is_none() {
1311 return false;
1312 }
1313 let deadline = Instant::now() + limit;
1314 loop {
1315 match section.pending() {
1316 Ok(pending) if pending.is_empty() => return true,
1317 Ok(_) if Instant::now() < deadline => {
1318 section.wake();
1319 std::thread::sleep(Duration::from_millis(50));
1320 }
1321 _ => return false,
1322 }
1323 }
1324 }
1325}
1326
1327/// `sb_section_poll`: the page list or conflict pages changed.
1328const LISTED: u32 = 1;
1329/// A change made elsewhere reached the section; open pages reload.
1330const CHANGED: u32 = 2;
1331/// The section refused an edit; the page shown returns to what is stored.
1332const REJECTED: u32 = 4;
1333
1334#[derive(serde::Serialize)]
1335#[serde(rename_all = "camelCase")]
1336pub(crate) struct Found {
1337 /// Which of the notebooks searched holds the page.
1338 pub(crate) notebook: usize,
1339 /// The section's catalog path.
1340 pub(crate) section: String,
1341 pub(crate) page: String,
1342 pub(crate) title: String,
1343 /// Every word is in the title, as OneNote's "Title contains" lists it.
1344 pub(crate) in_title: bool,
1345 /// Where the words match `title`, as UTF-16 `[start, end]`.
1346 pub(crate) title_hits: Vec<[usize; 2]>,
1347 /// The line around the first match.
1348 pub(crate) snippet: String,
1349 pub(crate) snippet_hits: Vec<[usize; 2]>,
1350}
1351
1352/// Pages of `libraries` holding every word of `query` in their title or text, as the desktop
1353/// searches and lists them; only of the section at catalog `section` where given.
1354pub(crate) fn search(
1355 libraries: &[&Library],
1356 section: Option<&str>,
1357 query: &str,
1358) -> Result<Vec<Found>> {
1359 let query = Query::new(query);
1360 let mut found = Vec::new();
1361 for (notebook, library) in libraries.iter().enumerate() {
1362 library.indexed(|index| {
1363 let scope = |key: &str| section.is_none_or(|section| key == section);
1364 found.extend(
1365 index
1366 .search(&query, scope)
1367 .into_iter()
1368 .map(|found| (notebook, found)),
1369 );
1370 })?;
1371 }
1372 found.sort_by_key(|(_, found)| found.rank());
1373 Ok(found
1374 .into_iter()
1375 .map(|(notebook, found)| Found {
1376 notebook,
1377 page: found.space.to_string(),
1378 title: one_line(&found.title),
1379 in_title: found.in_title,
1380 title_hits: utf16(&found.title, found.title_hits),
1381 snippet_hits: utf16(&found.snippet, found.snippet_hits),
1382 snippet: found.snippet,
1383 section: found.section,
1384 })
1385 .collect())
1386}
1387
1388/// Byte ranges of `text` as UTF-16 `[start, end]`, as `NSRange` counts.
1389fn utf16(text: &str, ranges: Vec<std::ops::Range<usize>>) -> Vec<[usize; 2]> {
1390 let units = |end: usize| text[..end].encode_utf16().count();
1391 ranges
1392 .into_iter()
1393 .map(|range| [units(range.start), units(range.end)])
1394 .collect()
1395}
1396
1397impl Library {
1398 /// The notebook's tagged paragraphs in page order, as OneNote's Tags Summary lists
1399 /// them: once for each of their tags.
1400 pub(crate) fn tagged(&self) -> Result<Vec<Tag>> {
1401 self.indexed(|index| {
1402 index
1403 .tagged(|_| true)
1404 .into_iter()
1405 .map(|tagged: Tagged| Tag {
1406 section: tagged.section,
1407 page: tagged.space.to_string(),
1408 title: one_line(&tagged.title),
1409 paragraph: tagged.paragraph.to_string(),
1410 name: tagged.name,
1411 shape: tagged.shape,
1412 checked: tagged.checked,
1413 text: tagged.text,
1414 })
1415 .collect()
1416 })
1417 }
1418
1419 /// `read` over the notebook's pages: the sections open as their edits leave them, others
1420 /// as stored, read again when their file changed.
1421 fn indexed<T>(&self, read: impl FnOnce(&Index) -> T) -> Result<T> {
1422 let open = self.open_sections();
1423 let tabs: Vec<String> = self
1424 .tabs()?
1425 .into_iter()
1426 .filter(|tab| tab.readable)
1427 .map(|tab| tab.path)
1428 .collect();
1429 let mut indexed = self.index.lock().unwrap_or_else(|error| error.into_inner());
1430 let (checked, index) = &mut *indexed;
1431 for path in &tabs {
1432 match open.iter().find(|(open, _)| open == path) {
1433 Some((_, shared)) => {
1434 index_replica(index, path, shared.section.replica())?;
1435 checked.remove(path);
1436 }
1437 None => {
1438 report(self.reindex(path, checked, index));
1439 }
1440 }
1441 }
1442 index.retain(|entry| tabs.contains(&entry.section));
1443 Ok(read(index))
1444 }
1445
1446 /// Each section's sync status in the notebook's order: an open section's from its
1447 /// session, the others' from the background.
1448 pub(crate) fn sync_status(&self) -> Vec<Synced> {
1449 let mut sections = self
1450 .background
1451 .as_ref()
1452 .map(Background::status)
1453 .unwrap_or_default();
1454 for (path, shared) in self.open_sections() {
1455 let Some(status) = report(shared.section.sync_status().map_err(Into::into)) else {
1456 continue;
1457 };
1458 match sections.iter_mut().find(|(listed, _)| *listed == path) {
1459 Some((_, listed)) => *listed = status,
1460 None => sections.push((path, status)),
1461 }
1462 }
1463 sections
1464 .into_iter()
1465 .map(|(path, status): (String, SyncStatus)| Synced {
1466 state: status.state() as u8,
1467 synced: status.synced.map(unix),
1468 queued: status.queued,
1469 error: status.error.map(|error| error.to_string()),
1470 path,
1471 })
1472 .collect()
1473 }
1474
1475 /// Publishes every edit the notebook's replicas hold within `limit`, then lets go of the
1476 /// notebook as OneNote closes one: nothing syncs from then on, and each replica holding
1477 /// nothing unpublished is deleted once no session holds it. An error leaves it syncing.
1478 pub(crate) fn close(&self, limit: Duration) -> Result<()> {
1479 self.flush(limit)?;
1480 if let Some(background) = &self.background {
1481 background.discard();
1482 }
1483 Ok(())
1484 }
1485
1486 /// Publishes every edit the notebook's replicas hold within `limit`, keeping them and the
1487 /// offline copies.
1488 pub(crate) fn flush(&self, limit: Duration) -> Result<()> {
1489 const WAITING: &str = "Some changes haven’t been saved to the notebook yet.";
1490 let deadline = Instant::now() + limit;
1491 let open = self.open_sections();
1492 for (_, shared) in &open {
1493 shared.section.written().map_err(|_| WAITING)?;
1494 while !shared.section.pending()?.is_empty() {
1495 if Instant::now() >= deadline {
1496 return Err(WAITING.into());
1497 }
1498 shared.section.wake();
1499 std::thread::sleep(Duration::from_millis(50));
1500 }
1501 }
1502 let Some(background) = &self.background else {
1503 return Ok(());
1504 };
1505 let before: HashMap<String, Option<u64>> = background
1506 .status()
1507 .into_iter()
1508 .map(|(path, status)| (path, status.synced))
1509 .collect();
1510 // Sections without a replica hold nothing to publish.
1511 let replicas: Vec<&String> = {
1512 let notebook = self.notebook();
1513 before
1514 .keys()
1515 .filter(|path| !open.iter().any(|(held, _)| held == *path))
1516 .filter(|path| {
1517 notebook
1518 .as_ref()
1519 .and_then(|notebook| notebook.replica_path(path).ok())
1520 .is_some_and(|replica| replica.exists())
1521 })
1522 .collect()
1523 };
1524 loop {
1525 // Working offline, the background checks only when woken.
1526 background.wake();
1527 let status = background.status();
1528 let mut waiting = replicas.iter().filter_map(|path| {
1529 match status.iter().find(|(listed, _)| listed == *path) {
1530 Some((_, status))
1531 if status.queued == 0
1532 && status.error.is_none()
1533 && status.synced > before[*path] =>
1534 {
1535 None
1536 }
1537 Some((_, status)) => Some(status.error.as_ref().map(ToString::to_string)),
1538 None => Some(None),
1539 }
1540 });
1541 let Some(error) = waiting.next() else { break };
1542 if Instant::now() >= deadline {
1543 return Err(error.unwrap_or_else(|| WAITING.to_owned()).into());
1544 }
1545 std::thread::sleep(Duration::from_millis(50));
1546 }
1547 Ok(())
1548 }
1549
1550 /// Runs `change` on the section at catalog `path`: through its session where one is open,
1551 /// else through one opened for it and closed after, its edits left to the background.
1552 fn with_section<T>(
1553 &self,
1554 path: &str,
1555 change: impl FnOnce(&session::Section) -> Result<T>,
1556 ) -> Result<T> {
1557 if let Some((_, shared)) = self
1558 .open_sections()
1559 .into_iter()
1560 .find(|(open, _)| open == path)
1561 {
1562 return change(&shared.section);
1563 }
1564 let section = self.section(path, || {})?;
1565 let result = change(&section);
1566 section.close()?;
1567 result
1568 }
1569
1570 /// Moves page `space` of the section at catalog `from` into the section at `to`, before
1571 /// `before` at `level` (last without), as OneNote moves a page dropped on a section's tab:
1572 /// it keeps its identity, title, date and content there. A section left without pages
1573 /// gains one titled `date` and `time`; `discard`, the page `to` gained when this page
1574 /// left it, goes while it holds nothing, as Undo takes the move back.
1575 #[allow(clippy::too_many_arguments)]
1576 pub(crate) fn move_page(
1577 &self,
1578 from: &str,
1579 space: ExGuid,
1580 to: &str,
1581 before: Option<ExGuid>,
1582 level: u32,
1583 discard: Option<ExGuid>,
1584 author: &str,
1585 [date, time]: [&str; 2],
1586 ) -> Result<MovedPage> {
1587 if from == to {
1588 return Err("The page is in that section already".into());
1589 }
1590 let (page, was) = self.with_section(from, |section| {
1591 let listed = section.pages()?;
1592 let at = (listed.iter().position(|(listed, ..)| *listed == space))
1593 .ok_or("The page is not listed")?;
1594 let next = listed.get(at + 1).map(|(next, ..)| *next);
1595 Ok((section.replica().moving(space)?, (next, listed[at].2)))
1596 })?;
1597 let import = session::moved(page.page(), author)?;
1598 let Op::Section(SectionOp::Import { creation, .. }) = &import else {
1599 unreachable!("notebook::session::moved imports");
1600 };
1601 let arrived = creation.space();
1602 self.with_section(to, |section| {
1603 let listed = section.pages()?;
1604 let has = |page: &ExGuid| listed.iter().any(|(space, ..)| space == page);
1605 let mut ops = vec![import];
1606 let before = before.filter(has);
1607 if before.is_some() || level != 1 {
1608 ops.push(Op::Section(SectionOp::Pages(vec![PageEdit::move_to(
1609 arrived, before, level,
1610 )?])));
1611 }
1612 if let Some(discard) = discard.filter(has)
1613 && session::blank(&section.page(discard)?)
1614 {
1615 ops.push(Op::Section(SectionOp::Delete(vec![discard])));
1616 }
1617 let edit = Edit {
1618 at: filetime(),
1619 ops,
1620 };
1621 Ok(section.replica().apply(author, edit)?)
1622 })?;
1623 let retired = self.with_section(from, |section| {
1624 let mut ops = vec![Op::Section(SectionOp::Delete(vec![space]))];
1625 let added = match section.pages()?.as_slice() {
1626 // The recycle bin keeps no placeholder page.
1627 [(only, ..)] if *only == space && !from.starts_with(&format!("{RECYCLE_BIN}/")) => {
1628 let fresh = dated(author, date, time)?;
1629 let added = fresh.space();
1630 ops.push(Op::Section(SectionOp::Create(fresh)));
1631 Some(added)
1632 }
1633 _ => None,
1634 };
1635 let edit = Edit {
1636 at: filetime(),
1637 ops,
1638 };
1639 section.replica().retire(author, edit, page)?;
1640 Ok(added)
1641 });
1642 let id = |space: Option<ExGuid>| space.map(|space| space.to_string());
1643 let (added, copied) = match retired {
1644 Ok(added) => (id(added), None),
1645 Err(error) => (None, Some(error.to_string())),
1646 };
1647 Ok(MovedPage {
1648 page: arrived.to_string(),
1649 added,
1650 before: id(was.0),
1651 level: was.1,
1652 copied,
1653 })
1654 }
1655
1656 /// Puts the section or group at catalog `path` into the group `folder` ("" for the
1657 /// notebook's top), moving it there unless it is there, as OneNote moves one dragged
1658 /// onto a group, then orders `folder` as `paths` lists its entries, as they are named
1659 /// once moved; entries left out follow in their order. Returns its catalog path.
1660 pub(crate) fn place(&self, path: &str, folder: &str, paths: &[String]) -> Result<String> {
1661 let parent = path.rsplit_once('/').map_or("", |(parent, _)| parent);
1662 self.with_notebook(true, |notebook| {
1663 notebook.refresh()?;
1664 let placed = match parent == folder {
1665 true => path.to_owned(),
1666 false => notebook.move_entry(path, folder)?,
1667 };
1668 if !paths.is_empty() {
1669 let paths: Vec<&str> = paths.iter().map(String::as_str).collect();
1670 notebook.reorder(folder, &paths)?;
1671 }
1672 Ok(placed)
1673 })
1674 }
1675
1676 fn open_sections(&self) -> Vec<(String, Arc<Shared>)> {
1677 let mut open = self.open.lock().unwrap_or_else(|error| error.into_inner());
1678 open.retain(|(_, shared)| shared.strong_count() > 0);
1679 open.iter()
1680 .filter_map(|(path, shared)| Some((path.clone(), shared.upgrade()?)))
1681 .collect()
1682 }
1683}
1684
1685/// A page `Library::move_page` moved, by id: where it went, the page the section it left
1686/// gained, and where it was there: before `before`, at `level`.
1687#[derive(serde::Serialize)]
1688pub(crate) struct MovedPage {
1689 pub(crate) page: String,
1690 pub(crate) added: Option<String>,
1691 pub(crate) before: Option<String>,
1692 pub(crate) level: u32,
1693 /// Why the page also stayed where it was: the move only copied it.
1694 pub(crate) copied: Option<String>,
1695}
1696
1697#[derive(serde::Serialize)]
1698pub(crate) struct Synced {
1699 pub(crate) path: String,
1700 /// `SyncState` by its place in the enum, best first.
1701 pub(crate) state: u8,
1702 /// When the section file was last reached, in seconds since 1970.
1703 pub(crate) synced: Option<i64>,
1704 /// Changes the file does not hold yet.
1705 pub(crate) queued: u64,
1706 pub(crate) error: Option<String>,
1707}
1708
1709/// A tagged paragraph, from `sb_library_tagged`.
1710#[derive(serde::Serialize)]
1711pub(crate) struct Tag {
1712 pub(crate) section: String,
1713 pub(crate) page: String,
1714 pub(crate) title: String,
1715 pub(crate) paragraph: String,
1716 pub(crate) name: String,
1717 pub(crate) shape: u16,
1718 pub(crate) checked: bool,
1719 pub(crate) text: String,
1720}
1721
1722impl Library {
1723 /// Reads the section at catalog `path` into `index` again when its file changed, and
1724 /// checks at most every 30 seconds.
1725 fn reindex(
1726 &self,
1727 path: &str,
1728 checked: &mut HashMap<String, Checked>,
1729 index: &mut Index,
1730 ) -> Result<()> {
1731 if checked
1732 .get(path)
1733 .is_some_and(|known| known.at.elapsed() < Duration::from_secs(30))
1734 {
1735 return Ok(());
1736 }
1737 let (stamp, read): (Vec<u8>, Reader) = match &self.place {
1738 Place::Share { root, .. } => {
1739 let client = self.client().ok_or("Not a share")?;
1740 let file = on_share(root, path);
1741 let stamp = client.stamp(&file)?;
1742 let mut key = stamp.header.to_vec();
1743 key.extend(stamp.length.to_le_bytes());
1744 (
1745 key,
1746 Box::new(move || Ok(client.read_storage(&file, LIMIT)?)),
1747 )
1748 }
1749 Place::Folder(root) => local(root.join(path))?,
1750 Place::File(file) => local(file.clone())?,
1751 // Indexed from its session while it is open.
1752 Place::Document(..) => return Ok(()),
1753 Place::Hosted(_) | Place::Provider(_) => {
1754 let cache = self
1755 .notebook()
1756 .as_ref()
1757 .ok_or_else(|| io::Error::from(io::ErrorKind::NotConnected))?
1758 .replica_path(path)?;
1759 let key = self.unlocked().get(path).cloned();
1760 let replica = Replica::open_or_create(cache, key.as_ref(), || {
1761 Err(io::Error::from(io::ErrorKind::NotFound).into())
1762 })?;
1763 index_replica(index, path, &replica)?;
1764 checked.remove(path);
1765 return Ok(());
1766 }
1767 };
1768 if checked.get(path).is_none_or(|known| known.stamp != stamp) {
1769 let pages = session::stored_pages(&read()?)?;
1770 index.retain(|entry| entry.section != path);
1771 for stored in pages {
1772 let modified = stored.modified.map_or(0, |filetime| {
1773 (filetime / 10_000_000).saturating_sub(11_960_006_400)
1774 });
1775 index.set(Entry::new(path, stored.space, &stored.page, modified));
1776 }
1777 }
1778 checked.insert(
1779 path.to_owned(),
1780 Checked {
1781 at: Instant::now(),
1782 stamp,
1783 },
1784 );
1785 Ok(())
1786 }
1787}
1788
1789fn index_replica(index: &mut Index, path: &str, replica: &Replica) -> Result<()> {
1790 let mut entries = Vec::new();
1791 for (space, ..) in replica.pages()? {
1792 let modified = index.get(path, space).map_or(0, |entry| entry.modified);
1793 entries.push(Entry::new(path, space, &replica.page(space)?, modified));
1794 }
1795 index.retain(|entry| entry.section != path);
1796 entries.into_iter().for_each(|entry| index.set(entry));
1797 Ok(())
1798}
1799
1800type Reader = Box<dyn Fn() -> Result<Vec<u8>>>;
1801
1802/// A local file's change key, its length and modification time, with its reader.
1803fn local(file: PathBuf) -> Result<(Vec<u8>, Reader)> {
1804 let metadata = std::fs::metadata(&file)?;
1805 let modified = metadata
1806 .modified()?
1807 .duration_since(std::time::UNIX_EPOCH)
1808 .unwrap_or_default();
1809 let mut key = metadata.len().to_le_bytes().to_vec();
1810 key.extend(modified.as_nanos().to_le_bytes());
1811 Ok((
1812 key,
1813 Box::new(move || Ok(coordinated(&file, false, || onestore::read_file(&file))??)),
1814 ))
1815}
1816
1817/// Writes `error` for the host to show, freed with `sb_string_free`.
1818fn failed(error: Box<dyn std::error::Error>, out: *mut *mut c_char) {
1819 eprintln!("snowbound: {error}");
1820 if !out.is_null() {
1821 // SAFETY: the caller passes null or a place for one string.
1822 unsafe { out.write(owned(error.to_string())) };
1823 }
1824}
1825
1826fn boxed<T>(result: Result<T>, error: *mut *mut c_char) -> *mut T {
1827 match result {
1828 Ok(value) => Box::into_raw(Box::new(value)),
1829 Err(cause) => {
1830 failed(cause, error);
1831 std::ptr::null_mut()
1832 }
1833 }
1834}
1835
1836fn shared(result: Result<Library>, error: *mut *mut c_char) -> *const Library {
1837 match result {
1838 Ok(library) => Arc::into_raw(Arc::new(library)),
1839 Err(cause) => {
1840 failed(cause, error);
1841 std::ptr::null()
1842 }
1843 }
1844}
1845
1846pub(crate) fn json(value: Result<impl serde::Serialize>) -> *mut c_char {
1847 report(value.and_then(|value| Ok(serde_json::to_string(&value)?)))
1848 .map_or(std::ptr::null_mut(), owned)
1849}
1850
1851pub(crate) fn optional(text: *const c_char) -> Option<String> {
1852 (!text.is_null()).then(|| string(text))
1853}
1854
1855/// Runs on the joining thread, with a token the host keeps alive until `sb_live_join`
1856/// returns; false cancels the join, and `approving` reports pending host approval.
1857pub type JoinWait = extern "C" fn(token: usize, approving: bool) -> bool;
1858
1859/// Joins through explicitly supplied relay/LAN routes, blocking off the UI thread. Returns
1860/// private JSON containing `credential`, or a machine-readable `refusal`; free it with
1861/// `sb_string_free`. The caller must durably keep the credential before opening its hosted library.
1862/// Cancellation cannot undo an admission the host has already granted.
1863///
1864/// # Safety
1865/// `author`, `code` and `password` are NUL-terminated UTF-8; `device` and `relay` may be null.
1866/// `waiting` and its token remain valid until this call returns; callbacks never overlap.
1867#[unsafe(no_mangle)]
1868pub unsafe extern "C" fn sb_live_join(
1869 author: *const c_char,
1870 device: *const c_char,
1871 code: *const c_char,
1872 password: *const c_char,
1873 relay: *const c_char,
1874 local_network: bool,
1875 waiting: JoinWait,
1876 token: usize,
1877) -> *mut c_char {
1878 use live::share::Refusal;
1879 let password = zeroize::Zeroizing::new(string(password));
1880 let relay = optional(relay);
1881 let joined = Hello::new(string(author), None)
1882 .map_err(|_| Refusal::Unreachable(live::Trouble::Other))
1883 .and_then(|mut hello| {
1884 hello.device = optional(device);
1885 live::share::join_while(
1886 hello,
1887 &string(code),
1888 &password,
1889 local_network.then_some(Reach::Network),
1890 relay.as_deref(),
1891 |approving| waiting(token, approving),
1892 )
1893 });
1894 let value = match joined {
1895 Ok(welcome) => serde_json::json!({"credential": Joined {
1896 share: welcome.share,
1897 secret: welcome.secret,
1898 protocol: live::wire::VERSION,
1899 notebook: welcome.notebook,
1900 host: welcome.host,
1901 }}),
1902 Err(refusal) => {
1903 let reason = match refusal {
1904 Refusal::Malformed => "malformed",
1905 Refusal::Version { theirs_newer } => {
1906 return json(Ok(
1907 serde_json::json!({"refusal": "version", "theirs_newer": theirs_newer}),
1908 ));
1909 }
1910 Refusal::Wrong => "wrong",
1911 Refusal::NoOne => "no_one",
1912 Refusal::Expired => "expired",
1913 Refusal::TooMany(wait) => {
1914 return json(Ok(
1915 serde_json::json!({"refusal": "too_many", "retry_seconds": wait.map(|wait| wait.as_secs_f64())}),
1916 ));
1917 }
1918 Refusal::Busy => "busy",
1919 Refusal::Unreachable(trouble) => {
1920 let (trouble, status) = match trouble {
1921 live::Trouble::Dns => ("dns", None),
1922 live::Trouble::Unreachable => ("unreachable", None),
1923 live::Trouble::TimedOut => ("timed_out", None),
1924 live::Trouble::ProxyUnreachable => ("proxy_unreachable", None),
1925 live::Trouble::ProxyAuthentication => ("proxy_authentication", None),
1926 live::Trouble::ProxyRefused(status) => ("proxy_refused", Some(status)),
1927 live::Trouble::Certificate => ("certificate", None),
1928 live::Trouble::Blocked => ("blocked", None),
1929 live::Trouble::Other => ("other", None),
1930 };
1931 return json(Ok(
1932 serde_json::json!({"refusal": "unreachable", "trouble": trouble, "status": status}),
1933 ));
1934 }
1935 Refusal::TimedOut => "timed_out",
1936 Refusal::Declined => "declined",
1937 Refusal::Cancelled => "cancelled",
1938 Refusal::NotAdmitted => "not_admitted",
1939 };
1940 serde_json::json!({"refusal": reason})
1941 }
1942 };
1943 json(Ok(value))
1944}
1945
1946/// Reopens an already persisted join against its original replicas. A cached notebook
1947/// opens while the host is absent; the first opening waits at most ten seconds to meet it.
1948/// `offline` applies before cached edits are watched.
1949/// Neither this function nor `sb_live_join` persists credentials.
1950///
1951/// # Safety
1952/// `credential`, `author` and `cache` are NUL-terminated UTF-8; `device` and `relay` may be
1953/// null. `credential` is the private object returned by `sb_live_join`, without its wrapper.
1954/// `error` is null or a place for a string; credential parse errors never echo its contents.
1955#[unsafe(no_mangle)]
1956pub unsafe extern "C" fn sb_library_hosted(
1957 credential: *const c_char,
1958 author: *const c_char,
1959 device: *const c_char,
1960 relay: *const c_char,
1961 local_network: bool,
1962 offline: bool,
1963 cache: *const c_char,
1964 error: *mut *mut c_char,
1965) -> *const Library {
1966 let credential = zeroize::Zeroizing::new(string(credential));
1967 let relay = optional(relay);
1968 shared(
1969 serde_json::from_str(&credential)
1970 .map_err(|_| io::Error::from(io::ErrorKind::InvalidData).into())
1971 .and_then(|joined| {
1972 Library::hosted(
1973 joined,
1974 string(author),
1975 optional(device),
1976 relay.as_deref(),
1977 local_network,
1978 offline,
1979 Path::new(&string(cache)),
1980 )
1981 }),
1982 error,
1983 )
1984}
1985
1986/// Derived Live Share status (`connected`, `not_connected`, `stopped`, or `removed`) and
1987/// the connected host's name, never its credential; null for other notebook sources.
1988/// On return to connected, the host can call `sb_library_sync_now` while not Work Offline.
1989#[unsafe(no_mangle)]
1990pub extern "C" fn sb_library_live_status(library: &Library) -> *mut c_char {
1991 let Place::Hosted(guest) = &library.place else {
1992 return std::ptr::null_mut();
1993 };
1994 let host = guest.host();
1995 let state = match (host.is_some(), guest.ended()) {
1996 (true, _) => "connected",
1997 (_, Some(live::share::Ended::Stopped)) => "stopped",
1998 (_, Some(live::share::Ended::Removed)) => "removed",
1999 _ => "not_connected",
2000 };
2001 json(Ok(
2002 serde_json::json!({"state": state, "host": host.map(|host| host.name.clone())}),
2003 ))
2004}
2005
2006/// The notebook folder or lone section file at `path`, its section replicas kept in the
2007/// directory `cache`; null with `error` set if it cannot be read. A folder `local` to this
2008/// device has the host report its changes to `sb_library_touched`; any other is checked
2009/// every few seconds and kept in offline copies.
2010///
2011/// # Safety
2012/// `path` and `cache` are NUL-terminated UTF-8; `error` is null or a place for a string.
2013#[unsafe(no_mangle)]
2014pub unsafe extern "C" fn sb_library_open(
2015 path: *const c_char,
2016 cache: *const c_char,
2017 local: bool,
2018 error: *mut *mut c_char,
2019) -> *const Library {
2020 shared(
2021 Library::open(Path::new(&string(path)), Path::new(&string(cache)), local),
2022 error,
2023 )
2024}
2025
2026/// The notebook folder `root`, `/`-separated from the top of `share` on the server at
2027/// `address` (`host` or `host:port`), opened as `user` or as a guest when `user` is empty.
2028/// While the server cannot be reached, a notebook listed before opens with its sections as
2029/// last listed. Blocks for up to ten seconds.
2030///
2031/// # Safety
2032/// Every string is NUL-terminated UTF-8; `error` is null or a place for a string.
2033#[unsafe(no_mangle)]
2034pub unsafe extern "C" fn sb_library_server(
2035 address: *const c_char,
2036 share: *const c_char,
2037 user: *const c_char,
2038 password: *const c_char,
2039 domain: *const c_char,
2040 root: *const c_char,
2041 cache: *const c_char,
2042 error: *mut *mut c_char,
2043) -> *const Library {
2044 let server = server(address, share, user, password, domain);
2045 shared(
2046 Library::server(server, &string(root), Path::new(&string(cache))),
2047 error,
2048 )
2049}
2050
2051/// Creates the notebook folder `path` holding one section with one page titled with `date`
2052/// and `time`, as OneNote's New Notebook does; `sb_library_open` opens it. False, with
2053/// `error` set, when it cannot be made.
2054///
2055/// # Safety
2056/// Every string is NUL-terminated UTF-8; `error` is null or a place for a string.
2057#[unsafe(no_mangle)]
2058pub unsafe extern "C" fn sb_notebook_create(
2059 path: *const c_char,
2060 cache: *const c_char,
2061 author: *const c_char,
2062 date: *const c_char,
2063 time: *const c_char,
2064 error: *mut *mut c_char,
2065) -> bool {
2066 use notebook::sidecar::themes::{Assignment, DEFAULT, Scope, Themes};
2067 let created = dated(&string(author), &string(date), &string(time)).and_then(|page| {
2068 let notebook = Notebook::create(string(path), string(cache), Notebook::NEW_COLOR, &page)?;
2069 notebook.save_themes(Themes {
2070 assignments: vec![Assignment {
2071 scope: Scope::Notebook,
2072 theme: Some(DEFAULT.into()),
2073 assigned: filetime(),
2074 }],
2075 ..Default::default()
2076 })?;
2077 Ok(())
2078 });
2079 created.map_err(|cause| failed(cause, error)).is_ok()
2080}
2081
2082/// Moves the replicas of the notebook folder or lone section file the app has just moved
2083/// from `from` to `to`, so that its edits waiting there still publish. False, with `error`
2084/// set, when they cannot be moved.
2085///
2086/// # Safety
2087/// Every string is NUL-terminated UTF-8; `error` is null or a place for a string.
2088#[unsafe(no_mangle)]
2089pub unsafe extern "C" fn sb_notebook_moved(
2090 cache: *const c_char,
2091 from: *const c_char,
2092 to: *const c_char,
2093 error: *mut *mut c_char,
2094) -> bool {
2095 let moved = || -> Result<()> {
2096 let from = notebook::location::local(Path::new(&string(from)))?;
2097 let to = notebook::location::local(Path::new(&string(to)))?;
2098 Ok(notebook::location::moved(
2099 Path::new(&string(cache)),
2100 &from,
2101 &to,
2102 )?)
2103 };
2104 moved().map_err(|cause| failed(cause, error)).is_ok()
2105}
2106
2107/// The notebook's sections read again, as JSON: each with `name`, `path`, `group`,
2108/// `color` as sRGB bytes, `readable`, `downloading` and `problem`, in the notebook's order; null
2109/// if it cannot be read.
2110#[unsafe(no_mangle)]
2111pub extern "C" fn sb_library_sections(library: &Library) -> *mut c_char {
2112 json(library.tabs())
2113}
2114
2115/// The notebook's colour as `0xRRGGBB`, as its sections were last read; -1 where it has none.
2116#[unsafe(no_mangle)]
2117pub extern "C" fn sb_library_color(library: &Library) -> i32 {
2118 library.color().map_or(-1, |color| {
2119 let [red, green, blue] = srgb(color);
2120 i32::from_be_bytes([0, red, green, blue])
2121 })
2122}
2123
2124/// Creates a section named `name` in the group at catalog path `folder` ("" for the
2125/// notebook's top) holding one page titled with `date` and `time`, as OneNote creates one;
2126/// returns its catalog path, or null.
2127///
2128/// # Safety
2129/// Every string is NUL-terminated UTF-8.
2130#[unsafe(no_mangle)]
2131pub unsafe extern "C" fn sb_library_new_section(
2132 library: &Library,
2133 folder: *const c_char,
2134 name: *const c_char,
2135 author: *const c_char,
2136 date: *const c_char,
2137 time: *const c_char,
2138) -> *mut c_char {
2139 let (folder, name) = (string(folder), string(name));
2140 let page = dated(&string(author), &string(date), &string(time));
2141 report(page.and_then(|page| {
2142 library.with_notebook(true, |notebook| {
2143 Ok(notebook.create_section(&folder, &name, &page)?)
2144 })
2145 }))
2146 .map_or(std::ptr::null_mut(), owned)
2147}
2148
2149/// Moves page `id` of the section at catalog `from` into the section at `to` (`Library::move_page`),
2150/// before page `before` at `level`, or last with `before` null; `discard`, unless null, is
2151/// the page `to` gained when this page left it. Returns JSON with `page`, its id there,
2152/// `added`, the page titled `date` and `time` that `from` gained, or null, and `before` and
2153/// `level`, where it was in `from`, and `copied`, why it also stayed in `from` where the move
2154/// only copied it, or null; null when it cannot move. Writes to both sections, so call it
2155/// off the main thread.
2156///
2157/// # Safety
2158/// Every string is NUL-terminated UTF-8; `before` and `discard` may be null.
2159#[unsafe(no_mangle)]
2160pub unsafe extern "C" fn sb_library_move_page(
2161 library: &Library,
2162 from: *const c_char,
2163 id: *const c_char,
2164 to: *const c_char,
2165 before: *const c_char,
2166 level: u32,
2167 discard: *const c_char,
2168 author: *const c_char,
2169 date: *const c_char,
2170 time: *const c_char,
2171) -> *mut c_char {
2172 let space = |text: *const c_char| optional(text).map(|id| id.parse()).transpose();
2173 json((|| {
2174 library.move_page(
2175 &string(from),
2176 string(id).parse()?,
2177 &string(to),
2178 space(before)?,
2179 level,
2180 space(discard)?,
2181 &string(author),
2182 [&string(date), &string(time)],
2183 )
2184 })())
2185}
2186
2187/// The sections of the notebook's recycle bin as JSON, as `sb_library_sections` lists them:
2188/// Deleted Pages, `OneNote_RecycleBin/OneNote_DeletedPages.one`, and each deleted section.
2189/// Pages leave it through `sb_library_move_page`, sections through `sb_library_place`. Reads
2190/// the notebook, so call it off the main thread.
2191#[unsafe(no_mangle)]
2192pub extern "C" fn sb_library_recycle_bin(library: &Library) -> *mut c_char {
2193 json(library.recycle_bin())
2194}
2195
2196/// Deletes for good what the notebook's recycle bin has held unchanged past 60 days, as
2197/// OneNote 2010 does after opening a notebook. Writes to the notebook, so call it off the main
2198/// thread.
2199#[unsafe(no_mangle)]
2200pub extern "C" fn sb_library_purge_recycle_bin(library: &Library) {
2201 report(library.purge_recycle_bin());
2202}
2203
2204/// Moves the section or group at catalog `path` into the notebook's recycle bin; false where
2205/// it can't. Writes to the notebook, so call it off the main thread.
2206///
2207/// # Safety
2208/// `path` is NUL-terminated UTF-8.
2209#[unsafe(no_mangle)]
2210pub unsafe extern "C" fn sb_library_delete(library: &Library, path: *const c_char) -> bool {
2211 report(library.delete(&string(path))).is_some()
2212}
2213
2214/// Puts the section or group at catalog `path` into the group at catalog path `folder` (""
2215/// for the notebook's top), moving it unless it is there, then orders `folder` as `paths`, a
2216/// JSON array of catalog paths as they are named after the move; entries left out follow
2217/// in their order. Returns its catalog path, or null.
2218///
2219/// # Safety
2220/// Every string is NUL-terminated UTF-8.
2221#[unsafe(no_mangle)]
2222pub unsafe extern "C" fn sb_library_place(
2223 library: &Library,
2224 path: *const c_char,
2225 folder: *const c_char,
2226 paths: *const c_char,
2227) -> *mut c_char {
2228 let placed = serde_json::from_str::<Vec<String>>(&string(paths))
2229 .map_err(Into::into)
2230 .and_then(|paths| library.place(&string(path), &string(folder), &paths));
2231 report(placed).map_or(std::ptr::null_mut(), owned)
2232}
2233
2234/// Pages of the `count` notebooks at `libraries` whose title or text holds `query`, title
2235/// matches first and then the most recently changed, as JSON: each with `notebook` (its
2236/// place in `libraries`), `section` (a catalog path), `page`, `title`, `inTitle`,
2237/// `snippet`, and `titleHits` and `snippetHits`, UTF-16 `[start, end]`. Only the section
2238/// at catalog path `section` where non-null. Open sections are searched as their edits leave
2239/// them; reads the notebooks' sections, so call it off the main thread.
2240///
2241/// # Safety
2242/// `libraries` holds `count` libraries; `query` and a non-null `section` are NUL-terminated
2243/// UTF-8.
2244#[unsafe(no_mangle)]
2245pub unsafe extern "C" fn sb_search(
2246 libraries: *const &Library,
2247 count: usize,
2248 section: *const c_char,
2249 query: *const c_char,
2250) -> *mut c_char {
2251 // SAFETY: the caller passes `count` libraries.
2252 let libraries = unsafe { std::slice::from_raw_parts(libraries, count) };
2253 json(search(
2254 libraries,
2255 optional(section).as_deref(),
2256 &string(query),
2257 ))
2258}
2259
2260/// The notebook's tagged paragraphs in page order as JSON, once for each of their tags:
2261/// each with `section`, `page`, `title`, `paragraph`, `name`, `shape` (the tag's symbol, 0
2262/// for a highlighting tag), `checked` and `text`. Open sections are read as their edits
2263/// leave them; reads the notebook's sections, so call it off the main thread.
2264#[unsafe(no_mangle)]
2265pub extern "C" fn sb_library_tagged(library: &Library) -> *mut c_char {
2266 json(library.tagged())
2267}
2268
2269/// Unlocks the password-protected section at catalog `path` with `password`, as OneNote's
2270/// Protected Section dialog does; false for a wrong password. The key stays in memory until
2271/// `sb_library_lock_all`.
2272///
2273/// # Safety
2274/// `path` and `password` are NUL-terminated UTF-8.
2275#[unsafe(no_mangle)]
2276pub unsafe extern "C" fn sb_library_unlock(
2277 library: &Library,
2278 path: *const c_char,
2279 password: *const c_char,
2280) -> bool {
2281 let password = zeroize::Zeroizing::new(string(password));
2282 report(library.unlock(&string(path), &password)).unwrap_or(false)
2283}
2284
2285/// Locks every protected section of the notebook, forgetting their keys: they open again only
2286/// once unlocked.
2287#[unsafe(no_mangle)]
2288pub extern "C" fn sb_library_lock_all(library: &Library) {
2289 library.unlocked().clear();
2290}
2291
2292/// Each section's sync status as JSON, in the notebook's order: `path`, `state` (`SyncState`
2293/// by its place, best first), `synced` (seconds since 1970, or null before the file was
2294/// reached), `queued` changes and `error`.
2295#[unsafe(no_mangle)]
2296pub extern "C" fn sb_library_sync_status(library: &Library) -> *mut c_char {
2297 json(Ok(library.sync_status()))
2298}
2299
2300/// Works offline, or online again: edits wait in the cache until then or until
2301/// `sb_library_sync_now`. Sections opened later follow.
2302#[unsafe(no_mangle)]
2303pub extern "C" fn sb_library_set_offline(library: &Library, offline: bool) {
2304 let mut open = library
2305 .open
2306 .lock()
2307 .unwrap_or_else(|error| error.into_inner());
2308 library.offline.store(offline, Ordering::Relaxed);
2309 if let Some(background) = &library.background {
2310 background.set_offline(offline);
2311 }
2312 open.retain(|(_, shared)| shared.strong_count() > 0);
2313 let sections: Vec<_> = open
2314 .iter()
2315 .filter_map(|(_, shared)| shared.upgrade())
2316 .collect();
2317 for shared in &sections {
2318 shared.section.set_offline(offline);
2319 }
2320 // Releasing the last Shared can join its replica's threads.
2321 drop(open);
2322}
2323
2324/// Checks the sections at or below `path`, `/`-separated from the notebook's folder, as the
2325/// host's watch on a local folder reports them changed; `""` names the folder.
2326///
2327/// # Safety
2328/// `path` is NUL-terminated UTF-8.
2329#[unsafe(no_mangle)]
2330pub unsafe extern "C" fn sb_library_touched(library: &Library, path: *const c_char) {
2331 if let Some(background) = &library.background {
2332 background.touched(&[string(path)]);
2333 }
2334}
2335
2336/// Syncs every section of the notebook now, working offline included.
2337#[unsafe(no_mangle)]
2338pub extern "C" fn sb_library_sync_now(library: &Library) {
2339 if let Some(background) = &library.background {
2340 background.wake();
2341 }
2342 for (_, shared) in library.open_sections() {
2343 shared.section.wake();
2344 }
2345}
2346
2347/// Publishes every edit the notebook holds within `seconds`, then lets go of it
2348/// (`Library::close`) so its folder can be moved or deleted: false, with `error` set, while
2349/// an edit is still unpublished, and the notebook syncs on.
2350///
2351/// # Safety
2352/// `error` is null or a place for a string.
2353#[unsafe(no_mangle)]
2354pub unsafe extern "C" fn sb_library_close(
2355 library: &Library,
2356 seconds: f64,
2357 error: *mut *mut c_char,
2358) -> bool {
2359 library
2360 .close(Duration::from_secs_f64(seconds))
2361 .map_err(|cause| failed(cause, error))
2362 .is_ok()
2363}
2364
2365/// Publishes every edit the notebook holds within `seconds`, keeping its offline copies, as an
2366/// app does that stops while the notebook stays open: false, with `error` set, while an edit
2367/// is still unpublished. Close Notebook is `sb_library_close`.
2368///
2369/// # Safety
2370/// `error` is null or a place for a string.
2371#[unsafe(no_mangle)]
2372pub unsafe extern "C" fn sb_library_flush(
2373 library: &Library,
2374 seconds: f64,
2375 error: *mut *mut c_char,
2376) -> bool {
2377 library
2378 .flush(Duration::from_secs_f64(seconds))
2379 .map_err(|cause| failed(cause, error))
2380 .is_ok()
2381}
2382
2383/// The notebook folder whose document is `root`, or with `folder` false the lone section
2384/// `root` names, as the provider `sb_set_provider` registered keeps it; `local` as
2385/// `sb_library_open` takes it, and `device` naming this device on the conflict pages its own
2386/// edits make when another device's upload replaced them. While the provider can't be reached, a folder listed before
2387/// opens as last listed, and sections opened before open from their copies; a revoked grant
2388/// refuses to open and keeps them.
2389///
2390/// # Safety
2391/// `root`, `device` and `cache` are NUL-terminated UTF-8; `error` is null or a place for a
2392/// string.
2393#[unsafe(no_mangle)]
2394pub unsafe extern "C" fn sb_library_provider(
2395 root: *const c_char,
2396 folder: bool,
2397 local: bool,
2398 device: *const c_char,
2399 cache: *const c_char,
2400 error: *mut *mut c_char,
2401) -> *const Library {
2402 let cache = string(cache);
2403 shared(
2404 Library::provider(
2405 &string(root),
2406 folder,
2407 local,
2408 &string(device),
2409 Path::new(&cache),
2410 ),
2411 error,
2412 )
2413}
2414
2415/// # Safety
2416/// `library` came from `sb_library_open`, `sb_library_server`, `sb_library_hosted` or
2417/// `sb_library_provider` and is not used again.
2418#[unsafe(no_mangle)]
2419pub unsafe extern "C" fn sb_library_free(library: *const Library) {
2420 drop(unsafe { Arc::from_raw(library) });
2421}
2422
2423/// Connects to `share` on the server at `address` (`host` or `host:port`) as `user`, or
2424/// as a guest when `user` is empty. Blocks for up to ten seconds.
2425///
2426/// # Safety
2427/// Every string is NUL-terminated UTF-8; `error` is null or a place for a string.
2428#[unsafe(no_mangle)]
2429pub unsafe extern "C" fn sb_share_connect(
2430 address: *const c_char,
2431 share: *const c_char,
2432 user: *const c_char,
2433 password: *const c_char,
2434 domain: *const c_char,
2435 error: *mut *mut c_char,
2436) -> *mut Share {
2437 let server = server(address, share, user, password, domain);
2438 boxed(server.connect().map_err(Into::into).map(Share), error)
2439}
2440
2441fn server(
2442 address: *const c_char,
2443 share: *const c_char,
2444 user: *const c_char,
2445 password: *const c_char,
2446 domain: *const c_char,
2447) -> Server {
2448 let mut address = string(address);
2449 if !address.contains(':') {
2450 address.push_str(":445");
2451 }
2452 Server {
2453 address,
2454 share: string(share),
2455 user: string(user),
2456 password: string(password),
2457 domain: string(domain),
2458 }
2459}
2460
2461#[derive(serde::Serialize)]
2462struct Listing {
2463 /// The folder holds a notebook's table of contents.
2464 notebook: bool,
2465 /// Folders, then section files, by name.
2466 folders: Vec<String>,
2467 sections: Vec<String>,
2468}
2469
2470/// The folder at `path` on the share, as JSON: `notebook`, `folders` and `sections`.
2471///
2472/// # Safety
2473/// `path` is NUL-terminated UTF-8.
2474#[unsafe(no_mangle)]
2475pub unsafe extern "C" fn sb_share_list(share: &Share, path: *const c_char) -> *mut c_char {
2476 json(
2477 share
2478 .0
2479 .read_dir(&string(path), 100_000)
2480 .map_err(Into::into)
2481 .map(|entries| {
2482 let extension = |name: &str, wanted: &str| {
2483 Path::new(name)
2484 .extension()
2485 .is_some_and(|extension| extension.eq_ignore_ascii_case(wanted))
2486 };
2487 // Hidden and system folders, OneNote's recycle bin among them, stay out.
2488 let shown = |name: &str| !name.starts_with('.') && name != RECYCLE_BIN;
2489 let mut listing = Listing {
2490 notebook: entries
2491 .iter()
2492 .any(|entry| extension(&entry.name, "onetoc2")),
2493 folders: Vec::new(),
2494 sections: Vec::new(),
2495 };
2496 for entry in entries.into_iter().filter(|entry| shown(&entry.name)) {
2497 if entry.attributes & 0x10 != 0 {
2498 listing.folders.push(entry.name);
2499 } else if extension(&entry.name, "one") {
2500 listing.sections.push(entry.name);
2501 }
2502 }
2503 listing.folders.sort_by_key(|name| name.to_lowercase());
2504 listing.sections.sort_by_key(|name| name.to_lowercase());
2505 listing
2506 }),
2507 )
2508}
2509
2510/// # Safety
2511/// `share` came from `sb_share_connect` and is not used again.
2512#[unsafe(no_mangle)]
2513pub unsafe extern "C" fn sb_share_free(share: *mut Share) {
2514 drop(unsafe { Box::from_raw(share) });
2515}
2516
2517/// Called on a background thread with the token `sb_section_open` took when the section
2518/// has events for `sb_section_poll`.
2519pub type Wake = extern "C" fn(token: usize);
2520
2521/// Opens the section at catalog `path` of `library` for editing, its edits naming
2522/// `author`. Reads the whole section the first time, so call it off the main thread.
2523///
2524/// # Safety
2525/// `path` and `author` are NUL-terminated UTF-8; `error` is null or a place for a string.
2526#[unsafe(no_mangle)]
2527pub unsafe extern "C" fn sb_section_open(
2528 library: &Library,
2529 path: *const c_char,
2530 author: *const c_char,
2531 wake: Wake,
2532 token: usize,
2533 error: *mut *mut c_char,
2534) -> *mut Section {
2535 // SAFETY: the host keeps the library alive while this call runs.
2536 let library = unsafe {
2537 Arc::increment_strong_count(library);
2538 Arc::from_raw(library as *const Library)
2539 };
2540 boxed(
2541 Section::open(library, &string(path), string(author), move || wake(token)),
2542 error,
2543 )
2544}
2545
2546/// The section's pages in order as JSON: each with `id`, `title`, `level` and `versions`,
2547/// its conflict pages, each with `id`, `user` and `created` (seconds since 1970, or null).
2548#[unsafe(no_mangle)]
2549pub extern "C" fn sb_section_pages(section: &Section) -> *mut c_char {
2550 json(section.rows())
2551}
2552
2553/// Takes the section's events: `LISTED` (1) the page list or conflict pages changed,
2554/// `CHANGED` (2) a change made elsewhere arrived, so open pages reload; `REJECTED` (4) an
2555/// edit was refused. Writes the saving status: 1 saved, 2 saving, 3 offline, 4 not saving,
2556/// or 0 before anything happened.
2557#[unsafe(no_mangle)]
2558pub extern "C" fn sb_section_poll(section: &Section, status: &mut u8) -> u32 {
2559 let flags = section.poll();
2560 *status = section.shared.status.load(Ordering::Relaxed);
2561 flags
2562}
2563
2564/// Adds a page, or with `parent` a subpage beneath that page, titled with `date` and
2565/// `time`; returns its id, or null.
2566///
2567/// # Safety
2568/// `date` and `time` are NUL-terminated UTF-8; `parent` too unless null.
2569#[unsafe(no_mangle)]
2570pub unsafe extern "C" fn sb_section_new_page(
2571 section: &Section,
2572 parent: *const c_char,
2573 date: *const c_char,
2574 time: *const c_char,
2575) -> *mut c_char {
2576 let page = optional(parent)
2577 .map(|parent| Ok::<_, Box<dyn std::error::Error>>(parent.parse()?))
2578 .transpose()
2579 .and_then(|parent| section.new_page(parent, &string(date), &string(time)));
2580 report(page).map_or(std::ptr::null_mut(), |space| owned(space.to_string()))
2581}
2582
2583/// The notebook's themes for page `id` as JSON: `themes`, each with `id` and `name`, then
2584/// the id each of `page`, `section` and `notebook` names itself, or null.
2585///
2586/// # Safety
2587/// `id` is NUL-terminated UTF-8.
2588#[unsafe(no_mangle)]
2589pub unsafe extern "C" fn sb_section_themes(section: &Section, id: *const c_char) -> *mut c_char {
2590 use notebook::sidecar::themes::Scope;
2591 #[derive(serde::Serialize)]
2592 struct Listed {
2593 id: String,
2594 name: String,
2595 }
2596 #[derive(serde::Serialize)]
2597 struct Shown {
2598 themes: Vec<Listed>,
2599 page: Option<String>,
2600 section: Option<String>,
2601 notebook: Option<String>,
2602 }
2603 let shown = (|| {
2604 let scopes = section.scopes(&string(id))?;
2605 let themes = section.themes();
2606 let named = |scope: &Option<Scope>| themes.assigned(scope.as_ref()?).map(|theme| theme.id);
2607 Ok(Shown {
2608 themes: themes
2609 .all()
2610 .into_iter()
2611 .map(|theme| Listed {
2612 id: theme.id,
2613 name: theme.name,
2614 })
2615 .collect(),
2616 page: named(&scopes[0]),
2617 section: named(&scopes[1]),
2618 notebook: named(&scopes[2]),
2619 })
2620 })();
2621 json(shown)
2622}
2623
2624/// Gives theme `theme` (null for none of its own) to page `id` (`scope` 0), its section (1)
2625/// or its notebook (2); the page wears it when next opened. Writes to the notebook, so call
2626/// it off the main thread.
2627///
2628/// # Safety
2629/// Every string is NUL-terminated UTF-8; `theme` may be null.
2630#[unsafe(no_mangle)]
2631pub unsafe extern "C" fn sb_section_set_theme(
2632 section: &Section,
2633 id: *const c_char,
2634 scope: u8,
2635 theme: *const c_char,
2636) -> bool {
2637 use notebook::sidecar::themes::{Assignment, Themes};
2638 let set = (|| {
2639 let scope = section
2640 .scopes(&string(id))?
2641 .into_iter()
2642 .nth(usize::from(scope))
2643 .flatten()
2644 .ok_or("No such scope")?;
2645 section.save_themes(Themes {
2646 assignments: vec![Assignment {
2647 scope,
2648 theme: optional(theme),
2649 assigned: filetime(),
2650 }],
2651 ..Default::default()
2652 })
2653 })();
2654 report(set).is_some()
2655}
2656
2657/// Recycles notebook page `id` before submitting its deletion; a lone section's page or a
2658/// conflict page goes for good. A section left empty gets one titled `date` and `time`.
2659/// Writes to the notebook, so call it off the main thread.
2660///
2661/// # Safety
2662/// Every string is NUL-terminated UTF-8.
2663#[unsafe(no_mangle)]
2664pub unsafe extern "C" fn sb_section_delete_page(
2665 section: &Section,
2666 id: *const c_char,
2667 date: *const c_char,
2668 time: *const c_char,
2669) -> bool {
2670 let deleted = string(id)
2671 .parse()
2672 .map_err(Into::into)
2673 .and_then(|space| section.delete_page(space, &string(date), &string(time)));
2674 report(deleted).is_some()
2675}
2676
2677/// Puts the pages `moved`, a JSON array of ids, where `order`, a JSON array of `{id, level}`
2678/// listing the section's pages, places them, at their levels, as one edit: a page dragged
2679/// to a new place, made a subpage or promoted, or put back as Undo does. False when none of
2680/// them is listed any more.
2681///
2682/// # Safety
2683/// `order` and `moved` are NUL-terminated UTF-8.
2684#[unsafe(no_mangle)]
2685pub unsafe extern "C" fn sb_section_arrange(
2686 section: &Section,
2687 order: *const c_char,
2688 moved: *const c_char,
2689) -> bool {
2690 #[derive(serde::Deserialize)]
2691 struct Placed {
2692 id: String,
2693 level: u32,
2694 }
2695 let arranged = (|| {
2696 let order: Vec<Placed> = serde_json::from_str(&string(order))?;
2697 let order = order
2698 .into_iter()
2699 .map(|placed| Ok((placed.id.parse()?, placed.level)))
2700 .collect::<Result<Vec<_>>>()?;
2701 let moved: Vec<String> = serde_json::from_str(&string(moved))?;
2702 let moved = moved
2703 .iter()
2704 .map(|id| Ok(id.parse()?))
2705 .collect::<Result<Vec<_>>>()?;
2706 section.arrange(&order, &moved)
2707 })();
2708 report(arranged).unwrap_or(false)
2709}
2710
2711/// Waits for every edit to be stored in the cache, then up to `seconds` for them to be
2712/// published; true when nothing waits. For the host's background time.
2713#[unsafe(no_mangle)]
2714pub extern "C" fn sb_section_flush(section: &Section, seconds: f64) -> bool {
2715 section.flush(Duration::from_secs_f64(seconds))
2716}
2717
2718/// Names `author` in the section's edits from now on, as when the reader changes their name.
2719///
2720/// # Safety
2721/// `author` is NUL-terminated UTF-8.
2722#[unsafe(no_mangle)]
2723pub unsafe extern "C" fn sb_section_set_author(section: &Section, author: *const c_char) {
2724 *section
2725 .shared
2726 .author
2727 .lock()
2728 .unwrap_or_else(|error| error.into_inner()) = string(author);
2729}
2730
2731/// Asks the section to look for changes made elsewhere now, as when the app returns.
2732#[unsafe(no_mangle)]
2733pub extern "C" fn sb_section_wake(section: &Section) {
2734 section.shared.section.wake();
2735}
2736
2737/// # Safety
2738/// `section` came from `sb_section_open` and is not used again.
2739#[unsafe(no_mangle)]
2740pub unsafe extern "C" fn sb_section_free(section: *mut Section) {
2741 drop(unsafe { Box::from_raw(section) });
2742}
2743
2744#[cfg(test)]
2745mod tests {
2746 use super::*;
2747
2748 #[test]
2749 fn deleting_a_cold_offline_share_page_preserves_its_source_and_queue() {
2750 let directory = tempfile::tempdir().unwrap();
2751 let root = directory.path().join("notebook");
2752 let cache = directory.path().join("cache");
2753 std::fs::create_dir(&root).unwrap();
2754 let bytes =
2755 onestore::create_section("Read.one", "Offline source content", "Fixture").unwrap();
2756 std::fs::write(root.join("Read.one"), &bytes).unwrap();
2757 let notebook = Notebook::open(&root, &cache).unwrap();
2758 let mut listed = Listed::default();
2759 tabs(notebook.catalog(), &HashMap::new(), &mut listed.tabs);
2760 files(notebook.catalog(), &mut listed);
2761 let identity = listed.files["Read.one"].clone();
2762 drop(notebook);
2763
2764 let address = "127.0.0.1:0";
2765 let location = notebook::location::smb(address, "agent", "Notebook");
2766 let replicas = notebook::location::folder(&cache, &location);
2767 std::fs::create_dir_all(&replicas).unwrap();
2768 let original = replicas.join(format!("{identity}.sqlite"));
2769 let replica = Replica::create(&original, &bytes).unwrap();
2770 let space = replica.pages().unwrap()[0].0;
2771 replica
2772 .apply(
2773 "Fixture",
2774 Edit {
2775 at: filetime(),
2776 ops: vec![Op::Page {
2777 space,
2778 op: onestore::op::PageOp::Color(Some(0x00ef_cdab)),
2779 }],
2780 },
2781 )
2782 .unwrap();
2783 let page = replica.page(space).unwrap();
2784 let pending = replica.pending().unwrap();
2785 assert_eq!(pending.len(), 1);
2786 drop(replica);
2787 let listing = cache.join("smb");
2788 std::fs::create_dir_all(&listing).unwrap();
2789 std::fs::write(
2790 listing.join("127_0_0_1_0_agent_Notebook.json"),
2791 serde_json::to_vec(&listed).unwrap(),
2792 )
2793 .unwrap();
2794
2795 let library = Arc::new(
2796 Library::server(
2797 Server {
2798 address: address.into(),
2799 share: "agent".into(),
2800 user: String::new(),
2801 password: String::new(),
2802 domain: String::new(),
2803 },
2804 "Notebook",
2805 &cache,
2806 )
2807 .unwrap(),
2808 );
2809 sb_library_set_offline(&library, true);
2810 assert!(library.notebook().is_none());
2811 let section =
2812 Section::open(Arc::clone(&library), "Read.one", "Fixture".into(), || {}).unwrap();
2813 assert_eq!(section.shared.section.page(space).unwrap(), page);
2814 assert_eq!(section.shared.section.pending().unwrap(), pending);
2815 assert_eq!(
2816 hex(&section.shared.section.replica().identity().unwrap()),
2817 identity
2818 );
2819
2820 assert!(section.delete_page(space, "Date", "Time").is_err());
2821 section.shared.section.written().unwrap();
2822 assert!(library.notebook().is_none());
2823 assert_eq!(section.shared.section.page(space).unwrap(), page);
2824 assert_eq!(section.shared.section.pending().unwrap(), pending);
2825 assert_eq!(std::fs::read(root.join("Read.one")).unwrap(), bytes);
2826 }
2827
2828 /// A copy of a section beside it on a share holds the same file identity. Offline, an
2829 /// edit made in the copy stays in the copy's replica and waits to publish to the copy,
2830 /// never reaching the original's.
2831 #[test]
2832 fn a_share_sections_copy_keeps_its_own_replica() {
2833 let directory = tempfile::tempdir().unwrap();
2834 let root = directory.path().join("notebook");
2835 let cache = directory.path().join("cache");
2836 std::fs::create_dir(&root).unwrap();
2837 let bytes = onestore::create_section("Notes.one", "Original text", "Fixture").unwrap();
2838 for name in ["Notes.one", "Notes - Copy.one"] {
2839 std::fs::write(root.join(name), &bytes).unwrap();
2840 }
2841 let notebook = Notebook::open(&root, &cache).unwrap();
2842 let mut listed = Listed::default();
2843 tabs(notebook.catalog(), &HashMap::new(), &mut listed.tabs);
2844 files(notebook.catalog(), &mut listed);
2845 drop(notebook);
2846 assert_eq!(
2847 listed.copies.iter().collect::<Vec<_>>(),
2848 ["Notes - Copy.one"]
2849 );
2850 let address = "127.0.0.1:0";
2851 let notebook = notebook::location::smb(address, "agent", "Notebook");
2852 for (path, identity) in &listed.files {
2853 let copy = listed.copies.contains(path);
2854 let location = session::replica_location(&notebook, path, copy);
2855 let replicas = notebook::location::claimed(&cache, &location).unwrap();
2856 Replica::create(replicas.join(format!("{identity}.sqlite")), &bytes).unwrap();
2857 }
2858 std::fs::create_dir_all(cache.join("smb")).unwrap();
2859 std::fs::write(
2860 cache.join("smb").join("127_0_0_1_0_agent_Notebook.json"),
2861 serde_json::to_vec(&listed).unwrap(),
2862 )
2863 .unwrap();
2864 let server = Server {
2865 address: address.into(),
2866 share: "agent".into(),
2867 user: String::new(),
2868 password: String::new(),
2869 domain: String::new(),
2870 };
2871 let library = Arc::new(Library::server(server, "Notebook", &cache).unwrap());
2872 sb_library_set_offline(&library, true);
2873 let open =
2874 |path| Section::open(Arc::clone(&library), path, "Fixture".into(), || {}).unwrap();
2875
2876 let copy = open("Notes - Copy.one");
2877 let space = copy.shared.section.pages().unwrap()[0].0;
2878 let colored = Edit {
2879 at: filetime(),
2880 ops: vec![Op::Page {
2881 space,
2882 op: onestore::op::PageOp::Color(Some(0x00ef_cdab)),
2883 }],
2884 };
2885 copy.shared.apply(colored).unwrap();
2886 copy.shared.section.written().unwrap();
2887 let shared = Arc::clone(&copy.shared);
2888 drop(copy);
2889 Arc::into_inner(shared).unwrap().section.close().unwrap();
2890
2891 let original = open("Notes.one");
2892 assert_eq!(original.shared.section.page(space).unwrap().color, None);
2893 assert!(original.shared.section.pending().unwrap().is_empty());
2894 let shared = Arc::clone(&original.shared);
2895 drop(original);
2896 Arc::into_inner(shared).unwrap().section.close().unwrap();
2897 let copy = open("Notes - Copy.one");
2898 assert_eq!(
2899 copy.shared.section.page(space).unwrap().color,
2900 Some(0x00ef_cdab)
2901 );
2902 assert_eq!(copy.shared.section.pending().unwrap().len(), 1);
2903 }
2904}