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