1import Foundation
2import Security
3import UIKit
4
5/// A string the Rust library allocated, taken and freed.
6func take(_ text: UnsafeMutablePointer<CChar>?) -> String? {
7 guard let text else { return nil }
8 defer { sb_string_free(text) }
9 return String(cString: text)
10}
11
12func decode<T: Decodable>(_ type: T.Type, _ json: UnsafeMutablePointer<CChar>?) -> T? {
13 take(json).flatMap { try? JSONDecoder().decode(type, from: Data($0.utf8)) }
14}
15
16/// A page's title date and time, as OneNote writes them: the long date and short time.
17func titleDate(_ date: Date = Date()) -> (date: String, time: String) {
18 let formatter = DateFormatter()
19 formatter.dateStyle = .full
20 formatter.timeStyle = .none
21 let day = formatter.string(from: date)
22 formatter.dateStyle = .none
23 formatter.timeStyle = .short
24 return (day, formatter.string(from: date))
25}
26
27/// The user name edits are stored under, OneNote's Personalize setting; asked once.
28enum Author {
29 private static let key = "author"
30
31 static var name: String? {
32 get { UserDefaults.standard.string(forKey: key) }
33 set {
34 UserDefaults.standard.set(newValue, forKey: key)
35 // Open sections name it in their edits from now on.
36 for section in Section.all {
37 if let handle = section.handle { sb_section_set_author(handle, newValue ?? "") }
38 }
39 }
40 }
41
42 /// Asks for the user name OneNote shows beside changes, then runs `then`.
43 static func ask(from controller: UIViewController, then: @escaping () -> Void) {
44 let alert = UIAlertController(
45 title: "Personalize",
46 message: "OneNote shows your user name beside the pages and changes you make.",
47 preferredStyle: .alert)
48 let save = UIAlertAction(title: "Continue", style: .default) { [weak alert] _ in
49 name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces)
50 then()
51 }
52 alert.addTextField { field in
53 field.text = name
54 field.placeholder = "User name"
55 field.textContentType = .name
56 field.autocapitalizationType = .words
57 save.isEnabled = !(field.text ?? "").isEmpty
58 NotificationCenter.default.addObserver(
59 forName: UITextField.textDidChangeNotification, object: field, queue: .main
60 ) { _ in save.isEnabled = !(field.text ?? "").trimmingCharacters(in: .whitespaces).isEmpty }
61 }
62 alert.addAction(save)
63 alert.preferredAction = save
64 controller.present(alert, animated: true)
65 }
66}
67
68/// An SMB share and the folder of a notebook on it.
69struct Server: Codable, Equatable {
70 /// `host` or `host:port`.
71 var host: String
72 var share: String
73 /// Empty for a guest.
74 var user: String
75 /// The notebook folder, `/`-separated from the share's top.
76 var root: String
77
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 }
164}
165
166/// The password of an SMB account, kept in the Keychain as Files keeps a server's.
167enum Keychain {
168 private static func query(_ server: Server) -> [String: Any] {
169 [
170 kSecClass as String: kSecClassInternetPassword,
171 kSecAttrServer as String: server.hostName,
172 kSecAttrPort as String: server.port,
173 kSecAttrProtocol as String: kSecAttrProtocolSMB,
174 kSecAttrAccount as String: server.user,
175 ]
176 }
177
178 static func password(_ server: Server) -> String? {
179 var query = query(server)
180 query[kSecReturnData as String] = true
181 var result: AnyObject?
182 guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data
183 else { return nil }
184 return String(data: data, encoding: .utf8)
185 }
186
187 static func save(_ password: String, for server: Server) {
188 SecItemDelete(query(server) as CFDictionary)
189 var item = query(server)
190 item[kSecValueData as String] = Data(password.utf8)
191 item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
192 SecItemAdd(item as CFDictionary, nil)
193 }
194}
195
196/// Where a notebook lives, as the notebook list keeps it.
197enum Source: Codable, Equatable {
198 /// A folder or section file chosen in Files, as a security-scoped bookmark.
199 case files(bookmark: Data)
200 /// A folder in the app's Documents, which Files shows as Snowbound's.
201 case documents(path: String)
202 /// A folder in Snowbound's folder in iCloud Drive (`ICloud.documents`).
203 case icloud(path: String)
204 /// A notebook folder on an SMB share, opened through Snowbound's own client.
205 case server(Server)
206 /// A folder or section at an absolute path, for scripted runs.
207 case path(String)
208}
209
210/// A section tab from `sb_library_sections`.
211struct Tab: Decodable, Equatable {
212 let name: String
213 /// The catalog path `sb_section_open` takes.
214 let path: String
215 /// The section group holding it, `/`-separated; empty at the notebook's top.
216 let group: String
217 let color: [UInt8]
218 let readable: Bool
219 /// Password protected and not unlocked: `Notebook.unlock` opens it.
220 let locked: Bool
221 /// Not on this device yet; `Notebook` asks iCloud Drive for it.
222 let downloading: Bool
223 /// Why the file could not be read, where retrying or repair may help.
224 let problem: String?
225
226 var uiColor: UIColor { UIColor(rgb: color) }
227}
228
229extension UIImage {
230 /// A notebook's binder, the desktop's art, `side` points square: its cover in `color`, or
231 /// the art's own orange.
232 static func notebook(_ color: UIColor?, side: CGFloat = 28) -> UIImage {
233 let frame = CGRect(x: 0, y: 0, width: side, height: side)
234 let cover = color ?? UIColor(rgb: [0xf3, 0x9c, 0x28])
235 return UIGraphicsImageRenderer(size: frame.size).image { _ in
236 UIImage(named: "NotebookBack")?.draw(in: frame)
237 UIImage(named: "NotebookCover")?.withTintColor(cover, renderingMode: .alwaysOriginal).draw(in: frame)
238 UIImage(named: "Notebook")?.draw(in: frame)
239 }.withRenderingMode(.alwaysOriginal)
240 }
241}
242
243extension UIViewController {
244 /// Tells the reader `title` and `message` in an alert they dismiss with OK.
245 func alert(_ title: String, _ message: String) {
246 let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
247 alert.addAction(UIAlertAction(title: "OK", style: .default))
248 present(alert, animated: true)
249 }
250}
251
252/// Runs `work` off the main thread, then `done` with its result on it.
253func background<T>(_ work: @escaping () -> T, done: @escaping (T) -> Void) {
254 DispatchQueue.global(qos: .userInitiated).async {
255 let result = work()
256 DispatchQueue.main.async { done(result) }
257 }
258}
259
260/// Where section replicas live: kept, as they hold edits not yet published.
261let cacheDirectory: URL = {
262 let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
263 .appendingPathComponent("Sections", isDirectory: true)
264 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
265 return url
266}()
267
268let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
269
270/// An open notebook: its Rust library and the sections it lists.
271final class Notebook {
272 /// A UUID, or `Documents/` and the folder's name for a notebook On My iPhone.
273 let id: String
274 private(set) var source: Source
275 private(set) var name: String
276 private(set) var handle: OpaquePointer?
277 private(set) var tabs: [Tab] = []
278 /// The notebook's colour, which its binder's cover takes in the list; none where it has none.
279 private(set) var color: UIColor?
280 /// Why the notebook could not be opened, while it cannot.
281 private(set) var problem: String?
282 /// The Files location being read, held open while the notebook is.
283 private var accessed: URL?
284 /// Reports other apps' changes to a folder on this device to the library.
285 private var presenter: FolderPresenter?
286 /// Lists the sections again while iCloud Drive downloads some.
287 private var recheck: DispatchWorkItem?
288 /// Posted on the main thread when the sections list again on their own.
289 static let listed = Notification.Name("NotebookListed")
290
291 init(id: String = UUID().uuidString, name: String, source: Source) {
292 self.id = id
293 self.name = name
294 self.source = source
295 }
296
297 deinit {
298 presenter?.stop()
299 if let handle { sb_library_free(handle) }
300 accessed?.stopAccessingSecurityScopedResource()
301 }
302
303 /// Opens the library off the main thread and lists its sections; `done` runs on the main
304 /// thread either way.
305 func open(done: @escaping () -> Void) {
306 let source = source
307 // The library, the Files location held open, why it failed, and a local folder to watch.
308 background({ () -> (OpaquePointer?, URL?, String?, URL?) in
309 var error: UnsafeMutablePointer<CChar>?
310 switch source {
311 case .server(let server):
312 let library = sb_library_server(
313 server.host, server.share, server.user, Keychain.password(server) ?? "", "", server.root,
314 cacheDirectory.path, &error)
315 return (library, nil, take(error), nil)
316 case .files(let bookmark):
317 var stale = false
318 guard let url = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale) else {
319 return (nil, nil, "The notebook was moved or deleted.", nil)
320 }
321 let accessed = url.startAccessingSecurityScopedResource() ? url : nil
322 let local = onThisDevice(url)
323 let (library, problem) = coordinatedOpen(url, local: local)
324 return (library, accessed, problem, local ? url : nil)
325 case .documents(let path):
326 let url = documentsDirectory.appendingPathComponent(path)
327 let library = sb_library_open(url.path, cacheDirectory.path, true, &error)
328 return (library, nil, take(error), url)
329 case .icloud(let path):
330 guard let url = ICloud.documents?.appendingPathComponent(path) else {
331 return (nil, nil, "Turn on iCloud Drive in Settings to open this notebook.", nil)
332 }
333 let (library, problem) = coordinatedOpen(url, local: false)
334 return (library, nil, problem, url)
335 case .path(let path):
336 let url = URL(fileURLWithPath: path)
337 let local = onThisDevice(url)
338 return (sb_library_open(path, cacheDirectory.path, local, &error), nil, take(error), local ? url : nil)
339 }
340 }) { [self] (library, accessed, problem, watched) in
341 self.accessed?.stopAccessingSecurityScopedResource()
342 self.accessed = accessed
343 presenter?.stop()
344 presenter = nil
345 if let handle { sb_library_free(handle) }
346 handle = library
347 if let library, let watched { presenter = FolderPresenter(watching: watched, for: library) }
348 self.problem = library == nil ? (problem ?? "The notebook can’t be read.") : nil
349 follow()
350 reload(done: done)
351 // As OneNote prunes the recycle bin after opening.
352 if let library {
353 let pointer = Int(bitPattern: library)
354 background({ sb_library_purge_recycle_bin(OpaquePointer(bitPattern: pointer)) }) { _ in }
355 }
356 }
357 }
358
359 /// Works offline or online, as Work Offline stands.
360 func follow() {
361 if let handle { sb_library_set_offline(handle, Sync.offline) }
362 }
363
364 /// Where the notebook is kept, as the sync sheet names it.
365 var location: String {
366 switch source {
367 case .files: "In Files"
368 case .documents: "On My \(UIDevice.current.model), in Snowbound’s folder"
369 case .icloud: "In iCloud Drive"
370 case .server(let server): server.url
371 case .path(let path): path
372 }
373 }
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
490 /// Unlocks the protected section at `path` with `password` off the main thread, then lists
491 /// the sections again; `done` learns whether the password matched.
492 func unlock(_ path: String, password: String, done: @escaping (Bool) -> Void) {
493 guard let handle else { return done(false) }
494 let pointer = Int(bitPattern: handle)
495 background({ sb_library_unlock(OpaquePointer(bitPattern: pointer), path, password) }) { [self] unlocked in
496 reload { done(unlocked) }
497 }
498 }
499
500 /// Locks every protected section, as OneNote's Lock All does.
501 func lockAll() {
502 if let handle { sb_library_lock_all(handle) }
503 }
504
505 /// Lists the sections again, off the main thread.
506 func reload(done: @escaping () -> Void) {
507 guard let handle else {
508 tabs = []
509 return done()
510 }
511 let pointer = Int(bitPattern: handle)
512 background({ () -> ([Tab]?, Int32) in
513 let library = OpaquePointer(bitPattern: pointer)
514 return (decode([Tab].self, sb_library_sections(library)), sb_library_color(library))
515 }) { [self] (tabs, color) in
516 if let tabs { self.tabs = tabs }
517 self.color = color < 0 ? nil : UIColor(rgb: [16, 8, 0].map { UInt8(truncatingIfNeeded: color >> $0) })
518 download()
519 done()
520 }
521 }
522
523 /// Asks iCloud Drive for the notebook files it keeps elsewhere, which iOS lists as
524 /// `.Name.icloud` or dataless under their names, or holds a newer version of, and lists the
525 /// sections again until they arrive.
526 private func download() {
527 let folder: URL? =
528 switch source {
529 case .files: accessed
530 case .documents(let path): documentsDirectory.appendingPathComponent(path)
531 case .icloud(let path): ICloud.documents?.appendingPathComponent(path)
532 case .path(let path): URL(fileURLWithPath: path)
533 case .server: nil
534 }
535 guard let folder, recheck == nil,
536 let files = FileManager.default.enumerator(
537 at: folder, includingPropertiesForKeys: [.ubiquitousItemDownloadingStatusKey])
538 else { return }
539 var waiting = false
540 for case let file as URL in files {
541 let stub = file.lastPathComponent.hasPrefix(".") && file.pathExtension == "icloud"
542 let status = try? file.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey])
543 let stale = status?.ubiquitousItemDownloadingStatus.map { $0 != .current } ?? false
544 guard stub || stale else { continue }
545 let real = file.deletingLastPathComponent().appendingPathComponent(
546 String(file.deletingPathExtension().lastPathComponent.dropFirst()))
547 try? FileManager.default.startDownloadingUbiquitousItem(at: stub ? real : file)
548 waiting = true
549 }
550 guard waiting else { return }
551 let recheck = DispatchWorkItem { [weak self] in
552 self?.recheck = nil
553 self?.reload { NotificationCenter.default.post(name: Self.listed, object: self) }
554 }
555 self.recheck = recheck
556 DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: recheck)
557 }
558
559 /// Stops hearing other apps' writes while in the background, where a suspended presenter
560 /// can deadlock their coordinated writes.
561 func pause() { presenter?.stop() }
562
563 /// Hears other apps' writes again, and checks the sections and their list for those
564 /// missed meanwhile.
565 func resume() {
566 presenter?.resume()
567 reload { NotificationCenter.default.post(name: Self.listed, object: self) }
568 }
569}
570
571/// Opens the library at `url` within a coordinated read, which brings a cloud folder's files
572/// down before they are read; nil with why where it cannot.
573private func coordinatedOpen(_ url: URL, local: Bool) -> (OpaquePointer?, String?) {
574 var library: OpaquePointer?
575 var error: UnsafeMutablePointer<CChar>?
576 var coordination: NSError?
577 NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &coordination) { url in
578 library = sb_library_open(url.path, cacheDirectory.path, local, &error)
579 }
580 return (library, take(error) ?? coordination?.localizedDescription)
581}
582
583/// Whether `url` is kept on this device, rather than by a file provider that keeps it elsewhere
584/// too, as iCloud Drive does.
585private func onThisDevice(_ url: URL) -> Bool {
586 let values = try? url.resourceValues(forKeys: [.volumeIsLocalKey, .isUbiquitousItemKey])
587 return values?.volumeIsLocal == true && values?.isUbiquitousItem != true
588}
589
590/// Tells a library which files of its folder on this device changed, as file coordination
591/// reports other apps' writes; the library checks just those sections.
592final class FolderPresenter: NSObject, NSFilePresenter {
593 let presentedItemURL: URL?
594 let presentedItemOperationQueue: OperationQueue = {
595 let queue = OperationQueue()
596 queue.maxConcurrentOperationCount = 1
597 return queue
598 }()
599 private let root: String
600 private let library: OpaquePointer
601
602 init(watching url: URL, for library: OpaquePointer) {
603 presentedItemURL = url
604 root = url.standardizedFileURL.resolvingSymlinksInPath().path
605 self.library = library
606 super.init()
607 NSFileCoordinator.addFilePresenter(self)
608 }
609
610 func resume() {
611 NSFileCoordinator.addFilePresenter(self)
612 touched("")
613 }
614
615 /// Stops reporting, before the library goes or the app leaves the foreground.
616 func stop() {
617 NSFileCoordinator.removeFilePresenter(self)
618 presentedItemOperationQueue.waitUntilAllOperationsAreFinished()
619 }
620
621 func presentedItemDidChange() { touched("") }
622 func presentedSubitemDidChange(at url: URL) { touched(url) }
623 func presentedSubitemDidAppear(at url: URL) { touched(url) }
624 /// Another device's commit that lost in iCloud Drive, which changes no file.
625 func presentedSubitem(at url: URL, didGain version: NSFileVersion) { touched(url) }
626 func presentedSubitem(at oldURL: URL, didMoveTo newURL: URL) {
627 touched(oldURL)
628 touched(newURL)
629 }
630 func accommodatePresentedSubitemDeletion(at url: URL, completionHandler: @escaping (Error?) -> Void) {
631 touched(url)
632 completionHandler(nil)
633 }
634
635 private func touched(_ url: URL) {
636 let path = url.standardizedFileURL.resolvingSymlinksInPath().path
637 touched(path.hasPrefix(root + "/") ? String(path.dropFirst(root.count + 1)) : "")
638 }
639
640 private func touched(_ path: String) {
641 sb_library_touched(library, path)
642 }
643}
644
645/// The notebooks the list shows: those in Documents, and those opened from elsewhere, kept
646/// across launches.
647enum Notebooks {
648 private struct Entry: Codable {
649 let id: String
650 let name: String
651 let source: Source
652 }
653
654 private static let key = "notebooks"
655 private static let hidden = "hidesOnDevice"
656 /// The notebooks' ids in the order the reader put them in.
657 private static let order = "notebookOrder"
658 /// The Snowbound Guide's folder, in the app and in Documents once copied there.
659 static let guide = "Snowbound Guide"
660 /// Whether the list offers the guide; off until Clover has read it through.
661 static let guideOffered = false
662 private static let scripted = ProcessInfo.processInfo.environment["SNOWBOUND_NOTEBOOK"]
663 /// The folders and sections in Documents, as On My iPhone lists them.
664 private(set) static var onDevice: [Notebook] = []
665 /// The folders in Snowbound's folder in iCloud Drive.
666 private(set) static var inCloud: [Notebook] = []
667 private(set) static var elsewhere: [Notebook] = []
668 static var all: [Notebook] { inCloud + onDevice + elsewhere }
669
670 /// Whether the list shows On My iPhone, as Files lets a location be hidden.
671 static var showsOnDevice: Bool {
672 get { scripted == nil && !UserDefaults.standard.bool(forKey: hidden) }
673 set { UserDefaults.standard.set(!newValue, forKey: hidden) }
674 }
675
676 /// The kept notebooks and those in Documents.
677 static func load() {
678 if let scripted {
679 elsewhere = [
680 Notebook(
681 name: URL(fileURLWithPath: scripted).deletingPathExtension().lastPathComponent,
682 source: .path(scripted))
683 ]
684 return
685 }
686 if let data = UserDefaults.standard.data(forKey: key),
687 let entries = try? JSONDecoder().decode([Entry].self, from: data)
688 {
689 elsewhere = ordered(entries.compactMap { entry in
690 switch entry.source {
691 case .documents, .icloud: return nil
692 default: break
693 }
694 return Notebook(id: entry.id, name: entry.name, source: entry.source)
695 })
696 } else {
697 // The notebook the first version remembered from Files.
698 if let bookmark = UserDefaults.standard.data(forKey: "notebook") {
699 var stale = false
700 let name = (try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale))?
701 .deletingPathExtension().lastPathComponent
702 elsewhere.append(Notebook(name: name ?? "Notebook", source: .files(bookmark: bookmark)))
703 }
704 save()
705 }
706 scan()
707 }
708
709 /// Lists Documents again, keeping the notebooks still there; returns those new to the list.
710 @discardableResult
711 static func scan() -> [Notebook] {
712 let folder = showsOnDevice ? documentsDirectory : nil
713 return rescan(folder, "Documents/", &onDevice) { .documents(path: $0) }
714 }
715
716 /// Lists Snowbound's folder in iCloud Drive again, as `scan` lists Documents; none while
717 /// iCloud Drive is off.
718 @discardableResult
719 static func scanICloud() -> [Notebook] {
720 rescan(scripted == nil ? ICloud.documents : nil, "iCloud/", &inCloud) { .icloud(path: $0) }
721 }
722
723 /// Lists `folder`'s notebooks into `list`, keeping those still there and naming new ones by
724 /// `prefix` and their `source`; returns the new ones.
725 private static func rescan(
726 _ folder: URL?, _ prefix: String, _ list: inout [Notebook], source: (String) -> Source
727 ) -> [Notebook] {
728 guard let folder else {
729 list = []
730 return []
731 }
732 guard let names = notebooks(in: folder) else { return [] }
733 var added: [Notebook] = []
734 list = ordered(
735 names.map { [list] name in
736 if let kept = list.first(where: { $0.id == prefix + name }) { return kept }
737 let notebook = Notebook(
738 id: prefix + name, name: (name as NSString).deletingPathExtension, source: source(name))
739 added.append(notebook)
740 return notebook
741 })
742 return added
743 }
744
745 /// `list` in the reader's order, those it doesn't name after in their own.
746 private static func ordered(_ list: [Notebook]) -> [Notebook] {
747 let order = UserDefaults.standard.stringArray(forKey: order) ?? []
748 let rank = { (notebook: Notebook) in order.firstIndex(of: notebook.id) ?? order.count }
749 return list.enumerated().sorted { (rank($0.element), $0.offset) < (rank($1.element), $1.offset) }.map(\.element)
750 }
751
752 /// The notebooks listed in the same place as `notebook`, in order.
753 static func siblings(of notebook: Notebook) -> [Notebook] {
754 [inCloud, onDevice, elsewhere].first { $0.contains { $0 === notebook } } ?? []
755 }
756
757 /// Puts `notebook` at `index` among the notebooks of its place, and keeps that order.
758 static func move(_ notebook: Notebook, to index: Int) {
759 func move(in list: inout [Notebook]) {
760 guard let at = list.firstIndex(where: { $0 === notebook }) else { return }
761 let moved = list.remove(at: at)
762 list.insert(moved, at: min(max(index, 0), list.count))
763 }
764 move(in: &inCloud)
765 move(in: &onDevice)
766 move(in: &elsewhere)
767 guard scripted == nil else { return }
768 UserDefaults.standard.set(all.map(\.id), forKey: order)
769 }
770
771 /// Whether Snowbound's folder in iCloud Drive holds other notebooks than the list shows, as
772 /// when another device added or removed one.
773 static var inCloudChanged: Bool {
774 guard let folder = ICloud.documents, scripted == nil, let names = notebooks(in: folder) else { return false }
775 return names.map { "iCloud/" + $0 } != inCloud.map(\.id)
776 }
777
778 /// The notebook folders and section files in `folder`, by name, as Files orders them.
779 private static func notebooks(in folder: URL) -> [String]? {
780 guard let listed = try? FileManager.default.contentsOfDirectory(
781 at: folder, includingPropertiesForKeys: [.isDirectoryKey], options: .skipsHiddenFiles)
782 else { return nil }
783 return listed.filter { url in
784 (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true
785 || url.pathExtension.lowercased() == "one"
786 }
787 .map(\.lastPathComponent)
788 .sorted { $0.localizedStandardCompare($1) == .orderedAscending }
789 }
790
791 static func add(_ notebook: Notebook) {
792 elsewhere.append(notebook)
793 save()
794 }
795
796 static func remove(_ notebook: Notebook) {
797 elsewhere.removeAll { $0 === notebook }
798 save()
799 }
800
801 static func save() {
802 guard scripted == nil else { return }
803 let entries = elsewhere.map { Entry(id: $0.id, name: $0.name, source: $0.source) }
804 UserDefaults.standard.set(try? JSONEncoder().encode(entries), forKey: key)
805 }
806}
807
808/// A page row from `sb_section_pages`.
809struct Row: Decodable, Equatable {
810 struct Version: Decodable, Equatable {
811 let id: String
812 let user: String
813 /// Seconds since 1970.
814 let created: Double?
815 }
816
817 let id: String
818 var title: String
819 /// 1 at the top, 2 for a subpage and so on.
820 let level: Int
821 /// Conflict pages: versions with changes a merge could not take.
822 let versions: [Version]
823}
824
825/// Saving as the section reports it, from `sb_section_poll`.
826enum SaveStatus: UInt8 {
827 case unknown, saved, saving, offline, notSaving
828}
829
830private let wakeSection: sb_wake = { token in
831 DispatchQueue.main.async { Section.open[Int(token)]?.value?.poll() }
832}
833
834private struct Weak<T: AnyObject> { weak var value: T? }
835
836/// A section open for editing: pages listed and saved through its replica.
837final class Section {
838 /// Sent on the main thread with `flags` from `sb_section_poll`, `listed` once the rows are read again.
839 static let changed = Notification.Name("SectionChanged")
840 static let listed: UInt32 = 1
841 static let remote: UInt32 = 2
842 static let rejected: UInt32 = 4
843
844 fileprivate static var open: [Int: Weak<Section>] = [:]
845 /// Sections reporting Not Saving, kept open so that edits waiting in memory stay with them.
846 private static var unsaved: [Int: Section] = [:]
847 private static var tokens = 0
848
849 let notebook: Notebook
850 let tab: Tab
851 private(set) var handle: OpaquePointer?
852 private let token: Int
853 private(set) var rows: [Row]
854 private(set) var status = SaveStatus.unknown
855 private var listing: (invalidated: Bool, completions: [() -> Void])?
856
857 static var all: [Section] { open.values.compactMap(\.value) }
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
865 private init(notebook: Notebook, tab: Tab, handle: OpaquePointer, token: Int, rows: [Row]) {
866 self.notebook = notebook
867 self.tab = tab
868 self.handle = handle
869 self.token = token
870 self.rows = rows
871 }
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
885 deinit {
886 Self.open[token] = nil
887 if let handle { sb_section_free(handle) }
888 }
889
890 /// Opens `tab` of `notebook` off the main thread, or hands back the section already open
891 /// there, as its replica takes one owner at a time.
892 static func open(_ tab: Tab, of notebook: Notebook, done: @escaping (Section?, String?) -> Void) {
893 if let section = all.first(where: { $0.notebook === notebook && $0.tab.path == tab.path }) {
894 return done(section, nil)
895 }
896 guard let library = notebook.handle else { return done(nil, notebook.problem) }
897 tokens += 1
898 let token = tokens
899 let pointer = Int(bitPattern: library)
900 let author = Author.name ?? ""
901 background({ () -> (Int, String?, [Row]) in
902 var error: UnsafeMutablePointer<CChar>?
903 let handle = sb_section_open(
904 OpaquePointer(bitPattern: pointer), tab.path, author, wakeSection, UInt(token), &error)
905 let rows = handle.flatMap { decode([Row].self, sb_section_pages($0)) } ?? []
906 return (Int(bitPattern: handle), take(error), rows)
907 }) { handle, error, rows in
908 guard let handle = OpaquePointer(bitPattern: handle) else { return done(nil, error) }
909 let section = Section(notebook: notebook, tab: tab, handle: handle, token: token, rows: rows)
910 open[token] = Weak(value: section)
911 done(section, nil)
912 // Wakes before `open[token]` was set went unheard.
913 section.poll()
914 }
915 }
916
917 /// Lists the pages again and tells the views.
918 func reloadRows() {
919 guard let handle else { return }
920 listing?.invalidated = true
921 rows = decode([Row].self, sb_section_pages(handle)) ?? rows
922 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
923 }
924
925 /// Lists the pages again off the main thread, tells the views, then runs `then`.
926 private func refreshRows(then: @escaping () -> Void = {}) {
927 guard listing == nil else {
928 listing?.invalidated = true
929 listing?.completions.append(then)
930 return
931 }
932 listing = (false, [then])
933 readRows()
934 }
935
936 private func readRows() {
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 }
946 // A read begun before a reload or retitle would undo it.
947 if current.invalidated, rows != nil {
948 listing?.invalidated = false
949 return readRows()
950 }
951 self.rows = rows ?? self.rows
952 let completions = current.completions
953 listing = nil
954 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
955 for completion in completions { completion() }
956 }
957 }
958
959 /// The row listing page or conflict page `id`, and the version when it is one.
960 func row(of id: String) -> (row: Row, version: Row.Version?)? {
961 for row in rows {
962 if row.id == id { return (row, nil) }
963 if let version = row.versions.first(where: { $0.id == id }) { return (row, version) }
964 }
965 return nil
966 }
967
968 fileprivate func poll() {
969 guard let handle else { return }
970 var status: UInt8 = 0
971 let flags = sb_section_poll(handle, &status)
972 let changed = SaveStatus(rawValue: status) ?? .unknown
973 if flags & Self.listed != 0 { refreshRows() }
974 let unlisted = flags & ~Self.listed
975 let unchanged = unlisted == 0 && changed == self.status
976 self.status = changed
977 Self.unsaved[token] = changed == .notSaving ? self : nil
978 NotificationCenter.default.post(
979 name: Self.changed, object: self,
980 userInfo: unchanged ? ["flags": unlisted, "unchanged": true] : ["flags": unlisted])
981 }
982
983 /// A page's title as typed, shown in the list before the section reports it.
984 func retitle(_ id: String, _ title: String) {
985 guard let index = rows.firstIndex(where: { $0.id == id }), rows[index].title != title else { return }
986 listing?.invalidated = true
987 rows[index].title = title
988 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": UInt32(0)])
989 }
990
991 /// Adds a page, or a subpage of `parent`; returns its id.
992 func newPage(under parent: String? = nil) -> String? {
993 guard let handle else { return nil }
994 let (date, time) = titleDate()
995 let id = take(sb_section_new_page(handle, parent, date, time))
996 reloadRows()
997 return id
998 }
999
1000 /// Deletes pages, conflict pages for good and the rest to the recycle bin, which a toast
1001 /// then offers.
1002 func delete(_ ids: [String], done: @escaping () -> Void = {}) {
1003 guard let handle, let release = Arranging.reserve() else { return }
1004 let recycled = notebook.hasRecycleBin ? ids.filter { row(of: $0)?.version == nil }.count : 0
1005 let (date, time) = titleDate()
1006 let pointer = Int(bitPattern: handle)
1007 background({
1008 for id in ids {
1009 guard sb_section_delete_page(OpaquePointer(bitPattern: pointer), id, date, time) else { return false }
1010 }
1011 return true
1012 }) { [self] deleted in
1013 refreshRows {
1014 release()
1015 let window = UIApplication.shared.connectedScenes.lazy.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first
1016 guard deleted else {
1017 window?.rootViewController?.alert("Can’t Delete", "Some pages couldn’t be deleted. Try again.")
1018 return
1019 }
1020 done()
1021 if recycled > 0, let window {
1022 let title = recycled == 1 ? "Page Moved to Recycle Bin" : "\(recycled) Pages Moved to Recycle Bin"
1023 let detail = recycled == 1 ? "Restore it from the Recycle Bin" : "Restore them from the Recycle Bin"
1024 SyncToast.show(title, detail, symbol: "trash", hint: "Opens the Recycle Bin", in: window) {
1025 [notebook = self.notebook] in RecycleBinViewController.present(notebook, in: window)
1026 }
1027 }
1028 }
1029 }
1030 }
1031
1032 /// The notebook's themes, and the one page `id`, its section and its notebook each name.
1033 struct Themes: Decodable {
1034 struct Listed: Decodable {
1035 let id: String
1036 let name: String
1037 }
1038 let themes: [Listed]
1039 let page: String?
1040 let section: String?
1041 let notebook: String?
1042 }
1043
1044 func themes(of id: String) -> Themes? {
1045 handle.flatMap { decode(Themes.self, sb_section_themes($0, id)) }
1046 }
1047
1048 /// Gives `theme`, or none of its own, to page `id` (scope 0), its section (1) or its
1049 /// notebook (2).
1050 func setTheme(_ theme: String?, scope: UInt8, of id: String, done: @escaping (Bool) -> Void) {
1051 guard let handle else { return done(false) }
1052 let pointer = Int(bitPattern: handle)
1053 background({ sb_section_set_theme(OpaquePointer(bitPattern: pointer), id, scope, theme) }, done: done)
1054 }
1055
1056 /// Stores every edit and publishes them within `seconds`; call off the main thread.
1057 func flush(_ seconds: Double) -> Bool {
1058 handle.map { sb_section_flush($0, seconds) } ?? true
1059 }
1060
1061 func wake() {
1062 if let handle { sb_section_wake(handle) }
1063 }
1064}