diff --git a/apps/ios/Snowbound/App.swift b/apps/ios/Snowbound/App.swift index ba526a51fbc4eef43feb9bd437ad5324abc67500..49d5a37e5accf3fa2747e514069d7c2db43ce7f1 100644 --- a/apps/ios/Snowbound/App.swift +++ b/apps/ios/Snowbound/App.swift @@ -164,10 +164,15 @@ private struct Place: Codable { /// Notebooks and sections, pages and a page, as Notes lays out folders, notes and a note: /// side by side on a wide screen, a navigation stack on a phone. final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewControllerDelegate { + private struct WeakPage { weak var value: PageViewController? } + var window: UIWindow? private let split = RootViewController(style: .tripleColumn) private let notebooks = NotebooksViewController() private let pages = PagesViewController() + /// Live page controllers created by this scene, tracked directly so `close(_:)` can tear + /// them down even when UIKit's collapsed split view keeps them off `.secondary`. + private var openPages: [WeakPage] = [] /// A first launch opened a page by itself. private var landed = false private var background = UIBackgroundTaskIdentifier.invalid @@ -292,6 +297,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro func show(section: Section, page: String, reveal: Reveal? = nil, titleFocus: Bool = false, revealPage: Bool = true) { let controller = PageViewController(section: section, page: page, reveal: reveal, titleFocus: titleFocus) + openPages.removeAll { $0.value == nil } + openPages.append(WeakPage(value: controller)) controller.onOpen = { [weak self, weak controller] id in guard let controller else { return } self?.show(section: section, page: id, revealPage: controller.viewIfLoaded?.window != nil) @@ -302,12 +309,53 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro Place.saved = Place(notebook: section.notebook.id, section: section.tab.path, page: page) } + /// The section and page currently open for `notebook`, if any, to restore after relocating it. + func shown(of notebook: Notebook) -> (section: String, page: String?)? { + guard let section = pages.section, section.notebook === notebook else { return nil } + let page = Place.saved?.notebook == notebook.id ? Place.saved?.page : nil + return (section.tab.path, page) + } + + /// Reopens a section and page previously returned by `shown(of:)` if still listed. + func reopen(_ shown: (section: String, page: String?), of notebook: Notebook) { + guard let tab = notebook.tabs.first(where: { $0.path == shown.section && $0.readable }) else { return } + open(tab, of: notebook, page: shown.page) + } + + private func pageControllers(in controller: UIViewController?) -> [PageViewController] { + guard let controller else { return [] } + var found: [PageViewController] = [] + if let page = controller as? PageViewController { found.append(page) } + if let nav = controller as? UINavigationController { + for child in nav.viewControllers { found += pageControllers(in: child) } + } + for child in controller.children { found += pageControllers(in: child) } + return found + } + /// Returns to the list from any section of `notebook` shown, as before its folder moves. func close(_ notebook: Notebook) { - guard pages.section?.notebook === notebook else { return } - pages.clear() + openPages.removeAll { $0.value == nil } + let pagesMatched = pages.section?.notebook === notebook + var shownPages = openPages.compactMap(\.value).filter { $0.notebook === notebook } + for controller in pageControllers(in: split.viewController(for: .secondary)) + + pageControllers(in: split.viewController(for: .compact)) + + pageControllers(in: notebooks.navigationController) + where controller.notebook === notebook && !shownPages.contains(where: { $0 === controller }) + { + shownPages.append(controller) + } + guard pagesMatched || !shownPages.isEmpty else { return } + for page in shownPages { page.tearDown() } + if pagesMatched { pages.clear() } + if split.isCollapsed && split.presentedViewController == nil { + (split.viewController(for: .compact) as? UINavigationController)?.popToRootViewController(animated: false) + notebooks.navigationController?.popToRootViewController(animated: false) + } split.setViewController(UIViewController(), for: .secondary) - split.show(.primary) + if split.presentedViewController == nil { + split.show(.primary) + } } /// Lets go of the section shown where it is the section or group at `path` of `notebook` diff --git a/apps/ios/Snowbound/Arranging.swift b/apps/ios/Snowbound/Arranging.swift index 6903ba3f35f8c7dd7453e5dc6fdcb41250ed4270..a51f003c1a0df730275bd1c9a54ac3c3e7b373ce 100644 --- a/apps/ios/Snowbound/Arranging.swift +++ b/apps/ios/Snowbound/Arranging.swift @@ -189,11 +189,14 @@ enum Arranging { _ pages: [(page: String, discard: String?)], from source: Section, to target: Section, order: [Placed], repairs: [(id: String, expected: Int, restore: Int)] = [] ) { - guard !pages.isEmpty, let library = source.notebook.handle, let release = reserve() else { return } + guard !pages.isEmpty, let library = source.notebook.handle, + let sourceHandle = source.handle, let targetHandle = target.handle, + let release = reserve() + else { return } let before = source.rows.map { Placed(id: $0.id, level: $0.level) } let pointer = Int(bitPattern: library) - let sourcePointer = Int(bitPattern: source.handle) - let targetPointer = Int(bitPattern: target.handle) + let sourcePointer = Int(bitPattern: sourceHandle) + let targetPointer = Int(bitPattern: targetHandle) let author = Author.name ?? "" let (date, time) = titleDate() var undo: () -> Void = {} @@ -310,7 +313,7 @@ extension UIResponder { extension Section { /// Puts page `id` where `order` places it, as one edit; false where it isn't listed. func arrange(_ order: [Placed], moving id: String) -> Bool { - guard sb_section_arrange(handle, json(order), json([id])) else { return false } + guard let handle, sb_section_arrange(handle, json(order), json([id])) else { return false } reloadRows() return true } diff --git a/apps/ios/Snowbound/CanvasView.swift b/apps/ios/Snowbound/CanvasView.swift index ccc816484fbd6a93124ad6f7c6c606e730a35abb..9ef19867dbee3116ae9e0cb0571c2fae4cf95cea 100644 --- a/apps/ios/Snowbound/CanvasView.swift +++ b/apps/ios/Snowbound/CanvasView.swift @@ -66,10 +66,23 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI UIGestureRecognizerDelegate, UIEditMenuInteractionDelegate, UIPencilInteractionDelegate, UIScribbleInteractionDelegate { + private struct WeakCanvas { weak var value: CanvasView? } + private static var active: [ObjectIdentifier: WeakCanvas] = [:] + + /// Tears down every live canvas displaying a section of `notebook` so its Rust `View` + /// releases its section handle immediately. + static func tearDownAll(of notebook: Notebook) { + active = active.filter { $0.value.value != nil } + for entry in active.values { + guard let canvas = entry.value, canvas.section?.notebook === notebook else { continue } + canvas.tearDown() + } + } + /// The zoom a page opens at once the reader has pinched one. private static let zoomKey = "zoom" - private let section: Section + private var section: Section? private let page: String private let metal = MetalView() /// Sized to the page content at 100%, so the scroll view's zoom scale is the page zoom. @@ -118,7 +131,7 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI private var fingerDraws = false /// The section's tab colour as a COLORREF, which its pen gallery and shapes follow. private var sectionColor: UInt32 { - section.tab.color.enumerated().reduce(0) { $0 | UInt32($1.element) << (8 * UInt32($1.offset)) } + (section?.tab.color ?? []).enumerated().reduce(0) { $0 | UInt32($1.element) << (8 * UInt32($1.offset)) } } private lazy var picker = InkPicker(pens: Pen.gallery(sectionColor)) @@ -152,10 +165,11 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI } } - init(section: Section, page: String) { + init(section: Section?, page: String) { self.section = section self.page = page super.init(frame: .zero) + Self.active[ObjectIdentifier(self)] = WeakCanvas(value: self) backgroundColor = .systemBackground delegate = self minimumZoomScale = 0.25 @@ -212,8 +226,20 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI required init?(coder: NSCoder) { fatalError() } deinit { + Self.active[ObjectIdentifier(self)] = nil + tearDown() + } + + /// Stops the display link, frees the Rust view, and drops the section reference + /// immediately so the underlying replica can close even while UIKit keeps the view alive. + func tearDown() { link?.invalidate() - if let handle { sb_view_free(handle) } + link = nil + if let handle { + sb_view_free(handle) + self.handle = nil + } + section = nil } // MARK: Drawing @@ -233,8 +259,9 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI sb_view_resize(handle, Float(bounds.width), Float(bounds.height), Float(scale)) if readingShown { reflowReading(readingWidth) } else { transform() } } else { + guard let section, let sectionHandle = section.handle else { return } handle = sb_view_new( - Unmanaged.passUnretained(metal.layer).toOpaque(), section.handle, page, + Unmanaged.passUnretained(metal.layer).toOpaque(), sectionHandle, page, Float(bounds.width), Float(bounds.height), Float(scale)) guard let handle else { return } sb_view_focus(handle, false) diff --git a/apps/ios/Snowbound/Lists.swift b/apps/ios/Snowbound/Lists.swift index 2f4cb108bf87df092486a3e76553e7a1ebb20820..102dad493814d082a5c13704999a651d619a2a7f 100644 --- a/apps/ios/Snowbound/Lists.swift +++ b/apps/ios/Snowbound/Lists.swift @@ -558,12 +558,19 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke } // A notebook On My iPhone is its folder there, handled as Files handles a folder. guard let folder = folder(of: notebook) else { + var extra: [UIMenuElement] = [] + if case .server = notebook.source { + extra.append( + UIAction(title: "Change Server Address", image: UIImage(systemName: "server.rack")) { [weak self] _ in + self?.changeServer(of: notebook) + }) + } let image = UIImage(systemName: "xmark.circle") let close = UIAction(title: "Close Notebook", image: image, attributes: .destructive) { [weak self] _ in Notebooks.remove(notebook) self?.reload() } - return UIMenu(children: status + actions + [close]) + return UIMenu(children: status + actions + extra + [close]) } let file = [ UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in @@ -1030,6 +1037,17 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke present(UINavigationController(rootViewController: server), animated: true) } + private func changeServer(of notebook: Notebook) { + let server = ServerViewController(editing: notebook) + server.onUpdate = { [weak self] restore in + self?.dismiss(animated: true) { + self?.reload() + restore() + } + } + present(UINavigationController(rootViewController: server), animated: true) + } + private func newSection(in notebook: Notebook) { let alert = UIAlertController(title: "New Section", message: nil, preferredStyle: .alert) alert.addTextField { field in diff --git a/apps/ios/Snowbound/Notebooks.swift b/apps/ios/Snowbound/Notebooks.swift index 7e14fd277c78e25503d5c3042ebdc514fbfcf955..24ed6e2a7d72830e699fd7e3e58ede4cfb204280 100644 --- a/apps/ios/Snowbound/Notebooks.swift +++ b/apps/ios/Snowbound/Notebooks.swift @@ -33,7 +33,9 @@ enum Author { set { UserDefaults.standard.set(newValue, forKey: key) // Open sections name it in their edits from now on. - for section in Section.all { sb_section_set_author(section.handle, newValue ?? "") } + for section in Section.all { + if let handle = section.handle { sb_section_set_author(handle, newValue ?? "") } + } } } @@ -73,8 +75,92 @@ struct Server: Codable, Equatable { /// The notebook folder, `/`-separated from the share's top. var root: String - var hostName: String { host.split(separator: ":").first.map(String.init) ?? host } - var port: Int { host.split(separator: ":").dropFirst().first.flatMap { Int($0) } ?? 445 } + var hostName: String { + if host.hasPrefix("["), let end = host.firstIndex(of: "]") { + return String(host[...end]) + } + return host.split(separator: ":").first.map(String.init) ?? host + } + + var port: Int { + if host.hasPrefix("["), let end = host.firstIndex(of: "]") { + let after = host[host.index(after: end)...] + return after.hasPrefix(":") ? Int(after.dropFirst()) ?? 445 : 445 + } + return host.split(separator: ":").dropFirst().first.flatMap { Int($0) } ?? 445 + } + + /// `smb://host/share/root`, as shown in Sync Status and pre-filled when editing the address. + var url: String { + "smb://\(host)/\([share, root].filter { !$0.isEmpty }.joined(separator: "/"))" + } + + /// The notebook's display name: its folder's name, or the share's when opened at the top. + var folderName: String { + root.split(separator: "/").last.map(String.init) ?? share + } + + /// Normalized location matching `notebook::location::smb` after `:445` defaulting. + var canonicalLocation: String { + let hasPort = host.hasPrefix("[") ? host.contains("]:") : host.contains(":") + let address = hasPort ? host : "\(host):445" + let trimmed = root.replacingOccurrences(of: "\\", with: "/") + .trimmingCharacters(in: CharacterSet(charactersIn: "/")) + return "smb://\(address)/\(share)/\(trimmed)" + } + + /// Parses `smb://[user@]host[:port]/share[/folder]`, `\\host\share[\folder]`, or the same + /// without a scheme, preserving spaces and characters such as `#` in folder names. + static func parse(_ raw: String, registered: Bool, username: String) -> Server? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + let rest: String + if let schemeEnd = trimmed.range(of: "://") { + guard trimmed[.. Void) -> Void) { + guard case .server(let oldServer) = source else { + return done("Only server notebooks have an address to change.", {}) + } + if Notebooks.all.contains(where: { other in + guard other !== self, case .server(let existing) = other.source else { return false } + return existing.canonicalLocation == newServer.canonicalLocation + }) { + return done( + "Another notebook in your list already uses this server address. Close it after its changes finish syncing, then try again.", + {}) + } + guard let release = Arranging.reserve() else { + return done("Wait for the current action to finish, then try again.", {}) + } + // Commit any active text composition before checking durability or closing sections. + NotificationCenter.default.post(name: PageViewController.leaving, object: nil) + let stopPointer = handle.map { Int(bitPattern: $0) } + background({ () -> String? in + guard let stopPointer, let library = OpaquePointer(bitPattern: stopPointer) else { return nil } + var error: UnsafeMutablePointer? + let stopped = sb_library_stop(library, &error) + return stopped ? nil : (take(error) ?? "Couldn’t stop syncing this notebook.") + }) { [self] stopError in + if let stopError { + release() + return done(stopError, {}) + } + var reopen: [(SceneDelegate, (section: String, page: String?))] = [] + for scene in UIApplication.shared.connectedScenes { + guard let delegate = scene.delegate as? SceneDelegate else { continue } + if let shown = delegate.shown(of: self) { + reopen.append((delegate, shown)) + } + delegate.close(self) + } + CanvasView.tearDownAll(of: self) + for section in Section.all where section.notebook === self { + section.close() + } + Section.releaseUnsaved(of: self) + recheck?.cancel() + recheck = nil + presenter?.stop() + presenter = nil + let detached = handle.map { Int(bitPattern: $0) } + handle = nil + let oldPassword = Keychain.password(oldServer) ?? "" + let newPassword = Keychain.password(newServer) ?? "" + background({ () -> (moved: Bool, library: Int, error: String?) in + if let detached, let oldLibrary = OpaquePointer(bitPattern: detached) { + sb_library_free(oldLibrary) + } + var error: UnsafeMutablePointer? + let moved = sb_server_moved( + cacheDirectory.path, + oldServer.host, oldServer.share, oldServer.root, + newServer.host, newServer.share, newServer.root, + &error) + if !moved { + let moveError = take(error) ?? "Couldn’t move this notebook’s local changes." + var ignored: UnsafeMutablePointer? + let restored = sb_library_server( + oldServer.host, oldServer.share, oldServer.user, oldPassword, "", oldServer.root, + cacheDirectory.path, &ignored) + _ = take(ignored) + return (false, Int(bitPattern: restored), moveError) + } + let library = sb_library_server( + newServer.host, newServer.share, newServer.user, newPassword, "", newServer.root, + cacheDirectory.path, &error) + return (true, Int(bitPattern: library), take(error)) + }) { [self] result in + let library = OpaquePointer(bitPattern: result.library) + handle = library + let restore = { [weak self] in + guard let self else { return } + for (delegate, shown) in reopen { delegate.reopen(shown, of: self) } + } + if !result.moved { + problem = library == nil ? "The notebook can’t be read." : nil + follow() + reload { + NotificationCenter.default.post(name: Self.listed, object: self) + release() + done(result.error, restore) + } + return + } + source = .server(newServer) + name = newServer.folderName + Notebooks.save() + problem = library == nil ? (result.error ?? "The notebook can’t be read.") : nil + follow() + if let library, !Sync.offline { + sb_library_sync_now(library) + } + reload { + NotificationCenter.default.post(name: Self.listed, object: self) + NotificationCenter.default.post(name: Sync.changed, object: nil) + if let library { + let pointer = Int(bitPattern: library) + background({ sb_library_purge_recycle_bin(OpaquePointer(bitPattern: pointer)) }) { _ in } + } + release() + done(nil, restore) + } + } + } + } + /// Unlocks the protected section at `path` with `password` off the main thread, then lists /// the sections again; `done` learns whether the password matched. func unlock(_ path: String, password: String, done: @escaping (Bool) -> Void) { @@ -598,7 +798,7 @@ enum Notebooks { save() } - private static func save() { + static func save() { guard scripted == nil else { return } let entries = elsewhere.map { Entry(id: $0.id, name: $0.name, source: $0.source) } UserDefaults.standard.set(try? JSONEncoder().encode(entries), forKey: key) @@ -648,7 +848,7 @@ final class Section { let notebook: Notebook let tab: Tab - let handle: OpaquePointer + private(set) var handle: OpaquePointer? private let token: Int private(set) var rows: [Row] private(set) var status = SaveStatus.unknown @@ -656,6 +856,12 @@ final class Section { static var all: [Section] { open.values.compactMap(\.value) } + /// Releases strong references held for Not Saving sections of `notebook` once their edits + /// are confirmed durable on disk, so their replicas can close and move. + static func releaseUnsaved(of notebook: Notebook) { + unsaved = unsaved.filter { $0.value.notebook !== notebook } + } + private init(notebook: Notebook, tab: Tab, handle: OpaquePointer, token: Int, rows: [Row]) { self.notebook = notebook self.tab = tab @@ -664,9 +870,21 @@ final class Section { self.rows = rows } + /// Explicitly frees the Rust section handle so its replica closes immediately without + /// waiting for UIKit or autorelease pools to release Swift references to `Section`. + func close() { + Self.open[token] = nil + Self.unsaved[token] = nil + listing = nil + if let handle { + self.handle = nil + sb_section_free(handle) + } + } + deinit { Self.open[token] = nil - sb_section_free(handle) + if let handle { sb_section_free(handle) } } /// Opens `tab` of `notebook` off the main thread, or hands back the section already open @@ -698,6 +916,7 @@ final class Section { /// Lists the pages again and tells the views. func reloadRows() { + guard let handle else { return } listing?.invalidated = true rows = decode([Row].self, sb_section_pages(handle)) ?? rows NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed]) @@ -715,14 +934,22 @@ final class Section { } private func readRows() { - background({ [self] in decode([Row].self, sb_section_pages(handle)) }) { [self] rows in + guard let handle else { + let completions = listing?.completions ?? [] + listing = nil + for completion in completions { completion() } + return + } + let pointer = Int(bitPattern: handle) + background({ decode([Row].self, sb_section_pages(OpaquePointer(bitPattern: pointer))) }) { [self] rows in + guard let current = listing else { return } // A read begun before a reload or retitle would undo it. - if listing!.invalidated, rows != nil { + if current.invalidated, rows != nil { listing?.invalidated = false return readRows() } self.rows = rows ?? self.rows - let completions = listing!.completions + let completions = current.completions listing = nil NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed]) for completion in completions { completion() } @@ -739,6 +966,7 @@ final class Section { } fileprivate func poll() { + guard let handle else { return } var status: UInt8 = 0 let flags = sb_section_poll(handle, &status) let changed = SaveStatus(rawValue: status) ?? .unknown @@ -762,6 +990,7 @@ final class Section { /// Adds a page, or a subpage of `parent`; returns its id. func newPage(under parent: String? = nil) -> String? { + guard let handle else { return nil } let (date, time) = titleDate() let id = take(sb_section_new_page(handle, parent, date, time)) reloadRows() @@ -771,7 +1000,7 @@ final class Section { /// Deletes pages, conflict pages for good and the rest to the recycle bin, which a toast /// then offers. func delete(_ ids: [String], done: @escaping () -> Void = {}) { - guard let release = Arranging.reserve() else { return } + guard let handle, let release = Arranging.reserve() else { return } let recycled = notebook.hasRecycleBin ? ids.filter { row(of: $0)?.version == nil }.count : 0 let (date, time) = titleDate() let pointer = Int(bitPattern: handle) @@ -812,17 +1041,24 @@ final class Section { let notebook: String? } - func themes(of id: String) -> Themes? { decode(Themes.self, sb_section_themes(handle, id)) } + func themes(of id: String) -> Themes? { + handle.flatMap { decode(Themes.self, sb_section_themes($0, id)) } + } /// Gives `theme`, or none of its own, to page `id` (scope 0), its section (1) or its /// notebook (2). func setTheme(_ theme: String?, scope: UInt8, of id: String, done: @escaping (Bool) -> Void) { + guard let handle else { return done(false) } let pointer = Int(bitPattern: handle) background({ sb_section_set_theme(OpaquePointer(bitPattern: pointer), id, scope, theme) }, done: done) } /// Stores every edit and publishes them within `seconds`; call off the main thread. - func flush(_ seconds: Double) -> Bool { sb_section_flush(handle, seconds) } + func flush(_ seconds: Double) -> Bool { + handle.map { sb_section_flush($0, seconds) } ?? true + } - func wake() { sb_section_wake(handle) } + func wake() { + if let handle { sb_section_wake(handle) } + } } diff --git a/apps/ios/Snowbound/PageViewController.swift b/apps/ios/Snowbound/PageViewController.swift index dd3cdf026b882b4971d71d2a4954c8f9bf35c7fe..3e523d81d2c97c5e621e1ac36d3f9414ce44a1e9 100644 --- a/apps/ios/Snowbound/PageViewController.swift +++ b/apps/ios/Snowbound/PageViewController.swift @@ -15,8 +15,9 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate /// Posted when the app leaves the screen or quits: marked text is committed so it saves. static let leaving = Notification.Name("SnowboundLeaving") - private let section: Section + private var section: Section? private let page: String + var notebook: Notebook? { section?.notebook } private let reveal: Reveal? private let titleFocus: Bool private lazy var canvas = CanvasView(section: section, page: page) @@ -57,6 +58,17 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate required init?(coder: NSCoder) { fatalError() } + /// Releases the canvas view, display link, timers, and section reference immediately so + /// the underlying section replica can close without waiting on UIKit transition cleanup. + func tearDown() { + NotificationCenter.default.removeObserver(self) + mediaClock?.invalidate() + mediaClock = nil + onOpen = nil + if isViewLoaded { canvas.tearDown() } + section = nil + } + override func loadView() { let view = UIView() view.backgroundColor = .systemBackground @@ -141,7 +153,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate private func editingChanged() { if !canvas.readOnly, let title = canvas.pageTitle { showTitle(title) - section.retitle(page, title) + section?.retitle(page, title) } fitTitle() draw.isSelected = canvas.pickerShown @@ -167,7 +179,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate return [readingAction()] + [ themeMenu(), UIAction(title: "Tags Summary", image: UIImage(systemName: "tag")) { [weak self] _ in - guard let self else { return } + guard let self, let section else { return } scene?.showTags(of: section.notebook, from: self) }, UIMenu(options: .displayInline, children: [ @@ -184,7 +196,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate }, UIAction(title: "Delete Page", image: UIImage(systemName: "trash"), attributes: .destructive) { [weak self] _ in - guard let self else { return } + guard let self, let section else { return } section.delete([page]) }, ]), @@ -248,7 +260,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate /// The page's theme, its section's and its notebook's, each pickable; the page wears a /// new one when it opens again. private func themeMenu() -> UIMenu { - guard let themes = section.themes(of: page) else { + guard let section, let themes = section.themes(of: page) else { return UIMenu(title: "Theme", image: UIImage(systemName: "textformat"), children: []) } let scopes: [(String, String?)] = [ @@ -260,7 +272,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate let choices = [(nil as String?, "None")] + themes.themes.map { ($0.id, $0.name) } return UIMenu(title: title, children: choices.map { id, name in UIAction(title: name, state: id == current ? .on : .off) { [weak self] _ in - guard let self else { return } + guard let self, let section = self.section else { return } section.setTheme(id, scope: UInt8(scope), of: page) { [weak self] _ in self?.onOpen?(page) } @@ -273,6 +285,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate /// Prints the page through the system's print sheet, or with `export` offers its PDF in /// the share sheet, laid out as OneNote 2010 prints it on the region's paper. private func printPage(export: Bool) { + guard let section else { return } let letter = ["US", "CA", "MX", "PR", "PH", "CL", "CO", "VE", "GT", "CR", "PA", "DO", "SV", "NI", "HN", "BZ"] .contains(Locale.current.region?.identifier ?? "US") let paper = letter ? CGSize(width: 612, height: 792) : CGSize(width: 595.276, height: 841.89) @@ -415,7 +428,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate canvas.reload(discard: false, pendingOnly: true) if notification.userInfo?["unchanged"] as? Bool == true { return } } - if flags & Section.listed != 0 { + if flags & Section.listed != 0, let section { if section.row(of: page) == nil { // Deleted elsewhere, or a conflict page resolved: back to what the section lists. if let first = section.rows.first { onOpen?(first.id) } @@ -429,7 +442,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate /// Only trouble shows: saving goes on quietly, as Notes saves. private func showStatus() { let status: String? = - switch section.status { + switch section?.status { case .offline: "Offline" case .notSaving: "Not Saving" default: nil @@ -444,7 +457,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate // MARK: Conflicts private func conflictChanged() { - guard let (row, version) = section.row(of: page) else { return bar.show(nil) } + guard let section, let (row, version) = section.row(of: page) else { return bar.show(nil) } if version != nil { // Deleting a conflict page cannot be undone, so the button asks first. let delete = UIAction( @@ -462,7 +475,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate } private func conflictAction() { - guard let (row, version) = section.row(of: page) else { return } + guard let section, let (row, version) = section.row(of: page) else { return } if version != nil { section.delete([page]) { [weak self] in self?.onOpen?(row.id) } } else if let newest = row.versions.max(by: { ($0.created ?? 0) < ($1.created ?? 0) }) { diff --git a/apps/ios/Snowbound/Server.swift b/apps/ios/Snowbound/Server.swift index 98b4a5c4c7246ac589f86cedea4a29ce15ecea40..f0690e21d0472dc7fb5d71d56226026b4df48d38 100644 --- a/apps/ios/Snowbound/Server.swift +++ b/apps/ios/Snowbound/Server.swift @@ -1,20 +1,25 @@ import UIKit /// Connect to Server, as Files and the Finder offer it: an `smb://` address, then a guest -/// or an account whose password goes in the Keychain, then a folder to open. +/// or an account whose password goes in the Keychain, then a folder to open — or, when +/// `editing` a server notebook, a new address and folder to relocate it to while keeping +/// its local changes. final class ServerViewController: UITableViewController, UITextFieldDelegate { private static let lastKey = "server" + private let editingNotebook: Notebook? private let address = UITextField() private let name = UITextField() private let password = UITextField() private let guest = UISegmentedControl(items: ["Guest", "Registered User"]) private var connecting = false var onOpen: ((Notebook) -> Void)? + var onUpdate: ((@escaping () -> Void) -> Void)? - init() { + init(editing notebook: Notebook? = nil) { + self.editingNotebook = notebook super.init(style: .insetGrouped) - title = "Connect to Server" + title = notebook == nil ? "Connect to Server" : "Change Server Address" } required init?(coder: NSCoder) { fatalError() } @@ -26,7 +31,6 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Connect", primaryAction: UIAction { [weak self] _ in self?.connect() }) address.placeholder = "smb://server/share" - address.text = UserDefaults.standard.string(forKey: Self.lastKey) address.keyboardType = .URL address.autocapitalizationType = .none address.autocorrectionType = .no @@ -42,7 +46,15 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { field.delegate = self field.returnKeyType = field === password || field === address ? .go : .next } - guest.selectedSegmentIndex = 1 + if case .server(let current) = editingNotebook?.source { + address.text = current.url + guest.selectedSegmentIndex = current.user.isEmpty ? 0 : 1 + name.text = current.user + password.text = current.user.isEmpty ? nil : Keychain.password(current) + } else { + address.text = UserDefaults.standard.string(forKey: Self.lastKey) + guest.selectedSegmentIndex = 1 + } guest.addAction(UIAction { [weak self] _ in self?.tableView.reloadData() }, for: .valueChanged) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "field") } @@ -65,17 +77,7 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { /// `smb://user@host:port/share/folder`, or the same without a scheme. private func server() -> Server? { - var text = address.text?.trimmingCharacters(in: .whitespaces) ?? "" - if !text.contains("://") { text = "smb://" + text } - guard let url = URLComponents(string: text), url.scheme?.lowercased() == "smb", let host = url.host, - !host.isEmpty - else { return nil } - let parts = url.path.split(separator: "/").map(String.init) - guard let share = parts.first else { return nil } - let user = url.user ?? (registered ? name.text ?? "" : "") - return Server( - host: url.port.map { "\(host):\($0)" } ?? host, share: share, user: user, - root: parts.dropFirst().joined(separator: "/")) + Server.parse(address.text ?? "", registered: registered, username: name.text ?? "") } private func connect() { @@ -103,9 +105,11 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { "Can’t Connect", "Check the address, name and password, and that the server is on this network.") } if registered { Keychain.save(secret, for: server) } - UserDefaults.standard.set(address.text, forKey: Self.lastKey) - let browser = ShareViewController(share: SharedConnection(share), server: server, path: server.root) + if editingNotebook == nil { UserDefaults.standard.set(address.text, forKey: Self.lastKey) } + let browser = ShareViewController( + share: SharedConnection(share), server: server, path: server.root, editing: editingNotebook) browser.onOpen = onOpen + browser.onUpdate = onUpdate navigationController?.pushViewController(browser, animated: true) } } @@ -157,13 +161,17 @@ final class ShareViewController: UITableViewController { private let share: SharedConnection private let server: Server private let path: String + private let editingNotebook: Notebook? private var listing: Listing? + private var updating = false var onOpen: ((Notebook) -> Void)? + var onUpdate: ((@escaping () -> Void) -> Void)? - init(share: SharedConnection, server: Server, path: String) { + init(share: SharedConnection, server: Server, path: String, editing notebook: Notebook? = nil) { self.share = share self.server = server self.path = path + self.editingNotebook = notebook super.init(style: .insetGrouped) title = path.split(separator: "/").last.map(String.init) ?? server.share } @@ -173,7 +181,9 @@ final class ShareViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "entry") - let open = UIBarButtonItem(title: "Open", primaryAction: UIAction { [weak self] _ in self?.open() }) + let open = UIBarButtonItem( + title: editingNotebook == nil ? "Open" : "Update", + primaryAction: UIAction { [weak self] _ in self?.open() }) open.style = .done open.isEnabled = false navigationItem.rightBarButtonItem = open @@ -192,6 +202,19 @@ final class ShareViewController: UITableViewController { if listing == nil { empty.text = "Can’t Read Folder" empty.secondaryText = "Check that this account can open it." + if !self.path.isEmpty { + var button = UIButton.Configuration.bordered() + button.title = "Browse “\(self.server.share)”" + empty.button = button + empty.buttonProperties.primaryAction = UIAction { [weak self] _ in + guard let self else { return } + let root = ShareViewController( + share: self.share, server: self.server, path: "", editing: self.editingNotebook) + root.onOpen = self.onOpen + root.onUpdate = self.onUpdate + self.navigationController?.pushViewController(root, animated: true) + } + } } else { empty.text = "No Folders" empty.secondaryText = "OneNote notebooks are folders with sections in them." @@ -202,10 +225,32 @@ final class ShareViewController: UITableViewController { } private func open() { + guard !updating else { return } var server = server server.root = path - let name = path.split(separator: "/").last.map(String.init) ?? server.share - onOpen?(Notebook(name: name, source: .server(server))) + guard let notebook = editingNotebook else { + onOpen?(Notebook(name: server.folderName, source: .server(server))) + return + } + updating = true + navigationItem.rightBarButtonItem?.isEnabled = false + navigationItem.hidesBackButton = true + navigationController?.isModalInPresentation = true + let spinner = UIActivityIndicatorView(style: .medium) + spinner.startAnimating() + navigationItem.titleView = spinner + notebook.relocate(to: server) { [weak self] problem, restore in + guard let self else { return } + updating = false + navigationItem.rightBarButtonItem?.isEnabled = true + navigationItem.hidesBackButton = false + navigationController?.isModalInPresentation = false + navigationItem.titleView = nil + if let problem { + return alert("Can’t Update Server", problem) + } + onUpdate?(restore) + } } override func numberOfSections(in tableView: UITableView) -> Int { 2 } @@ -245,8 +290,9 @@ final class ShareViewController: UITableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let folder = listing?.folders[indexPath.row] else { return } let child = ShareViewController( - share: share, server: server, path: path.isEmpty ? folder : "\(path)/\(folder)") + share: share, server: server, path: path.isEmpty ? folder : "\(path)/\(folder)", editing: editingNotebook) child.onOpen = onOpen + child.onUpdate = onUpdate navigationController?.pushViewController(child, animated: true) } } diff --git a/apps/ios/Snowbound/Sync.swift b/apps/ios/Snowbound/Sync.swift index ccb85365f51d09e0d9cfa3a999524c8cc6222831..452be713160765bd5e0781d9263b5dade1fa203a 100644 --- a/apps/ios/Snowbound/Sync.swift +++ b/apps/ios/Snowbound/Sync.swift @@ -237,10 +237,17 @@ final class SyncViewController: UITableViewController { } } + private func isServer(_ notebook: Notebook) -> Bool { + if case .server = notebook.source { return true } + return false + } + override func numberOfSections(in tableView: UITableView) -> Int { 1 + notebooks.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - section == 0 ? 2 : notebooks[section - 1].1.count + guard section > 0 else { return 2 } + let (notebook, sections) = notebooks[section - 1] + return sections.count + (isServer(notebook) ? 1 : 0) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { @@ -279,6 +286,15 @@ final class SyncViewController: UITableViewController { return cell } let (notebook, sections) = notebooks[indexPath.section - 1] + if indexPath.row == sections.count { + var content = UIListContentConfiguration.cell() + content.text = "Change Server Address" + content.image = UIImage(systemName: "server.rack") + content.textProperties.color = .tintColor + cell.selectionStyle = .default + cell.contentConfiguration = content + return cell + } let sync = sections[indexPath.row] var content = UIListContentConfiguration.valueCell() let tab = notebook.tabs.first { $0.path == sync.path } @@ -301,8 +317,21 @@ final class SyncViewController: UITableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) - guard indexPath == IndexPath(row: 1, section: 0) else { return } - Sync.now() - refresh() + if indexPath == IndexPath(row: 1, section: 0) { + Sync.now() + refresh() + return + } + guard indexPath.section > 0 else { return } + let (notebook, sections) = notebooks[indexPath.section - 1] + guard indexPath.row == sections.count, isServer(notebook) else { return } + let server = ServerViewController(editing: notebook) + server.onUpdate = { [weak self] restore in + self?.dismiss(animated: true) { + self?.refresh() + restore() + } + } + present(UINavigationController(rootViewController: server), animated: true) } } diff --git a/crates/mobile/include/snowbound.h b/crates/mobile/include/snowbound.h index 8cff4b8473ca1b3386d64866d89d8c9a79ce5091..22edea8b716df857b851d53406ae0e6186889eac 100644 --- a/crates/mobile/include/snowbound.h +++ b/crates/mobile/include/snowbound.h @@ -66,6 +66,8 @@ char *sb_library_live_status(const Library *library); bool sb_notebook_create(const char *path, const char *cache, const char *author, const char *date, const char *time, char **error); bool sb_notebook_moved(const char *cache, const char *from, const char *to, char **error); +bool sb_server_moved(const char *cache, const char *from_address, const char *from_share, const char *from_root, + const char *to_address, const char *to_share, const char *to_root, char **error); char *sb_library_sections(const Library *library); int32_t sb_library_color(const Library *library); char *sb_library_new_section(const Library *library, const char *folder, const char *name, const char *author, @@ -86,6 +88,7 @@ void sb_library_touched(const Library *library, const char *path); void sb_library_sync_now(const Library *library); // Publishes, keeping offline copies; sb_library_close is Close Notebook and deletes them. bool sb_library_flush(const Library *library, double seconds, char **error); +bool sb_library_stop(const Library *library, char **error); bool sb_library_close(const Library *library, double seconds, char **error); void sb_library_free(const Library *library); diff --git a/crates/mobile/src/library.rs b/crates/mobile/src/library.rs index 841569ef9c2acdc5132b35accb72698237abeacd..900a31658014babc7e887cc339f5c6eb02a475e7 100644 --- a/crates/mobile/src/library.rs +++ b/crates/mobile/src/library.rs @@ -376,6 +376,8 @@ pub struct Library { open: Mutex)>>, /// Work Offline, which sections opened later follow too. offline: AtomicBool, + /// Set by `Library::stop` before relocating, so any in-flight `Section::flush` exits promptly. + stopping: AtomicBool, /// Keys of the protected sections unlocked this run, by catalog path; in memory only. keys: Mutex>, /// A file provider keeps the notebook elsewhere too, as iCloud Drive does: edits wait for a @@ -502,6 +504,7 @@ impl Library { background, open: Mutex::default(), offline: AtomicBool::new(false), + stopping: AtomicBool::new(false), keys: Default::default(), elsewhere: !local, }) @@ -525,6 +528,7 @@ impl Library { background: Some(background), open: Mutex::default(), offline: AtomicBool::new(false), + stopping: AtomicBool::new(false), keys: Default::default(), elsewhere: false, }; @@ -584,6 +588,7 @@ impl Library { background: Some(background), open: Mutex::default(), offline: AtomicBool::new(offline), + stopping: AtomicBool::new(false), keys: Default::default(), elsewhere: false, }) @@ -621,6 +626,7 @@ impl Library { background, open: Mutex::default(), offline: AtomicBool::new(false), + stopping: AtomicBool::new(false), keys: Default::default(), elsewhere: !local, }) @@ -662,11 +668,7 @@ impl Library { let Place::Share { server, root, .. } = &self.place else { return None; }; - let name: String = format!("{}/{}/{root}", server.address, server.share) - .chars() - .map(|char| if char.is_alphanumeric() { char } else { '_' }) - .collect(); - Some(self.cache.join("smb").join(format!("{name}.json"))) + Some(smb_listing(&self.cache, &server.address, &server.share, root)) } fn listed(&self) -> Option { @@ -1312,6 +1314,9 @@ impl Section { } let deadline = Instant::now() + limit; loop { + if self.library.stopping.load(Ordering::Acquire) { + return false; + } match section.pending() { Ok(pending) if pending.is_empty() => return true, Ok(_) if Instant::now() < deadline => { @@ -1483,6 +1488,24 @@ impl Library { Ok(()) } + /// Makes every open section's submitted edits locally durable, then stops the background + /// sync thread without discarding replicas or queued edits, so the notebook's cache can be + /// relocated to a new URL. + pub(crate) fn stop(&self) -> Result<()> { + self.stopping.store(true, Ordering::Release); + for (_, shared) in self.open_sections() { + shared.section.set_offline(true); + shared + .section + .written() + .map_err(|_| "Some changes couldn’t be saved to this device.")?; + } + if let Some(background) = &self.background { + background.stop(); + } + Ok(()) + } + /// Publishes every edit the notebook's replicas hold within `limit`, keeping them and the /// offline copies. pub(crate) fn flush(&self, limit: Duration) -> Result<()> { @@ -2104,6 +2127,68 @@ pub unsafe extern "C" fn sb_notebook_moved( moved().map_err(|cause| failed(cause, error)).is_ok() } +/// Moves the replicas and cached section listing of an SMB notebook from one server location +/// to another, keeping all offline copies and queued edits so they publish to the new URL. +/// Call after stopping the old library and closing its open sections. False, with `error` +/// set, when the replicas cannot be moved (for instance if the new URL already holds +/// conflicting unsaved edits). +/// +/// # Safety +/// Every string is NUL-terminated UTF-8; `error` is null or a place for a string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn sb_server_moved( + cache: *const c_char, + from_address: *const c_char, + from_share: *const c_char, + from_root: *const c_char, + to_address: *const c_char, + to_share: *const c_char, + to_root: *const c_char, + error: *mut *mut c_char, +) -> bool { + server_moved( + Path::new(&string(cache)), + &string(from_address), + &string(from_share), + &string(from_root), + &string(to_address), + &string(to_share), + &string(to_root), + ) + .map_err(|cause| failed(cause, error)) + .is_ok() +} + +pub(crate) fn server_moved( + cache: &Path, + from_address: &str, + from_share: &str, + from_root: &str, + to_address: &str, + to_share: &str, + to_root: &str, +) -> Result<()> { + let from_address = normalize_address(from_address.to_owned()); + let to_address = normalize_address(to_address.to_owned()); + let from_location = notebook::location::smb(&from_address, from_share, from_root); + let to_location = notebook::location::smb(&to_address, to_share, to_root); + notebook::location::relocate( + cache, + &from_location, + &to_location, + TIMEOUT + Duration::from_secs(5), + )?; + let from_listing = smb_listing(cache, &from_address, from_share, from_root); + let to_listing = smb_listing(cache, &to_address, to_share, to_root); + if from_listing != to_listing && from_listing.exists() { + if let Some(parent) = to_listing.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::rename(&from_listing, &to_listing)?; + } + Ok(()) +} + /// The notebook's sections read again, as JSON: each with `name`, `path`, `group`, /// `color` as sRGB bytes, `readable`, `downloading` and `problem`, in the notebook's order; null /// if it cannot be read. @@ -2380,6 +2465,19 @@ pub unsafe extern "C" fn sb_library_flush( .is_ok() } +/// Ensures open sections' edits are durable on disk and stops the background sync thread +/// without discarding replicas or queued edits, before relocating a notebook (`sb_server_moved`). +/// +/// # Safety +/// `error` is null or a place for a string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn sb_library_stop(library: &Library, error: *mut *mut c_char) -> bool { + library + .stop() + .map_err(|cause| failed(cause, error)) + .is_ok() +} + /// The notebook folder whose document is `root`, or with `folder` false the lone section /// `root` names, as the provider `sb_set_provider` registered keeps it; `local` as /// `sb_library_open` takes it, and `device` naming this device on the conflict pages its own @@ -2438,6 +2536,26 @@ pub unsafe extern "C" fn sb_share_connect( boxed(server.connect().map_err(Into::into).map(Share), error) } +fn normalize_address(mut address: String) -> String { + let has_port = if address.starts_with('[') { + address.contains("]:") + } else { + address.contains(':') + }; + if !has_port { + address.push_str(":445"); + } + address +} + +fn smb_listing(cache: &Path, address: &str, share: &str, root: &str) -> PathBuf { + let name: String = format!("{address}/{share}/{root}") + .chars() + .map(|char| if char.is_alphanumeric() { char } else { '_' }) + .collect(); + cache.join("smb").join(format!("{name}.json")) +} + fn server( address: *const c_char, share: *const c_char, @@ -2445,12 +2563,8 @@ fn server( password: *const c_char, domain: *const c_char, ) -> Server { - let mut address = string(address); - if !address.contains(':') { - address.push_str(":445"); - } Server { - address, + address: normalize_address(string(address)), share: string(share), user: string(user), password: string(password), @@ -2901,4 +3015,149 @@ mod tests { ); assert_eq!(copy.shared.section.pending().unwrap().len(), 1); } + + /// Changing an unreachable SMB share notebook's URL preserves its cached listing, + /// section replicas, copy-section replicas, and queued offline edits so they reopen and + /// sync under the new URL. + #[test] + fn relocating_an_offline_share_notebook_preserves_edits_and_listing() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().join("notebook"); + let cache = directory.path().join("cache"); + std::fs::create_dir(&root).unwrap(); + let bytes = onestore::create_section("Notes.one", "Original text", "Fixture").unwrap(); + for name in ["Notes.one", "Notes - Copy.one"] { + std::fs::write(root.join(name), &bytes).unwrap(); + } + let notebook = Notebook::open(&root, &cache).unwrap(); + let mut listed = Listed::default(); + tabs(notebook.catalog(), &HashMap::new(), &mut listed.tabs); + files(notebook.catalog(), &mut listed); + drop(notebook); + + let old_address = "127.0.0.1:9"; + let old_loc = notebook::location::smb(old_address, "oldshare", "OldFolder"); + for (path, identity) in &listed.files { + let copy = listed.copies.contains(path); + let location = session::replica_location(&old_loc, path, copy); + let replicas = notebook::location::claimed(&cache, &location).unwrap(); + Replica::create(replicas.join(format!("{identity}.sqlite")), &bytes).unwrap(); + } + let old_listing = smb_listing(&cache, old_address, "oldshare", "OldFolder"); + std::fs::create_dir_all(old_listing.parent().unwrap()).unwrap(); + std::fs::write(&old_listing, serde_json::to_vec(&listed).unwrap()).unwrap(); + + let library = Arc::new( + Library::server( + Server { + address: old_address.into(), + share: "oldshare".into(), + user: String::new(), + password: String::new(), + domain: String::new(), + }, + "OldFolder", + &cache, + ) + .unwrap(), + ); + sb_library_set_offline(&library, true); + + // Queue an offline edit in both the original section and the copy section. + let section = + Section::open(Arc::clone(&library), "Notes.one", "Fixture".into(), || {}).unwrap(); + let space = section.shared.section.pages().unwrap()[0].0; + section + .shared + .apply(Edit { + at: filetime(), + ops: vec![Op::Page { + space, + op: onestore::op::PageOp::Color(Some(0x0012_3456)), + }], + }) + .unwrap(); + let copy = Section::open( + Arc::clone(&library), + "Notes - Copy.one", + "Fixture".into(), + || {}, + ) + .unwrap(); + copy.shared + .apply(Edit { + at: filetime(), + ops: vec![Op::Page { + space, + op: onestore::op::PageOp::Color(Some(0x0065_4321)), + }], + }) + .unwrap(); + + // Stop the library (ensuring durability and joining background), then drop sections & library. + library.stop().unwrap(); + drop((section, copy, library)); + + // Relocate via server_moved to a new host (omitting :445 to test normalization), share, and root. + server_moved( + &cache, + old_address, + "oldshare", + "OldFolder", + "127.0.0.1", + "newshare", + "NewFolder", + ) + .unwrap(); + assert!(!old_listing.exists()); + assert!(smb_listing(&cache, "127.0.0.1:445", "newshare", "NewFolder").exists()); + + // Same-location relocate (with vs without explicit :445) is a clean no-op. + server_moved( + &cache, + "127.0.0.1", + "newshare", + "NewFolder", + "127.0.0.1:445", + "newshare", + "NewFolder", + ) + .unwrap(); + + // Reopen offline under the new URL: both sections and their queued edits survived. + let relocated = Arc::new( + Library::server( + Server { + address: "127.0.0.1:445".into(), + share: "newshare".into(), + user: String::new(), + password: String::new(), + domain: String::new(), + }, + "NewFolder", + &cache, + ) + .unwrap(), + ); + sb_library_set_offline(&relocated, true); + let original = + Section::open(Arc::clone(&relocated), "Notes.one", "Fixture".into(), || {}).unwrap(); + assert_eq!( + original.shared.section.page(space).unwrap().color, + Some(0x0012_3456) + ); + assert_eq!(original.shared.section.pending().unwrap().len(), 1); + let relocated_copy = Section::open( + Arc::clone(&relocated), + "Notes - Copy.one", + "Fixture".into(), + || {}, + ) + .unwrap(); + assert_eq!( + relocated_copy.shared.section.page(space).unwrap().color, + Some(0x0065_4321) + ); + assert_eq!(relocated_copy.shared.section.pending().unwrap().len(), 1); + } } diff --git a/crates/notebook/src/location.rs b/crates/notebook/src/location.rs index 2d1ddbf34728736772c5e525e45526ab13857244..1405da68c2a97668b9d3fb892dc9792cbada7f24 100644 --- a/crates/notebook/src/location.rs +++ b/crates/notebook/src/location.rs @@ -11,7 +11,9 @@ use onestore::{Header, Stamp}; use std::{ io, path::{Path, PathBuf}, + time::Duration, }; +use web_time::Instant; /// The file in a replica folder naming the location its replicas belong to. const LOCATION: &str = "location"; @@ -46,6 +48,9 @@ pub fn smb(address: &str, share: &str, root: &str) -> String { /// location within it, as a copy of a section keeps its own. Each replica `to` already holds /// for the same section stays. Every replica moved must be closed. pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> { + if from == to { + return Ok(()); + } let inner = within(cache, from); move_folder(cache, from, to)?; for (_, location) in inner { @@ -58,6 +63,146 @@ pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> { Ok(()) } +/// Moves a notebook's replicas (and its copy-section replicas and discovery listing) from +/// `from` to `to`, waiting up to `wait` for any closing section worker to release its cache. +/// If `to` already holds a replica for the same section with no queued edits while `from` +/// has queued edits, `from`'s replica replaces it so local changes survive; if both hold +/// queued edits, returns `AlreadyExists` without moving anything. +pub fn relocate(cache: &Path, from: &str, to: &str, wait: Duration) -> io::Result<()> { + if from == to { + return Ok(()); + } + let deadline = Instant::now() + wait; + let mut locations = vec![(from.to_owned(), to.to_owned())]; + for (_, location) in within(cache, from) { + let target = format!("{to}{}", &location[from.len()..]); + locations.push((location, target)); + } + + enum Action { + Adopt(PathBuf, PathBuf), + Replace(PathBuf, PathBuf), + DropOld(PathBuf), + } + + struct FolderPlan { + old: PathBuf, + to: String, + actions: Vec, + } + + let mut plan = Vec::new(); + for (src, dst) in locations { + let old = folder(cache, &src); + if fs::metadata(&old).is_err() { + continue; + } + let new = folder(cache, &dst); + let mut actions = Vec::new(); + for entry in fs::read_dir(&old)? { + let name = entry?.file_name(); + if Path::new(&name).extension() != Some("sqlite".as_ref()) { + continue; + } + let old_file = old.join(&name); + let new_file = new.join(&name); + let old_queued = { + let connection = wait_closed(&old_file, deadline)?; + queued(&connection) + }; + if fs::metadata(&new_file).is_ok() { + let new_queued = { + let connection = wait_closed(&new_file, deadline)?; + queued(&connection) + }; + if old_queued > 0 && new_queued > 0 { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "The new location already has unsaved changes.", + )); + } + if old_queued > 0 { + actions.push(Action::Replace(old_file, new_file)); + } else { + actions.push(Action::DropOld(old_file)); + } + } else { + actions.push(Action::Adopt(old_file, new_file)); + } + } + plan.push(FolderPlan { + old, + to: dst, + actions, + }); + } + + for folder_plan in plan { + if folder_plan + .actions + .iter() + .any(|action| matches!(action, Action::Adopt(..) | Action::Replace(..))) + { + claimed(cache, &folder_plan.to)?; + } + for action in folder_plan.actions { + match action { + Action::Adopt(old_file, new_file) => adopt(&old_file, &new_file)?, + Action::Replace(old_file, new_file) => { + crate::remove_replica(&new_file)?; + adopt(&old_file, &new_file)?; + } + Action::DropOld(old_file) => crate::remove_replica(&old_file)?, + } + } + tidy(&folder_plan.old); + } + + let from_listing = crate::session::listing(cache, from); + let to_listing = crate::session::listing(cache, to); + if fs::metadata(&from_listing).is_ok() { + if fs::metadata(&to_listing).is_err() { + if let Some(parent) = to_listing.parent() { + fs::create_dir_all(parent)?; + } + fs::rename(&from_listing, &to_listing)?; + } else { + let _ = fs::remove_file(&from_listing); + } + } + Ok(()) +} + +/// Opens a closed replica, retrying while another holder releases it until `deadline`. +fn wait_closed(path: &Path, deadline: Instant) -> io::Result { + loop { + match crate::cache_connection(path) { + Ok(connection) => return Ok(connection), + Err(error) if error.busy() => { + if Instant::now() >= deadline { + return Err(io::Error::new( + io::ErrorKind::ResourceBusy, + "A section of this notebook is still busy; try again.", + )); + } + #[cfg(not(target_arch = "wasm32"))] + std::thread::sleep(Duration::from_millis(50)); + } + Err(error) => return Err(io::Error::other(error.to_string())), + } + } +} + +/// Number of queued edits in a closed replica; treats an unreadable schema conservatively as +/// non-empty so it is never discarded. +fn queued(connection: &rusqlite::Connection) -> u64 { + connection + .query_row("SELECT count(*) FROM edits", [], |row| row.get::<_, i64>(0)) + .ok() + .and_then(|count| u64::try_from(count).ok()) + .unwrap_or(1) +} + /// The folders of the locations within `location`, labelled, with their locations. fn within(cache: &Path, location: &str) -> Vec<(PathBuf, String)> { let within = format!("{location}/"); diff --git a/crates/notebook/tests/location.rs b/crates/notebook/tests/location.rs index 7e2fbc0cc51f0c7f9cfce51f2cfd0cc67c48a825..3926bd30bd70bb7425b6ea32e6dbb5ff70dfda43 100644 --- a/crates/notebook/tests/location.rs +++ b/crates/notebook/tests/location.rs @@ -366,3 +366,108 @@ fn forgetting_a_deleted_notebook_drops_its_replicas_and_queue_alone() { assert_eq!(published(&root, &cache), 0); assert_eq!(published(&other, &cache), 1); } + +#[test] +fn relocate_moves_queued_edits_replaces_clean_target_and_refuses_conflicting_queues() { + use notebook::Replica; + use onestore::op::{Edit, Op, PageOp}; + use std::time::Duration; + + let directory = tempfile::tempdir().unwrap(); + let cache = directory.path().join("cache"); + let bytes = onestore::create_section("Notes.one", "Original", "Fixture").unwrap(); + let other_bytes = onestore::create_section("Other.one", "Other", "Fixture").unwrap(); + let id_notes: String = onestore::Store::parse(&bytes) + .unwrap() + .header + .file_id + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + let id_other: String = onestore::Store::parse(&other_bytes) + .unwrap() + .header + .file_id + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + + let queue_edit = |path: &Path, source: &[u8], color: u32| { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let replica = Replica::create(path, source).unwrap(); + let space = replica.pages().unwrap()[0].0; + replica + .apply( + "Fixture", + Edit { + at: 134_000_000_000_000_000, + ops: vec![Op::Page { + space, + op: PageOp::Color(Some(color)), + }], + }, + ) + .unwrap(); + replica.written().unwrap(); + space + }; + + let from = notebook::location::smb("old:445", "share", "Notebook"); + let to = notebook::location::smb("new:445", "share", "Notebook"); + let from_copy = notebook::session::replica_location(&from, "Notes - Copy.one", true); + let to_copy = notebook::session::replica_location(&to, "Notes - Copy.one", true); + + let from_dir = notebook::location::claimed(&cache, &from).unwrap(); + let from_copy_dir = notebook::location::claimed(&cache, &from_copy).unwrap(); + let to_dir = notebook::location::claimed(&cache, &to).unwrap(); + + // Source has queued edits in Notes.one, Other.one, and a copy section. + let space = queue_edit(&from_dir.join(format!("{id_notes}.sqlite")), &bytes, 0x0011_2233); + queue_edit(&from_dir.join(format!("{id_other}.sqlite")), &other_bytes, 0x0022_3344); + let copy_space = queue_edit( + &from_copy_dir.join(format!("{id_notes}.sqlite")), + &bytes, + 0x0033_4455, + ); + + // Target ALSO has a queued edit in Notes.one -> relocate must refuse atomically. + queue_edit(&to_dir.join(format!("{id_notes}.sqlite")), &bytes, 0x00aa_bbcc); + let err = notebook::location::relocate(&cache, &from, &to, Duration::from_secs(2)).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists); + // Nothing moved, including the non-colliding Other.one and copy replica. + assert!(from_dir.join(format!("{id_notes}.sqlite")).exists()); + assert!(from_dir.join(format!("{id_other}.sqlite")).exists()); + assert!(from_copy_dir.join(format!("{id_notes}.sqlite")).exists()); + assert!(!to_dir.join(format!("{id_other}.sqlite")).exists()); + + // Replace target Notes.one with a clean replica (0 queued edits), as from an earlier + // read-only open of the new URL -> relocate must preserve source's queued edits. + std::fs::remove_file(to_dir.join(format!("{id_notes}.sqlite"))).unwrap(); + let clean = Replica::create(to_dir.join(format!("{id_notes}.sqlite")), &bytes).unwrap(); + drop(clean); + + // Also verify relocate waits cleanly for a replica released on another thread. + let held_path = from_dir.join(format!("{id_notes}.sqlite")); + let held = Replica::open(&held_path).unwrap(); + let releaser = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(120)); + drop(held); + }); + notebook::location::relocate(&cache, &from, &to, Duration::from_secs(5)).unwrap(); + releaser.join().unwrap(); + + // Same-location relocate is a clean no-op. + notebook::location::relocate(&cache, &to, &to, Duration::from_secs(1)).unwrap(); + + assert!(!from_dir.exists()); + assert!(!from_copy_dir.exists()); + let moved_notes = Replica::open(to_dir.join(format!("{id_notes}.sqlite"))).unwrap(); + assert_eq!(moved_notes.pending().unwrap().len(), 1); + assert_eq!(moved_notes.page(space).unwrap().color, Some(0x0011_2233)); + let moved_other = Replica::open(to_dir.join(format!("{id_other}.sqlite"))).unwrap(); + assert_eq!(moved_other.pending().unwrap().len(), 1); + let to_copy_dir = notebook::location::folder(&cache, &to_copy); + let moved_copy = Replica::open(to_copy_dir.join(format!("{id_notes}.sqlite"))).unwrap(); + assert_eq!(moved_copy.pending().unwrap().len(), 1); + assert_eq!(moved_copy.page(copy_space).unwrap().color, Some(0x0033_4455)); +}