authoravatarclover caruso<git@paperclover.net>2026-11-29 00:08:32-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-29 21:43:10-08:00
logc290c8e689023cd6ec7b18311c39a3b4caa4f17d
tree6409b646f69ba6f40159f943b401f6bbed1b84be
parentca7603e74bf287c2d05cb1f051d882098ab43795
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat(ios): change an SMB notebook's server address while keeping local edits


12 files changed, 1008 insertions(+), 76 deletions(-)

apps/ios/Snowbound/App.swift+51-3
......@@ -164,10 +164,15 @@ private struct Place: Codable {
164164/// Notebooks and sections, pages and a page, as Notes lays out folders, notes and a note:
165165/// side by side on a wide screen, a navigation stack on a phone.
166166final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewControllerDelegate {
167 private struct WeakPage { weak var value: PageViewController? }
168
167169 var window: UIWindow?
168170 private let split = RootViewController(style: .tripleColumn)
169171 private let notebooks = NotebooksViewController()
170172 private let pages = PagesViewController()
173 /// Live page controllers created by this scene, tracked directly so `close(_:)` can tear
174 /// them down even when UIKit's collapsed split view keeps them off `.secondary`.
175 private var openPages: [WeakPage] = []
171176 /// A first launch opened a page by itself.
172177 private var landed = false
173178 private var background = UIBackgroundTaskIdentifier.invalid
......@@ -292,6 +297,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro
292297
293298 func show(section: Section, page: String, reveal: Reveal? = nil, titleFocus: Bool = false, revealPage: Bool = true) {
294299 let controller = PageViewController(section: section, page: page, reveal: reveal, titleFocus: titleFocus)
300 openPages.removeAll { $0.value == nil }
301 openPages.append(WeakPage(value: controller))
295302 controller.onOpen = { [weak self, weak controller] id in
296303 guard let controller else { return }
297304 self?.show(section: section, page: id, revealPage: controller.viewIfLoaded?.window != nil)
......@@ -302,12 +309,53 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro
302309 Place.saved = Place(notebook: section.notebook.id, section: section.tab.path, page: page)
303310 }
304311
312 /// The section and page currently open for `notebook`, if any, to restore after relocating it.
313 func shown(of notebook: Notebook) -> (section: String, page: String?)? {
314 guard let section = pages.section, section.notebook === notebook else { return nil }
315 let page = Place.saved?.notebook == notebook.id ? Place.saved?.page : nil
316 return (section.tab.path, page)
317 }
318
319 /// Reopens a section and page previously returned by `shown(of:)` if still listed.
320 func reopen(_ shown: (section: String, page: String?), of notebook: Notebook) {
321 guard let tab = notebook.tabs.first(where: { $0.path == shown.section && $0.readable }) else { return }
322 open(tab, of: notebook, page: shown.page)
323 }
324
325 private func pageControllers(in controller: UIViewController?) -> [PageViewController] {
326 guard let controller else { return [] }
327 var found: [PageViewController] = []
328 if let page = controller as? PageViewController { found.append(page) }
329 if let nav = controller as? UINavigationController {
330 for child in nav.viewControllers { found += pageControllers(in: child) }
331 }
332 for child in controller.children { found += pageControllers(in: child) }
333 return found
334 }
335
305336 /// Returns to the list from any section of `notebook` shown, as before its folder moves.
306337 func close(_ notebook: Notebook) {
307 guard pages.section?.notebook === notebook else { return }
308 pages.clear()
338 openPages.removeAll { $0.value == nil }
339 let pagesMatched = pages.section?.notebook === notebook
340 var shownPages = openPages.compactMap(\.value).filter { $0.notebook === notebook }
341 for controller in pageControllers(in: split.viewController(for: .secondary))
342 + pageControllers(in: split.viewController(for: .compact))
343 + pageControllers(in: notebooks.navigationController)
344 where controller.notebook === notebook && !shownPages.contains(where: { $0 === controller })
345 {
346 shownPages.append(controller)
347 }
348 guard pagesMatched || !shownPages.isEmpty else { return }
349 for page in shownPages { page.tearDown() }
350 if pagesMatched { pages.clear() }
351 if split.isCollapsed && split.presentedViewController == nil {
352 (split.viewController(for: .compact) as? UINavigationController)?.popToRootViewController(animated: false)
353 notebooks.navigationController?.popToRootViewController(animated: false)
354 }
309355 split.setViewController(UIViewController(), for: .secondary)
310 split.show(.primary)
356 if split.presentedViewController == nil {
357 split.show(.primary)
358 }
311359 }
312360
313361 /// Lets go of the section shown where it is the section or group at `path` of `notebook`
apps/ios/Snowbound/Arranging.swift+7-4
......@@ -189,11 +189,14 @@ enum Arranging {
189189 _ pages: [(page: String, discard: String?)], from source: Section, to target: Section, order: [Placed],
190190 repairs: [(id: String, expected: Int, restore: Int)] = []
191191 ) {
192 guard !pages.isEmpty, let library = source.notebook.handle, let release = reserve() else { return }
192 guard !pages.isEmpty, let library = source.notebook.handle,
193 let sourceHandle = source.handle, let targetHandle = target.handle,
194 let release = reserve()
195 else { return }
193196 let before = source.rows.map { Placed(id: $0.id, level: $0.level) }
194197 let pointer = Int(bitPattern: library)
195 let sourcePointer = Int(bitPattern: source.handle)
196 let targetPointer = Int(bitPattern: target.handle)
198 let sourcePointer = Int(bitPattern: sourceHandle)
199 let targetPointer = Int(bitPattern: targetHandle)
197200 let author = Author.name ?? ""
198201 let (date, time) = titleDate()
199202 var undo: () -> Void = {}
......@@ -310,7 +313,7 @@ extension UIResponder {
310313extension Section {
311314 /// Puts page `id` where `order` places it, as one edit; false where it isn't listed.
312315 func arrange(_ order: [Placed], moving id: String) -> Bool {
313 guard sb_section_arrange(handle, json(order), json([id])) else { return false }
316 guard let handle, sb_section_arrange(handle, json(order), json([id])) else { return false }
314317 reloadRows()
315318 return true
316319 }
apps/ios/Snowbound/CanvasView.swift+32-5
......@@ -66,10 +66,23 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
6666 UIGestureRecognizerDelegate, UIEditMenuInteractionDelegate,
6767 UIPencilInteractionDelegate, UIScribbleInteractionDelegate
6868{
69 private struct WeakCanvas { weak var value: CanvasView? }
70 private static var active: [ObjectIdentifier: WeakCanvas] = [:]
71
72 /// Tears down every live canvas displaying a section of `notebook` so its Rust `View`
73 /// releases its section handle immediately.
74 static func tearDownAll(of notebook: Notebook) {
75 active = active.filter { $0.value.value != nil }
76 for entry in active.values {
77 guard let canvas = entry.value, canvas.section?.notebook === notebook else { continue }
78 canvas.tearDown()
79 }
80 }
81
6982 /// The zoom a page opens at once the reader has pinched one.
7083 private static let zoomKey = "zoom"
7184
72 private let section: Section
85 private var section: Section?
7386 private let page: String
7487 private let metal = MetalView()
7588 /// 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
118131 private var fingerDraws = false
119132 /// The section's tab colour as a COLORREF, which its pen gallery and shapes follow.
120133 private var sectionColor: UInt32 {
121 section.tab.color.enumerated().reduce(0) { $0 | UInt32($1.element) << (8 * UInt32($1.offset)) }
134 (section?.tab.color ?? []).enumerated().reduce(0) { $0 | UInt32($1.element) << (8 * UInt32($1.offset)) }
122135 }
123136 private lazy var picker = InkPicker(pens: Pen.gallery(sectionColor))
124137
......@@ -152,10 +165,11 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
152165 }
153166 }
154167
155 init(section: Section, page: String) {
168 init(section: Section?, page: String) {
156169 self.section = section
157170 self.page = page
158171 super.init(frame: .zero)
172 Self.active[ObjectIdentifier(self)] = WeakCanvas(value: self)
159173 backgroundColor = .systemBackground
160174 delegate = self
161175 minimumZoomScale = 0.25
......@@ -212,8 +226,20 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
212226 required init?(coder: NSCoder) { fatalError() }
213227
214228 deinit {
229 Self.active[ObjectIdentifier(self)] = nil
230 tearDown()
231 }
232
233 /// Stops the display link, frees the Rust view, and drops the section reference
234 /// immediately so the underlying replica can close even while UIKit keeps the view alive.
235 func tearDown() {
215236 link?.invalidate()
216 if let handle { sb_view_free(handle) }
237 link = nil
238 if let handle {
239 sb_view_free(handle)
240 self.handle = nil
241 }
242 section = nil
217243 }
218244
219245 // MARK: Drawing
......@@ -233,8 +259,9 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
233259 sb_view_resize(handle, Float(bounds.width), Float(bounds.height), Float(scale))
234260 if readingShown { reflowReading(readingWidth) } else { transform() }
235261 } else {
262 guard let section, let sectionHandle = section.handle else { return }
236263 handle = sb_view_new(
237 Unmanaged.passUnretained(metal.layer).toOpaque(), section.handle, page,
264 Unmanaged.passUnretained(metal.layer).toOpaque(), sectionHandle, page,
238265 Float(bounds.width), Float(bounds.height), Float(scale))
239266 guard let handle else { return }
240267 sb_view_focus(handle, false)
apps/ios/Snowbound/Lists.swift+19-1
......@@ -558,12 +558,19 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke
558558 }
559559 // A notebook On My iPhone is its folder there, handled as Files handles a folder.
560560 guard let folder = folder(of: notebook) else {
561 var extra: [UIMenuElement] = []
562 if case .server = notebook.source {
563 extra.append(
564 UIAction(title: "Change Server Address", image: UIImage(systemName: "server.rack")) { [weak self] _ in
565 self?.changeServer(of: notebook)
566 })
567 }
561568 let image = UIImage(systemName: "xmark.circle")
562569 let close = UIAction(title: "Close Notebook", image: image, attributes: .destructive) { [weak self] _ in
563570 Notebooks.remove(notebook)
564571 self?.reload()
565572 }
566 return UIMenu(children: status + actions + [close])
573 return UIMenu(children: status + actions + extra + [close])
567574 }
568575 let file = [
569576 UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in
......@@ -1030,6 +1037,17 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke
10301037 present(UINavigationController(rootViewController: server), animated: true)
10311038 }
10321039
1040 private func changeServer(of notebook: Notebook) {
1041 let server = ServerViewController(editing: notebook)
1042 server.onUpdate = { [weak self] restore in
1043 self?.dismiss(animated: true) {
1044 self?.reload()
1045 restore()
1046 }
1047 }
1048 present(UINavigationController(rootViewController: server), animated: true)
1049 }
1050
10331051 private func newSection(in notebook: Notebook) {
10341052 let alert = UIAlertController(title: "New Section", message: nil, preferredStyle: .alert)
10351053 alert.addTextField { field in
apps/ios/Snowbound/Notebooks.swift+252-16
......@@ -33,7 +33,9 @@ enum Author {
3333 set {
3434 UserDefaults.standard.set(newValue, forKey: key)
3535 // Open sections name it in their edits from now on.
36 for section in Section.all { sb_section_set_author(section.handle, newValue ?? "") }
36 for section in Section.all {
37 if let handle = section.handle { sb_section_set_author(handle, newValue ?? "") }
38 }
3739 }
3840 }
3941
......@@ -73,8 +75,92 @@ struct Server: Codable, Equatable {
7375 /// The notebook folder, `/`-separated from the share's top.
7476 var root: String
7577
76 var hostName: String { host.split(separator: ":").first.map(String.init) ?? host }
77 var port: Int { host.split(separator: ":").dropFirst().first.flatMap { Int($0) } ?? 445 }
78 var hostName: String {
79 if host.hasPrefix("["), let end = host.firstIndex(of: "]") {
80 return String(host[...end])
81 }
82 return host.split(separator: ":").first.map(String.init) ?? host
83 }
84
85 var port: Int {
86 if host.hasPrefix("["), let end = host.firstIndex(of: "]") {
87 let after = host[host.index(after: end)...]
88 return after.hasPrefix(":") ? Int(after.dropFirst()) ?? 445 : 445
89 }
90 return host.split(separator: ":").dropFirst().first.flatMap { Int($0) } ?? 445
91 }
92
93 /// `smb://host/share/root`, as shown in Sync Status and pre-filled when editing the address.
94 var url: String {
95 "smb://\(host)/\([share, root].filter { !$0.isEmpty }.joined(separator: "/"))"
96 }
97
98 /// The notebook's display name: its folder's name, or the share's when opened at the top.
99 var folderName: String {
100 root.split(separator: "/").last.map(String.init) ?? share
101 }
102
103 /// Normalized location matching `notebook::location::smb` after `:445` defaulting.
104 var canonicalLocation: String {
105 let hasPort = host.hasPrefix("[") ? host.contains("]:") : host.contains(":")
106 let address = hasPort ? host : "\(host):445"
107 let trimmed = root.replacingOccurrences(of: "\\", with: "/")
108 .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
109 return "smb://\(address)/\(share)/\(trimmed)"
110 }
111
112 /// Parses `smb://[user@]host[:port]/share[/folder]`, `\\host\share[\folder]`, or the same
113 /// without a scheme, preserving spaces and characters such as `#` in folder names.
114 static func parse(_ raw: String, registered: Bool, username: String) -> Server? {
115 let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
116 guard !trimmed.isEmpty else { return nil }
117 let rest: String
118 if let schemeEnd = trimmed.range(of: "://") {
119 guard trimmed[..<schemeEnd.lowerBound].lowercased() == "smb" else { return nil }
120 rest = String(trimmed[schemeEnd.upperBound...])
121 } else {
122 rest = String(trimmed.drop { $0 == "/" || $0 == "\\" })
123 }
124 let normalized = rest.replacingOccurrences(of: "\\", with: "/")
125 guard let slash = normalized.firstIndex(of: "/") else { return nil }
126 let authority = String(normalized[..<slash])
127 let path = String(normalized[normalized.index(after: slash)...])
128 let account: String
129 let host: String
130 if let at = authority.lastIndex(of: "@") {
131 account = String(authority[..<at])
132 host = String(authority[authority.index(after: at)...])
133 } else {
134 account = ""
135 host = authority
136 }
137 guard !host.isEmpty, host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil else { return nil }
138 if host.hasPrefix("[") {
139 guard let end = host.firstIndex(of: "]") else { return nil }
140 let after = host[host.index(after: end)...]
141 if !after.isEmpty {
142 guard after.hasPrefix(":"), let port = Int(after.dropFirst()), (1...65535).contains(port) else {
143 return nil
144 }
145 }
146 } else if let colon = host.firstIndex(of: ":") {
147 let portText = host[host.index(after: colon)...]
148 guard let port = Int(portText), (1...65535).contains(port) else { return nil }
149 }
150 let parts = path.split(separator: "/").map {
151 let part = String($0)
152 return part.removingPercentEncoding ?? part
153 }.filter { !$0.isEmpty }
154 guard let share = parts.first else { return nil }
155 let user: String
156 if !account.isEmpty {
157 let name = String(account.split(separator: ":", maxSplits: 1).first ?? "")
158 user = name.removingPercentEncoding ?? name
159 } else {
160 user = registered ? username : ""
161 }
162 return Server(host: host, share: share, user: user, root: parts.dropFirst().joined(separator: "/"))
163 }
78164}
79165
80166/// The password of an SMB account, kept in the Keychain as Files keeps a server's.
......@@ -185,7 +271,7 @@ let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .
185271final class Notebook {
186272 /// A UUID, or `Documents/` and the folder's name for a notebook On My iPhone.
187273 let id: String
188 let source: Source
274 private(set) var source: Source
189275 private(set) var name: String
190276 private(set) var handle: OpaquePointer?
191277 private(set) var tabs: [Tab] = []
......@@ -281,12 +367,126 @@ final class Notebook {
281367 case .files: "In Files"
282368 case .documents: "On My \(UIDevice.current.model), in Snowbound’s folder"
283369 case .icloud: "In iCloud Drive"
284 case .server(let server):
285 "smb://\(server.host)/\([server.share, server.root].filter { !$0.isEmpty }.joined(separator: "/"))"
370 case .server(let server): server.url
286371 case .path(let path): path
287372 }
288373 }
289374
375 /// Points a server notebook at `newServer`, moving its replicas and queued offline edits
376 /// so they sync to the new URL without losing changes. Calls `done` on the main thread
377 /// with an error message on failure (or `nil` on success) and a closure to restore any
378 /// previously open sections once any presenting modal sheet has dismissed.
379 func relocate(to newServer: Server, done: @escaping (String?, @escaping () -> Void) -> Void) {
380 guard case .server(let oldServer) = source else {
381 return done("Only server notebooks have an address to change.", {})
382 }
383 if Notebooks.all.contains(where: { other in
384 guard other !== self, case .server(let existing) = other.source else { return false }
385 return existing.canonicalLocation == newServer.canonicalLocation
386 }) {
387 return done(
388 "Another notebook in your list already uses this server address. Close it after its changes finish syncing, then try again.",
389 {})
390 }
391 guard let release = Arranging.reserve() else {
392 return done("Wait for the current action to finish, then try again.", {})
393 }
394 // Commit any active text composition before checking durability or closing sections.
395 NotificationCenter.default.post(name: PageViewController.leaving, object: nil)
396 let stopPointer = handle.map { Int(bitPattern: $0) }
397 background({ () -> String? in
398 guard let stopPointer, let library = OpaquePointer(bitPattern: stopPointer) else { return nil }
399 var error: UnsafeMutablePointer<CChar>?
400 let stopped = sb_library_stop(library, &error)
401 return stopped ? nil : (take(error) ?? "Couldn’t stop syncing this notebook.")
402 }) { [self] stopError in
403 if let stopError {
404 release()
405 return done(stopError, {})
406 }
407 var reopen: [(SceneDelegate, (section: String, page: String?))] = []
408 for scene in UIApplication.shared.connectedScenes {
409 guard let delegate = scene.delegate as? SceneDelegate else { continue }
410 if let shown = delegate.shown(of: self) {
411 reopen.append((delegate, shown))
412 }
413 delegate.close(self)
414 }
415 CanvasView.tearDownAll(of: self)
416 for section in Section.all where section.notebook === self {
417 section.close()
418 }
419 Section.releaseUnsaved(of: self)
420 recheck?.cancel()
421 recheck = nil
422 presenter?.stop()
423 presenter = nil
424 let detached = handle.map { Int(bitPattern: $0) }
425 handle = nil
426 let oldPassword = Keychain.password(oldServer) ?? ""
427 let newPassword = Keychain.password(newServer) ?? ""
428 background({ () -> (moved: Bool, library: Int, error: String?) in
429 if let detached, let oldLibrary = OpaquePointer(bitPattern: detached) {
430 sb_library_free(oldLibrary)
431 }
432 var error: UnsafeMutablePointer<CChar>?
433 let moved = sb_server_moved(
434 cacheDirectory.path,
435 oldServer.host, oldServer.share, oldServer.root,
436 newServer.host, newServer.share, newServer.root,
437 &error)
438 if !moved {
439 let moveError = take(error) ?? "Couldn’t move this notebook’s local changes."
440 var ignored: UnsafeMutablePointer<CChar>?
441 let restored = sb_library_server(
442 oldServer.host, oldServer.share, oldServer.user, oldPassword, "", oldServer.root,
443 cacheDirectory.path, &ignored)
444 _ = take(ignored)
445 return (false, Int(bitPattern: restored), moveError)
446 }
447 let library = sb_library_server(
448 newServer.host, newServer.share, newServer.user, newPassword, "", newServer.root,
449 cacheDirectory.path, &error)
450 return (true, Int(bitPattern: library), take(error))
451 }) { [self] result in
452 let library = OpaquePointer(bitPattern: result.library)
453 handle = library
454 let restore = { [weak self] in
455 guard let self else { return }
456 for (delegate, shown) in reopen { delegate.reopen(shown, of: self) }
457 }
458 if !result.moved {
459 problem = library == nil ? "The notebook can’t be read." : nil
460 follow()
461 reload {
462 NotificationCenter.default.post(name: Self.listed, object: self)
463 release()
464 done(result.error, restore)
465 }
466 return
467 }
468 source = .server(newServer)
469 name = newServer.folderName
470 Notebooks.save()
471 problem = library == nil ? (result.error ?? "The notebook can’t be read.") : nil
472 follow()
473 if let library, !Sync.offline {
474 sb_library_sync_now(library)
475 }
476 reload {
477 NotificationCenter.default.post(name: Self.listed, object: self)
478 NotificationCenter.default.post(name: Sync.changed, object: nil)
479 if let library {
480 let pointer = Int(bitPattern: library)
481 background({ sb_library_purge_recycle_bin(OpaquePointer(bitPattern: pointer)) }) { _ in }
482 }
483 release()
484 done(nil, restore)
485 }
486 }
487 }
488 }
489
290490 /// Unlocks the protected section at `path` with `password` off the main thread, then lists
291491 /// the sections again; `done` learns whether the password matched.
292492 func unlock(_ path: String, password: String, done: @escaping (Bool) -> Void) {
......@@ -598,7 +798,7 @@ enum Notebooks {
598798 save()
599799 }
600800
601 private static func save() {
801 static func save() {
602802 guard scripted == nil else { return }
603803 let entries = elsewhere.map { Entry(id: $0.id, name: $0.name, source: $0.source) }
604804 UserDefaults.standard.set(try? JSONEncoder().encode(entries), forKey: key)
......@@ -648,7 +848,7 @@ final class Section {
648848
649849 let notebook: Notebook
650850 let tab: Tab
651 let handle: OpaquePointer
851 private(set) var handle: OpaquePointer?
652852 private let token: Int
653853 private(set) var rows: [Row]
654854 private(set) var status = SaveStatus.unknown
......@@ -656,6 +856,12 @@ final class Section {
656856
657857 static var all: [Section] { open.values.compactMap(\.value) }
658858
859 /// Releases strong references held for Not Saving sections of `notebook` once their edits
860 /// are confirmed durable on disk, so their replicas can close and move.
861 static func releaseUnsaved(of notebook: Notebook) {
862 unsaved = unsaved.filter { $0.value.notebook !== notebook }
863 }
864
659865 private init(notebook: Notebook, tab: Tab, handle: OpaquePointer, token: Int, rows: [Row]) {
660866 self.notebook = notebook
661867 self.tab = tab
......@@ -664,9 +870,21 @@ final class Section {
664870 self.rows = rows
665871 }
666872
873 /// Explicitly frees the Rust section handle so its replica closes immediately without
874 /// waiting for UIKit or autorelease pools to release Swift references to `Section`.
875 func close() {
876 Self.open[token] = nil
877 Self.unsaved[token] = nil
878 listing = nil
879 if let handle {
880 self.handle = nil
881 sb_section_free(handle)
882 }
883 }
884
667885 deinit {
668886 Self.open[token] = nil
669 sb_section_free(handle)
887 if let handle { sb_section_free(handle) }
670888 }
671889
672890 /// Opens `tab` of `notebook` off the main thread, or hands back the section already open
......@@ -698,6 +916,7 @@ final class Section {
698916
699917 /// Lists the pages again and tells the views.
700918 func reloadRows() {
919 guard let handle else { return }
701920 listing?.invalidated = true
702921 rows = decode([Row].self, sb_section_pages(handle)) ?? rows
703922 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
......@@ -715,14 +934,22 @@ final class Section {
715934 }
716935
717936 private func readRows() {
718 background({ [self] in decode([Row].self, sb_section_pages(handle)) }) { [self] rows in
937 guard let handle else {
938 let completions = listing?.completions ?? []
939 listing = nil
940 for completion in completions { completion() }
941 return
942 }
943 let pointer = Int(bitPattern: handle)
944 background({ decode([Row].self, sb_section_pages(OpaquePointer(bitPattern: pointer))) }) { [self] rows in
945 guard let current = listing else { return }
719946 // A read begun before a reload or retitle would undo it.
720 if listing!.invalidated, rows != nil {
947 if current.invalidated, rows != nil {
721948 listing?.invalidated = false
722949 return readRows()
723950 }
724951 self.rows = rows ?? self.rows
725 let completions = listing!.completions
952 let completions = current.completions
726953 listing = nil
727954 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
728955 for completion in completions { completion() }
......@@ -739,6 +966,7 @@ final class Section {
739966 }
740967
741968 fileprivate func poll() {
969 guard let handle else { return }
742970 var status: UInt8 = 0
743971 let flags = sb_section_poll(handle, &status)
744972 let changed = SaveStatus(rawValue: status) ?? .unknown
......@@ -762,6 +990,7 @@ final class Section {
762990
763991 /// Adds a page, or a subpage of `parent`; returns its id.
764992 func newPage(under parent: String? = nil) -> String? {
993 guard let handle else { return nil }
765994 let (date, time) = titleDate()
766995 let id = take(sb_section_new_page(handle, parent, date, time))
767996 reloadRows()
......@@ -771,7 +1000,7 @@ final class Section {
7711000 /// Deletes pages, conflict pages for good and the rest to the recycle bin, which a toast
7721001 /// then offers.
7731002 func delete(_ ids: [String], done: @escaping () -> Void = {}) {
774 guard let release = Arranging.reserve() else { return }
1003 guard let handle, let release = Arranging.reserve() else { return }
7751004 let recycled = notebook.hasRecycleBin ? ids.filter { row(of: $0)?.version == nil }.count : 0
7761005 let (date, time) = titleDate()
7771006 let pointer = Int(bitPattern: handle)
......@@ -812,17 +1041,24 @@ final class Section {
8121041 let notebook: String?
8131042 }
8141043
815 func themes(of id: String) -> Themes? { decode(Themes.self, sb_section_themes(handle, id)) }
1044 func themes(of id: String) -> Themes? {
1045 handle.flatMap { decode(Themes.self, sb_section_themes($0, id)) }
1046 }
8161047
8171048 /// Gives `theme`, or none of its own, to page `id` (scope 0), its section (1) or its
8181049 /// notebook (2).
8191050 func setTheme(_ theme: String?, scope: UInt8, of id: String, done: @escaping (Bool) -> Void) {
1051 guard let handle else { return done(false) }
8201052 let pointer = Int(bitPattern: handle)
8211053 background({ sb_section_set_theme(OpaquePointer(bitPattern: pointer), id, scope, theme) }, done: done)
8221054 }
8231055
8241056 /// Stores every edit and publishes them within `seconds`; call off the main thread.
825 func flush(_ seconds: Double) -> Bool { sb_section_flush(handle, seconds) }
1057 func flush(_ seconds: Double) -> Bool {
1058 handle.map { sb_section_flush($0, seconds) } ?? true
1059 }
8261060
827 func wake() { sb_section_wake(handle) }
1061 func wake() {
1062 if let handle { sb_section_wake(handle) }
1063 }
8281064}
apps/ios/Snowbound/PageViewController.swift+23-10
......@@ -15,8 +15,9 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
1515 /// Posted when the app leaves the screen or quits: marked text is committed so it saves.
1616 static let leaving = Notification.Name("SnowboundLeaving")
1717
18 private let section: Section
18 private var section: Section?
1919 private let page: String
20 var notebook: Notebook? { section?.notebook }
2021 private let reveal: Reveal?
2122 private let titleFocus: Bool
2223 private lazy var canvas = CanvasView(section: section, page: page)
......@@ -57,6 +58,17 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
5758
5859 required init?(coder: NSCoder) { fatalError() }
5960
61 /// Releases the canvas view, display link, timers, and section reference immediately so
62 /// the underlying section replica can close without waiting on UIKit transition cleanup.
63 func tearDown() {
64 NotificationCenter.default.removeObserver(self)
65 mediaClock?.invalidate()
66 mediaClock = nil
67 onOpen = nil
68 if isViewLoaded { canvas.tearDown() }
69 section = nil
70 }
71
6072 override func loadView() {
6173 let view = UIView()
6274 view.backgroundColor = .systemBackground
......@@ -141,7 +153,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
141153 private func editingChanged() {
142154 if !canvas.readOnly, let title = canvas.pageTitle {
143155 showTitle(title)
144 section.retitle(page, title)
156 section?.retitle(page, title)
145157 }
146158 fitTitle()
147159 draw.isSelected = canvas.pickerShown
......@@ -167,7 +179,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
167179 return [readingAction()] + [
168180 themeMenu(),
169181 UIAction(title: "Tags Summary", image: UIImage(systemName: "tag")) { [weak self] _ in
170 guard let self else { return }
182 guard let self, let section else { return }
171183 scene?.showTags(of: section.notebook, from: self)
172184 },
173185 UIMenu(options: .displayInline, children: [
......@@ -184,7 +196,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
184196 },
185197 UIAction(title: "Delete Page", image: UIImage(systemName: "trash"), attributes: .destructive) {
186198 [weak self] _ in
187 guard let self else { return }
199 guard let self, let section else { return }
188200 section.delete([page])
189201 },
190202 ]),
......@@ -248,7 +260,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
248260 /// The page's theme, its section's and its notebook's, each pickable; the page wears a
249261 /// new one when it opens again.
250262 private func themeMenu() -> UIMenu {
251 guard let themes = section.themes(of: page) else {
263 guard let section, let themes = section.themes(of: page) else {
252264 return UIMenu(title: "Theme", image: UIImage(systemName: "textformat"), children: [])
253265 }
254266 let scopes: [(String, String?)] = [
......@@ -260,7 +272,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
260272 let choices = [(nil as String?, "None")] + themes.themes.map { ($0.id, $0.name) }
261273 return UIMenu(title: title, children: choices.map { id, name in
262274 UIAction(title: name, state: id == current ? .on : .off) { [weak self] _ in
263 guard let self else { return }
275 guard let self, let section = self.section else { return }
264276 section.setTheme(id, scope: UInt8(scope), of: page) { [weak self] _ in
265277 self?.onOpen?(page)
266278 }
......@@ -273,6 +285,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
273285 /// Prints the page through the system's print sheet, or with `export` offers its PDF in
274286 /// the share sheet, laid out as OneNote 2010 prints it on the region's paper.
275287 private func printPage(export: Bool) {
288 guard let section else { return }
276289 let letter = ["US", "CA", "MX", "PR", "PH", "CL", "CO", "VE", "GT", "CR", "PA", "DO", "SV", "NI", "HN", "BZ"]
277290 .contains(Locale.current.region?.identifier ?? "US")
278291 let paper = letter ? CGSize(width: 612, height: 792) : CGSize(width: 595.276, height: 841.89)
......@@ -415,7 +428,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
415428 canvas.reload(discard: false, pendingOnly: true)
416429 if notification.userInfo?["unchanged"] as? Bool == true { return }
417430 }
418 if flags & Section.listed != 0 {
431 if flags & Section.listed != 0, let section {
419432 if section.row(of: page) == nil {
420433 // Deleted elsewhere, or a conflict page resolved: back to what the section lists.
421434 if let first = section.rows.first { onOpen?(first.id) }
......@@ -429,7 +442,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
429442 /// Only trouble shows: saving goes on quietly, as Notes saves.
430443 private func showStatus() {
431444 let status: String? =
432 switch section.status {
445 switch section?.status {
433446 case .offline: "Offline"
434447 case .notSaving: "Not Saving"
435448 default: nil
......@@ -444,7 +457,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
444457 // MARK: Conflicts
445458
446459 private func conflictChanged() {
447 guard let (row, version) = section.row(of: page) else { return bar.show(nil) }
460 guard let section, let (row, version) = section.row(of: page) else { return bar.show(nil) }
448461 if version != nil {
449462 // Deleting a conflict page cannot be undone, so the button asks first.
450463 let delete = UIAction(
......@@ -462,7 +475,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
462475 }
463476
464477 private func conflictAction() {
465 guard let (row, version) = section.row(of: page) else { return }
478 guard let section, let (row, version) = section.row(of: page) else { return }
466479 if version != nil {
467480 section.delete([page]) { [weak self] in self?.onOpen?(row.id) }
468481 } else if let newest = row.versions.max(by: { ($0.created ?? 0) < ($1.created ?? 0) }) {
apps/ios/Snowbound/Server.swift+69-23
......@@ -1,20 +1,25 @@
11import UIKit
22
33/// Connect to Server, as Files and the Finder offer it: an `smb://` address, then a guest
4/// or an account whose password goes in the Keychain, then a folder to open.
4/// or an account whose password goes in the Keychain, then a folder to open — or, when
5/// `editing` a server notebook, a new address and folder to relocate it to while keeping
6/// its local changes.
57final class ServerViewController: UITableViewController, UITextFieldDelegate {
68 private static let lastKey = "server"
79
10 private let editingNotebook: Notebook?
811 private let address = UITextField()
912 private let name = UITextField()
1013 private let password = UITextField()
1114 private let guest = UISegmentedControl(items: ["Guest", "Registered User"])
1215 private var connecting = false
1316 var onOpen: ((Notebook) -> Void)?
17 var onUpdate: ((@escaping () -> Void) -> Void)?
1418
15 init() {
19 init(editing notebook: Notebook? = nil) {
20 self.editingNotebook = notebook
1621 super.init(style: .insetGrouped)
17 title = "Connect to Server"
22 title = notebook == nil ? "Connect to Server" : "Change Server Address"
1823 }
1924
2025 required init?(coder: NSCoder) { fatalError() }
......@@ -26,7 +31,6 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
2631 navigationItem.rightBarButtonItem = UIBarButtonItem(
2732 title: "Connect", primaryAction: UIAction { [weak self] _ in self?.connect() })
2833 address.placeholder = "smb://server/share"
29 address.text = UserDefaults.standard.string(forKey: Self.lastKey)
3034 address.keyboardType = .URL
3135 address.autocapitalizationType = .none
3236 address.autocorrectionType = .no
......@@ -42,7 +46,15 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
4246 field.delegate = self
4347 field.returnKeyType = field === password || field === address ? .go : .next
4448 }
45 guest.selectedSegmentIndex = 1
49 if case .server(let current) = editingNotebook?.source {
50 address.text = current.url
51 guest.selectedSegmentIndex = current.user.isEmpty ? 0 : 1
52 name.text = current.user
53 password.text = current.user.isEmpty ? nil : Keychain.password(current)
54 } else {
55 address.text = UserDefaults.standard.string(forKey: Self.lastKey)
56 guest.selectedSegmentIndex = 1
57 }
4658 guest.addAction(UIAction { [weak self] _ in self?.tableView.reloadData() }, for: .valueChanged)
4759 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "field")
4860 }
......@@ -65,17 +77,7 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
6577
6678 /// `smb://user@host:port/share/folder`, or the same without a scheme.
6779 private func server() -> Server? {
68 var text = address.text?.trimmingCharacters(in: .whitespaces) ?? ""
69 if !text.contains("://") { text = "smb://" + text }
70 guard let url = URLComponents(string: text), url.scheme?.lowercased() == "smb", let host = url.host,
71 !host.isEmpty
72 else { return nil }
73 let parts = url.path.split(separator: "/").map(String.init)
74 guard let share = parts.first else { return nil }
75 let user = url.user ?? (registered ? name.text ?? "" : "")
76 return Server(
77 host: url.port.map { "\(host):\($0)" } ?? host, share: share, user: user,
78 root: parts.dropFirst().joined(separator: "/"))
80 Server.parse(address.text ?? "", registered: registered, username: name.text ?? "")
7981 }
8082
8183 private func connect() {
......@@ -103,9 +105,11 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
103105 "Can’t Connect", "Check the address, name and password, and that the server is on this network.")
104106 }
105107 if registered { Keychain.save(secret, for: server) }
106 UserDefaults.standard.set(address.text, forKey: Self.lastKey)
107 let browser = ShareViewController(share: SharedConnection(share), server: server, path: server.root)
108 if editingNotebook == nil { UserDefaults.standard.set(address.text, forKey: Self.lastKey) }
109 let browser = ShareViewController(
110 share: SharedConnection(share), server: server, path: server.root, editing: editingNotebook)
108111 browser.onOpen = onOpen
112 browser.onUpdate = onUpdate
109113 navigationController?.pushViewController(browser, animated: true)
110114 }
111115 }
......@@ -157,13 +161,17 @@ final class ShareViewController: UITableViewController {
157161 private let share: SharedConnection
158162 private let server: Server
159163 private let path: String
164 private let editingNotebook: Notebook?
160165 private var listing: Listing?
166 private var updating = false
161167 var onOpen: ((Notebook) -> Void)?
168 var onUpdate: ((@escaping () -> Void) -> Void)?
162169
163 init(share: SharedConnection, server: Server, path: String) {
170 init(share: SharedConnection, server: Server, path: String, editing notebook: Notebook? = nil) {
164171 self.share = share
165172 self.server = server
166173 self.path = path
174 self.editingNotebook = notebook
167175 super.init(style: .insetGrouped)
168176 title = path.split(separator: "/").last.map(String.init) ?? server.share
169177 }
......@@ -173,7 +181,9 @@ final class ShareViewController: UITableViewController {
173181 override func viewDidLoad() {
174182 super.viewDidLoad()
175183 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "entry")
176 let open = UIBarButtonItem(title: "Open", primaryAction: UIAction { [weak self] _ in self?.open() })
184 let open = UIBarButtonItem(
185 title: editingNotebook == nil ? "Open" : "Update",
186 primaryAction: UIAction { [weak self] _ in self?.open() })
177187 open.style = .done
178188 open.isEnabled = false
179189 navigationItem.rightBarButtonItem = open
......@@ -192,6 +202,19 @@ final class ShareViewController: UITableViewController {
192202 if listing == nil {
193203 empty.text = "Can’t Read Folder"
194204 empty.secondaryText = "Check that this account can open it."
205 if !self.path.isEmpty {
206 var button = UIButton.Configuration.bordered()
207 button.title = "Browse “\(self.server.share)”"
208 empty.button = button
209 empty.buttonProperties.primaryAction = UIAction { [weak self] _ in
210 guard let self else { return }
211 let root = ShareViewController(
212 share: self.share, server: self.server, path: "", editing: self.editingNotebook)
213 root.onOpen = self.onOpen
214 root.onUpdate = self.onUpdate
215 self.navigationController?.pushViewController(root, animated: true)
216 }
217 }
195218 } else {
196219 empty.text = "No Folders"
197220 empty.secondaryText = "OneNote notebooks are folders with sections in them."
......@@ -202,10 +225,32 @@ final class ShareViewController: UITableViewController {
202225 }
203226
204227 private func open() {
228 guard !updating else { return }
205229 var server = server
206230 server.root = path
207 let name = path.split(separator: "/").last.map(String.init) ?? server.share
208 onOpen?(Notebook(name: name, source: .server(server)))
231 guard let notebook = editingNotebook else {
232 onOpen?(Notebook(name: server.folderName, source: .server(server)))
233 return
234 }
235 updating = true
236 navigationItem.rightBarButtonItem?.isEnabled = false
237 navigationItem.hidesBackButton = true
238 navigationController?.isModalInPresentation = true
239 let spinner = UIActivityIndicatorView(style: .medium)
240 spinner.startAnimating()
241 navigationItem.titleView = spinner
242 notebook.relocate(to: server) { [weak self] problem, restore in
243 guard let self else { return }
244 updating = false
245 navigationItem.rightBarButtonItem?.isEnabled = true
246 navigationItem.hidesBackButton = false
247 navigationController?.isModalInPresentation = false
248 navigationItem.titleView = nil
249 if let problem {
250 return alert("Can’t Update Server", problem)
251 }
252 onUpdate?(restore)
253 }
209254 }
210255
211256 override func numberOfSections(in tableView: UITableView) -> Int { 2 }
......@@ -245,8 +290,9 @@ final class ShareViewController: UITableViewController {
245290 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
246291 guard let folder = listing?.folders[indexPath.row] else { return }
247292 let child = ShareViewController(
248 share: share, server: server, path: path.isEmpty ? folder : "\(path)/\(folder)")
293 share: share, server: server, path: path.isEmpty ? folder : "\(path)/\(folder)", editing: editingNotebook)
249294 child.onOpen = onOpen
295 child.onUpdate = onUpdate
250296 navigationController?.pushViewController(child, animated: true)
251297 }
252298}
apps/ios/Snowbound/Sync.swift+33-4
......@@ -237,10 +237,17 @@ final class SyncViewController: UITableViewController {
237237 }
238238 }
239239
240 private func isServer(_ notebook: Notebook) -> Bool {
241 if case .server = notebook.source { return true }
242 return false
243 }
244
240245 override func numberOfSections(in tableView: UITableView) -> Int { 1 + notebooks.count }
241246
242247 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
243 section == 0 ? 2 : notebooks[section - 1].1.count
248 guard section > 0 else { return 2 }
249 let (notebook, sections) = notebooks[section - 1]
250 return sections.count + (isServer(notebook) ? 1 : 0)
244251 }
245252
246253 override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
......@@ -279,6 +286,15 @@ final class SyncViewController: UITableViewController {
279286 return cell
280287 }
281288 let (notebook, sections) = notebooks[indexPath.section - 1]
289 if indexPath.row == sections.count {
290 var content = UIListContentConfiguration.cell()
291 content.text = "Change Server Address"
292 content.image = UIImage(systemName: "server.rack")
293 content.textProperties.color = .tintColor
294 cell.selectionStyle = .default
295 cell.contentConfiguration = content
296 return cell
297 }
282298 let sync = sections[indexPath.row]
283299 var content = UIListContentConfiguration.valueCell()
284300 let tab = notebook.tabs.first { $0.path == sync.path }
......@@ -301,8 +317,21 @@ final class SyncViewController: UITableViewController {
301317
302318 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
303319 tableView.deselectRow(at: indexPath, animated: true)
304 guard indexPath == IndexPath(row: 1, section: 0) else { return }
305 Sync.now()
306 refresh()
320 if indexPath == IndexPath(row: 1, section: 0) {
321 Sync.now()
322 refresh()
323 return
324 }
325 guard indexPath.section > 0 else { return }
326 let (notebook, sections) = notebooks[indexPath.section - 1]
327 guard indexPath.row == sections.count, isServer(notebook) else { return }
328 let server = ServerViewController(editing: notebook)
329 server.onUpdate = { [weak self] restore in
330 self?.dismiss(animated: true) {
331 self?.refresh()
332 restore()
333 }
334 }
335 present(UINavigationController(rootViewController: server), animated: true)
307336 }
308337}
crates/mobile/include/snowbound.h+3
......@@ -66,6 +66,8 @@ char *sb_library_live_status(const Library *library);
6666bool sb_notebook_create(const char *path, const char *cache, const char *author, const char *date, const char *time,
6767 char **error);
6868bool sb_notebook_moved(const char *cache, const char *from, const char *to, char **error);
69bool sb_server_moved(const char *cache, const char *from_address, const char *from_share, const char *from_root,
70 const char *to_address, const char *to_share, const char *to_root, char **error);
6971char *sb_library_sections(const Library *library);
7072int32_t sb_library_color(const Library *library);
7173char *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);
8688void sb_library_sync_now(const Library *library);
8789// Publishes, keeping offline copies; sb_library_close is Close Notebook and deletes them.
8890bool sb_library_flush(const Library *library, double seconds, char **error);
91bool sb_library_stop(const Library *library, char **error);
8992bool sb_library_close(const Library *library, double seconds, char **error);
9093void sb_library_free(const Library *library);
9194
crates/mobile/src/library.rs+269-10
......@@ -376,6 +376,8 @@ pub struct Library {
376376 open: Mutex<Vec<(String, Weak<Shared>)>>,
377377 /// Work Offline, which sections opened later follow too.
378378 offline: AtomicBool,
379 /// Set by `Library::stop` before relocating, so any in-flight `Section::flush` exits promptly.
380 stopping: AtomicBool,
379381 /// Keys of the protected sections unlocked this run, by catalog path; in memory only.
380382 keys: Mutex<HashMap<String, Key>>,
381383 /// A file provider keeps the notebook elsewhere too, as iCloud Drive does: edits wait for a
......@@ -502,6 +504,7 @@ impl Library {
502504 background,
503505 open: Mutex::default(),
504506 offline: AtomicBool::new(false),
507 stopping: AtomicBool::new(false),
505508 keys: Default::default(),
506509 elsewhere: !local,
507510 })
......@@ -525,6 +528,7 @@ impl Library {
525528 background: Some(background),
526529 open: Mutex::default(),
527530 offline: AtomicBool::new(false),
531 stopping: AtomicBool::new(false),
528532 keys: Default::default(),
529533 elsewhere: false,
530534 };
......@@ -584,6 +588,7 @@ impl Library {
584588 background: Some(background),
585589 open: Mutex::default(),
586590 offline: AtomicBool::new(offline),
591 stopping: AtomicBool::new(false),
587592 keys: Default::default(),
588593 elsewhere: false,
589594 })
......@@ -621,6 +626,7 @@ impl Library {
621626 background,
622627 open: Mutex::default(),
623628 offline: AtomicBool::new(false),
629 stopping: AtomicBool::new(false),
624630 keys: Default::default(),
625631 elsewhere: !local,
626632 })
......@@ -662,11 +668,7 @@ impl Library {
662668 let Place::Share { server, root, .. } = &self.place else {
663669 return None;
664670 };
665 let name: String = format!("{}/{}/{root}", server.address, server.share)
666 .chars()
667 .map(|char| if char.is_alphanumeric() { char } else { '_' })
668 .collect();
669 Some(self.cache.join("smb").join(format!("{name}.json")))
671 Some(smb_listing(&self.cache, &server.address, &server.share, root))
670672 }
671673
672674 fn listed(&self) -> Option<Listed> {
......@@ -1312,6 +1314,9 @@ impl Section {
13121314 }
13131315 let deadline = Instant::now() + limit;
13141316 loop {
1317 if self.library.stopping.load(Ordering::Acquire) {
1318 return false;
1319 }
13151320 match section.pending() {
13161321 Ok(pending) if pending.is_empty() => return true,
13171322 Ok(_) if Instant::now() < deadline => {
......@@ -1483,6 +1488,24 @@ impl Library {
14831488 Ok(())
14841489 }
14851490
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
14861509 /// Publishes every edit the notebook's replicas hold within `limit`, keeping them and the
14871510 /// offline copies.
14881511 pub(crate) fn flush(&self, limit: Duration) -> Result<()> {
......@@ -2104,6 +2127,68 @@ pub unsafe extern "C" fn sb_notebook_moved(
21042127 moved().map_err(|cause| failed(cause, error)).is_ok()
21052128}
21062129
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
21072192/// The notebook's sections read again, as JSON: each with `name`, `path`, `group`,
21082193/// `color` as sRGB bytes, `readable`, `downloading` and `problem`, in the notebook's order; null
21092194/// if it cannot be read.
......@@ -2380,6 +2465,19 @@ pub unsafe extern "C" fn sb_library_flush(
23802465 .is_ok()
23812466}
23822467
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
23832481/// The notebook folder whose document is `root`, or with `folder` false the lone section
23842482/// `root` names, as the provider `sb_set_provider` registered keeps it; `local` as
23852483/// `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(
24382536 boxed(server.connect().map_err(Into::into).map(Share), error)
24392537}
24402538
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
24412559fn server(
24422560 address: *const c_char,
24432561 share: *const c_char,
......@@ -2445,12 +2563,8 @@ fn server(
24452563 password: *const c_char,
24462564 domain: *const c_char,
24472565) -> Server {
2448 let mut address = string(address);
2449 if !address.contains(':') {
2450 address.push_str(":445");
2451 }
24522566 Server {
2453 address,
2567 address: normalize_address(string(address)),
24542568 share: string(share),
24552569 user: string(user),
24562570 password: string(password),
......@@ -2901,4 +3015,149 @@ mod tests {
29013015 );
29023016 assert_eq!(copy.shared.section.pending().unwrap().len(), 1);
29033017 }
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 }
29043163}
crates/notebook/src/location.rs+145
......@@ -11,7 +11,9 @@ use onestore::{Header, Stamp};
1111use std::{
1212 io,
1313 path::{Path, PathBuf},
14 time::Duration,
1415};
16use web_time::Instant;
1517
1618/// The file in a replica folder naming the location its replicas belong to.
1719const LOCATION: &str = "location";
......@@ -46,6 +48,9 @@ pub fn smb(address: &str, share: &str, root: &str) -> String {
4648/// location within it, as a copy of a section keeps its own. Each replica `to` already holds
4749/// for the same section stays. Every replica moved must be closed.
4850pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> {
51 if from == to {
52 return Ok(());
53 }
4954 let inner = within(cache, from);
5055 move_folder(cache, from, to)?;
5156 for (_, location) in inner {
......@@ -58,6 +63,146 @@ pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> {
5863 Ok(())
5964}
6065
66/// Moves a notebook's replicas (and its copy-section replicas and discovery listing) from
67/// `from` to `to`, waiting up to `wait` for any closing section worker to release its cache.
68/// If `to` already holds a replica for the same section with no queued edits while `from`
69/// has queued edits, `from`'s replica replaces it so local changes survive; if both hold
70/// queued edits, returns `AlreadyExists` without moving anything.
71pub fn relocate(cache: &Path, from: &str, to: &str, wait: Duration) -> io::Result<()> {
72 if from == to {
73 return Ok(());
74 }
75 let deadline = Instant::now() + wait;
76 let mut locations = vec![(from.to_owned(), to.to_owned())];
77 for (_, location) in within(cache, from) {
78 let target = format!("{to}{}", &location[from.len()..]);
79 locations.push((location, target));
80 }
81
82 enum Action {
83 Adopt(PathBuf, PathBuf),
84 Replace(PathBuf, PathBuf),
85 DropOld(PathBuf),
86 }
87
88 struct FolderPlan {
89 old: PathBuf,
90 to: String,
91 actions: Vec<Action>,
92 }
93
94 let mut plan = Vec::new();
95 for (src, dst) in locations {
96 let old = folder(cache, &src);
97 if fs::metadata(&old).is_err() {
98 continue;
99 }
100 let new = folder(cache, &dst);
101 let mut actions = Vec::new();
102 for entry in fs::read_dir(&old)? {
103 let name = entry?.file_name();
104 if Path::new(&name).extension() != Some("sqlite".as_ref()) {
105 continue;
106 }
107 let old_file = old.join(&name);
108 let new_file = new.join(&name);
109 let old_queued = {
110 let connection = wait_closed(&old_file, deadline)?;
111 queued(&connection)
112 };
113 if fs::metadata(&new_file).is_ok() {
114 let new_queued = {
115 let connection = wait_closed(&new_file, deadline)?;
116 queued(&connection)
117 };
118 if old_queued > 0 && new_queued > 0 {
119 return Err(io::Error::new(
120 io::ErrorKind::AlreadyExists,
121 "The new location already has unsaved changes.",
122 ));
123 }
124 if old_queued > 0 {
125 actions.push(Action::Replace(old_file, new_file));
126 } else {
127 actions.push(Action::DropOld(old_file));
128 }
129 } else {
130 actions.push(Action::Adopt(old_file, new_file));
131 }
132 }
133 plan.push(FolderPlan {
134 old,
135 to: dst,
136 actions,
137 });
138 }
139
140 for folder_plan in plan {
141 if folder_plan
142 .actions
143 .iter()
144 .any(|action| matches!(action, Action::Adopt(..) | Action::Replace(..)))
145 {
146 claimed(cache, &folder_plan.to)?;
147 }
148 for action in folder_plan.actions {
149 match action {
150 Action::Adopt(old_file, new_file) => adopt(&old_file, &new_file)?,
151 Action::Replace(old_file, new_file) => {
152 crate::remove_replica(&new_file)?;
153 adopt(&old_file, &new_file)?;
154 }
155 Action::DropOld(old_file) => crate::remove_replica(&old_file)?,
156 }
157 }
158 tidy(&folder_plan.old);
159 }
160
161 let from_listing = crate::session::listing(cache, from);
162 let to_listing = crate::session::listing(cache, to);
163 if fs::metadata(&from_listing).is_ok() {
164 if fs::metadata(&to_listing).is_err() {
165 if let Some(parent) = to_listing.parent() {
166 fs::create_dir_all(parent)?;
167 }
168 fs::rename(&from_listing, &to_listing)?;
169 } else {
170 let _ = fs::remove_file(&from_listing);
171 }
172 }
173 Ok(())
174}
175
176/// Opens a closed replica, retrying while another holder releases it until `deadline`.
177fn wait_closed(path: &Path, deadline: Instant) -> io::Result<rusqlite::Connection> {
178 loop {
179 match crate::cache_connection(path) {
180 Ok(connection) => return Ok(connection),
181 Err(error) if error.busy() => {
182 if Instant::now() >= deadline {
183 return Err(io::Error::new(
184 io::ErrorKind::ResourceBusy,
185 "A section of this notebook is still busy; try again.",
186 ));
187 }
188 #[cfg(not(target_arch = "wasm32"))]
189 std::thread::sleep(Duration::from_millis(50));
190 }
191 Err(error) => return Err(io::Error::other(error.to_string())),
192 }
193 }
194}
195
196/// Number of queued edits in a closed replica; treats an unreadable schema conservatively as
197/// non-empty so it is never discarded.
198fn queued(connection: &rusqlite::Connection) -> u64 {
199 connection
200 .query_row("SELECT count(*) FROM edits", [], |row| row.get::<_, i64>(0))
201 .ok()
202 .and_then(|count| u64::try_from(count).ok())
203 .unwrap_or(1)
204}
205
61206/// The folders of the locations within `location`, labelled, with their locations.
62207fn within(cache: &Path, location: &str) -> Vec<(PathBuf, String)> {
63208 let within = format!("{location}/");
crates/notebook/tests/location.rs+105
......@@ -366,3 +366,108 @@ fn forgetting_a_deleted_notebook_drops_its_replicas_and_queue_alone() {
366366 assert_eq!(published(&root, &cache), 0);
367367 assert_eq!(published(&other, &cache), 1);
368368}
369
370#[test]
371fn relocate_moves_queued_edits_replaces_clean_target_and_refuses_conflicting_queues() {
372 use notebook::Replica;
373 use onestore::op::{Edit, Op, PageOp};
374 use std::time::Duration;
375
376 let directory = tempfile::tempdir().unwrap();
377 let cache = directory.path().join("cache");
378 let bytes = onestore::create_section("Notes.one", "Original", "Fixture").unwrap();
379 let other_bytes = onestore::create_section("Other.one", "Other", "Fixture").unwrap();
380 let id_notes: String = onestore::Store::parse(&bytes)
381 .unwrap()
382 .header
383 .file_id
384 .iter()
385 .map(|b| format!("{b:02x}"))
386 .collect();
387 let id_other: String = onestore::Store::parse(&other_bytes)
388 .unwrap()
389 .header
390 .file_id
391 .iter()
392 .map(|b| format!("{b:02x}"))
393 .collect();
394
395 let queue_edit = |path: &Path, source: &[u8], color: u32| {
396 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
397 let replica = Replica::create(path, source).unwrap();
398 let space = replica.pages().unwrap()[0].0;
399 replica
400 .apply(
401 "Fixture",
402 Edit {
403 at: 134_000_000_000_000_000,
404 ops: vec![Op::Page {
405 space,
406 op: PageOp::Color(Some(color)),
407 }],
408 },
409 )
410 .unwrap();
411 replica.written().unwrap();
412 space
413 };
414
415 let from = notebook::location::smb("old:445", "share", "Notebook");
416 let to = notebook::location::smb("new:445", "share", "Notebook");
417 let from_copy = notebook::session::replica_location(&from, "Notes - Copy.one", true);
418 let to_copy = notebook::session::replica_location(&to, "Notes - Copy.one", true);
419
420 let from_dir = notebook::location::claimed(&cache, &from).unwrap();
421 let from_copy_dir = notebook::location::claimed(&cache, &from_copy).unwrap();
422 let to_dir = notebook::location::claimed(&cache, &to).unwrap();
423
424 // Source has queued edits in Notes.one, Other.one, and a copy section.
425 let space = queue_edit(&from_dir.join(format!("{id_notes}.sqlite")), &bytes, 0x0011_2233);
426 queue_edit(&from_dir.join(format!("{id_other}.sqlite")), &other_bytes, 0x0022_3344);
427 let copy_space = queue_edit(
428 &from_copy_dir.join(format!("{id_notes}.sqlite")),
429 &bytes,
430 0x0033_4455,
431 );
432
433 // Target ALSO has a queued edit in Notes.one -> relocate must refuse atomically.
434 queue_edit(&to_dir.join(format!("{id_notes}.sqlite")), &bytes, 0x00aa_bbcc);
435 let err = notebook::location::relocate(&cache, &from, &to, Duration::from_secs(2)).unwrap_err();
436 assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
437 // Nothing moved, including the non-colliding Other.one and copy replica.
438 assert!(from_dir.join(format!("{id_notes}.sqlite")).exists());
439 assert!(from_dir.join(format!("{id_other}.sqlite")).exists());
440 assert!(from_copy_dir.join(format!("{id_notes}.sqlite")).exists());
441 assert!(!to_dir.join(format!("{id_other}.sqlite")).exists());
442
443 // Replace target Notes.one with a clean replica (0 queued edits), as from an earlier
444 // read-only open of the new URL -> relocate must preserve source's queued edits.
445 std::fs::remove_file(to_dir.join(format!("{id_notes}.sqlite"))).unwrap();
446 let clean = Replica::create(to_dir.join(format!("{id_notes}.sqlite")), &bytes).unwrap();
447 drop(clean);
448
449 // Also verify relocate waits cleanly for a replica released on another thread.
450 let held_path = from_dir.join(format!("{id_notes}.sqlite"));
451 let held = Replica::open(&held_path).unwrap();
452 let releaser = std::thread::spawn(move || {
453 std::thread::sleep(Duration::from_millis(120));
454 drop(held);
455 });
456 notebook::location::relocate(&cache, &from, &to, Duration::from_secs(5)).unwrap();
457 releaser.join().unwrap();
458
459 // Same-location relocate is a clean no-op.
460 notebook::location::relocate(&cache, &to, &to, Duration::from_secs(1)).unwrap();
461
462 assert!(!from_dir.exists());
463 assert!(!from_copy_dir.exists());
464 let moved_notes = Replica::open(to_dir.join(format!("{id_notes}.sqlite"))).unwrap();
465 assert_eq!(moved_notes.pending().unwrap().len(), 1);
466 assert_eq!(moved_notes.page(space).unwrap().color, Some(0x0011_2233));
467 let moved_other = Replica::open(to_dir.join(format!("{id_other}.sqlite"))).unwrap();
468 assert_eq!(moved_other.pending().unwrap().len(), 1);
469 let to_copy_dir = notebook::location::folder(&cache, &to_copy);
470 let moved_copy = Replica::open(to_copy_dir.join(format!("{id_notes}.sqlite"))).unwrap();
471 assert_eq!(moved_copy.pending().unwrap().len(), 1);
472 assert_eq!(moved_copy.page(copy_space).unwrap().color, Some(0x0033_4455));
473}