Sources/OrgstarMobile/MobileModel.swift
268 lines · 12173 bytes
1#if os(iOS)
2import Foundation
3import Observation
4import OrgApp
5import OrgCore
6import OrgIndex
7import OrgPresentation
8import OrgWorkspace
9import UIKit
10import WidgetKit
11
12/// The app's models, and the settings from the configuration folder: a folder you choose
13/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
14@MainActor
15@Observable
16final class MobileModel {
17 /// One per process: Shortcuts runs the capture action without a window.
18 static let shared = MobileModel()
19
20 let workspace: WorkspaceModel?
21 let failure: String?
22 let session = DocumentSession()
23 let agenda: AgendaModel?
24 let scheduler = ReminderScheduler(center: SystemReminderCenter())
25 let clock = ClockModel()
26 let clockPrompts = ClockPrompter()
27 let spotlight = SpotlightIndexer()
28 /// Captures from the share extension; nil without the app group.
29 let inbox = CaptureInbox()
30 private(set) var configFolder: URL?
31 private(set) var configProblems: [String] = []
32 /// An entry to show, from a tapped reminder.
33 var openRequest: ReaderRoute?
34 /// Agenda days to show, from a followed timestamp: the first (a `Days` number) and how many.
35 var agendaRequest: AgendaDays?
36 /// A capture to show, from the agenda.
37 var captureRequest: CaptureRequest?
38 /// Calendar's events for the agenda, with `calendar-events`.
39 let calendarEvents = CalendarEvents()
40
41 struct AgendaDays: Equatable {
42 let start: Int
43 let count: Int
44 }
45 /// Bumped when settings apply, so views that read them update.
46 private(set) var settingsVersion = 0
47 /// The theme from `config.toml` and its theme file, with the type settings.
48 private(set) var theme = ThemeSpec.default
49 /// `show-markup`, toggled in the editor; the folder's value applies when it changes.
50 var showMarkup = false
51 /// `org-stored-links`, most recent first; kept while the app runs, as in Emacs.
52 var storedLinks: [StoredLink] = []
53 @ObservationIgnored private var configShowMarkup: Bool?
54 @ObservationIgnored private var presenter: FolderPresenter?
55 @ObservationIgnored private var sizeObserver: NSObjectProtocol?
56
57 private static let bookmarkKey = "configFolderBookmark"
58
59 private init() {
60 // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
61 let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
62 UserConfig.directoryOverride = folder
63 let (problems, colors) = Self.readConfig(folder)
64 let settings = OrgPreferences.orgSettings()
65 do {
66 let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
67 self.workspace = workspace
68 agenda = AgendaModel(workspace: workspace)
69 failure = nil
70 } catch {
71 workspace = nil
72 agenda = nil
73 failure = error.localizedDescription
74 }
75 configFolder = folder
76 configProblems = problems
77 applySettings(colors)
78 shareTemplates()
79 watchConfig()
80 // A new Dynamic Type size restyles editors and the reader.
81 sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
82 MainActor.assumeIsolated { self?.settingsVersion += 1 }
83 }
84 }
85
86 /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
87 func setConfigFolder(_ url: URL?) {
88 if let url {
89 _ = url.startAccessingSecurityScopedResource()
90 if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
91 Self.createConfig(in: url)
92 } else {
93 UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
94 // What the folder set no longer applies.
95 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
96 }
97 configFolder = url
98 reloadConfig()
99 watchConfig()
100 }
101
102 func reloadConfig() {
103 let interval = Perf.begin("config.reload")
104 defer { interval.end() }
105 UserConfig.directoryOverride = configFolder
106 let (problems, colors) = Self.readConfig(configFolder)
107 configProblems = problems
108 applySettings(colors)
109 shareTemplates()
110 }
111
112 private func applySettings(_ colors: ThemeSpec) {
113 theme = OrgPreferences.theme(colors)
114 let markup = OrgPreferences.showMarkup()
115 if markup != configShowMarkup {
116 configShowMarkup = markup
117 showMarkup = markup
118 }
119 let settings = OrgPreferences.orgSettings()
120 session.defaults = settings
121 session.options = OrgPreferences.options()
122 workspace?.settings = .with(todoKeywords: settings)
123 if let agenda {
124 agenda.span = OrgPreferences.agendaSpan()
125 agenda.startOffset = OrgPreferences.agendaStartOffset()
126 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
127 agenda.options = OrgPreferences.agendaOptions(agenda.options)
128 agenda.calendarEvents = OrgPreferences.calendarEvents() ? calendarEvents : nil
129 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
130 }
131 settingsVersion += 1
132 }
133
134 /// The folder's `config.toml`, read in coordination with the app that syncs it.
135 func configText() -> String? {
136 configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
137 }
138
139 /// Writes the folder's `config.toml` and applies it.
140 func saveConfig(_ text: String) {
141 guard let configFolder else { return }
142 var error: NSError?
143 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: configFolder.appendingPathComponent("config.toml"), options: [], error: &error) { url in
144 try? text.write(to: url, atomically: true, encoding: .utf8)
145 }
146 reloadConfig()
147 }
148
149 /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
150 /// the Mac's Settings write it, else in this device's settings.
151 func set(_ defaultsKey: String, to value: TOML.Value) {
152 guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
153 if let configFolder {
154 let file = configFolder.appendingPathComponent("config.toml")
155 var error: NSError?
156 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
157 let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
158 try? UserConfig.setting(text, section: setting.section, key: setting.key, to: value).write(to: url, atomically: true, encoding: .utf8)
159 }
160 } else {
161 switch value {
162 case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
163 case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
164 case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
165 }
166 }
167 reloadConfig()
168 }
169
170 /// The capture templates, for the share extension to offer.
171 private func shareTemplates() {
172 try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
173 }
174
175 /// Edits to the folder's files, synced from the Mac, apply as they arrive.
176 private func watchConfig() {
177 presenter?.stop()
178 presenter = nil
179 guard let configFolder else { return }
180 let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
181 Task { @MainActor [weak self] in self?.reloadConfig() }
182 }
183 presenter.start()
184 self.presenter = presenter
185 }
186
187 private static func resolveBookmark() -> URL? {
188 guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
189 var stale = false
190 guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
191 _ = url.startAccessingSecurityScopedResource()
192 if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
193 return url
194 }
195
196 /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
197 /// colors.
198 /// Writes `config.toml` with every setting at its default when the folder has none.
199 private static func createConfig(in folder: URL) {
200 let file = folder.appendingPathComponent("config.toml")
201 var error: NSError?
202 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
203 guard !FileManager.default.fileExists(atPath: url.path) else { return }
204 try? UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8)
205 }
206 }
207
208 private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
209 guard let folder else { return ([], .default) }
210 guard let text = read(folder.appendingPathComponent("config.toml")) else {
211 return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
212 }
213 let problems = UserConfig.apply(text, to: .standard)
214 guard let theme = UserConfig.theme(config: text, themeFile: UserDefaults.standard.string(forKey: "themeFile"), in: folder, read: read) else {
215 return (problems, .default)
216 }
217 return (problems + theme.problems, theme.theme)
218 }
219
220 /// A file of the folder, read in coordination with the app that syncs it.
221 private static func read(_ file: URL) -> String? {
222 var text: String?
223 var error: NSError?
224 NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
225 text = try? String(contentsOf: url, encoding: .utf8)
226 }
227 return text
228 }
229
230 /// Notifications for the next week's timed entries, at most 64, as iOS allows.
231 func updateReminders() async {
232 let interval = Perf.begin("reminders.update")
233 defer { interval.end() }
234 guard let workspace else { return }
235 guard OrgPreferences.reminders() else {
236 await scheduler.clear()
237 return
238 }
239 guard !workspace.files.isEmpty else { return }
240 // The agenda's cache and options, so files it has read aren't read again.
241 let agenda = AgendaModel(workspace: workspace, cache: self.agenda?.cache ?? AgendaSourceCache())
242 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
243 if let options = self.agenda?.options { agenda.options = options }
244 let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
245 await scheduler.reconcile(reminders)
246 }
247
248 /// The widgets' agenda: today and the next days in the app group's container, with the
249 /// widgets reloaded when it changed.
250 func updateWidgets() async {
251 let interval = Perf.begin("widgets.update")
252 defer { interval.end() }
253 guard let workspace, let file = AgendaSnapshot.file() else { return }
254 let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
255 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
256 if let agenda {
257 days.includeSubfolders = agenda.includeSubfolders
258 days.options = agenda.options
259 days.options.logMode = false
260 days.calendarEvents = agenda.calendarEvents
261 days.calendarNames = agenda.calendarNames
262 }
263 await days.refresh(open: session.openTexts)
264 let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
265 if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
266 }
267}
268#endif