Sources/OrgstarMobile/MobileModel.swift
134 lines · 5413 bytes
1#if os(iOS)
2import Foundation
3import Observation
4import OrgApp
5import OrgCore
6import OrgIndex
7import OrgWorkspace
8
9/// The app's models, and the settings from the configuration folder: a folder you choose
10/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
11@MainActor
12@Observable
13final class MobileModel {
14 let workspace: WorkspaceModel?
15 let failure: String?
16 let session = DocumentSession()
17 let agenda: AgendaModel?
18 let scheduler = ReminderScheduler(center: SystemReminderCenter())
19 let clock = ClockModel()
20 private(set) var configFolder: URL?
21 private(set) var configProblems: [String] = []
22 /// An entry to show, from a tapped reminder.
23 var openRequest: ReaderRoute?
24 /// Bumped when settings apply, so views that read them update.
25 private(set) var settingsVersion = 0
26 @ObservationIgnored private var presenter: FolderPresenter?
27
28 private static let bookmarkKey = "configFolderBookmark"
29
30 init() {
31 // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
32 let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
33 UserConfig.directoryOverride = folder
34 let problems = Self.readConfig(folder)
35 let settings = OrgPreferences.orgSettings()
36 do {
37 let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
38 self.workspace = workspace
39 agenda = AgendaModel(workspace: workspace)
40 failure = nil
41 } catch {
42 workspace = nil
43 agenda = nil
44 failure = error.localizedDescription
45 }
46 configFolder = folder
47 configProblems = problems
48 applySettings()
49 watchConfig()
50 }
51
52 /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
53 func setConfigFolder(_ url: URL?) {
54 if let url {
55 _ = url.startAccessingSecurityScopedResource()
56 if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
57 } else {
58 UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
59 // What the folder set no longer applies.
60 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
61 }
62 configFolder = url
63 reloadConfig()
64 watchConfig()
65 }
66
67 func reloadConfig() {
68 UserConfig.directoryOverride = configFolder
69 configProblems = Self.readConfig(configFolder)
70 applySettings()
71 }
72
73 private func applySettings() {
74 let settings = OrgPreferences.orgSettings()
75 session.defaults = settings
76 session.options = OrgPreferences.options()
77 workspace?.settings = .with(todoKeywords: settings)
78 if let agenda {
79 agenda.span = OrgPreferences.agendaSpan()
80 agenda.startOffset = OrgPreferences.agendaStartOffset()
81 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
82 }
83 settingsVersion += 1
84 }
85
86 /// Edits to the folder's files, synced from the Mac, apply as they arrive.
87 private func watchConfig() {
88 presenter?.stop()
89 presenter = nil
90 guard let configFolder else { return }
91 let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
92 Task { @MainActor [weak self] in self?.reloadConfig() }
93 }
94 presenter.start()
95 self.presenter = presenter
96 }
97
98 private static func resolveBookmark() -> URL? {
99 guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
100 var stale = false
101 guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
102 _ = url.startAccessingSecurityScopedResource()
103 if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
104 return url
105 }
106
107 /// Applies the folder's `config.toml` to the settings; returns its problems.
108 private static func readConfig(_ folder: URL?) -> [String] {
109 guard let folder else { return [] }
110 let file = folder.appendingPathComponent("config.toml")
111 var text: String?
112 var error: NSError?
113 NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
114 text = try? String(contentsOf: url, encoding: .utf8)
115 }
116 guard let text else { return ["No config.toml in \(folder.lastPathComponent); the defaults apply."] }
117 return UserConfig.apply(text, to: .standard)
118 }
119
120 /// Notifications for the next week's timed entries, at most 64, as iOS allows.
121 func updateReminders() async {
122 guard let workspace else { return }
123 guard OrgPreferences.reminders() else {
124 await scheduler.clear()
125 return
126 }
127 guard !workspace.files.isEmpty else { return }
128 let agenda = AgendaModel(workspace: workspace)
129 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
130 let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
131 await scheduler.reconcile(reminders)
132 }
133}
134#endif