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 { sb_section_set_author(section.handle, newValue ?? "") }
37 }
38 }
39
40 /// Asks for the user name OneNote shows beside changes, then runs `then`.
41 static func ask(from controller: UIViewController, then: @escaping () -> Void) {
42 let alert = UIAlertController(
43 title: "Personalize",
44 message: "OneNote shows your user name beside the pages and changes you make.",
45 preferredStyle: .alert)
46 let save = UIAlertAction(title: "Continue", style: .default) { [weak alert] _ in
47 name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces)
48 then()
49 }
50 alert.addTextField { field in
51 field.text = name
52 field.placeholder = "User name"
53 field.textContentType = .name
54 field.autocapitalizationType = .words
55 save.isEnabled = !(field.text ?? "").isEmpty
56 NotificationCenter.default.addObserver(
57 forName: UITextField.textDidChangeNotification, object: field, queue: .main
58 ) { _ in save.isEnabled = !(field.text ?? "").trimmingCharacters(in: .whitespaces).isEmpty }
59 }
60 alert.addAction(save)
61 alert.preferredAction = save
62 controller.present(alert, animated: true)
63 }
64}
65
66/// An SMB share and the folder of a notebook on it.
67struct Server: Codable, Equatable {
68 /// `host` or `host:port`.
69 var host: String
70 var share: String
71 /// Empty for a guest.
72 var user: String
73 /// The notebook folder, `/`-separated from the share's top.
74 var root: String
75
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}
79
80/// The password of an SMB account, kept in the Keychain as Files keeps a server's.
81enum Keychain {
82 private static func query(_ server: Server) -> [String: Any] {
83 [
84 kSecClass as String: kSecClassInternetPassword,
85 kSecAttrServer as String: server.hostName,
86 kSecAttrPort as String: server.port,
87 kSecAttrProtocol as String: kSecAttrProtocolSMB,
88 kSecAttrAccount as String: server.user,
89 ]
90 }
91
92 static func password(_ server: Server) -> String? {
93 var query = query(server)
94 query[kSecReturnData as String] = true
95 var result: AnyObject?
96 guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data
97 else { return nil }
98 return String(data: data, encoding: .utf8)
99 }
100
101 static func save(_ password: String, for server: Server) {
102 SecItemDelete(query(server) as CFDictionary)
103 var item = query(server)
104 item[kSecValueData as String] = Data(password.utf8)
105 item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
106 SecItemAdd(item as CFDictionary, nil)
107 }
108}
109
110/// Where a notebook lives, as the notebook list keeps it.
111enum Source: Codable, Equatable {
112 /// A folder or section file chosen in Files, as a security-scoped bookmark.
113 case files(bookmark: Data)
114 /// A folder in the app's Documents, which Files shows as Snowbound's.
115 case documents(path: String)
116 /// A folder in Snowbound's folder in iCloud Drive (`ICloud.documents`).
117 case icloud(path: String)
118 /// A notebook folder on an SMB share, opened through Snowbound's own client.
119 case server(Server)
120 /// A folder or section at an absolute path, for scripted runs.
121 case path(String)
122}
123
124/// A section tab from `sb_library_sections`.
125struct Tab: Decodable, Equatable {
126 let name: String
127 /// The catalog path `sb_section_open` takes.
128 let path: String
129 /// The section group holding it, `/`-separated; empty at the notebook's top.
130 let group: String
131 let color: [UInt8]
132 let readable: Bool
133 /// Password protected and not unlocked: `Notebook.unlock` opens it.
134 let locked: Bool
135 /// Not on this device yet; `Notebook` asks iCloud Drive for it.
136 let downloading: Bool
137 /// Why the file could not be read, where retrying or repair may help.
138 let problem: String?
139
140 var uiColor: UIColor { UIColor(rgb: color) }
141}
142
143extension UIImage {
144 /// A notebook's binder, the desktop's art, `side` points square: its cover in `color`, or
145 /// the art's own orange.
146 static func notebook(_ color: UIColor?, side: CGFloat = 28) -> UIImage {
147 let frame = CGRect(x: 0, y: 0, width: side, height: side)
148 let cover = color ?? UIColor(rgb: [0xf3, 0x9c, 0x28])
149 return UIGraphicsImageRenderer(size: frame.size).image { _ in
150 UIImage(named: "NotebookBack")?.draw(in: frame)
151 UIImage(named: "NotebookCover")?.withTintColor(cover, renderingMode: .alwaysOriginal).draw(in: frame)
152 UIImage(named: "Notebook")?.draw(in: frame)
153 }.withRenderingMode(.alwaysOriginal)
154 }
155}
156
157extension UIViewController {
158 /// Tells the reader `title` and `message` in an alert they dismiss with OK.
159 func alert(_ title: String, _ message: String) {
160 let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
161 alert.addAction(UIAlertAction(title: "OK", style: .default))
162 present(alert, animated: true)
163 }
164}
165
166/// Runs `work` off the main thread, then `done` with its result on it.
167func background<T>(_ work: @escaping () -> T, done: @escaping (T) -> Void) {
168 DispatchQueue.global(qos: .userInitiated).async {
169 let result = work()
170 DispatchQueue.main.async { done(result) }
171 }
172}
173
174/// Where section replicas live: kept, as they hold edits not yet published.
175let cacheDirectory: URL = {
176 let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
177 .appendingPathComponent("Sections", isDirectory: true)
178 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
179 return url
180}()
181
182let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
183
184/// An open notebook: its Rust library and the sections it lists.
185final class Notebook {
186 /// A UUID, or `Documents/` and the folder's name for a notebook On My iPhone.
187 let id: String
188 let source: Source
189 private(set) var name: String
190 private(set) var handle: OpaquePointer?
191 private(set) var tabs: [Tab] = []
192 /// The notebook's colour, which its binder's cover takes in the list; none where it has none.
193 private(set) var color: UIColor?
194 /// Why the notebook could not be opened, while it cannot.
195 private(set) var problem: String?
196 /// The Files location being read, held open while the notebook is.
197 private var accessed: URL?
198 /// Reports other apps' changes to a folder on this device to the library.
199 private var presenter: FolderPresenter?
200 /// Lists the sections again while iCloud Drive downloads some.
201 private var recheck: DispatchWorkItem?
202 /// Posted on the main thread when the sections list again on their own.
203 static let listed = Notification.Name("NotebookListed")
204
205 init(id: String = UUID().uuidString, name: String, source: Source) {
206 self.id = id
207 self.name = name
208 self.source = source
209 }
210
211 deinit {
212 presenter?.stop()
213 if let handle { sb_library_free(handle) }
214 accessed?.stopAccessingSecurityScopedResource()
215 }
216
217 /// Opens the library off the main thread and lists its sections; `done` runs on the main
218 /// thread either way.
219 func open(done: @escaping () -> Void) {
220 let source = source
221 // The library, the Files location held open, why it failed, and a local folder to watch.
222 background({ () -> (OpaquePointer?, URL?, String?, URL?) in
223 var error: UnsafeMutablePointer<CChar>?
224 switch source {
225 case .server(let server):
226 let library = sb_library_server(
227 server.host, server.share, server.user, Keychain.password(server) ?? "", "", server.root,
228 cacheDirectory.path, &error)
229 return (library, nil, take(error), nil)
230 case .files(let bookmark):
231 var stale = false
232 guard let url = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale) else {
233 return (nil, nil, "The notebook was moved or deleted.", nil)
234 }
235 let accessed = url.startAccessingSecurityScopedResource() ? url : nil
236 let local = onThisDevice(url)
237 let (library, problem) = coordinatedOpen(url, local: local)
238 return (library, accessed, problem, local ? url : nil)
239 case .documents(let path):
240 let url = documentsDirectory.appendingPathComponent(path)
241 let library = sb_library_open(url.path, cacheDirectory.path, true, &error)
242 return (library, nil, take(error), url)
243 case .icloud(let path):
244 guard let url = ICloud.documents?.appendingPathComponent(path) else {
245 return (nil, nil, "Turn on iCloud Drive in Settings to open this notebook.", nil)
246 }
247 let (library, problem) = coordinatedOpen(url, local: false)
248 return (library, nil, problem, url)
249 case .path(let path):
250 let url = URL(fileURLWithPath: path)
251 let local = onThisDevice(url)
252 return (sb_library_open(path, cacheDirectory.path, local, &error), nil, take(error), local ? url : nil)
253 }
254 }) { [self] (library, accessed, problem, watched) in
255 self.accessed?.stopAccessingSecurityScopedResource()
256 self.accessed = accessed
257 presenter?.stop()
258 presenter = nil
259 if let handle { sb_library_free(handle) }
260 handle = library
261 if let library, let watched { presenter = FolderPresenter(watching: watched, for: library) }
262 self.problem = library == nil ? (problem ?? "The notebook can’t be read.") : nil
263 follow()
264 reload(done: done)
265 // As OneNote prunes the recycle bin after opening.
266 if let library {
267 let pointer = Int(bitPattern: library)
268 background({ sb_library_purge_recycle_bin(OpaquePointer(bitPattern: pointer)) }) { _ in }
269 }
270 }
271 }
272
273 /// Works offline or online, as Work Offline stands.
274 func follow() {
275 if let handle { sb_library_set_offline(handle, Sync.offline) }
276 }
277
278 /// Where the notebook is kept, as the sync sheet names it.
279 var location: String {
280 switch source {
281 case .files: "In Files"
282 case .documents: "On My \(UIDevice.current.model), in Snowbound’s folder"
283 case .icloud: "In iCloud Drive"
284 case .server(let server):
285 "smb://\(server.host)/\([server.share, server.root].filter { !$0.isEmpty }.joined(separator: "/"))"
286 case .path(let path): path
287 }
288 }
289
290 /// Unlocks the protected section at `path` with `password` off the main thread, then lists
291 /// the sections again; `done` learns whether the password matched.
292 func unlock(_ path: String, password: String, done: @escaping (Bool) -> Void) {
293 guard let handle else { return done(false) }
294 let pointer = Int(bitPattern: handle)
295 background({ sb_library_unlock(OpaquePointer(bitPattern: pointer), path, password) }) { [self] unlocked in
296 reload { done(unlocked) }
297 }
298 }
299
300 /// Locks every protected section, as OneNote's Lock All does.
301 func lockAll() {
302 if let handle { sb_library_lock_all(handle) }
303 }
304
305 /// Lists the sections again, off the main thread.
306 func reload(done: @escaping () -> Void) {
307 guard let handle else {
308 tabs = []
309 return done()
310 }
311 let pointer = Int(bitPattern: handle)
312 background({ () -> ([Tab]?, Int32) in
313 let library = OpaquePointer(bitPattern: pointer)
314 return (decode([Tab].self, sb_library_sections(library)), sb_library_color(library))
315 }) { [self] (tabs, color) in
316 if let tabs { self.tabs = tabs }
317 self.color = color < 0 ? nil : UIColor(rgb: [16, 8, 0].map { UInt8(truncatingIfNeeded: color >> $0) })
318 download()
319 done()
320 }
321 }
322
323 /// Asks iCloud Drive for the notebook files it keeps elsewhere, which iOS lists as
324 /// `.Name.icloud` or dataless under their names, or holds a newer version of, and lists the
325 /// sections again until they arrive.
326 private func download() {
327 let folder: URL? =
328 switch source {
329 case .files: accessed
330 case .documents(let path): documentsDirectory.appendingPathComponent(path)
331 case .icloud(let path): ICloud.documents?.appendingPathComponent(path)
332 case .path(let path): URL(fileURLWithPath: path)
333 case .server: nil
334 }
335 guard let folder, recheck == nil,
336 let files = FileManager.default.enumerator(
337 at: folder, includingPropertiesForKeys: [.ubiquitousItemDownloadingStatusKey])
338 else { return }
339 var waiting = false
340 for case let file as URL in files {
341 let stub = file.lastPathComponent.hasPrefix(".") && file.pathExtension == "icloud"
342 let status = try? file.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey])
343 let stale = status?.ubiquitousItemDownloadingStatus.map { $0 != .current } ?? false
344 guard stub || stale else { continue }
345 let real = file.deletingLastPathComponent().appendingPathComponent(
346 String(file.deletingPathExtension().lastPathComponent.dropFirst()))
347 try? FileManager.default.startDownloadingUbiquitousItem(at: stub ? real : file)
348 waiting = true
349 }
350 guard waiting else { return }
351 let recheck = DispatchWorkItem { [weak self] in
352 self?.recheck = nil
353 self?.reload { NotificationCenter.default.post(name: Self.listed, object: self) }
354 }
355 self.recheck = recheck
356 DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: recheck)
357 }
358
359 /// Stops hearing other apps' writes while in the background, where a suspended presenter
360 /// can deadlock their coordinated writes.
361 func pause() { presenter?.stop() }
362
363 /// Hears other apps' writes again, and checks the sections and their list for those
364 /// missed meanwhile.
365 func resume() {
366 presenter?.resume()
367 reload { NotificationCenter.default.post(name: Self.listed, object: self) }
368 }
369}
370
371/// Opens the library at `url` within a coordinated read, which brings a cloud folder's files
372/// down before they are read; nil with why where it cannot.
373private func coordinatedOpen(_ url: URL, local: Bool) -> (OpaquePointer?, String?) {
374 var library: OpaquePointer?
375 var error: UnsafeMutablePointer<CChar>?
376 var coordination: NSError?
377 NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &coordination) { url in
378 library = sb_library_open(url.path, cacheDirectory.path, local, &error)
379 }
380 return (library, take(error) ?? coordination?.localizedDescription)
381}
382
383/// Whether `url` is kept on this device, rather than by a file provider that keeps it elsewhere
384/// too, as iCloud Drive does.
385private func onThisDevice(_ url: URL) -> Bool {
386 let values = try? url.resourceValues(forKeys: [.volumeIsLocalKey, .isUbiquitousItemKey])
387 return values?.volumeIsLocal == true && values?.isUbiquitousItem != true
388}
389
390/// Tells a library which files of its folder on this device changed, as file coordination
391/// reports other apps' writes; the library checks just those sections.
392final class FolderPresenter: NSObject, NSFilePresenter {
393 let presentedItemURL: URL?
394 let presentedItemOperationQueue: OperationQueue = {
395 let queue = OperationQueue()
396 queue.maxConcurrentOperationCount = 1
397 return queue
398 }()
399 private let root: String
400 private let library: OpaquePointer
401
402 init(watching url: URL, for library: OpaquePointer) {
403 presentedItemURL = url
404 root = url.standardizedFileURL.resolvingSymlinksInPath().path
405 self.library = library
406 super.init()
407 NSFileCoordinator.addFilePresenter(self)
408 }
409
410 func resume() {
411 NSFileCoordinator.addFilePresenter(self)
412 touched("")
413 }
414
415 /// Stops reporting, before the library goes or the app leaves the foreground.
416 func stop() {
417 NSFileCoordinator.removeFilePresenter(self)
418 presentedItemOperationQueue.waitUntilAllOperationsAreFinished()
419 }
420
421 func presentedItemDidChange() { touched("") }
422 func presentedSubitemDidChange(at url: URL) { touched(url) }
423 func presentedSubitemDidAppear(at url: URL) { touched(url) }
424 /// Another device's commit that lost in iCloud Drive, which changes no file.
425 func presentedSubitem(at url: URL, didGain version: NSFileVersion) { touched(url) }
426 func presentedSubitem(at oldURL: URL, didMoveTo newURL: URL) {
427 touched(oldURL)
428 touched(newURL)
429 }
430 func accommodatePresentedSubitemDeletion(at url: URL, completionHandler: @escaping (Error?) -> Void) {
431 touched(url)
432 completionHandler(nil)
433 }
434
435 private func touched(_ url: URL) {
436 let path = url.standardizedFileURL.resolvingSymlinksInPath().path
437 touched(path.hasPrefix(root + "/") ? String(path.dropFirst(root.count + 1)) : "")
438 }
439
440 private func touched(_ path: String) {
441 sb_library_touched(library, path)
442 }
443}
444
445/// The notebooks the list shows: those in Documents, and those opened from elsewhere, kept
446/// across launches.
447enum Notebooks {
448 private struct Entry: Codable {
449 let id: String
450 let name: String
451 let source: Source
452 }
453
454 private static let key = "notebooks"
455 private static let hidden = "hidesOnDevice"
456 /// The notebooks' ids in the order the reader put them in.
457 private static let order = "notebookOrder"
458 /// The Snowbound Guide's folder, in the app and in Documents once copied there.
459 static let guide = "Snowbound Guide"
460 /// Whether the list offers the guide; off until Clover has read it through.
461 static let guideOffered = false
462 private static let scripted = ProcessInfo.processInfo.environment["SNOWBOUND_NOTEBOOK"]
463 /// The folders and sections in Documents, as On My iPhone lists them.
464 private(set) static var onDevice: [Notebook] = []
465 /// The folders in Snowbound's folder in iCloud Drive.
466 private(set) static var inCloud: [Notebook] = []
467 private(set) static var elsewhere: [Notebook] = []
468 static var all: [Notebook] { inCloud + onDevice + elsewhere }
469
470 /// Whether the list shows On My iPhone, as Files lets a location be hidden.
471 static var showsOnDevice: Bool {
472 get { scripted == nil && !UserDefaults.standard.bool(forKey: hidden) }
473 set { UserDefaults.standard.set(!newValue, forKey: hidden) }
474 }
475
476 /// The kept notebooks and those in Documents.
477 static func load() {
478 if let scripted {
479 elsewhere = [
480 Notebook(
481 name: URL(fileURLWithPath: scripted).deletingPathExtension().lastPathComponent,
482 source: .path(scripted))
483 ]
484 return
485 }
486 if let data = UserDefaults.standard.data(forKey: key),
487 let entries = try? JSONDecoder().decode([Entry].self, from: data)
488 {
489 elsewhere = ordered(entries.compactMap { entry in
490 switch entry.source {
491 case .documents, .icloud: return nil
492 default: break
493 }
494 return Notebook(id: entry.id, name: entry.name, source: entry.source)
495 })
496 } else {
497 // The notebook the first version remembered from Files.
498 if let bookmark = UserDefaults.standard.data(forKey: "notebook") {
499 var stale = false
500 let name = (try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale))?
501 .deletingPathExtension().lastPathComponent
502 elsewhere.append(Notebook(name: name ?? "Notebook", source: .files(bookmark: bookmark)))
503 }
504 save()
505 }
506 scan()
507 }
508
509 /// Lists Documents again, keeping the notebooks still there; returns those new to the list.
510 @discardableResult
511 static func scan() -> [Notebook] {
512 let folder = showsOnDevice ? documentsDirectory : nil
513 return rescan(folder, "Documents/", &onDevice) { .documents(path: $0) }
514 }
515
516 /// Lists Snowbound's folder in iCloud Drive again, as `scan` lists Documents; none while
517 /// iCloud Drive is off.
518 @discardableResult
519 static func scanICloud() -> [Notebook] {
520 rescan(scripted == nil ? ICloud.documents : nil, "iCloud/", &inCloud) { .icloud(path: $0) }
521 }
522
523 /// Lists `folder`'s notebooks into `list`, keeping those still there and naming new ones by
524 /// `prefix` and their `source`; returns the new ones.
525 private static func rescan(
526 _ folder: URL?, _ prefix: String, _ list: inout [Notebook], source: (String) -> Source
527 ) -> [Notebook] {
528 guard let folder else {
529 list = []
530 return []
531 }
532 guard let names = notebooks(in: folder) else { return [] }
533 var added: [Notebook] = []
534 list = ordered(
535 names.map { [list] name in
536 if let kept = list.first(where: { $0.id == prefix + name }) { return kept }
537 let notebook = Notebook(
538 id: prefix + name, name: (name as NSString).deletingPathExtension, source: source(name))
539 added.append(notebook)
540 return notebook
541 })
542 return added
543 }
544
545 /// `list` in the reader's order, those it doesn't name after in their own.
546 private static func ordered(_ list: [Notebook]) -> [Notebook] {
547 let order = UserDefaults.standard.stringArray(forKey: order) ?? []
548 let rank = { (notebook: Notebook) in order.firstIndex(of: notebook.id) ?? order.count }
549 return list.enumerated().sorted { (rank($0.element), $0.offset) < (rank($1.element), $1.offset) }.map(\.element)
550 }
551
552 /// The notebooks listed in the same place as `notebook`, in order.
553 static func siblings(of notebook: Notebook) -> [Notebook] {
554 [inCloud, onDevice, elsewhere].first { $0.contains { $0 === notebook } } ?? []
555 }
556
557 /// Puts `notebook` at `index` among the notebooks of its place, and keeps that order.
558 static func move(_ notebook: Notebook, to index: Int) {
559 func move(in list: inout [Notebook]) {
560 guard let at = list.firstIndex(where: { $0 === notebook }) else { return }
561 let moved = list.remove(at: at)
562 list.insert(moved, at: min(max(index, 0), list.count))
563 }
564 move(in: &inCloud)
565 move(in: &onDevice)
566 move(in: &elsewhere)
567 guard scripted == nil else { return }
568 UserDefaults.standard.set(all.map(\.id), forKey: order)
569 }
570
571 /// Whether Snowbound's folder in iCloud Drive holds other notebooks than the list shows, as
572 /// when another device added or removed one.
573 static var inCloudChanged: Bool {
574 guard let folder = ICloud.documents, scripted == nil, let names = notebooks(in: folder) else { return false }
575 return names.map { "iCloud/" + $0 } != inCloud.map(\.id)
576 }
577
578 /// The notebook folders and section files in `folder`, by name, as Files orders them.
579 private static func notebooks(in folder: URL) -> [String]? {
580 guard let listed = try? FileManager.default.contentsOfDirectory(
581 at: folder, includingPropertiesForKeys: [.isDirectoryKey], options: .skipsHiddenFiles)
582 else { return nil }
583 return listed.filter { url in
584 (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true
585 || url.pathExtension.lowercased() == "one"
586 }
587 .map(\.lastPathComponent)
588 .sorted { $0.localizedStandardCompare($1) == .orderedAscending }
589 }
590
591 static func add(_ notebook: Notebook) {
592 elsewhere.append(notebook)
593 save()
594 }
595
596 static func remove(_ notebook: Notebook) {
597 elsewhere.removeAll { $0 === notebook }
598 save()
599 }
600
601 private static func save() {
602 guard scripted == nil else { return }
603 let entries = elsewhere.map { Entry(id: $0.id, name: $0.name, source: $0.source) }
604 UserDefaults.standard.set(try? JSONEncoder().encode(entries), forKey: key)
605 }
606}
607
608/// A page row from `sb_section_pages`.
609struct Row: Decodable, Equatable {
610 struct Version: Decodable, Equatable {
611 let id: String
612 let user: String
613 /// Seconds since 1970.
614 let created: Double?
615 }
616
617 let id: String
618 var title: String
619 /// 1 at the top, 2 for a subpage and so on.
620 let level: Int
621 /// Conflict pages: versions with changes a merge could not take.
622 let versions: [Version]
623}
624
625/// Saving as the section reports it, from `sb_section_poll`.
626enum SaveStatus: UInt8 {
627 case unknown, saved, saving, offline, notSaving
628}
629
630private let wakeSection: sb_wake = { token in
631 DispatchQueue.main.async { Section.open[Int(token)]?.value?.poll() }
632}
633
634private struct Weak<T: AnyObject> { weak var value: T? }
635
636/// A section open for editing: pages listed and saved through its replica.
637final class Section {
638 /// Sent on the main thread with `flags` from `sb_section_poll`, `listed` once the rows are read again.
639 static let changed = Notification.Name("SectionChanged")
640 static let listed: UInt32 = 1
641 static let remote: UInt32 = 2
642 static let rejected: UInt32 = 4
643
644 fileprivate static var open: [Int: Weak<Section>] = [:]
645 /// Sections reporting Not Saving, kept open so that edits waiting in memory stay with them.
646 private static var unsaved: [Int: Section] = [:]
647 private static var tokens = 0
648
649 let notebook: Notebook
650 let tab: Tab
651 let handle: OpaquePointer
652 private let token: Int
653 private(set) var rows: [Row]
654 private(set) var status = SaveStatus.unknown
655 private var listing: (invalidated: Bool, completions: [() -> Void])?
656
657 static var all: [Section] { open.values.compactMap(\.value) }
658
659 private init(notebook: Notebook, tab: Tab, handle: OpaquePointer, token: Int, rows: [Row]) {
660 self.notebook = notebook
661 self.tab = tab
662 self.handle = handle
663 self.token = token
664 self.rows = rows
665 }
666
667 deinit {
668 Self.open[token] = nil
669 sb_section_free(handle)
670 }
671
672 /// Opens `tab` of `notebook` off the main thread, or hands back the section already open
673 /// there, as its replica takes one owner at a time.
674 static func open(_ tab: Tab, of notebook: Notebook, done: @escaping (Section?, String?) -> Void) {
675 if let section = all.first(where: { $0.notebook === notebook && $0.tab.path == tab.path }) {
676 return done(section, nil)
677 }
678 guard let library = notebook.handle else { return done(nil, notebook.problem) }
679 tokens += 1
680 let token = tokens
681 let pointer = Int(bitPattern: library)
682 let author = Author.name ?? ""
683 background({ () -> (Int, String?, [Row]) in
684 var error: UnsafeMutablePointer<CChar>?
685 let handle = sb_section_open(
686 OpaquePointer(bitPattern: pointer), tab.path, author, wakeSection, UInt(token), &error)
687 let rows = handle.flatMap { decode([Row].self, sb_section_pages($0)) } ?? []
688 return (Int(bitPattern: handle), take(error), rows)
689 }) { handle, error, rows in
690 guard let handle = OpaquePointer(bitPattern: handle) else { return done(nil, error) }
691 let section = Section(notebook: notebook, tab: tab, handle: handle, token: token, rows: rows)
692 open[token] = Weak(value: section)
693 done(section, nil)
694 // Wakes before `open[token]` was set went unheard.
695 section.poll()
696 }
697 }
698
699 /// Lists the pages again and tells the views.
700 func reloadRows() {
701 listing?.invalidated = true
702 rows = decode([Row].self, sb_section_pages(handle)) ?? rows
703 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
704 }
705
706 /// Lists the pages again off the main thread, tells the views, then runs `then`.
707 private func refreshRows(then: @escaping () -> Void = {}) {
708 guard listing == nil else {
709 listing?.invalidated = true
710 listing?.completions.append(then)
711 return
712 }
713 listing = (false, [then])
714 readRows()
715 }
716
717 private func readRows() {
718 background({ [self] in decode([Row].self, sb_section_pages(handle)) }) { [self] rows in
719 // A read begun before a reload or retitle would undo it.
720 if listing!.invalidated, rows != nil {
721 listing?.invalidated = false
722 return readRows()
723 }
724 self.rows = rows ?? self.rows
725 let completions = listing!.completions
726 listing = nil
727 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": Self.listed])
728 for completion in completions { completion() }
729 }
730 }
731
732 /// The row listing page or conflict page `id`, and the version when it is one.
733 func row(of id: String) -> (row: Row, version: Row.Version?)? {
734 for row in rows {
735 if row.id == id { return (row, nil) }
736 if let version = row.versions.first(where: { $0.id == id }) { return (row, version) }
737 }
738 return nil
739 }
740
741 fileprivate func poll() {
742 var status: UInt8 = 0
743 let flags = sb_section_poll(handle, &status)
744 let changed = SaveStatus(rawValue: status) ?? .unknown
745 if flags & Self.listed != 0 { refreshRows() }
746 let unlisted = flags & ~Self.listed
747 let unchanged = unlisted == 0 && changed == self.status
748 self.status = changed
749 Self.unsaved[token] = changed == .notSaving ? self : nil
750 NotificationCenter.default.post(
751 name: Self.changed, object: self,
752 userInfo: unchanged ? ["flags": unlisted, "unchanged": true] : ["flags": unlisted])
753 }
754
755 /// A page's title as typed, shown in the list before the section reports it.
756 func retitle(_ id: String, _ title: String) {
757 guard let index = rows.firstIndex(where: { $0.id == id }), rows[index].title != title else { return }
758 listing?.invalidated = true
759 rows[index].title = title
760 NotificationCenter.default.post(name: Self.changed, object: self, userInfo: ["flags": UInt32(0)])
761 }
762
763 /// Adds a page, or a subpage of `parent`; returns its id.
764 func newPage(under parent: String? = nil) -> String? {
765 let (date, time) = titleDate()
766 let id = take(sb_section_new_page(handle, parent, date, time))
767 reloadRows()
768 return id
769 }
770
771 /// Deletes pages, conflict pages for good and the rest to the recycle bin, which a toast
772 /// then offers.
773 func delete(_ ids: [String], done: @escaping () -> Void = {}) {
774 guard let release = Arranging.reserve() else { return }
775 let recycled = notebook.hasRecycleBin ? ids.filter { row(of: $0)?.version == nil }.count : 0
776 let (date, time) = titleDate()
777 let pointer = Int(bitPattern: handle)
778 background({
779 for id in ids {
780 guard sb_section_delete_page(OpaquePointer(bitPattern: pointer), id, date, time) else { return false }
781 }
782 return true
783 }) { [self] deleted in
784 refreshRows {
785 release()
786 let window = UIApplication.shared.connectedScenes.lazy.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first
787 guard deleted else {
788 window?.rootViewController?.alert("Can’t Delete", "Some pages couldn’t be deleted. Try again.")
789 return
790 }
791 done()
792 if recycled > 0, let window {
793 let title = recycled == 1 ? "Page Moved to Recycle Bin" : "\(recycled) Pages Moved to Recycle Bin"
794 let detail = recycled == 1 ? "Restore it from the Recycle Bin" : "Restore them from the Recycle Bin"
795 SyncToast.show(title, detail, symbol: "trash", hint: "Opens the Recycle Bin", in: window) {
796 [notebook = self.notebook] in RecycleBinViewController.present(notebook, in: window)
797 }
798 }
799 }
800 }
801 }
802
803 /// The notebook's themes, and the one page `id`, its section and its notebook each name.
804 struct Themes: Decodable {
805 struct Listed: Decodable {
806 let id: String
807 let name: String
808 }
809 let themes: [Listed]
810 let page: String?
811 let section: String?
812 let notebook: String?
813 }
814
815 func themes(of id: String) -> Themes? { decode(Themes.self, sb_section_themes(handle, id)) }
816
817 /// Gives `theme`, or none of its own, to page `id` (scope 0), its section (1) or its
818 /// notebook (2).
819 func setTheme(_ theme: String?, scope: UInt8, of id: String, done: @escaping (Bool) -> Void) {
820 let pointer = Int(bitPattern: handle)
821 background({ sb_section_set_theme(OpaquePointer(bitPattern: pointer), id, scope, theme) }, done: done)
822 }
823
824 /// Stores every edit and publishes them within `seconds`; call off the main thread.
825 func flush(_ seconds: Double) -> Bool { sb_section_flush(handle, seconds) }
826
827 func wake() { sb_section_wake(handle) }
828}