| author | |
| committer | |
| log | c290c8e689023cd6ec7b18311c39a3b4caa4f17d |
| tree | 6409b646f69ba6f40159f943b401f6bbed1b84be |
| parent | ca7603e74bf287c2d05cb1f051d882098ab43795 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
12 files changed, 1008 insertions(+), 76 deletions(-)
apps/ios/Snowbound/App.swift+51-3| ... | ... | @@ -164,10 +164,15 @@ private struct Place: Codable { |
| 164 | 164 | /// Notebooks and sections, pages and a page, as Notes lays out folders, notes and a note: |
| 165 | 165 | /// side by side on a wide screen, a navigation stack on a phone. |
| 166 | 166 | final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewControllerDelegate { |
| 167 | private struct WeakPage { weak var value: PageViewController? } | |
| 168 | ||
| 167 | 169 | var window: UIWindow? |
| 168 | 170 | private let split = RootViewController(style: .tripleColumn) |
| 169 | 171 | private let notebooks = NotebooksViewController() |
| 170 | 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 | 176 | /// A first launch opened a page by itself. |
| 172 | 177 | private var landed = false |
| 173 | 178 | private var background = UIBackgroundTaskIdentifier.invalid |
| ... | ... | @@ -292,6 +297,8 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro |
| 292 | 297 | |
| 293 | 298 | func show(section: Section, page: String, reveal: Reveal? = nil, titleFocus: Bool = false, revealPage: Bool = true) { |
| 294 | 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 | 302 | controller.onOpen = { [weak self, weak controller] id in |
| 296 | 303 | guard let controller else { return } |
| 297 | 304 | self?.show(section: section, page: id, revealPage: controller.viewIfLoaded?.window != nil) |
| ... | ... | @@ -302,12 +309,53 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewContro |
| 302 | 309 | Place.saved = Place(notebook: section.notebook.id, section: section.tab.path, page: page) |
| 303 | 310 | } |
| 304 | 311 | |
| 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 | 336 | /// Returns to the list from any section of `notebook` shown, as before its folder moves. |
| 306 | 337 | 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 | } | |
| 309 | 355 | split.setViewController(UIViewController(), for: .secondary) |
| 310 | split.show(.primary) | |
| 356 | if split.presentedViewController == nil { | |
| 357 | split.show(.primary) | |
| 358 | } | |
| 311 | 359 | } |
| 312 | 360 | |
| 313 | 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 | 189 | _ pages: [(page: String, discard: String?)], from source: Section, to target: Section, order: [Placed], |
| 190 | 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 | 196 | let before = source.rows.map { Placed(id: $0.id, level: $0.level) } |
| 194 | 197 | 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) | |
| 197 | 200 | let author = Author.name ?? "" |
| 198 | 201 | let (date, time) = titleDate() |
| 199 | 202 | var undo: () -> Void = {} |
| ... | ... | @@ -310,7 +313,7 @@ extension UIResponder { |
| 310 | 313 | extension Section { |
| 311 | 314 | /// Puts page `id` where `order` places it, as one edit; false where it isn't listed. |
| 312 | 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 | 317 | reloadRows() |
| 315 | 318 | return true |
| 316 | 319 | } |
apps/ios/Snowbound/CanvasView.swift+32-5| ... | ... | @@ -66,10 +66,23 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI |
| 66 | 66 | UIGestureRecognizerDelegate, UIEditMenuInteractionDelegate, |
| 67 | 67 | 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 | 82 | /// The zoom a page opens at once the reader has pinched one. |
| 70 | 83 | private static let zoomKey = "zoom" |
| 71 | 84 | |
| 72 | private let section: Section | |
| 85 | private var section: Section? | |
| 73 | 86 | private let page: String |
| 74 | 87 | private let metal = MetalView() |
| 75 | 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 | 131 | private var fingerDraws = false |
| 119 | 132 | /// The section's tab colour as a COLORREF, which its pen gallery and shapes follow. |
| 120 | 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 | 136 | private lazy var picker = InkPicker(pens: Pen.gallery(sectionColor)) |
| 124 | 137 | |
| ... | ... | @@ -152,10 +165,11 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI |
| 152 | 165 | } |
| 153 | 166 | } |
| 154 | 167 | |
| 155 | init(section: Section, page: String) { | |
| 168 | init(section: Section?, page: String) { | |
| 156 | 169 | self.section = section |
| 157 | 170 | self.page = page |
| 158 | 171 | super.init(frame: .zero) |
| 172 | Self.active[ObjectIdentifier(self)] = WeakCanvas(value: self) | |
| 159 | 173 | backgroundColor = .systemBackground |
| 160 | 174 | delegate = self |
| 161 | 175 | minimumZoomScale = 0.25 |
| ... | ... | @@ -212,8 +226,20 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI |
| 212 | 226 | required init?(coder: NSCoder) { fatalError() } |
| 213 | 227 | |
| 214 | 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 | 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 | } |
| 218 | 244 | |
| 219 | 245 | // MARK: Drawing |
| ... | ... | @@ -233,8 +259,9 @@ final class CanvasView: UIScrollView, UIScrollViewDelegate, UITextInput, UITextI |
| 233 | 259 | sb_view_resize(handle, Float(bounds.width), Float(bounds.height), Float(scale)) |
| 234 | 260 | if readingShown { reflowReading(readingWidth) } else { transform() } |
| 235 | 261 | } else { |
| 262 | guard let section, let sectionHandle = section.handle else { return } | |
| 236 | 263 | handle = sb_view_new( |
| 237 | Unmanaged.passUnretained(metal.layer).toOpaque(), section.handle, page, | |
| 264 | Unmanaged.passUnretained(metal.layer).toOpaque(), sectionHandle, page, | |
| 238 | 265 | Float(bounds.width), Float(bounds.height), Float(scale)) |
| 239 | 266 | guard let handle else { return } |
| 240 | 267 | sb_view_focus(handle, false) |
apps/ios/Snowbound/Lists.swift+19-1| ... | ... | @@ -558,12 +558,19 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke |
| 558 | 558 | } |
| 559 | 559 | // A notebook On My iPhone is its folder there, handled as Files handles a folder. |
| 560 | 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 | 568 | let image = UIImage(systemName: "xmark.circle") |
| 562 | 569 | let close = UIAction(title: "Close Notebook", image: image, attributes: .destructive) { [weak self] _ in |
| 563 | 570 | Notebooks.remove(notebook) |
| 564 | 571 | self?.reload() |
| 565 | 572 | } |
| 566 | return UIMenu(children: status + actions + [close]) | |
| 573 | return UIMenu(children: status + actions + extra + [close]) | |
| 567 | 574 | } |
| 568 | 575 | let file = [ |
| 569 | 576 | UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in |
| ... | ... | @@ -1030,6 +1037,17 @@ final class NotebooksViewController: UICollectionViewController, UIDocumentPicke |
| 1030 | 1037 | present(UINavigationController(rootViewController: server), animated: true) |
| 1031 | 1038 | } |
| 1032 | 1039 | |
| 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 | 1051 | private func newSection(in notebook: Notebook) { |
| 1034 | 1052 | let alert = UIAlertController(title: "New Section", message: nil, preferredStyle: .alert) |
| 1035 | 1053 | alert.addTextField { field in |
apps/ios/Snowbound/Notebooks.swift+252-16| ... | ... | @@ -33,7 +33,9 @@ enum Author { |
| 33 | 33 | set { |
| 34 | 34 | UserDefaults.standard.set(newValue, forKey: key) |
| 35 | 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 | } |
| 39 | 41 | |
| ... | ... | @@ -73,8 +75,92 @@ struct Server: Codable, Equatable { |
| 73 | 75 | /// The notebook folder, `/`-separated from the share's top. |
| 74 | 76 | var root: String |
| 75 | 77 | |
| 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 | } | |
| 78 | 164 | } |
| 79 | 165 | |
| 80 | 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 | 271 | final class Notebook { |
| 186 | 272 | /// A UUID, or `Documents/` and the folder's name for a notebook On My iPhone. |
| 187 | 273 | let id: String |
| 188 | let source: Source | |
| 274 | private(set) var source: Source | |
| 189 | 275 | private(set) var name: String |
| 190 | 276 | private(set) var handle: OpaquePointer? |
| 191 | 277 | private(set) var tabs: [Tab] = [] |
| ... | ... | @@ -281,12 +367,126 @@ final class Notebook { |
| 281 | 367 | case .files: "In Files" |
| 282 | 368 | case .documents: "On My \(UIDevice.current.model), in Snowbound’s folder" |
| 283 | 369 | 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 | |
| 286 | 371 | case .path(let path): path |
| 287 | 372 | } |
| 288 | 373 | } |
| 289 | 374 | |
| 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 | 490 | /// Unlocks the protected section at `path` with `password` off the main thread, then lists |
| 291 | 491 | /// the sections again; `done` learns whether the password matched. |
| 292 | 492 | func unlock(_ path: String, password: String, done: @escaping (Bool) -> Void) { |
| ... | ... | @@ -598,7 +798,7 @@ enum Notebooks { |
| 598 | 798 | save() |
| 599 | 799 | } |
| 600 | 800 | |
| 601 | private static func save() { | |
| 801 | static func save() { | |
| 602 | 802 | guard scripted == nil else { return } |
| 603 | 803 | let entries = elsewhere.map { Entry(id: $0.id, name: $0.name, source: $0.source) } |
| 604 | 804 | UserDefaults.standard.set(try? JSONEncoder().encode(entries), forKey: key) |
| ... | ... | @@ -648,7 +848,7 @@ final class Section { |
| 648 | 848 | |
| 649 | 849 | let notebook: Notebook |
| 650 | 850 | let tab: Tab |
| 651 | let handle: OpaquePointer | |
| 851 | private(set) var handle: OpaquePointer? | |
| 652 | 852 | private let token: Int |
| 653 | 853 | private(set) var rows: [Row] |
| 654 | 854 | private(set) var status = SaveStatus.unknown |
| ... | ... | @@ -656,6 +856,12 @@ final class Section { |
| 656 | 856 | |
| 657 | 857 | static var all: [Section] { open.values.compactMap(\.value) } |
| 658 | 858 | |
| 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 | 865 | private init(notebook: Notebook, tab: Tab, handle: OpaquePointer, token: Int, rows: [Row]) { |
| 660 | 866 | self.notebook = notebook |
| 661 | 867 | self.tab = tab |
| ... | ... | @@ -664,9 +870,21 @@ final class Section { |
| 664 | 870 | self.rows = rows |
| 665 | 871 | } |
| 666 | 872 | |
| 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 | 885 | deinit { |
| 668 | 886 | Self.open[token] = nil |
| 669 | sb_section_free(handle) | |
| 887 | if let handle { sb_section_free(handle) } | |
| 670 | 888 | } |
| 671 | 889 | |
| 672 | 890 | /// Opens `tab` of `notebook` off the main thread, or hands back the section already open |
| ... | ... | @@ -698,6 +916,7 @@ final class Section { |
| 698 | 916 | |
| 699 | 917 | /// Lists the pages again and tells the views. |
| 700 | 918 | func reloadRows() { |
| 919 | guard let handle else { return } | |
| 701 | 920 | listing?.invalidated = true |
| 702 | 921 | rows = decode([Row].self, sb_section_pages(handle)) ?? rows |
| 703 | 922 | NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed]) |
| ... | ... | @@ -715,14 +934,22 @@ final class Section { |
| 715 | 934 | } |
| 716 | 935 | |
| 717 | 936 | 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 } | |
| 719 | 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 | 948 | listing?.invalidated = false |
| 722 | 949 | return readRows() |
| 723 | 950 | } |
| 724 | 951 | self.rows = rows ?? self.rows |
| 725 | let completions = listing!.completions | |
| 952 | let completions = current.completions | |
| 726 | 953 | listing = nil |
| 727 | 954 | NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed]) |
| 728 | 955 | for completion in completions { completion() } |
| ... | ... | @@ -739,6 +966,7 @@ final class Section { |
| 739 | 966 | } |
| 740 | 967 | |
| 741 | 968 | fileprivate func poll() { |
| 969 | guard let handle else { return } | |
| 742 | 970 | var status: UInt8 = 0 |
| 743 | 971 | let flags = sb_section_poll(handle, &status) |
| 744 | 972 | let changed = SaveStatus(rawValue: status) ?? .unknown |
| ... | ... | @@ -762,6 +990,7 @@ final class Section { |
| 762 | 990 | |
| 763 | 991 | /// Adds a page, or a subpage of `parent`; returns its id. |
| 764 | 992 | func newPage(under parent: String? = nil) -> String? { |
| 993 | guard let handle else { return nil } | |
| 765 | 994 | let (date, time) = titleDate() |
| 766 | 995 | let id = take(sb_section_new_page(handle, parent, date, time)) |
| 767 | 996 | reloadRows() |
| ... | ... | @@ -771,7 +1000,7 @@ final class Section { |
| 771 | 1000 | /// Deletes pages, conflict pages for good and the rest to the recycle bin, which a toast |
| 772 | 1001 | /// then offers. |
| 773 | 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 | 1004 | let recycled = notebook.hasRecycleBin ? ids.filter { row(of: $0)?.version == nil }.count : 0 |
| 776 | 1005 | let (date, time) = titleDate() |
| 777 | 1006 | let pointer = Int(bitPattern: handle) |
| ... | ... | @@ -812,17 +1041,24 @@ final class Section { |
| 812 | 1041 | let notebook: String? |
| 813 | 1042 | } |
| 814 | 1043 | |
| 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 | } | |
| 816 | 1047 | |
| 817 | 1048 | /// Gives `theme`, or none of its own, to page `id` (scope 0), its section (1) or its |
| 818 | 1049 | /// notebook (2). |
| 819 | 1050 | func setTheme(_ theme: String?, scope: UInt8, of id: String, done: @escaping (Bool) -> Void) { |
| 1051 | guard let handle else { return done(false) } | |
| 820 | 1052 | let pointer = Int(bitPattern: handle) |
| 821 | 1053 | background({ sb_section_set_theme(OpaquePointer(bitPattern: pointer), id, scope, theme) }, done: done) |
| 822 | 1054 | } |
| 823 | 1055 | |
| 824 | 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 | } | |
| 826 | 1060 | |
| 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 | 15 | /// Posted when the app leaves the screen or quits: marked text is committed so it saves. |
| 16 | 16 | static let leaving = Notification.Name("SnowboundLeaving") |
| 17 | 17 | |
| 18 | private let section: Section | |
| 18 | private var section: Section? | |
| 19 | 19 | private let page: String |
| 20 | var notebook: Notebook? { section?.notebook } | |
| 20 | 21 | private let reveal: Reveal? |
| 21 | 22 | private let titleFocus: Bool |
| 22 | 23 | private lazy var canvas = CanvasView(section: section, page: page) |
| ... | ... | @@ -57,6 +58,17 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 57 | 58 | |
| 58 | 59 | required init?(coder: NSCoder) { fatalError() } |
| 59 | 60 | |
| 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 | 72 | override func loadView() { |
| 61 | 73 | let view = UIView() |
| 62 | 74 | view.backgroundColor = .systemBackground |
| ... | ... | @@ -141,7 +153,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 141 | 153 | private func editingChanged() { |
| 142 | 154 | if !canvas.readOnly, let title = canvas.pageTitle { |
| 143 | 155 | showTitle(title) |
| 144 | section.retitle(page, title) | |
| 156 | section?.retitle(page, title) | |
| 145 | 157 | } |
| 146 | 158 | fitTitle() |
| 147 | 159 | draw.isSelected = canvas.pickerShown |
| ... | ... | @@ -167,7 +179,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 167 | 179 | return [readingAction()] + [ |
| 168 | 180 | themeMenu(), |
| 169 | 181 | 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 | 183 | scene?.showTags(of: section.notebook, from: self) |
| 172 | 184 | }, |
| 173 | 185 | UIMenu(options: .displayInline, children: [ |
| ... | ... | @@ -184,7 +196,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 184 | 196 | }, |
| 185 | 197 | UIAction(title: "Delete Page", image: UIImage(systemName: "trash"), attributes: .destructive) { |
| 186 | 198 | [weak self] _ in |
| 187 | guard let self else { return } | |
| 199 | guard let self, let section else { return } | |
| 188 | 200 | section.delete([page]) |
| 189 | 201 | }, |
| 190 | 202 | ]), |
| ... | ... | @@ -248,7 +260,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 248 | 260 | /// The page's theme, its section's and its notebook's, each pickable; the page wears a |
| 249 | 261 | /// new one when it opens again. |
| 250 | 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 | 264 | return UIMenu(title: "Theme", image: UIImage(systemName: "textformat"), children: []) |
| 253 | 265 | } |
| 254 | 266 | let scopes: [(String, String?)] = [ |
| ... | ... | @@ -260,7 +272,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 260 | 272 | let choices = [(nil as String?, "None")] + themes.themes.map { ($0.id, $0.name) } |
| 261 | 273 | return UIMenu(title: title, children: choices.map { id, name in |
| 262 | 274 | 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 | 276 | section.setTheme(id, scope: UInt8(scope), of: page) { [weak self] _ in |
| 265 | 277 | self?.onOpen?(page) |
| 266 | 278 | } |
| ... | ... | @@ -273,6 +285,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 273 | 285 | /// Prints the page through the system's print sheet, or with `export` offers its PDF in |
| 274 | 286 | /// the share sheet, laid out as OneNote 2010 prints it on the region's paper. |
| 275 | 287 | private func printPage(export: Bool) { |
| 288 | guard let section else { return } | |
| 276 | 289 | let letter = ["US", "CA", "MX", "PR", "PH", "CL", "CO", "VE", "GT", "CR", "PA", "DO", "SV", "NI", "HN", "BZ"] |
| 277 | 290 | .contains(Locale.current.region?.identifier ?? "US") |
| 278 | 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 | 428 | canvas.reload(discard: false, pendingOnly: true) |
| 416 | 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 | 432 | if section.row(of: page) == nil { |
| 420 | 433 | // Deleted elsewhere, or a conflict page resolved: back to what the section lists. |
| 421 | 434 | if let first = section.rows.first { onOpen?(first.id) } |
| ... | ... | @@ -429,7 +442,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 429 | 442 | /// Only trouble shows: saving goes on quietly, as Notes saves. |
| 430 | 443 | private func showStatus() { |
| 431 | 444 | let status: String? = |
| 432 | switch section.status { | |
| 445 | switch section?.status { | |
| 433 | 446 | case .offline: "Offline" |
| 434 | 447 | case .notSaving: "Not Saving" |
| 435 | 448 | default: nil |
| ... | ... | @@ -444,7 +457,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 444 | 457 | // MARK: Conflicts |
| 445 | 458 | |
| 446 | 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 | 461 | if version != nil { |
| 449 | 462 | // Deleting a conflict page cannot be undone, so the button asks first. |
| 450 | 463 | let delete = UIAction( |
| ... | ... | @@ -462,7 +475,7 @@ final class PageViewController: UIViewController, PHPickerViewControllerDelegate |
| 462 | 475 | } |
| 463 | 476 | |
| 464 | 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 | 479 | if version != nil { |
| 467 | 480 | section.delete([page]) { [weak self] in self?.onOpen?(row.id) } |
| 468 | 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 | 1 | import UIKit |
| 2 | 2 | |
| 3 | 3 | /// 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. | |
| 5 | 7 | final class ServerViewController: UITableViewController, UITextFieldDelegate { |
| 6 | 8 | private static let lastKey = "server" |
| 7 | 9 | |
| 10 | private let editingNotebook: Notebook? | |
| 8 | 11 | private let address = UITextField() |
| 9 | 12 | private let name = UITextField() |
| 10 | 13 | private let password = UITextField() |
| 11 | 14 | private let guest = UISegmentedControl(items: ["Guest", "Registered User"]) |
| 12 | 15 | private var connecting = false |
| 13 | 16 | var onOpen: ((Notebook) -> Void)? |
| 17 | var onUpdate: ((@escaping () -> Void) -> Void)? | |
| 14 | 18 | |
| 15 | init() { | |
| 19 | init(editing notebook: Notebook? = nil) { | |
| 20 | self.editingNotebook = notebook | |
| 16 | 21 | super.init(style: .insetGrouped) |
| 17 | title = "Connect to Server" | |
| 22 | title = notebook == nil ? "Connect to Server" : "Change Server Address" | |
| 18 | 23 | } |
| 19 | 24 | |
| 20 | 25 | required init?(coder: NSCoder) { fatalError() } |
| ... | ... | @@ -26,7 +31,6 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { |
| 26 | 31 | navigationItem.rightBarButtonItem = UIBarButtonItem( |
| 27 | 32 | title: "Connect", primaryAction: UIAction { [weak self] _ in self?.connect() }) |
| 28 | 33 | address.placeholder = "smb://server/share" |
| 29 | address.text = UserDefaults.standard.string(forKey: Self.lastKey) | |
| 30 | 34 | address.keyboardType = .URL |
| 31 | 35 | address.autocapitalizationType = .none |
| 32 | 36 | address.autocorrectionType = .no |
| ... | ... | @@ -42,7 +46,15 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { |
| 42 | 46 | field.delegate = self |
| 43 | 47 | field.returnKeyType = field === password || field === address ? .go : .next |
| 44 | 48 | } |
| 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 | } | |
| 46 | 58 | guest.addAction(UIAction { [weak self] _ in self?.tableView.reloadData() }, for: .valueChanged) |
| 47 | 59 | tableView.register(UITableViewCell.self, forCellReuseIdentifier: "field") |
| 48 | 60 | } |
| ... | ... | @@ -65,17 +77,7 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { |
| 65 | 77 | |
| 66 | 78 | /// `smb://user@host:port/share/folder`, or the same without a scheme. |
| 67 | 79 | 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 ?? "") | |
| 79 | 81 | } |
| 80 | 82 | |
| 81 | 83 | private func connect() { |
| ... | ... | @@ -103,9 +105,11 @@ final class ServerViewController: UITableViewController, UITextFieldDelegate { |
| 103 | 105 | "Can’t Connect", "Check the address, name and password, and that the server is on this network.") |
| 104 | 106 | } |
| 105 | 107 | 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) | |
| 108 | 111 | browser.onOpen = onOpen |
| 112 | browser.onUpdate = onUpdate | |
| 109 | 113 | navigationController?.pushViewController(browser, animated: true) |
| 110 | 114 | } |
| 111 | 115 | } |
| ... | ... | @@ -157,13 +161,17 @@ final class ShareViewController: UITableViewController { |
| 157 | 161 | private let share: SharedConnection |
| 158 | 162 | private let server: Server |
| 159 | 163 | private let path: String |
| 164 | private let editingNotebook: Notebook? | |
| 160 | 165 | private var listing: Listing? |
| 166 | private var updating = false | |
| 161 | 167 | var onOpen: ((Notebook) -> Void)? |
| 168 | var onUpdate: ((@escaping () -> Void) -> Void)? | |
| 162 | 169 | |
| 163 | init(share: SharedConnection, server: Server, path: String) { | |
| 170 | init(share: SharedConnection, server: Server, path: String, editing notebook: Notebook? = nil) { | |
| 164 | 171 | self.share = share |
| 165 | 172 | self.server = server |
| 166 | 173 | self.path = path |
| 174 | self.editingNotebook = notebook | |
| 167 | 175 | super.init(style: .insetGrouped) |
| 168 | 176 | title = path.split(separator: "/").last.map(String.init) ?? server.share |
| 169 | 177 | } |
| ... | ... | @@ -173,7 +181,9 @@ final class ShareViewController: UITableViewController { |
| 173 | 181 | override func viewDidLoad() { |
| 174 | 182 | super.viewDidLoad() |
| 175 | 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 | 187 | open.style = .done |
| 178 | 188 | open.isEnabled = false |
| 179 | 189 | navigationItem.rightBarButtonItem = open |
| ... | ... | @@ -192,6 +202,19 @@ final class ShareViewController: UITableViewController { |
| 192 | 202 | if listing == nil { |
| 193 | 203 | empty.text = "Can’t Read Folder" |
| 194 | 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 | 218 | } else { |
| 196 | 219 | empty.text = "No Folders" |
| 197 | 220 | empty.secondaryText = "OneNote notebooks are folders with sections in them." |
| ... | ... | @@ -202,10 +225,32 @@ final class ShareViewController: UITableViewController { |
| 202 | 225 | } |
| 203 | 226 | |
| 204 | 227 | private func open() { |
| 228 | guard !updating else { return } | |
| 205 | 229 | var server = server |
| 206 | 230 | 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 | } | |
| 209 | 254 | } |
| 210 | 255 | |
| 211 | 256 | override func numberOfSections(in tableView: UITableView) -> Int { 2 } |
| ... | ... | @@ -245,8 +290,9 @@ final class ShareViewController: UITableViewController { |
| 245 | 290 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { |
| 246 | 291 | guard let folder = listing?.folders[indexPath.row] else { return } |
| 247 | 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 | 294 | child.onOpen = onOpen |
| 295 | child.onUpdate = onUpdate | |
| 250 | 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 | 237 | } |
| 238 | 238 | } |
| 239 | 239 | |
| 240 | private func isServer(_ notebook: Notebook) -> Bool { | |
| 241 | if case .server = notebook.source { return true } | |
| 242 | return false | |
| 243 | } | |
| 244 | ||
| 240 | 245 | override func numberOfSections(in tableView: UITableView) -> Int { 1 + notebooks.count } |
| 241 | 246 | |
| 242 | 247 | 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) | |
| 244 | 251 | } |
| 245 | 252 | |
| 246 | 253 | override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { |
| ... | ... | @@ -279,6 +286,15 @@ final class SyncViewController: UITableViewController { |
| 279 | 286 | return cell |
| 280 | 287 | } |
| 281 | 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 | 298 | let sync = sections[indexPath.row] |
| 283 | 299 | var content = UIListContentConfiguration.valueCell() |
| 284 | 300 | let tab = notebook.tabs.first { $0.path == sync.path } |
| ... | ... | @@ -301,8 +317,21 @@ final class SyncViewController: UITableViewController { |
| 301 | 317 | |
| 302 | 318 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { |
| 303 | 319 | 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) | |
| 307 | 336 | } |
| 308 | 337 | } |
crates/mobile/include/snowbound.h+3| ... | ... | @@ -66,6 +66,8 @@ char *sb_library_live_status(const Library *library); |
| 66 | 66 | bool sb_notebook_create(const char *path, const char *cache, const char *author, const char *date, const char *time, |
| 67 | 67 | char **error); |
| 68 | 68 | bool sb_notebook_moved(const char *cache, const char *from, const char *to, char **error); |
| 69 | bool 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); | |
| 69 | 71 | char *sb_library_sections(const Library *library); |
| 70 | 72 | int32_t sb_library_color(const Library *library); |
| 71 | 73 | char *sb_library_new_section(const Library *library, const char *folder, const char *name, const char *author, |
| ... | ... | @@ -86,6 +88,7 @@ void sb_library_touched(const Library *library, const char *path); |
| 86 | 88 | void sb_library_sync_now(const Library *library); |
| 87 | 89 | // Publishes, keeping offline copies; sb_library_close is Close Notebook and deletes them. |
| 88 | 90 | bool sb_library_flush(const Library *library, double seconds, char **error); |
| 91 | bool sb_library_stop(const Library *library, char **error); | |
| 89 | 92 | bool sb_library_close(const Library *library, double seconds, char **error); |
| 90 | 93 | void sb_library_free(const Library *library); |
| 91 | 94 |
crates/mobile/src/library.rs+269-10| ... | ... | @@ -376,6 +376,8 @@ pub struct Library { |
| 376 | 376 | open: Mutex<Vec<(String, Weak<Shared>)>>, |
| 377 | 377 | /// Work Offline, which sections opened later follow too. |
| 378 | 378 | offline: AtomicBool, |
| 379 | /// Set by `Library::stop` before relocating, so any in-flight `Section::flush` exits promptly. | |
| 380 | stopping: AtomicBool, | |
| 379 | 381 | /// Keys of the protected sections unlocked this run, by catalog path; in memory only. |
| 380 | 382 | keys: Mutex<HashMap<String, Key>>, |
| 381 | 383 | /// A file provider keeps the notebook elsewhere too, as iCloud Drive does: edits wait for a |
| ... | ... | @@ -502,6 +504,7 @@ impl Library { |
| 502 | 504 | background, |
| 503 | 505 | open: Mutex::default(), |
| 504 | 506 | offline: AtomicBool::new(false), |
| 507 | stopping: AtomicBool::new(false), | |
| 505 | 508 | keys: Default::default(), |
| 506 | 509 | elsewhere: !local, |
| 507 | 510 | }) |
| ... | ... | @@ -525,6 +528,7 @@ impl Library { |
| 525 | 528 | background: Some(background), |
| 526 | 529 | open: Mutex::default(), |
| 527 | 530 | offline: AtomicBool::new(false), |
| 531 | stopping: AtomicBool::new(false), | |
| 528 | 532 | keys: Default::default(), |
| 529 | 533 | elsewhere: false, |
| 530 | 534 | }; |
| ... | ... | @@ -584,6 +588,7 @@ impl Library { |
| 584 | 588 | background: Some(background), |
| 585 | 589 | open: Mutex::default(), |
| 586 | 590 | offline: AtomicBool::new(offline), |
| 591 | stopping: AtomicBool::new(false), | |
| 587 | 592 | keys: Default::default(), |
| 588 | 593 | elsewhere: false, |
| 589 | 594 | }) |
| ... | ... | @@ -621,6 +626,7 @@ impl Library { |
| 621 | 626 | background, |
| 622 | 627 | open: Mutex::default(), |
| 623 | 628 | offline: AtomicBool::new(false), |
| 629 | stopping: AtomicBool::new(false), | |
| 624 | 630 | keys: Default::default(), |
| 625 | 631 | elsewhere: !local, |
| 626 | 632 | }) |
| ... | ... | @@ -662,11 +668,7 @@ impl Library { |
| 662 | 668 | let Place::Share { server, root, .. } = &self.place else { |
| 663 | 669 | return None; |
| 664 | 670 | }; |
| 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)) | |
| 670 | 672 | } |
| 671 | 673 | |
| 672 | 674 | fn listed(&self) -> Option<Listed> { |
| ... | ... | @@ -1312,6 +1314,9 @@ impl Section { |
| 1312 | 1314 | } |
| 1313 | 1315 | let deadline = Instant::now() + limit; |
| 1314 | 1316 | loop { |
| 1317 | if self.library.stopping.load(Ordering::Acquire) { | |
| 1318 | return false; | |
| 1319 | } | |
| 1315 | 1320 | match section.pending() { |
| 1316 | 1321 | Ok(pending) if pending.is_empty() => return true, |
| 1317 | 1322 | Ok(_) if Instant::now() < deadline => { |
| ... | ... | @@ -1483,6 +1488,24 @@ impl Library { |
| 1483 | 1488 | Ok(()) |
| 1484 | 1489 | } |
| 1485 | 1490 | |
| 1491 | /// Makes every open section's submitted edits locally durable, then stops the background | |
| 1492 | /// sync thread without discarding replicas or queued edits, so the notebook's cache can be | |
| 1493 | /// relocated to a new URL. | |
| 1494 | pub(crate) fn stop(&self) -> Result<()> { | |
| 1495 | self.stopping.store(true, Ordering::Release); | |
| 1496 | for (_, shared) in self.open_sections() { | |
| 1497 | shared.section.set_offline(true); | |
| 1498 | shared | |
| 1499 | .section | |
| 1500 | .written() | |
| 1501 | .map_err(|_| "Some changes couldn’t be saved to this device.")?; | |
| 1502 | } | |
| 1503 | if let Some(background) = &self.background { | |
| 1504 | background.stop(); | |
| 1505 | } | |
| 1506 | Ok(()) | |
| 1507 | } | |
| 1508 | ||
| 1486 | 1509 | /// Publishes every edit the notebook's replicas hold within `limit`, keeping them and the |
| 1487 | 1510 | /// offline copies. |
| 1488 | 1511 | pub(crate) fn flush(&self, limit: Duration) -> Result<()> { |
| ... | ... | @@ -2104,6 +2127,68 @@ pub unsafe extern "C" fn sb_notebook_moved( |
| 2104 | 2127 | moved().map_err(|cause| failed(cause, error)).is_ok() |
| 2105 | 2128 | } |
| 2106 | 2129 | |
| 2130 | /// Moves the replicas and cached section listing of an SMB notebook from one server location | |
| 2131 | /// to another, keeping all offline copies and queued edits so they publish to the new URL. | |
| 2132 | /// Call after stopping the old library and closing its open sections. False, with `error` | |
| 2133 | /// set, when the replicas cannot be moved (for instance if the new URL already holds | |
| 2134 | /// conflicting unsaved edits). | |
| 2135 | /// | |
| 2136 | /// # Safety | |
| 2137 | /// Every string is NUL-terminated UTF-8; `error` is null or a place for a string. | |
| 2138 | #[unsafe(no_mangle)] | |
| 2139 | pub 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 | ||
| 2162 | pub(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 | 2192 | /// The notebook's sections read again, as JSON: each with `name`, `path`, `group`, |
| 2108 | 2193 | /// `color` as sRGB bytes, `readable`, `downloading` and `problem`, in the notebook's order; null |
| 2109 | 2194 | /// if it cannot be read. |
| ... | ... | @@ -2380,6 +2465,19 @@ pub unsafe extern "C" fn sb_library_flush( |
| 2380 | 2465 | .is_ok() |
| 2381 | 2466 | } |
| 2382 | 2467 | |
| 2468 | /// Ensures open sections' edits are durable on disk and stops the background sync thread | |
| 2469 | /// without discarding replicas or queued edits, before relocating a notebook (`sb_server_moved`). | |
| 2470 | /// | |
| 2471 | /// # Safety | |
| 2472 | /// `error` is null or a place for a string. | |
| 2473 | #[unsafe(no_mangle)] | |
| 2474 | pub 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 | 2481 | /// The notebook folder whose document is `root`, or with `folder` false the lone section |
| 2384 | 2482 | /// `root` names, as the provider `sb_set_provider` registered keeps it; `local` as |
| 2385 | 2483 | /// `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 | 2536 | boxed(server.connect().map_err(Into::into).map(Share), error) |
| 2439 | 2537 | } |
| 2440 | 2538 | |
| 2539 | fn 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 | ||
| 2551 | fn 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 | ||
| 2441 | 2559 | fn server( |
| 2442 | 2560 | address: *const c_char, |
| 2443 | 2561 | share: *const c_char, |
| ... | ... | @@ -2445,12 +2563,8 @@ fn server( |
| 2445 | 2563 | password: *const c_char, |
| 2446 | 2564 | domain: *const c_char, |
| 2447 | 2565 | ) -> Server { |
| 2448 | let mut address = string(address); | |
| 2449 | if !address.contains(':') { | |
| 2450 | address.push_str(":445"); | |
| 2451 | } | |
| 2452 | 2566 | Server { |
| 2453 | address, | |
| 2567 | address: normalize_address(string(address)), | |
| 2454 | 2568 | share: string(share), |
| 2455 | 2569 | user: string(user), |
| 2456 | 2570 | password: string(password), |
| ... | ... | @@ -2901,4 +3015,149 @@ mod tests { |
| 2901 | 3015 | ); |
| 2902 | 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 | 11 | use std::{ |
| 12 | 12 | io, |
| 13 | 13 | path::{Path, PathBuf}, |
| 14 | time::Duration, | |
| 14 | 15 | }; |
| 16 | use web_time::Instant; | |
| 15 | 17 | |
| 16 | 18 | /// The file in a replica folder naming the location its replicas belong to. |
| 17 | 19 | const LOCATION: &str = "location"; |
| ... | ... | @@ -46,6 +48,9 @@ pub fn smb(address: &str, share: &str, root: &str) -> String { |
| 46 | 48 | /// location within it, as a copy of a section keeps its own. Each replica `to` already holds |
| 47 | 49 | /// for the same section stays. Every replica moved must be closed. |
| 48 | 50 | pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> { |
| 51 | if from == to { | |
| 52 | return Ok(()); | |
| 53 | } | |
| 49 | 54 | let inner = within(cache, from); |
| 50 | 55 | move_folder(cache, from, to)?; |
| 51 | 56 | for (_, location) in inner { |
| ... | ... | @@ -58,6 +63,146 @@ pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> { |
| 58 | 63 | Ok(()) |
| 59 | 64 | } |
| 60 | 65 | |
| 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. | |
| 71 | pub 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`. | |
| 177 | fn 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. | |
| 198 | fn 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 | 206 | /// The folders of the locations within `location`, labelled, with their locations. |
| 62 | 207 | fn within(cache: &Path, location: &str) -> Vec<(PathBuf, String)> { |
| 63 | 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 | 366 | assert_eq!(published(&root, &cache), 0); |
| 367 | 367 | assert_eq!(published(&other, &cache), 1); |
| 368 | 368 | } |
| 369 | ||
| 370 | #[test] | |
| 371 | fn 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 | } |