diff --git a/apps/ios/Snowbound/Notebooks.swift b/apps/ios/Snowbound/Notebooks.swift index f8377b990545fec9ec2bd22f8641d6f785140f00..b92f169bf2596dd7a500ef9995482a3b364062ba 100644 --- a/apps/ios/Snowbound/Notebooks.swift +++ b/apps/ios/Snowbound/Notebooks.swift @@ -262,6 +262,11 @@ final class Notebook { self.problem = library == nil ? (problem ?? "The notebook can’t be read.") : nil follow() reload(done: done) + // As OneNote prunes the recycle bin after opening. + if let library { + let pointer = Int(bitPattern: library) + background({ sb_library_purge_recycle_bin(OpaquePointer(bitPattern: pointer)) }) { _ in } + } } } @@ -785,7 +790,8 @@ final class Section { done() if recycled > 0, let window { let title = recycled == 1 ? "Page Moved to Recycle Bin" : "\(recycled) Pages Moved to Recycle Bin" - SyncToast.show(title, "Tap to restore", symbol: "trash", hint: "Opens the Recycle Bin", in: window) { + let detail = recycled == 1 ? "Restore it from the Recycle Bin" : "Restore them from the Recycle Bin" + SyncToast.show(title, detail, symbol: "trash", hint: "Opens the Recycle Bin", in: window) { [notebook = self.notebook] in RecycleBinViewController.present(notebook, in: window) } } diff --git a/apps/ios/Snowbound/Recycle.swift b/apps/ios/Snowbound/Recycle.swift index 6f181dc134b4a89e9e507f3a27fe1f9cf09080cd..175ed6c78f6c0dc036e7d48c5d0d04a135d64e0a 100644 --- a/apps/ios/Snowbound/Recycle.swift +++ b/apps/ios/Snowbound/Recycle.swift @@ -1,8 +1,9 @@ import UIKit extension Notebook { - /// Whether the notebook keeps a recycle bin: a folder does, a lone section doesn't. - var hasRecycleBin: Bool { tabs.contains { !$0.path.isEmpty && !$0.path.hasPrefix("/") } } + /// Whether the notebook keeps a recycle bin: an open folder does, even with no sections + /// left, and a lone section, listed by its file's path or none, doesn't. + var hasRecycleBin: Bool { handle != nil && !tabs.contains { $0.path.isEmpty || $0.path.hasPrefix("/") } } } /// OneNote's Notebook Recycle Bin: the pages and sections deleted from a notebook, each @@ -14,6 +15,7 @@ final class RecycleBinViewController: UITableViewController { /// Deleted Pages, open while the bin shows. private var deleted: Section? private var sections: [Tab] = [] + private var observers: [NSObjectProtocol] = [] /// Shows `notebook`'s bin as a sheet over the controller on top of `window`. static func present(_ notebook: Notebook, in window: UIWindow?) { @@ -33,16 +35,24 @@ final class RecycleBinViewController: UITableViewController { required init?(coder: NSCoder) { fatalError() } + deinit { observers.forEach(NotificationCenter.default.removeObserver) } + override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "binned") navigationItem.rightBarButtonItem = UIBarButtonItem( systemItem: .done, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) }) - NotificationCenter.default.addObserver(forName: Section.changed, object: nil, queue: .main) { [weak self] note in - if let self, note.object as AnyObject? === deleted { show() } - } - NotificationCenter.default.addObserver(forName: Notebook.listed, object: notebook, queue: .main) { [weak self] _ in - self?.reload() + observers = [ + NotificationCenter.default.addObserver(forName: Section.changed, object: nil, queue: .main) { [weak self] note in + if let self, note.object as AnyObject? === deleted { show() } + }, + NotificationCenter.default.addObserver(forName: Notebook.listed, object: notebook, queue: .main) { + [weak self] _ in self?.reload() + }, + ] + // Each row's Restore button takes its size as the row is made. + registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (self: Self, _) in + self.tableView.reloadData() } var loading = UIContentUnavailableConfiguration.loading() loading.text = "Opening…" @@ -53,26 +63,29 @@ final class RecycleBinViewController: UITableViewController { private var pages: [Row] { deleted?.rows ?? [] } private func reload() { - guard let library = notebook.handle else { return } + guard let library = notebook.handle else { return failed(notebook.problem) } let pointer = Int(bitPattern: library) background({ decode([Tab].self, sb_library_recycle_bin(OpaquePointer(bitPattern: pointer))) }) { [weak self] tabs in guard let self else { return } - guard let tabs else { - var failed = UIContentUnavailableConfiguration.empty() - failed.text = "Can’t Open Recycle Bin" - failed.secondaryText = "Check that the notebook can be reached, then try again." - contentUnavailableConfiguration = failed - return - } + guard let tabs else { return failed(nil) } sections = tabs.filter { $0.path != Self.deletedPages } guard deleted == nil, let tab = tabs.first(where: { $0.path == Self.deletedPages }) else { return show() } - Section.open(tab, of: notebook) { [weak self] section, _ in + Section.open(tab, of: notebook) { [weak self] section, problem in + guard let section else { return self?.failed(problem) ?? () } self?.deleted = section self?.show() } } } + /// Says the bin can't be read, rather than that it is empty. + private func failed(_ problem: String?) { + var failed = UIContentUnavailableConfiguration.empty() + failed.text = "Can’t Open Recycle Bin" + failed.secondaryText = problem ?? "Check that the notebook can be reached, then try again." + contentUnavailableConfiguration = failed + } + private func show() { tableView.reloadData() var empty = UIContentUnavailableConfiguration.empty() @@ -119,6 +132,7 @@ final class RecycleBinViewController: UITableViewController { let button = UIButton(configuration: restore) button.menu = menu(at: indexPath) button.showsMenuAsPrimaryAction = true + button.accessibilityLabel = "Restore \(content.text ?? "")" button.sizeToFit() cell.accessoryView = button return cell @@ -142,16 +156,21 @@ final class RecycleBinViewController: UITableViewController { Arranging.move(page: page, of: notebook, from: Self.deletedPages, to: tab.path) } } - return UIMenu(title: "Restore To", children: choices) + let none = UIAction(title: "No Sections", subtitle: "Add or restore a section first", attributes: .disabled) { _ in } + return UIMenu(title: "Restore To", children: choices.isEmpty ? [none] : choices) } let path = sections[indexPath.row].path let file = path.split(separator: "/").last.map(String.init) ?? path let choices = ([""] + notebook.groups).map { folder in - // A section of the same file name there would refuse it. - let taken = notebook.entries(in: folder).contains { $0.split(separator: "/").last.map(String.init) == file } - return UIAction(title: folder.isEmpty ? notebook.name : place(folder), attributes: taken ? .disabled : []) { - [notebook] _ in Arranging.place(path, of: notebook, in: folder) + // A section of the same file name there would refuse it, as the file systems + // notebooks live on ignore case. + let taken = notebook.entries(in: folder).contains { + ($0.split(separator: "/").last.map(String.init) ?? $0).caseInsensitiveCompare(file) == .orderedSame } + return UIAction( + title: folder.isEmpty ? notebook.name : place(folder), + subtitle: taken ? "A section with this name is already here" : nil, attributes: taken ? .disabled : [] + ) { [notebook] _ in Arranging.place(path, of: notebook, in: folder) } } return UIMenu(title: "Restore To", children: choices) } diff --git a/apps/ios/Snowbound/Sync.swift b/apps/ios/Snowbound/Sync.swift index d15ed9441f6a378f93bcabdc3abf44711b2cc31c..ccb85365f51d09e0d9cfa3a999524c8cc6222831 100644 --- a/apps/ios/Snowbound/Sync.swift +++ b/apps/ios/Snowbound/Sync.swift @@ -172,7 +172,14 @@ enum SyncToast { ]) UIView.animate(withDuration: 0.3) { toast.alpha = 1 } UIAccessibility.post(notification: .announcement, argument: "\(title). \(detail)") - DispatchQueue.main.asyncAfter(deadline: .now() + 6, execute: dismiss) + // VoiceOver needs time to reach it, so it stays while VoiceOver runs. + func expire() { + DispatchQueue.main.asyncAfter(deadline: .now() + 6) { [weak toast] in + guard toast?.superview != nil else { return } + if UIAccessibility.isVoiceOverRunning { expire() } else { dismiss() } + } + } + expire() } } diff --git a/crates/mobile/include/snowbound.h b/crates/mobile/include/snowbound.h index e5500719711aa682ca2192e952f1085854910364..7b850d304925fff40e36432a70956b73060e41ba 100644 --- a/crates/mobile/include/snowbound.h +++ b/crates/mobile/include/snowbound.h @@ -74,6 +74,7 @@ char *sb_library_move_page(const Library *library, const char *from, const char uint32_t level, const char *discard, const char *author, const char *date, const char *time); char *sb_library_place(const Library *library, const char *path, const char *folder, const char *paths); char *sb_library_recycle_bin(const Library *library); +void sb_library_purge_recycle_bin(const Library *library); bool sb_library_delete(const Library *library, const char *path); char *sb_search(const Library *const *libraries, size_t count, const char *section, const char *query); char *sb_library_tagged(const Library *library); diff --git a/crates/mobile/src/library.rs b/crates/mobile/src/library.rs index cf8425d7743ad31f9f0630342ddf9644a5d0e25d..f4e8dc16f8adedab85cba18eaff07d780c55a2ce 100644 --- a/crates/mobile/src/library.rs +++ b/crates/mobile/src/library.rs @@ -718,8 +718,9 @@ impl Library { if matches!(self.place, Place::File(_) | Place::Document(..)) { return Ok(Vec::new()); } + // Listed again, a share's bin sections open by the identities the listing keeps. + self.tabs()?; self.with_notebook(false, |notebook| { - notebook.refresh()?; let mut binned = Vec::new(); let catalog = notebook.catalog(); if let Some(bin) = catalog @@ -733,13 +734,28 @@ impl Library { }) } + /// Deletes for good what the recycle bin has held unchanged past OneNote's 60 days, as + /// OneNote 2010 prunes it after opening; a guest leaves that to its host's notebook, and a + /// share not reached is left for the next time. + pub(crate) fn purge_recycle_bin(&self) -> Result { + if matches!(self.place, Place::Hosted(_)) || self.notebook().is_none() { + return Ok(0); + } + // Time32 counts seconds from 1980; FILETIME, tenths of microseconds from 1601. + let now = (filetime() / 10_000_000).saturating_sub(11_960_006_400); + let now = u32::try_from(now).unwrap_or(u32::MAX); + self.with_notebook(true, |notebook| Ok(notebook.purge_recycle_bin(now)?)) + } + /// Moves the section or group at catalog `path` into the recycle bin, as OneNote 2010 /// deletes one. pub(crate) fn delete(&self, path: &str) -> Result<()> { self.with_notebook(true, |notebook| { notebook.refresh()?; Ok(notebook.delete(path)?) - }) + })?; + // Listed again, the background syncs the binned sections, edits waiting among them. + self.tabs().map(drop) } /// The section at catalog `path`, through a replica in the cache, following Work @@ -2092,6 +2108,14 @@ pub extern "C" fn sb_library_recycle_bin(library: &Library) -> *mut c_char { json(library.recycle_bin()) } +/// Deletes for good what the notebook's recycle bin has held unchanged past 60 days, as +/// OneNote 2010 does after opening a notebook. Writes to the notebook, so call it off the main +/// thread. +#[unsafe(no_mangle)] +pub extern "C" fn sb_library_purge_recycle_bin(library: &Library) { + report(library.purge_recycle_bin()); +} + /// Moves the section or group at catalog `path` into the notebook's recycle bin; false where /// it can't. Writes to the notebook, so call it off the main thread. /// diff --git a/crates/mobile/src/tests.rs b/crates/mobile/src/tests.rs index 610ccda4de7dd109a15bd5c81c81bf99b644ebb4..46074f898d2a89e833b2cb16660cfa7a6ef0bbcd 100644 --- a/crates/mobile/src/tests.rs +++ b/crates/mobile/src/tests.rs @@ -618,6 +618,63 @@ fn deleted_pages_and_sections_restore_from_the_recycle_bin_to_where_they_are_put ); } +/// A group deleted through the C surface takes its sections to the recycle bin, one with an +/// edit not yet published keeping it there; and a page leaves Deleted Pages while the bin +/// holds it open, as the iOS sheet does. +#[test] +fn a_group_with_an_unpublished_edit_goes_to_the_bin_and_an_open_bin_gives_up_its_page() { + const DELETED: &str = "OneNote_RecycleBin/OneNote_DeletedPages.one"; + let date = ["Monday, October 19, 2026", "9:00 AM"]; + let (_directory, root, library, features) = notebook_open("Features.one", true); + let duplicate = open(&library, "Group A/Duplicate.one"); + let before = duplicate.rows().unwrap().len(); + duplicate.new_page(None, date[0], date[1]).unwrap(); + duplicate.shared.section.written().unwrap(); + drop(duplicate); + let group = CString::new("Group A").unwrap(); + assert!(unsafe { library::sb_library_delete(&library, group.as_ptr()) }); + let binned = "OneNote_RecycleBin/Duplicate.one"; + let listed = take_json(library::sb_library_recycle_bin(&library)); + assert!( + listed + .as_array() + .unwrap() + .iter() + .any(|tab| tab["path"] == binned) + ); + assert!(!root.join("Group A").exists()); + sb_library_set_offline(&library, false); + sb_library_sync_now(&library); + let stored = || { + let bytes = std::fs::read(root.join(binned)).unwrap(); + notebook::session::stored_pages(&bytes).unwrap().len() + }; + assert!( + eventually(|| stored() == before + 1), + "the edit reached the binned section" + ); + + let space = features.rows().unwrap()[0].id.parse().unwrap(); + features.delete_page(space, date[0], date[1]).unwrap(); + drop(features); + let bin = open(&library, DELETED); + let recycled = bin.shared.section.pages().unwrap()[0].0; + let restored = library + .move_page( + DELETED, + recycled, + "Features.one", + None, + 1, + None, + "Clover Test", + date, + ) + .unwrap(); + assert_eq!((restored.added, restored.copied), (None, None)); + assert!(bin.shared.section.pages().unwrap().is_empty()); +} + #[test] fn deleting_a_lone_section_page_still_creates_its_replacement_without_a_bin() { let directory = tempfile::tempdir().unwrap(); @@ -4341,3 +4398,91 @@ fn a_provider_that_lists_but_cannot_open_opens_from_the_offline_copies() { assert!(stored_text(&file, space).contains("Offline")); closed(section); } + +/// A page restored from a share's recycle bin while working offline waits in the cache and +/// publishes once online: a cold reopen finds it, content and identity kept, in the section +/// it was restored to, and Deleted Pages empty. `ONESTORE_SMB_LAB=HOST:PORT` names a guest +/// share `agent` (`tools/w7/linux_vm.py up NAME`); the notebook goes in a fresh folder. +#[test] +#[ignore = "requires an owned Samba share at ONESTORE_SMB_LAB"] +fn a_page_restored_offline_on_a_share_publishes_once_online() { + const DELETED: &str = "OneNote_RecycleBin/OneNote_DeletedPages.one"; + let date = ["Monday, October 19, 2026", "9:00 AM"]; + let server = || library::Server { + address: std::env::var("ONESTORE_SMB_LAB").unwrap(), + share: "agent".into(), + user: String::new(), + password: String::new(), + domain: String::new(), + }; + let root = format!("snowbound-recycle-{}", std::process::id()); + let directory = tempfile::tempdir().unwrap(); + let client = Arc::new(server().connect().unwrap()); + client.create_directory(&root).unwrap(); + let mut notebook = notebook::session::Notebook::open_smb( + Arc::clone(&client), + &root, + directory.path().join("made"), + ) + .unwrap(); + for (name, title) in [("Kept", "Restored over SMB"), ("Target", "Already there")] { + let page = onestore::PageCreation::new(None, Some(title), "Clover Test").unwrap(); + notebook.create_section("", name, &page).unwrap(); + } + drop(notebook); + + let library = + Arc::new(Library::server(server(), &root, &directory.path().join("cache")).unwrap()); + library.tabs().unwrap(); + let kept = open(&library, "Kept.one"); + let deleted = space(&kept, "Restored over SMB"); + let page = kept.shared.section.page(deleted).unwrap(); + kept.delete_page(deleted, date[0], date[1]).unwrap(); + drop(kept); + // As the iOS sheet lists the bin, then opens Deleted Pages. + assert_eq!(library.recycle_bin().unwrap()[0].path, DELETED); + let bin = open(&library, DELETED); + let recycled = bin.shared.section.pages().unwrap()[0].0; + + sb_library_set_offline(&library, true); + let restored = library + .move_page( + DELETED, + recycled, + "Target.one", + None, + 1, + None, + "Clover Test", + date, + ) + .unwrap(); + assert_eq!((restored.added, restored.copied), (None, None)); + assert!( + !bin.shared.section.pending().unwrap().is_empty(), + "the bin's edit waits offline" + ); + drop(bin); + sb_library_set_offline(&library, false); + sb_library_sync_now(&library); + library.close(Duration::from_secs(60)).unwrap(); + drop(library); + + let cold = Arc::new(Library::server(server(), &root, &directory.path().join("cold")).unwrap()); + cold.tabs().unwrap(); + let target = open(&cold, "Target.one"); + let arrived = space(&target, "Restored over SMB"); + assert_eq!( + target.shared.section.page(arrived).unwrap().identity, + page.identity + ); + drop(target); + assert!( + open(&cold, DELETED) + .shared + .section + .pages() + .unwrap() + .is_empty() + ); +}