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 {...@@ -164,10 +164,15 @@ private struct Place: Codable {
164/// Notebooks and sections, pages and a page, as Notes lays out folders, notes and a note:164/// Notebooks and sections, pages and a page, as Notes lays out folders, notes and a note:
165/// side by side on a wide screen, a navigation stack on a phone.165/// side by side on a wide screen, a navigation stack on a phone.
166final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewControllerDelegate {166final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewControllerDelegate {
167 private struct WeakPage { weak var value: PageViewController? }
168
167 var window: UIWindow?169 var window: UIWindow?
168 private let split = RootViewController(style: .tripleColumn)170 private let split = RootViewController(style: .tripleColumn)
169 private let notebooks = NotebooksViewController()171 private let notebooks = NotebooksViewController()
170 private let pages = PagesViewController()172 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] = []
171 /// A first launch opened a page by itself.176 /// A first launch opened a page by itself.
172 private var landed = false177 private var landed = false
173 private var background = UIBackgroundTaskIdentifier.invalid178 private var background = UIBackgroundTaskIdentifier.invalid
...@@ -292,6 +297,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro...@@ -292,6 +297,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro
292297
293 func show(section: Section, page: String, reveal: Reveal? = nil, titleFocus: Bool = false, revealPage: Bool = true) {298 func show(section: Section, page: String, reveal: Reveal? = nil, titleFocus: Bool = false, revealPage: Bool = true) {
294 let controller = PageViewController(section: section, page: page, reveal: reveal, titleFocus: titleFocus)299 let controller = PageViewController(section: section, page: page, reveal: reveal, titleFocus: titleFocus)
300 openPages.removeAll { $0.value == nil }
301 openPages.append(WeakPage(value: controller))
295 controller.onOpen = { [weak self, weak controller] id in302 controller.onOpen = { [weak self, weak controller] id in
296 guard let controller else { return }303 guard let controller else { return }
297 self?.show(section: section, page: id, revealPage: controller.viewIfLoaded?.window != nil)304 self?.show(section: section, page: id, revealPage: controller.viewIfLoaded?.window != nil)
...@@ -302,12 +309,53 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro...@@ -302,12 +309,53 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro
302 Place.saved = Place(notebook: section.notebook.id, section: section.tab.path, page: page)309 Place.saved = Place(notebook: section.notebook.id, section: section.tab.path, page: page)
303 }310 }
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
305 /// Returns to the list from any section of `notebook` shown, as before its folder moves.336 /// Returns to the list from any section of `notebook` shown, as before its folder moves.
306 func close(_ notebook: Notebook) {337 func close(_ notebook: Notebook) {
307 guard pages.section?.notebook === notebook else { return }338 openPages.removeAll { $0.value == nil }
308 pages.clear()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 }
309 split.setViewController(UIViewController(), for: .secondary)355 split.setViewController(UIViewController(), for: .secondary)
310 split.show(.primary)356 if split.presentedViewController == nil {
357 split.show(.primary)
358 }
311 }359 }
312360
313 /// Lets go of the section shown where it is the section or group at `path` of `notebook`361 /// 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 {...@@ -189,11 +189,14 @@ enum Arranging {
189 _ pages: [(page: String, discard: String?)], from source: Section, to target: Section, order: [Placed],189 _ pages: [(page: String, discard: String?)], from source: Section, to target: Section, order: [Placed],
190 repairs: [(id: String, expected: Int, restore: Int)] = []190 repairs: [(id: String, expected: Int, restore: Int)] = []
191 ) {191 ) {
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 }
193 let before = source.rows.map { Placed(id: $0.id, level: $0.level) }196 let before = source.rows.map { Placed(id: $0.id, level: $0.level) }
194 let pointer = Int(bitPattern: library)197 let pointer = Int(bitPattern: library)
195 let sourcePointer = Int(bitPattern: source.handle)198 let sourcePointer = Int(bitPattern: sourceHandle)
196 let targetPointer = Int(bitPattern: target.handle)199 let targetPointer = Int(bitPattern: targetHandle)
197 let author = Author.name ?? ""200 let author = Author.name ?? ""
198 let (date, time) = titleDate()201 let (date, time) = titleDate()
199 var undo: () -> Void = {}202 var undo: () -> Void = {}
...@@ -310,7 +313,7 @@ extension UIResponder {...@@ -310,7 +313,7 @@ extension UIResponder {
310extension Section {313extension Section {
311 /// Puts page `id` where `order` places it, as one edit; false where it isn't listed.314 /// Puts page `id` where `order` places it, as one edit; false where it isn't listed.
312 func arrange(_ order: [Placed], moving id: String) -> Bool {315 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 }
314 reloadRows()317 reloadRows()
315 return true318 return true
316 }319 }
apps/ios/Snowbound/CanvasView.swift+32-5
...@@ -66,10 +66,23 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI...@@ -66,10 +66,23 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
66 UIGestureRecognizerDelegate, UIEditMenuInteractionDelegate,66 UIGestureRecognizerDelegate, UIEditMenuInteractionDelegate,
67 UIPencilInteractionDelegate, UIScribbleInteractionDelegate67 UIPencilInteractionDelegate, UIScribbleInteractionDelegate
68{68{
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
69 /// The zoom a page opens at once the reader has pinched one.82 /// The zoom a page opens at once the reader has pinched one.
70 private static let zoomKey = "zoom"83 private static let zoomKey = "zoom"
7184
72 private let section: Section85 private var section: Section?
73 private let page: String86 private let page: String
74 private let metal = MetalView()87 private let metal = MetalView()
75 /// Sized to the page content at 100%, so the scroll view's zoom scale is the page zoom.88 /// 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...@@ -118,7 +131,7 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
118 private var fingerDraws = false131 private var fingerDraws = false
119 /// The section's tab colour as a COLORREF, which its pen gallery and shapes follow.132 /// The section's tab colour as a COLORREF, which its pen gallery and shapes follow.
120 private var sectionColor: UInt32 {133 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)) }
122 }135 }
123 private lazy var picker = InkPicker(pens: Pen.gallery(sectionColor))136 private lazy var picker = InkPicker(pens: Pen.gallery(sectionColor))
124137
...@@ -152,10 +165,11 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI...@@ -152,10 +165,11 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
152 }165 }
153 }166 }
154167
155 init(section: Section, page: String) {168 init(section: Section?, page: String) {
156 self.section = section169 self.section = section
157 self.page = page170 self.page = page
158 super.init(frame: .zero)171 super.init(frame: .zero)
172 Self.active[ObjectIdentifier(self)] = WeakCanvas(value: self)
159 backgroundColor = .systemBackground173 backgroundColor = .systemBackground
160 delegate = self174 delegate = self
161 minimumZoomScale = 0.25175 minimumZoomScale = 0.25
...@@ -212,8 +226,20 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI...@@ -212,8 +226,20 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
212 required init?(coder: NSCoder) { fatalError() }226 required init?(coder: NSCoder) { fatalError() }
213227
214 deinit {228 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() {
215 link?.invalidate()236 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
217 }243 }
218244
219 // MARK: Drawing245 // MARK: Drawing
...@@ -233,8 +259,9 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI...@@ -233,8 +259,9 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI
233 sb_view_resize(handle, Float(bounds.width), Float(bounds.height), Float(scale))259 sb_view_resize(handle, Float(bounds.width), Float(bounds.height), Float(scale))
234 if readingShown { reflowReading(readingWidth) } else { transform() }260 if readingShown { reflowReading(readingWidth) } else { transform() }
235 } else {261 } else {
262 guard let section, let sectionHandle = section.handle else { return }
236 handle = sb_view_new(263 handle = sb_view_new(
237 Unmanaged.passUnretained(metal.layer).toOpaque(), section.handle, page,264 Unmanaged.passUnretained(metal.layer).toOpaque(), sectionHandle, page,
238 Float(bounds.width), Float(bounds.height), Float(scale))265 Float(bounds.width), Float(bounds.height), Float(scale))
239 guard let handle else { return }266 guard let handle else { return }
240 sb_view_focus(handle, false)267 sb_view_focus(handle, false)
apps/ios/Snowbound/Lists.swift+19-1
...@@ -558,12 +558,19 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke...@@ -558,12 +558,19 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke
558 }558 }
559 // A notebook On My iPhone is its folder there, handled as Files handles a folder.559 // A notebook On My iPhone is its folder there, handled as Files handles a folder.
560 guard let folder = folder(of: notebook) else {560 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 }
561 let image = UIImage(systemName: "xmark.circle")568 let image = UIImage(systemName: "xmark.circle")
562 let close = UIAction(title: "Close Notebook", image: image, attributes: .destructive) { [weak self] _ in569 let close = UIAction(title: "Close Notebook", image: image, attributes: .destructive) { [weak self] _ in
563 Notebooks.remove(notebook)570 Notebooks.remove(notebook)
564 self?.reload()571 self?.reload()
565 }572 }
566 return UIMenu(children: status + actions + [close])573 return UIMenu(children: status + actions + extra + [close])
567 }574 }
568 let file = [575 let file = [
569 UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in576 UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in
...@@ -1030,6 +1037,17 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke...@@ -1030,6 +1037,17 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke
1030 present(UINavigationController(rootViewController: server), animated: true)1037 present(UINavigationController(rootViewController: server), animated: true)
1031 }1038 }
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
1033 private func newSection(in notebook: Notebook) {1051 private func newSection(in notebook: Notebook) {
1034 let alert = UIAlertController(title: "New Section", message: nil, preferredStyle: .alert)1052 let alert = UIAlertController(title: "New Section", message: nil, preferredStyle: .alert)
1035 alert.addTextField { field in1053 alert.addTextField { field in
apps/ios/Snowbound/Notebooks.swift+252-16
...@@ -33,7 +33,9 @@ enum Author {...@@ -33,7 +33,9 @@ enum Author {
33 set {33 set {
34 UserDefaults.standard.set(newValue, forKey: key)34 UserDefaults.standard.set(newValue, forKey: key)
35 // Open sections name it in their edits from now on.35 // 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 }
37 }39 }
38 }40 }
3941
...@@ -73,8 +75,92 @@ struct Server: Codable, Equatable {...@@ -73,8 +75,92 @@ struct Server: Codable, Equatable {
73 /// The notebook folder, `/`-separated from the share's top.75 /// The notebook folder, `/`-separated from the share's top.
74 var root: String76 var root: String
7577
76 var hostName: String { host.split(separator: ":").first.map(String.init) ?? host }78 var hostName: String {
77 var port: Int { host.split(separator: ":").dropFirst().first.flatMap { Int($0) } ?? 445 }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 }
78}164}
79165
80/// The password of an SMB account, kept in the Keychain as Files keeps a server's.166/// 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: ....@@ -185,7 +271,7 @@ let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .
185final class Notebook {271final class Notebook {
186 /// A UUID, or `Documents/` and the folder's name for a notebook On My iPhone.272 /// A UUID, or `Documents/` and the folder's name for a notebook On My iPhone.
187 let id: String273 let id: String
188 let source: Source274 private(set) var source: Source
189 private(set) var name: String275 private(set) var name: String
190 private(set) var handle: OpaquePointer?276 private(set) var handle: OpaquePointer?
191 private(set) var tabs: [Tab] = []277 private(set) var tabs: [Tab] = []
...@@ -281,12 +367,126 @@ final class Notebook {...@@ -281,12 +367,126 @@ final class Notebook {
281 case .files: "In Files"367 case .files: "In Files"
282 case .documents: "On My \(UIDevice.current.model), in Snowbound’s folder"368 case .documents: "On My \(UIDevice.current.model), in Snowbound’s folder"
283 case .icloud: "In iCloud Drive"369 case .icloud: "In iCloud Drive"
284 case .server(let server):370 case .server(let server): server.url
285 "smb://\(server.host)/\([server.share, server.root].filter { !$0.isEmpty }.joined(separator: "/"))"
286 case .path(let path): path371 case .path(let path): path
287 }372 }
288 }373 }
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
290 /// Unlocks the protected section at `path` with `password` off the main thread, then lists490 /// Unlocks the protected section at `path` with `password` off the main thread, then lists
291 /// the sections again; `done` learns whether the password matched.491 /// the sections again; `done` learns whether the password matched.
292 func unlock(_ path: String, password: String, done: @escaping (Bool) -> Void) {492 func unlock(_ path: String, password: String, done: @escaping (Bool) -> Void) {
...@@ -598,7 +798,7 @@ enum Notebooks {...@@ -598,7 +798,7 @@ enum Notebooks {
598 save()798 save()
599 }799 }
600800
601 private static func save() {801 static func save() {
602 guard scripted == nil else { return }802 guard scripted == nil else { return }
603 let entries = elsewhere.map { Entry(id: $0.id, name: $0.name, source: $0.source) }803 let entries = elsewhere.map { Entry(id: $0.id, name: $0.name, source: $0.source) }
604 UserDefaults.standard.set(try? JSONEncoder().encode(entries), forKey: key)804 UserDefaults.standard.set(try? JSONEncoder().encode(entries), forKey: key)
...@@ -648,7 +848,7 @@ final class Section {...@@ -648,7 +848,7 @@ final class Section {
648848
649 let notebook: Notebook849 let notebook: Notebook
650 let tab: Tab850 let tab: Tab
651 let handle: OpaquePointer851 private(set) var handle: OpaquePointer?
652 private let token: Int852 private let token: Int
653 private(set) var rows: [Row]853 private(set) var rows: [Row]
654 private(set) var status = SaveStatus.unknown854 private(set) var status = SaveStatus.unknown
...@@ -656,6 +856,12 @@ final class Section {...@@ -656,6 +856,12 @@ final class Section {
656856
657 static var all: [Section] { open.values.compactMap(\.value) }857 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
659 private init(notebook: Notebook, tab: Tab, handle: OpaquePointer, token: Int, rows: [Row]) {865 private init(notebook: Notebook, tab: Tab, handle: OpaquePointer, token: Int, rows: [Row]) {
660 self.notebook = notebook866 self.notebook = notebook
661 self.tab = tab867 self.tab = tab
...@@ -664,9 +870,21 @@ final class Section {...@@ -664,9 +870,21 @@ final class Section {
664 self.rows = rows870 self.rows = rows
665 }871 }
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
667 deinit {885 deinit {
668 Self.open[token] = nil886 Self.open[token] = nil
669 sb_section_free(handle)887 if let handle { sb_section_free(handle) }
670 }888 }
671889
672 /// Opens `tab` of `notebook` off the main thread, or hands back the section already open890 /// Opens `tab` of `notebook` off the main thread, or hands back the section already open
...@@ -698,6 +916,7 @@ final class Section {...@@ -698,6 +916,7 @@ final class Section {
698916
699 /// Lists the pages again and tells the views.917 /// Lists the pages again and tells the views.
700 func reloadRows() {918 func reloadRows() {
919 guard let handle else { return }
701 listing?.invalidated = true920 listing?.invalidated = true
702 rows = decode([Row].self, sb_section_pages(handle)) ?? rows921 rows = decode([Row].self, sb_section_pages(handle)) ?? rows
703 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])922 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
...@@ -715,14 +934,22 @@ final class Section {...@@ -715,14 +934,22 @@ final class Section {
715 }934 }
716935
717 private func readRows() {936 private func readRows() {
718 background({ [self] in decode([Row].self, sb_section_pages(handle)) }) { [self] rows in937 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 }
719 // A read begun before a reload or retitle would undo it.946 // A read begun before a reload or retitle would undo it.
720 if listing!.invalidated, rows != nil {947 if current.invalidated, rows != nil {
721 listing?.invalidated = false948 listing?.invalidated = false
722 return readRows()949 return readRows()
723 }950 }
724 self.rows = rows ?? self.rows951 self.rows = rows ?? self.rows
725 let completions = listing!.completions952 let completions = current.completions
726 listing = nil953 listing = nil
727 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])954 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
728 for completion in completions { completion() }955 for completion in completions { completion() }
...@@ -739,6 +966,7 @@ final class Section {...@@ -739,6 +966,7 @@ final class Section {
739 }966 }
740967
741 fileprivate func poll() {968 fileprivate func poll() {
969 guard let handle else { return }
742 var status: UInt8 = 0970 var status: UInt8 = 0
743 let flags = sb_section_poll(handle, &status)971 let flags = sb_section_poll(handle, &status)
744 let changed = SaveStatus(rawValue: status) ?? .unknown972 let changed = SaveStatus(rawValue: status) ?? .unknown
...@@ -762,6 +990,7 @@ final class Section {...@@ -762,6 +990,7 @@ final class Section {
762990
763 /// Adds a page, or a subpage of `parent`; returns its id.991 /// Adds a page, or a subpage of `parent`; returns its id.
764 func newPage(under parent: String? = nil) -> String? {992 func newPage(under parent: String? = nil) -> String? {
993 guard let handle else { return nil }
765 let (date, time) = titleDate()994 let (date, time) = titleDate()
766 let id = take(sb_section_new_page(handle, parent, date, time))995 let id = take(sb_section_new_page(handle, parent, date, time))
767 reloadRows()996 reloadRows()
...@@ -771,7 +1000,7 @@ final class Section {...@@ -771,7 +1000,7 @@ final class Section {
771 /// Deletes pages, conflict pages for good and the rest to the recycle bin, which a toast1000 /// Deletes pages, conflict pages for good and the rest to the recycle bin, which a toast
772 /// then offers.1001 /// then offers.
773 func delete(_ ids: [String], done: @escaping () -> Void = {}) {1002 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 }
775 let recycled = notebook.hasRecycleBin ? ids.filter { row(of: $0)?.version == nil }.count : 01004 let recycled = notebook.hasRecycleBin ? ids.filter { row(of: $0)?.version == nil }.count : 0
776 let (date, time) = titleDate()1005 let (date, time) = titleDate()
777 let pointer = Int(bitPattern: handle)1006 let pointer = Int(bitPattern: handle)
...@@ -812,17 +1041,24 @@ final class Section {...@@ -812,17 +1041,24 @@ final class Section {
812 let notebook: String?1041 let notebook: String?
813 }1042 }
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
817 /// Gives `theme`, or none of its own, to page `id` (scope 0), its section (1) or its1048 /// Gives `theme`, or none of its own, to page `id` (scope 0), its section (1) or its
818 /// notebook (2).1049 /// notebook (2).
819 func setTheme(_ theme: String?, scope: UInt8, of id: String, done: @escaping (Bool) -> Void) {1050 func setTheme(_ theme: String?, scope: UInt8, of id: String, done: @escaping (Bool) -> Void) {
1051 guard let handle else { return done(false) }
820 let pointer = Int(bitPattern: handle)1052 let pointer = Int(bitPattern: handle)
821 background({ sb_section_set_theme(OpaquePointer(bitPattern: pointer), id, scope, theme) }, done: done)1053 background({ sb_section_set_theme(OpaquePointer(bitPattern: pointer), id, scope, theme) }, done: done)
822 }1054 }
8231055
824 /// Stores every edit and publishes them within `seconds`; call off the main thread.1056 /// 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 }
828}1064}
apps/ios/Snowbound/PageViewController.swift+23-10
...@@ -15,8 +15,9 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -15,8 +15,9 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
15 /// Posted when the app leaves the screen or quits: marked text is committed so it saves.15 /// Posted when the app leaves the screen or quits: marked text is committed so it saves.
16 static let leaving = Notification.Name("SnowboundLeaving")16 static let leaving = Notification.Name("SnowboundLeaving")
1717
18 private let section: Section18 private var section: Section?
19 private let page: String19 private let page: String
20 var notebook: Notebook? { section?.notebook }
20 private let reveal: Reveal?21 private let reveal: Reveal?
21 private let titleFocus: Bool22 private let titleFocus: Bool
22 private lazy var canvas = CanvasView(section: section, page: page)23 private lazy var canvas = CanvasView(section: section, page: page)
...@@ -57,6 +58,17 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -57,6 +58,17 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
5758
58 required init?(coder: NSCoder) { fatalError() }59 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
60 override func loadView() {72 override func loadView() {
61 let view = UIView()73 let view = UIView()
62 view.backgroundColor = .systemBackground74 view.backgroundColor = .systemBackground
...@@ -141,7 +153,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -141,7 +153,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
141 private func editingChanged() {153 private func editingChanged() {
142 if !canvas.readOnly, let title = canvas.pageTitle {154 if !canvas.readOnly, let title = canvas.pageTitle {
143 showTitle(title)155 showTitle(title)
144 section.retitle(page, title)156 section?.retitle(page, title)
145 }157 }
146 fitTitle()158 fitTitle()
147 draw.isSelected = canvas.pickerShown159 draw.isSelected = canvas.pickerShown
...@@ -167,7 +179,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -167,7 +179,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
167 return [readingAction()] + [179 return [readingAction()] + [
168 themeMenu(),180 themeMenu(),
169 UIAction(title: "Tags Summary", image: UIImage(systemName: "tag")) { [weak self] _ in181 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 }
171 scene?.showTags(of: section.notebook, from: self)183 scene?.showTags(of: section.notebook, from: self)
172 },184 },
173 UIMenu(options: .displayInline, children: [185 UIMenu(options: .displayInline, children: [
...@@ -184,7 +196,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -184,7 +196,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
184 },196 },
185 UIAction(title: "Delete Page", image: UIImage(systemName: "trash"), attributes: .destructive) {197 UIAction(title: "Delete Page", image: UIImage(systemName: "trash"), attributes: .destructive) {
186 [weak self] _ in198 [weak self] _ in
187 guard let self else { return }199 guard let self, let section else { return }
188 section.delete([page])200 section.delete([page])
189 },201 },
190 ]),202 ]),
...@@ -248,7 +260,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -248,7 +260,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
248 /// The page's theme, its section's and its notebook's, each pickable; the page wears a260 /// The page's theme, its section's and its notebook's, each pickable; the page wears a
249 /// new one when it opens again.261 /// new one when it opens again.
250 private func themeMenu() -> UIMenu {262 private func themeMenu() -> UIMenu {
251 guard let themes = section.themes(of: page) else {263 guard let section, let themes = section.themes(of: page) else {
252 return UIMenu(title: "Theme", image: UIImage(systemName: "textformat"), children: [])264 return UIMenu(title: "Theme", image: UIImage(systemName: "textformat"), children: [])
253 }265 }
254 let scopes: [(String, String?)] = [266 let scopes: [(String, String?)] = [
...@@ -260,7 +272,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -260,7 +272,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
260 let choices = [(nil as String?, "None")] + themes.themes.map { ($0.id, $0.name) }272 let choices = [(nil as String?, "None")] + themes.themes.map { ($0.id, $0.name) }
261 return UIMenu(title: title, children: choices.map { id, name in273 return UIMenu(title: title, children: choices.map { id, name in
262 UIAction(title: name, state: id == current ? .on : .off) { [weak self] _ in274 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 }
264 section.setTheme(id, scope: UInt8(scope), of: page) { [weak self] _ in276 section.setTheme(id, scope: UInt8(scope), of: page) { [weak self] _ in
265 self?.onOpen?(page)277 self?.onOpen?(page)
266 }278 }
...@@ -273,6 +285,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -273,6 +285,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
273 /// Prints the page through the system's print sheet, or with `export` offers its PDF in285 /// Prints the page through the system's print sheet, or with `export` offers its PDF in
274 /// the share sheet, laid out as OneNote 2010 prints it on the region's paper.286 /// the share sheet, laid out as OneNote 2010 prints it on the region's paper.
275 private func printPage(export: Bool) {287 private func printPage(export: Bool) {
288 guard let section else { return }
276 let letter = ["US", "CA", "MX", "PR", "PH", "CL", "CO", "VE", "GT", "CR", "PA", "DO", "SV", "NI", "HN", "BZ"]289 let letter = ["US", "CA", "MX", "PR", "PH", "CL", "CO", "VE", "GT", "CR", "PA", "DO", "SV", "NI", "HN", "BZ"]
277 .contains(Locale.current.region?.identifier ?? "US")290 .contains(Locale.current.region?.identifier ?? "US")
278 let paper = letter ? CGSize(width: 612, height: 792) : CGSize(width: 595.276, height: 841.89)291 let paper = letter ? CGSize(width: 612, height: 792) : CGSize(width: 595.276, height: 841.89)
...@@ -415,7 +428,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -415,7 +428,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
415 canvas.reload(discard: false, pendingOnly: true)428 canvas.reload(discard: false, pendingOnly: true)
416 if notification.userInfo?["unchanged"] as? Bool == true { return }429 if notification.userInfo?["unchanged"] as? Bool == true { return }
417 }430 }
418 if flags & Section.listed != 0 {431 if flags & Section.listed != 0, let section {
419 if section.row(of: page) == nil {432 if section.row(of: page) == nil {
420 // Deleted elsewhere, or a conflict page resolved: back to what the section lists.433 // Deleted elsewhere, or a conflict page resolved: back to what the section lists.
421 if let first = section.rows.first { onOpen?(first.id) }434 if let first = section.rows.first { onOpen?(first.id) }
...@@ -429,7 +442,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -429,7 +442,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
429 /// Only trouble shows: saving goes on quietly, as Notes saves.442 /// Only trouble shows: saving goes on quietly, as Notes saves.
430 private func showStatus() {443 private func showStatus() {
431 let status: String? =444 let status: String? =
432 switch section.status {445 switch section?.status {
433 case .offline: "Offline"446 case .offline: "Offline"
434 case .notSaving: "Not Saving"447 case .notSaving: "Not Saving"
435 default: nil448 default: nil
...@@ -444,7 +457,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -444,7 +457,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
444 // MARK: Conflicts457 // MARK: Conflicts
445458
446 private func conflictChanged() {459 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) }
448 if version != nil {461 if version != nil {
449 // Deleting a conflict page cannot be undone, so the button asks first.462 // Deleting a conflict page cannot be undone, so the button asks first.
450 let delete = UIAction(463 let delete = UIAction(
...@@ -462,7 +475,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate...@@ -462,7 +475,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate
462 }475 }
463476
464 private func conflictAction() {477 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 }
466 if version != nil {479 if version != nil {
467 section.delete([page]) { [weak self] in self?.onOpen?(row.id) }480 section.delete([page]) { [weak self] in self?.onOpen?(row.id) }
468 } else if let newest = row.versions.max(by: { ($0.created ?? 0) < ($1.created ?? 0) }) {481 } 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 @@...@@ -1,20 +1,25 @@
1import UIKit1import UIKit
22
3/// Connect to Server, as Files and the Finder offer it: an `smb://` address, then a guest3/// 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.
5final class ServerViewController: UITableViewController, UITextFieldDelegate {7final class ServerViewController: UITableViewController, UITextFieldDelegate {
6 private static let lastKey = "server"8 private static let lastKey = "server"
79
10 private let editingNotebook: Notebook?
8 private let address = UITextField()11 private let address = UITextField()
9 private let name = UITextField()12 private let name = UITextField()
10 private let password = UITextField()13 private let password = UITextField()
11 private let guest = UISegmentedControl(items: ["Guest", "Registered User"])14 private let guest = UISegmentedControl(items: ["Guest", "Registered User"])
12 private var connecting = false15 private var connecting = false
13 var onOpen: ((Notebook) -> Void)?16 var onOpen: ((Notebook) -> Void)?
17 var onUpdate: ((@escaping () -> Void) -> Void)?
1418
15 init() {19 init(editing notebook: Notebook? = nil) {
20 self.editingNotebook = notebook
16 super.init(style: .insetGrouped)21 super.init(style: .insetGrouped)
17 title = "Connect to Server"22 title = notebook == nil ? "Connect to Server" : "Change Server Address"
18 }23 }
1924
20 required init?(coder: NSCoder) { fatalError() }25 required init?(coder: NSCoder) { fatalError() }
...@@ -26,7 +31,6 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {...@@ -26,7 +31,6 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
26 navigationItem.rightBarButtonItem = UIBarButtonItem(31 navigationItem.rightBarButtonItem = UIBarButtonItem(
27 title: "Connect", primaryAction: UIAction { [weak self] _ in self?.connect() })32 title: "Connect", primaryAction: UIAction { [weak self] _ in self?.connect() })
28 address.placeholder = "smb://server/share"33 address.placeholder = "smb://server/share"
29 address.text = UserDefaults.standard.string(forKey: Self.lastKey)
30 address.keyboardType = .URL34 address.keyboardType = .URL
31 address.autocapitalizationType = .none35 address.autocapitalizationType = .none
32 address.autocorrectionType = .no36 address.autocorrectionType = .no
...@@ -42,7 +46,15 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {...@@ -42,7 +46,15 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
42 field.delegate = self46 field.delegate = self
43 field.returnKeyType = field === password || field === address ? .go : .next47 field.returnKeyType = field === password || field === address ? .go : .next
44 }48 }
45 guest.selectedSegmentIndex = 149 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 }
46 guest.addAction(UIAction { [weak self] _ in self?.tableView.reloadData() }, for: .valueChanged)58 guest.addAction(UIAction { [weak self] _ in self?.tableView.reloadData() }, for: .valueChanged)
47 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "field")59 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "field")
48 }60 }
...@@ -65,17 +77,7 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {...@@ -65,17 +77,7 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
6577
66 /// `smb://user@host:port/share/folder`, or the same without a scheme.78 /// `smb://user@host:port/share/folder`, or the same without a scheme.
67 private func server() -> Server? {79 private func server() -> Server? {
68 var text = address.text?.trimmingCharacters(in: .whitespaces) ?? ""80 Server.parse(address.text ?? "", registered: registered, username: name.text ?? "")
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: "/"))
79 }81 }
8082
81 private func connect() {83 private func connect() {
...@@ -103,9 +105,11 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {...@@ -103,9 +105,11 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate {
103 "Can’t Connect", "Check the address, name and password, and that the server is on this network.")105 "Can’t Connect", "Check the address, name and password, and that the server is on this network.")
104 }106 }
105 if registered { Keychain.save(secret, for: server) }107 if registered { Keychain.save(secret, for: server) }
106 UserDefaults.standard.set(address.text, forKey: Self.lastKey)108 if editingNotebook == nil { UserDefaults.standard.set(address.text, forKey: Self.lastKey) }
107 let browser = ShareViewController(share: SharedConnection(share), server: server, path: server.root)109 let browser = ShareViewController(
110 share: SharedConnection(share), server: server, path: server.root, editing: editingNotebook)
108 browser.onOpen = onOpen111 browser.onOpen = onOpen
112 browser.onUpdate = onUpdate
109 navigationController?.pushViewController(browser, animated: true)113 navigationController?.pushViewController(browser, animated: true)
110 }114 }
111 }115 }
...@@ -157,13 +161,17 @@ final class ShareViewController: UITableViewController {...@@ -157,13 +161,17 @@ final class ShareViewController: UITableViewController {
157 private let share: SharedConnection161 private let share: SharedConnection
158 private let server: Server162 private let server: Server
159 private let path: String163 private let path: String
164 private let editingNotebook: Notebook?
160 private var listing: Listing?165 private var listing: Listing?
166 private var updating = false
161 var onOpen: ((Notebook) -> Void)?167 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) {
164 self.share = share171 self.share = share
165 self.server = server172 self.server = server
166 self.path = path173 self.path = path
174 self.editingNotebook = notebook
167 super.init(style: .insetGrouped)175 super.init(style: .insetGrouped)
168 title = path.split(separator: "/").last.map(String.init) ?? server.share176 title = path.split(separator: "/").last.map(String.init) ?? server.share
169 }177 }
...@@ -173,7 +181,9 @@ final class ShareViewController: UITableViewController {...@@ -173,7 +181,9 @@ final class ShareViewController: UITableViewController {
173 override func viewDidLoad() {181 override func viewDidLoad() {
174 super.viewDidLoad()182 super.viewDidLoad()
175 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "entry")183 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() })
177 open.style = .done187 open.style = .done
178 open.isEnabled = false188 open.isEnabled = false
179 navigationItem.rightBarButtonItem = open189 navigationItem.rightBarButtonItem = open
...@@ -192,6 +202,19 @@ final class ShareViewController: UITableViewController {...@@ -192,6 +202,19 @@ final class ShareViewController: UITableViewController {
192 if listing == nil {202 if listing == nil {
193 empty.text = "Can’t Read Folder"203 empty.text = "Can’t Read Folder"
194 empty.secondaryText = "Check that this account can open it."204 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 }
195 } else {218 } else {
196 empty.text = "No Folders"219 empty.text = "No Folders"
197 empty.secondaryText = "OneNote notebooks are folders with sections in them."220 empty.secondaryText = "OneNote notebooks are folders with sections in them."
...@@ -202,10 +225,32 @@ final class ShareViewController: UITableViewController {...@@ -202,10 +225,32 @@ final class ShareViewController: UITableViewController {
202 }225 }
203226
204 private func open() {227 private func open() {
228 guard !updating else { return }
205 var server = server229 var server = server
206 server.root = path230 server.root = path
207 let name = path.split(separator: "/").last.map(String.init) ?? server.share231 guard let notebook = editingNotebook else {
208 onOpen?(Notebook(name: name, source: .server(server)))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 }
209 }254 }
210255
211 override func numberOfSections(in tableView: UITableView) -> Int { 2 }256 override func numberOfSections(in tableView: UITableView) -> Int { 2 }
...@@ -245,8 +290,9 @@ final class ShareViewController: UITableViewController {...@@ -245,8 +290,9 @@ final class ShareViewController: UITableViewController {
245 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {290 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
246 guard let folder = listing?.folders[indexPath.row] else { return }291 guard let folder = listing?.folders[indexPath.row] else { return }
247 let child = ShareViewController(292 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)
249 child.onOpen = onOpen294 child.onOpen = onOpen
295 child.onUpdate = onUpdate
250 navigationController?.pushViewController(child, animated: true)296 navigationController?.pushViewController(child, animated: true)
251 }297 }
252}298}
apps/ios/Snowbound/Sync.swift+33-4
...@@ -237,10 +237,17 @@ final class SyncViewController: UITableViewController {...@@ -237,10 +237,17 @@ final class SyncViewController: UITableViewController {
237 }237 }
238 }238 }
239239
240 private func isServer(_ notebook: Notebook) -> Bool {
241 if case .server = notebook.source { return true }
242 return false
243 }
244
240 override func numberOfSections(in tableView: UITableView) -> Int { 1 + notebooks.count }245 override func numberOfSections(in tableView: UITableView) -> Int { 1 + notebooks.count }
241246
242 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {247 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
243 section == 0 ? 2 : notebooks[section - 1].1.count248 guard section > 0 else { return 2 }
249 let (notebook, sections) = notebooks[section - 1]
250 return sections.count + (isServer(notebook) ? 1 : 0)
244 }251 }
245252
246 override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {253 override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
...@@ -279,6 +286,15 @@ final class SyncViewController: UITableViewController {...@@ -279,6 +286,15 @@ final class SyncViewController: UITableViewController {
279 return cell286 return cell
280 }287 }
281 let (notebook, sections) = notebooks[indexPath.section - 1]288 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 }
282 let sync = sections[indexPath.row]298 let sync = sections[indexPath.row]
283 var content = UIListContentConfiguration.valueCell()299 var content = UIListContentConfiguration.valueCell()
284 let tab = notebook.tabs.first { $0.path == sync.path }300 let tab = notebook.tabs.first { $0.path == sync.path }
...@@ -301,8 +317,21 @@ final class SyncViewController: UITableViewController {...@@ -301,8 +317,21 @@ final class SyncViewController: UITableViewController {
301317
302 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {318 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
303 tableView.deselectRow(at: indexPath, animated: true)319 tableView.deselectRow(at: indexPath, animated: true)
304 guard indexPath == IndexPath(row: 1, section: 0) else { return }320 if indexPath == IndexPath(row: 1, section: 0) {
305 Sync.now()321 Sync.now()
306 refresh()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)
307 }336 }
308}337}
crates/mobile/include/snowbound.h+3
...@@ -66,6 +66,8 @@ char *sb_library_live_status(const Library *library);...@@ -66,6 +66,8 @@ char *sb_library_live_status(const Library *library);
66bool sb_notebook_create(const char *path, const char *cache, const char *author, const char *date, const char *time,66bool sb_notebook_create(const char *path, const char *cache, const char *author, const char *date, const char *time,
67 char **error);67 char **error);
68bool sb_notebook_moved(const char *cache, const char *from, const char *to, char **error);68bool 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);
69char *sb_library_sections(const Library *library);71char *sb_library_sections(const Library *library);
70int32_t sb_library_color(const Library *library);72int32_t sb_library_color(const Library *library);
71char *sb_library_new_section(const Library *library, const char *folder, const char *name, const char *author,73char *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);...@@ -86,6 +88,7 @@ void sb_library_touched(const Library *library, const char *path);
86void sb_library_sync_now(const Library *library);88void sb_library_sync_now(const Library *library);
87// Publishes, keeping offline copies; sb_library_close is Close Notebook and deletes them.89// Publishes, keeping offline copies; sb_library_close is Close Notebook and deletes them.
88bool sb_library_flush(const Library *library, double seconds, char **error);90bool sb_library_flush(const Library *library, double seconds, char **error);
91bool sb_library_stop(const Library *library, char **error);
89bool sb_library_close(const Library *library, double seconds, char **error);92bool sb_library_close(const Library *library, double seconds, char **error);
90void sb_library_free(const Library *library);93void sb_library_free(const Library *library);
9194
crates/mobile/src/library.rs+269-10
...@@ -376,6 +376,8 @@ pub struct Library {...@@ -376,6 +376,8 @@ pub struct Library {
376 open: Mutex<Vec<(String, Weak<Shared>)>>,376 open: Mutex<Vec<(String, Weak<Shared>)>>,
377 /// Work Offline, which sections opened later follow too.377 /// Work Offline, which sections opened later follow too.
378 offline: AtomicBool,378 offline: AtomicBool,
379 /// Set by `Library::stop` before relocating, so any in-flight `Section::flush` exits promptly.
380 stopping: AtomicBool,
379 /// Keys of the protected sections unlocked this run, by catalog path; in memory only.381 /// Keys of the protected sections unlocked this run, by catalog path; in memory only.
380 keys: Mutex<HashMap<String, Key>>,382 keys: Mutex<HashMap<String, Key>>,
381 /// A file provider keeps the notebook elsewhere too, as iCloud Drive does: edits wait for a383 /// A file provider keeps the notebook elsewhere too, as iCloud Drive does: edits wait for a
...@@ -502,6 +504,7 @@ impl Library {...@@ -502,6 +504,7 @@ impl Library {
502 background,504 background,
503 open: Mutex::default(),505 open: Mutex::default(),
504 offline: AtomicBool::new(false),506 offline: AtomicBool::new(false),
507 stopping: AtomicBool::new(false),
505 keys: Default::default(),508 keys: Default::default(),
506 elsewhere: !local,509 elsewhere: !local,
507 })510 })
...@@ -525,6 +528,7 @@ impl Library {...@@ -525,6 +528,7 @@ impl Library {
525 background: Some(background),528 background: Some(background),
526 open: Mutex::default(),529 open: Mutex::default(),
527 offline: AtomicBool::new(false),530 offline: AtomicBool::new(false),
531 stopping: AtomicBool::new(false),
528 keys: Default::default(),532 keys: Default::default(),
529 elsewhere: false,533 elsewhere: false,
530 };534 };
...@@ -584,6 +588,7 @@ impl Library {...@@ -584,6 +588,7 @@ impl Library {
584 background: Some(background),588 background: Some(background),
585 open: Mutex::default(),589 open: Mutex::default(),
586 offline: AtomicBool::new(offline),590 offline: AtomicBool::new(offline),
591 stopping: AtomicBool::new(false),
587 keys: Default::default(),592 keys: Default::default(),
588 elsewhere: false,593 elsewhere: false,
589 })594 })
...@@ -621,6 +626,7 @@ impl Library {...@@ -621,6 +626,7 @@ impl Library {
621 background,626 background,
622 open: Mutex::default(),627 open: Mutex::default(),
623 offline: AtomicBool::new(false),628 offline: AtomicBool::new(false),
629 stopping: AtomicBool::new(false),
624 keys: Default::default(),630 keys: Default::default(),
625 elsewhere: !local,631 elsewhere: !local,
626 })632 })
...@@ -662,11 +668,7 @@ impl Library {...@@ -662,11 +668,7 @@ impl Library {
662 let Place::Share { server, root, .. } = &self.place else {668 let Place::Share { server, root, .. } = &self.place else {
663 return None;669 return None;
664 };670 };
665 let name: String = format!("{}/{}/{root}", server.address, server.share)671 Some(smb_listing(&self.cache, &server.address, &server.share, root))
666 .chars()
667 .map(|char| if char.is_alphanumeric() { char } else { '_' })
668 .collect();
669 Some(self.cache.join("smb").join(format!("{name}.json")))
670 }672 }
671673
672 fn listed(&self) -> Option<Listed> {674 fn listed(&self) -> Option<Listed> {
...@@ -1312,6 +1314,9 @@ impl Section {...@@ -1312,6 +1314,9 @@ impl Section {
1312 }1314 }
1313 let deadline = Instant::now() + limit;1315 let deadline = Instant::now() + limit;
1314 loop {1316 loop {
1317 if self.library.stopping.load(Ordering::Acquire) {
1318 return false;
1319 }
1315 match section.pending() {1320 match section.pending() {
1316 Ok(pending) if pending.is_empty() => return true,1321 Ok(pending) if pending.is_empty() => return true,
1317 Ok(_) if Instant::now() < deadline => {1322 Ok(_) if Instant::now() < deadline => {
...@@ -1483,6 +1488,24 @@ impl Library {...@@ -1483,6 +1488,24 @@ impl Library {
1483 Ok(())1488 Ok(())
1484 }1489 }
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
1486 /// Publishes every edit the notebook's replicas hold within `limit`, keeping them and the1509 /// Publishes every edit the notebook's replicas hold within `limit`, keeping them and the
1487 /// offline copies.1510 /// offline copies.
1488 pub(crate) fn flush(&self, limit: Duration) -> Result<()> {1511 pub(crate) fn flush(&self, limit: Duration) -> Result<()> {
...@@ -2104,6 +2127,68 @@ pub unsafe extern "C" fn sb_notebook_moved(...@@ -2104,6 +2127,68 @@ pub unsafe extern "C" fn sb_notebook_moved(
2104 moved().map_err(|cause| failed(cause, error)).is_ok()2127 moved().map_err(|cause| failed(cause, error)).is_ok()
2105}2128}
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
2107/// The notebook's sections read again, as JSON: each with `name`, `path`, `group`,2192/// The notebook's sections read again, as JSON: each with `name`, `path`, `group`,
2108/// `color` as sRGB bytes, `readable`, `downloading` and `problem`, in the notebook's order; null2193/// `color` as sRGB bytes, `readable`, `downloading` and `problem`, in the notebook's order; null
2109/// if it cannot be read.2194/// if it cannot be read.
...@@ -2380,6 +2465,19 @@ pub unsafe extern "C" fn sb_library_flush(...@@ -2380,6 +2465,19 @@ pub unsafe extern "C" fn sb_library_flush(
2380 .is_ok()2465 .is_ok()
2381}2466}
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
2383/// The notebook folder whose document is `root`, or with `folder` false the lone section2481/// The notebook folder whose document is `root`, or with `folder` false the lone section
2384/// `root` names, as the provider `sb_set_provider` registered keeps it; `local` as2482/// `root` names, as the provider `sb_set_provider` registered keeps it; `local` as
2385/// `sb_library_open` takes it, and `device` naming this device on the conflict pages its own2483/// `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(...@@ -2438,6 +2536,26 @@ pub unsafe extern "C" fn sb_share_connect(
2438 boxed(server.connect().map_err(Into::into).map(Share), error)2536 boxed(server.connect().map_err(Into::into).map(Share), error)
2439}2537}
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
2441fn server(2559fn server(
2442 address: *const c_char,2560 address: *const c_char,
2443 share: *const c_char,2561 share: *const c_char,
...@@ -2445,12 +2563,8 @@ fn server(...@@ -2445,12 +2563,8 @@ fn server(
2445 password: *const c_char,2563 password: *const c_char,
2446 domain: *const c_char,2564 domain: *const c_char,
2447) -> Server {2565) -> Server {
2448 let mut address = string(address);
2449 if !address.contains(':') {
2450 address.push_str(":445");
2451 }
2452 Server {2566 Server {
2453 address,2567 address: normalize_address(string(address)),
2454 share: string(share),2568 share: string(share),
2455 user: string(user),2569 user: string(user),
2456 password: string(password),2570 password: string(password),
...@@ -2901,4 +3015,149 @@ mod tests {...@@ -2901,4 +3015,149 @@ mod tests {
2901 );3015 );
2902 assert_eq!(copy.shared.section.pending().unwrap().len(), 1);3016 assert_eq!(copy.shared.section.pending().unwrap().len(), 1);
2903 }3017 }
3018
3019 /// Changing an unreachable SMB share notebook's URL preserves its cached listing,
3020 /// section replicas, copy-section replicas, and queued offline edits so they reopen and
3021 /// sync under the new URL.
3022 #[test]
3023 fn relocating_an_offline_share_notebook_preserves_edits_and_listing() {
3024 let directory = tempfile::tempdir().unwrap();
3025 let root = directory.path().join("notebook");
3026 let cache = directory.path().join("cache");
3027 std::fs::create_dir(&root).unwrap();
3028 let bytes = onestore::create_section("Notes.one", "Original text", "Fixture").unwrap();
3029 for name in ["Notes.one", "Notes - Copy.one"] {
3030 std::fs::write(root.join(name), &bytes).unwrap();
3031 }
3032 let notebook = Notebook::open(&root, &cache).unwrap();
3033 let mut listed = Listed::default();
3034 tabs(notebook.catalog(), &HashMap::new(), &mut listed.tabs);
3035 files(notebook.catalog(), &mut listed);
3036 drop(notebook);
3037
3038 let old_address = "127.0.0.1:9";
3039 let old_loc = notebook::location::smb(old_address, "oldshare", "OldFolder");
3040 for (path, identity) in &listed.files {
3041 let copy = listed.copies.contains(path);
3042 let location = session::replica_location(&old_loc, path, copy);
3043 let replicas = notebook::location::claimed(&cache, &location).unwrap();
3044 Replica::create(replicas.join(format!("{identity}.sqlite")), &bytes).unwrap();
3045 }
3046 let old_listing = smb_listing(&cache, old_address, "oldshare", "OldFolder");
3047 std::fs::create_dir_all(old_listing.parent().unwrap()).unwrap();
3048 std::fs::write(&old_listing, serde_json::to_vec(&listed).unwrap()).unwrap();
3049
3050 let library = Arc::new(
3051 Library::server(
3052 Server {
3053 address: old_address.into(),
3054 share: "oldshare".into(),
3055 user: String::new(),
3056 password: String::new(),
3057 domain: String::new(),
3058 },
3059 "OldFolder",
3060 &cache,
3061 )
3062 .unwrap(),
3063 );
3064 sb_library_set_offline(&library, true);
3065
3066 // Queue an offline edit in both the original section and the copy section.
3067 let section =
3068 Section::open(Arc::clone(&library), "Notes.one", "Fixture".into(), || {}).unwrap();
3069 let space = section.shared.section.pages().unwrap()[0].0;
3070 section
3071 .shared
3072 .apply(Edit {
3073 at: filetime(),
3074 ops: vec![Op::Page {
3075 space,
3076 op: onestore::op::PageOp::Color(Some(0x0012_3456)),
3077 }],
3078 })
3079 .unwrap();
3080 let copy = Section::open(
3081 Arc::clone(&library),
3082 "Notes - Copy.one",
3083 "Fixture".into(),
3084 || {},
3085 )
3086 .unwrap();
3087 copy.shared
3088 .apply(Edit {
3089 at: filetime(),
3090 ops: vec![Op::Page {
3091 space,
3092 op: onestore::op::PageOp::Color(Some(0x0065_4321)),
3093 }],
3094 })
3095 .unwrap();
3096
3097 // Stop the library (ensuring durability and joining background), then drop sections & library.
3098 library.stop().unwrap();
3099 drop((section, copy, library));
3100
3101 // Relocate via server_moved to a new host (omitting :445 to test normalization), share, and root.
3102 server_moved(
3103 &cache,
3104 old_address,
3105 "oldshare",
3106 "OldFolder",
3107 "127.0.0.1",
3108 "newshare",
3109 "NewFolder",
3110 )
3111 .unwrap();
3112 assert!(!old_listing.exists());
3113 assert!(smb_listing(&cache, "127.0.0.1:445", "newshare", "NewFolder").exists());
3114
3115 // Same-location relocate (with vs without explicit :445) is a clean no-op.
3116 server_moved(
3117 &cache,
3118 "127.0.0.1",
3119 "newshare",
3120 "NewFolder",
3121 "127.0.0.1:445",
3122 "newshare",
3123 "NewFolder",
3124 )
3125 .unwrap();
3126
3127 // Reopen offline under the new URL: both sections and their queued edits survived.
3128 let relocated = Arc::new(
3129 Library::server(
3130 Server {
3131 address: "127.0.0.1:445".into(),
3132 share: "newshare".into(),
3133 user: String::new(),
3134 password: String::new(),
3135 domain: String::new(),
3136 },
3137 "NewFolder",
3138 &cache,
3139 )
3140 .unwrap(),
3141 );
3142 sb_library_set_offline(&relocated, true);
3143 let original =
3144 Section::open(Arc::clone(&relocated), "Notes.one", "Fixture".into(), || {}).unwrap();
3145 assert_eq!(
3146 original.shared.section.page(space).unwrap().color,
3147 Some(0x0012_3456)
3148 );
3149 assert_eq!(original.shared.section.pending().unwrap().len(), 1);
3150 let relocated_copy = Section::open(
3151 Arc::clone(&relocated),
3152 "Notes - Copy.one",
3153 "Fixture".into(),
3154 || {},
3155 )
3156 .unwrap();
3157 assert_eq!(
3158 relocated_copy.shared.section.page(space).unwrap().color,
3159 Some(0x0065_4321)
3160 );
3161 assert_eq!(relocated_copy.shared.section.pending().unwrap().len(), 1);
3162 }
2904}3163}
crates/notebook/src/location.rs+145
...@@ -11,7 +11,9 @@ use onestore::{Header, Stamp};...@@ -11,7 +11,9 @@ use onestore::{Header, Stamp};
11use std::{11use std::{
12 io,12 io,
13 path::{Path, PathBuf},13 path::{Path, PathBuf},
14 time::Duration,
14};15};
16use web_time::Instant;
1517
16/// The file in a replica folder naming the location its replicas belong to.18/// The file in a replica folder naming the location its replicas belong to.
17const LOCATION: &str = "location";19const LOCATION: &str = "location";
...@@ -46,6 +48,9 @@ pub fn smb(address: &str, share: &str, root: &str) -> String {...@@ -46,6 +48,9 @@ pub fn smb(address: &str, share: &str, root: &str) -> String {
46/// location within it, as a copy of a section keeps its own. Each replica `to` already holds48/// location within it, as a copy of a section keeps its own. Each replica `to` already holds
47/// for the same section stays. Every replica moved must be closed.49/// for the same section stays. Every replica moved must be closed.
48pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> {50pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> {
51 if from == to {
52 return Ok(());
53 }
49 let inner = within(cache, from);54 let inner = within(cache, from);
50 move_folder(cache, from, to)?;55 move_folder(cache, from, to)?;
51 for (_, location) in inner {56 for (_, location) in inner {
...@@ -58,6 +63,146 @@ pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> {...@@ -58,6 +63,146 @@ pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> {
58 Ok(())63 Ok(())
59}64}
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
61/// The folders of the locations within `location`, labelled, with their locations.206/// The folders of the locations within `location`, labelled, with their locations.
62fn within(cache: &Path, location: &str) -> Vec<(PathBuf, String)> {207fn within(cache: &Path, location: &str) -> Vec<(PathBuf, String)> {
63 let within = format!("{location}/");208 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() {...@@ -366,3 +366,108 @@ fn forgetting_a_deleted_notebook_drops_its_replicas_and_queue_alone() {
366 assert_eq!(published(&root, &cache), 0);366 assert_eq!(published(&root, &cache), 0);
367 assert_eq!(published(&other, &cache), 1);367 assert_eq!(published(&other, &cache), 1);
368}368}
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}