1import UIKit
2
3/// Runs the library's file access under `NSFileCoordinator`, so file providers such as
4/// iCloud Drive download before it reads and learn of what it writes.
5private let coordinate: sb_coordinator = { path, write, body, context in
6 guard let path, let body else { return }
7 let url = URL(fileURLWithPath: String(cString: path))
8 var error: NSError?
9 if write {
10 NSFileCoordinator().coordinate(writingItemAt: url, options: .forMerging, error: &error) { _ in body(context) }
11 } else {
12 NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &error) { _ in body(context) }
13 }
14}
15
16@main
17final class AppDelegate: UIResponder, UIApplicationDelegate {
18 func application(
19 _ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]?
20 ) -> Bool {
21 Crash.start()
22 sb_set_coordinator(coordinate)
23 Editing.apply()
24 ICloud.start()
25 sb_set_sync_wake { DispatchQueue.main.async { NotificationCenter.default.post(name: Sync.changed, object: nil) } }
26 #if DEBUG
27 Presenter.watch()
28 #endif
29 return true
30 }
31
32 func application(
33 _ application: UIApplication,
34 configurationForConnecting session: UISceneSession,
35 options: UIScene.ConnectionOptions
36 ) -> UISceneConfiguration {
37 let configuration = UISceneConfiguration(name: nil, sessionRole: session.role)
38 configuration.delegateClass = SceneDelegate.self
39 return configuration
40 }
41
42 /// Edits are in the cache once stored; this gives publishing a moment before the app goes.
43 func applicationWillTerminate(_ application: UIApplication) {
44 NotificationCenter.default.post(name: PageViewController.leaving, object: nil)
45 for section in Section.all { _ = section.flush(2) }
46 }
47}
48
49/// The desktop's Appearance option: the system's, or light or dark regardless of it.
50enum Appearance {
51 static let key = "appearance"
52
53 static var style: UIUserInterfaceStyle {
54 get { UIUserInterfaceStyle(rawValue: UserDefaults.standard.integer(forKey: key)) ?? .unspecified }
55 set {
56 UserDefaults.standard.set(newValue.rawValue, forKey: key)
57 for case let scene as UIWindowScene in UIApplication.shared.connectedScenes {
58 for window in scene.windows { window.overrideUserInterfaceStyle = newValue }
59 }
60 }
61 }
62
63 static func menu() -> UIMenu {
64 let choices: [(String, UIUserInterfaceStyle)] = [("System", .unspecified), ("Light", .light), ("Dark", .dark)]
65 return UIMenu(
66 title: "Appearance", image: UIImage(systemName: "circle.lefthalf.filled"),
67 children: choices.map { title, style in
68 let action = UIAction(title: title) { _ in Appearance.style = style }
69 action.state = Appearance.style == style ? .on : .off
70 return action
71 })
72 }
73}
74
75/// OneNote's Snap To Grid and Default font, and Markdown Shortcuts, kept between launches,
76/// which the pages opened from then on take.
77enum Editing {
78 /// OneNote 2010's Default font sizes, in points.
79 static let sizes: [Float] = [8, 9, 9.5, 10, 10.5, 11, 11.5, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72]
80 static let faces = ["Calibri", "Arial", "Times New Roman", "Courier New", "Georgia", "Verdana"]
81
82 static var snapToGrid: Bool {
83 get { !UserDefaults.standard.bool(forKey: "ignoreGrid") }
84 set {
85 UserDefaults.standard.set(!newValue, forKey: "ignoreGrid")
86 apply()
87 }
88 }
89
90 static var markdownShortcuts: Bool {
91 get { !UserDefaults.standard.bool(forKey: "ignoreMarkdown") }
92 set {
93 UserDefaults.standard.set(!newValue, forKey: "ignoreMarkdown")
94 apply()
95 }
96 }
97
98 static var face: String {
99 get { UserDefaults.standard.string(forKey: "defaultFontFace") ?? "Calibri" }
100 set {
101 UserDefaults.standard.set(newValue, forKey: "defaultFontFace")
102 apply()
103 }
104 }
105
106 static var size: Float {
107 get { UserDefaults.standard.object(forKey: "defaultFontSize") as? Float ?? 11 }
108 set {
109 UserDefaults.standard.set(newValue, forKey: "defaultFontSize")
110 apply()
111 }
112 }
113
114 static func apply() {
115 sb_set_snap_to_grid(snapToGrid)
116 sb_set_default_font(face, size)
117 sb_set_markdown_shortcuts(markdownShortcuts)
118 }
119
120 /// Markdown Shortcuts: typed Markdown becomes formatting.
121 static func markdownAction() -> UIAction {
122 let action = UIAction(title: "Markdown Shortcuts", image: UIImage(systemName: "number")) { _ in
123 markdownShortcuts.toggle()
124 }
125 action.state = markdownShortcuts ? .on : .off
126 return action
127 }
128
129 /// Options' Default font: the face and size new text takes.
130 static func fontMenu() -> UIMenu {
131 let faces = faces.map { name in
132 let action = UIAction(title: name) { _ in face = name }
133 action.state = face == name ? .on : .off
134 return action
135 }
136 let sizes = sizes.map { points in
137 let action = UIAction(title: points.formatted()) { _ in size = points }
138 action.state = size == points ? .on : .off
139 return action
140 }
141 return UIMenu(
142 title: "Default Font", image: UIImage(systemName: "textformat"),
143 children: [
144 UIMenu(options: .displayInline, children: faces),
145 UIMenu(title: "Size", children: sizes),
146 ])
147 }
148}
149
150/// Where the reader was, reopened on the next launch as Notes reopens its last note.
151private struct Place: Codable {
152 let notebook: String
153 let section: String
154 let page: String?
155
156 static let key = "place"
157
158 static var saved: Place? {
159 get { UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode(Place.self, from: $0) } }
160 set { UserDefaults.standard.set(try? JSONEncoder().encode(newValue), forKey: key) }
161 }
162}
163
164/// Notebooks and sections, pages and a page, as Notes lays out folders, notes and a note:
165/// side by side on a wide screen, a navigation stack on a phone.
166final class SceneDelegate: UIResponder, UIWindowSceneDelegate, UISplitViewControllerDelegate {
167 private struct WeakPage { weak var value: PageViewController? }
168
169 var window: UIWindow?
170 private let split = RootViewController(style: .tripleColumn)
171 private let notebooks = NotebooksViewController()
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] = []
176 /// A first launch opened a page by itself.
177 private var landed = false
178 private var background = UIBackgroundTaskIdentifier.invalid
179
180 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {
181 guard let scene = scene as? UIWindowScene else { return }
182 let window = UIWindow(windowScene: scene)
183 window.overrideUserInterfaceStyle = Appearance.style
184 split.delegate = self
185 split.scene = self
186 split.preferredDisplayMode = .oneBesideSecondary
187 split.preferredSplitBehavior = .tile
188 split.setViewController(notebooks, for: .primary)
189 split.setViewController(pages, for: .supplementary)
190 split.setViewController(UIViewController(), for: .secondary)
191 notebooks.onOpen = { [weak self] tab, notebook in self?.open(tab, of: notebook) }
192 pages.onOpen = { [weak self] section, id in self?.show(section: section, page: id) }
193 window.rootViewController = split
194 window.makeKeyAndVisible()
195 self.window = window
196 Notebooks.load()
197 notebooks.reload()
198 Crash.offer(from: split) { [weak self] in
199 guard let self else { return }
200 for notebook in Notebooks.all {
201 notebook.open { [weak self] in
202 self?.notebooks.reload()
203 self?.restore(notebook)
204 }
205 }
206 // iCloud Drive's notebooks list once its folder is found, and again when the account
207 // changes; it may have been found while the report was offered.
208 NotificationCenter.default.addObserver(forName: ICloud.changed, object: nil, queue: .main) { [weak self] _ in
209 self?.notebooks.rescan { self?.restore($0) }
210 }
211 notebooks.rescan { [weak self] in self?.restore($0) }
212 self.scene(scene, openURLContexts: options.urlContexts)
213 }
214 }
215
216 /// A section file Files opens in Snowbound, in place.
217 func scene(_ scene: UIScene, openURLContexts contexts: Set<UIOpenURLContext>) {
218 for context in contexts where context.url.isFileURL { notebooks.open(document: context.url) }
219 }
220
221 /// Reopens the section and page shown last, or the scripted one.
222 private func restore(_ notebook: Notebook) {
223 let environment = ProcessInfo.processInfo.environment
224 if let index = environment["SNOWBOUND_SECTION"].flatMap(Int.init) {
225 let readable = notebook.tabs.filter(\.readable)
226 guard index < readable.count else { return }
227 open(readable[index], of: notebook) { [weak self] section in
228 guard let page = environment["SNOWBOUND_PAGE"].flatMap(Int.init), page < section.rows.count else {
229 return
230 }
231 self?.show(section: section, page: section.rows[page].id)
232 }
233 return
234 }
235 guard let place = Place.saved else {
236 // The first notebook found opens at its first page, as Notes opens on a note.
237 guard Prototype.welcome, !landed, let tab = notebook.tabs.first(where: \.readable) else { return }
238 landed = true
239 return open(tab, of: notebook) { [weak self] section in
240 if let page = section.rows.first { self?.show(section: section, page: page.id) }
241 }
242 }
243 guard place.notebook == notebook.id, let tab = notebook.tabs.first(where: { $0.path == place.section })
244 else { return }
245 open(tab, of: notebook, page: place.page)
246 }
247
248 func open(
249 _ tab: Tab, of notebook: Notebook, page: String? = nil, reveal: Reveal? = nil,
250 then: ((Section) -> Void)? = nil
251 ) {
252 // The welcome prototype asks at the first edit instead.
253 guard Author.name != nil || Prototype.welcome else {
254 return Author.ask(from: split) { [weak self] in
255 self?.open(tab, of: notebook, page: page, reveal: reveal, then: then)
256 }
257 }
258 pages.loading(tab)
259 split.show(.supplementary)
260 Section.open(tab, of: notebook) { [weak self] section, problem in
261 guard let self else { return }
262 guard let section else {
263 pages.failed(problem)
264 return
265 }
266 pages.load(section)
267 notebooks.select(tab, of: notebook)
268 Place.saved = Place(notebook: notebook.id, section: tab.path, page: page)
269 if let page, section.row(of: page) != nil {
270 show(section: section, page: page, reveal: reveal)
271 }
272 then?(section)
273 }
274 }
275
276 /// Opens `page` of the section at catalog `path` in `notebook`, as a search result or
277 /// the Tags Summary leads there.
278 func open(_ path: String, of notebook: Notebook, page: String, reveal: Reveal) {
279 if let section = pages.section, section.notebook === notebook, section.tab.path == path {
280 return show(section: section, page: page, reveal: reveal)
281 }
282 guard let tab = notebook.tabs.first(where: { $0.path == path }) else { return }
283 open(tab, of: notebook, page: page, reveal: reveal)
284 }
285
286 /// OneNote's Tags Summary for `notebook`, as a sheet over `controller`.
287 func showTags(of notebook: Notebook, from controller: UIViewController) {
288 let tags = TagsViewController(notebook: notebook)
289 tags.onOpen = { [weak self] notebook, path, page, paragraph in
290 self?.open(path, of: notebook, page: page, reveal: .paragraph(paragraph))
291 }
292 let navigation = UINavigationController(rootViewController: tags)
293 navigation.sheetPresentationController?.detents = [.medium(), .large()]
294 navigation.sheetPresentationController?.prefersGrabberVisible = true
295 controller.present(navigation, animated: true)
296 }
297
298 func show(section: Section, page: String, reveal: Reveal? = nil, titleFocus: Bool = false, revealPage: Bool = true) {
299 let controller = PageViewController(section: section, page: page, reveal: reveal, titleFocus: titleFocus)
300 openPages.removeAll { $0.value == nil }
301 openPages.append(WeakPage(value: controller))
302 controller.onOpen = { [weak self, weak controller] id in
303 guard let controller else { return }
304 self?.show(section: section, page: id, revealPage: controller.viewIfLoaded?.window != nil)
305 }
306 split.setViewController(UINavigationController(rootViewController: controller), for: .secondary)
307 if revealPage { split.show(.secondary) }
308 pages.select(page)
309 Place.saved = Place(notebook: section.notebook.id, section: section.tab.path, page: page)
310 }
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
336 /// Returns to the list from any section of `notebook` shown, as before its folder moves.
337 func close(_ notebook: Notebook) {
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 }
355 split.setViewController(UIViewController(), for: .secondary)
356 if split.presentedViewController == nil {
357 split.show(.primary)
358 }
359 }
360
361 /// Lets go of the section shown where it is the section or group at `path` of `notebook`
362 /// or within it, as before its file moves; its path and page, to open once moved.
363 func release(_ path: String, of notebook: Notebook) -> (section: String, page: String?)? {
364 guard let section = pages.section, section.notebook === notebook,
365 section.tab.path == path || section.tab.path.hasPrefix(path + "/")
366 else { return nil }
367 let shown = (section.tab.path, Place.saved?.page)
368 close(notebook)
369 return shown
370 }
371
372 /// Adds a page to the open section and opens it, its title ready for typing.
373 func newPage(subpage: Bool = false) {
374 guard let section = pages.section else { return }
375 let parent = subpage ? (Place.saved?.page).flatMap { section.row(of: $0)?.row.id } : nil
376 guard let id = section.newPage(under: parent) else { return }
377 show(section: section, page: id, titleFocus: true)
378 }
379
380 func search() {
381 split.show(.supplementary)
382 pages.startSearching()
383 }
384
385 /// A phone opens on the notebooks, as Notes opens on its folders.
386 func splitViewController(
387 _ svc: UISplitViewController, topColumnForCollapsingToProposedTopColumn proposedTopColumn: UISplitViewController.Column
388 ) -> UISplitViewController.Column {
389 let detail = (svc.viewController(for: .secondary) as? UINavigationController)?.topViewController
390 return detail is PageViewController ? proposedTopColumn : .primary
391 }
392
393 /// Composition ends and every edit is stored and published while the system allows.
394 func sceneDidEnterBackground(_ scene: UIScene) {
395 NotificationCenter.default.post(name: PageViewController.leaving, object: nil)
396 // Protected sections open again only once unlocked.
397 for notebook in Notebooks.all { notebook.pause(); notebook.lockAll() }
398 let sections = Section.all
399 guard !sections.isEmpty, background == .invalid else { return }
400 background = UIApplication.shared.beginBackgroundTask(withName: "Saving") { [weak self] in
401 self?.finishBackground()
402 }
403 DispatchQueue.global(qos: .userInitiated).async {
404 for section in sections { _ = section.flush(20) }
405 DispatchQueue.main.async { [weak self] in self?.finishBackground() }
406 }
407 }
408
409 private func finishBackground() {
410 guard background != .invalid else { return }
411 UIApplication.shared.endBackgroundTask(background)
412 background = .invalid
413 }
414
415 /// Someone moving to another device finds their edits there: they publish now rather than
416 /// after a pause in typing.
417 func sceneWillResignActive(_ scene: UIScene) {
418 for section in Section.all { section.wake() }
419 }
420
421 /// Changes made elsewhere while away show at once.
422 func sceneWillEnterForeground(_ scene: UIScene) {
423 for notebook in Notebooks.all { notebook.resume() }
424 notebooks.rescan()
425 for section in Section.all { section.wake() }
426 }
427}
428
429/// Takes the app's keyboard shortcuts wherever focus is.
430final class RootViewController: UISplitViewController {
431 weak var scene: SceneDelegate?
432
433 override var keyCommands: [UIKeyCommand]? {
434 [
435 UIKeyCommand(title: "New Page", action: #selector(newPage), input: "n", modifierFlags: .command),
436 UIKeyCommand(
437 title: "New Subpage", action: #selector(newSubpage), input: "n",
438 modifierFlags: [.command, .shift, .alternate]),
439 UIKeyCommand(title: "Search", action: #selector(search), input: "f", modifierFlags: [.command, .alternate]),
440 ]
441 }
442
443 @objc private func newPage() { scene?.newPage() }
444 @objc private func newSubpage() { scene?.newPage(subpage: true) }
445 @objc private func search() { scene?.search() }
446}