Sources/OrgstarMobile/MobileModel.swift
392 lines · 19754 bytes
1#if os(iOS)
2import Foundation
3import Observation
4import OrgApp
5import OrgCore
6import OrgIndex
7import OrgPresentation
8import OrgWatchData
9import OrgWorkspace
10import UIKit
11import UserNotifications
12import WidgetKit
13
14/// The app's models, and the settings from the configuration folder: a folder you choose
15/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
16@MainActor
17@Observable
18final class MobileModel {
19 /// One per process: Shortcuts runs the capture action without a window.
20 static let shared = MobileModel()
21
22 let workspace: WorkspaceModel?
23 let failure: String?
24 let session = DocumentSession()
25 /// The open files' editors, shared by every scene's panes.
26 let editors = MobileEditorStore()
27 let agenda: AgendaModel?
28 let scheduler = ReminderScheduler(center: SystemReminderCenter())
29 let clock = ClockModel()
30 let clockPrompts = ClockPrompter()
31 let spotlight = SpotlightIndexer()
32 /// Captures from the share extension; nil without the app group.
33 let inbox = CaptureInbox()
34 private(set) var configFolder: URL?
35 private(set) var configProblems: [String] = []
36 /// An entry to show, from a tapped reminder.
37 var openRequest: ReaderRoute?
38 /// Agenda days to show, from a followed timestamp: the first (a `Days` number) and how many.
39 var agendaRequest: AgendaDays?
40 /// A capture to show, from the agenda or the capture control.
41 var captureRequest: CaptureRequest?
42 /// Folders shows its folder picker, from File ▸ Add Folder… in the menu bar.
43 var addingFolder = false
44 /// Calendar's events for the agenda, with `calendar-events`.
45 let calendarEvents = CalendarEvents()
46 /// Captures the watch sent, for the root view to pick up from the inbox.
47 var watchCaptures = 0
48 /// Reminders for the agenda, with `agenda-reminders`.
49 let reminderLists = ReminderLists()
50
51 struct AgendaDays: Equatable {
52 let start: Int
53 let count: Int
54 }
55 /// Bumped when settings apply, so views that read them update.
56 private(set) var settingsVersion = 0
57 /// The `keymap` preset with the folder's `keymap.toml` on it, for a hardware keyboard, and
58 /// whether it is Doom's modal one.
59 private(set) var keymap = KeymapPreset.emacs.keymap
60 private(set) var modalKeys = false
61 /// The theme from `config.toml` and its theme file, with the type settings.
62 private(set) var theme = ThemeSpec.default
63 /// `show-markup`, toggled in the editor; the folder's value applies when it changes.
64 var showMarkup = false
65 /// `org-stored-links`, most recent first; kept while the app runs, as in Emacs.
66 var storedLinks: [StoredLink] = []
67 @ObservationIgnored private var configShowMarkup: Bool?
68 /// Whether orgstar+ was locked at the last widget update; nil before the first.
69 @ObservationIgnored private var widgetsLocked: Bool?
70 @ObservationIgnored private var presenter: FolderPresenter?
71 @ObservationIgnored private var sizeObserver: NSObjectProtocol?
72
73 private init() {
74 // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
75 let folder = ConfigFolder.resolve() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
76 UserConfig.directoryOverride = folder
77 let (problems, colors) = Self.readConfig(folder)
78 let settings = OrgPreferences.orgSettings()
79 // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
80 TableBlocks.allowed = { ProAccess.isUnlockedNow }
81 do {
82 let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
83 // Recently Deleted where the folder's provider keeps one (iCloud Drive); otherwise gone.
84 workspace.trasher = { url in
85 do { try FileManager.default.trashItem(at: url, resultingItemURL: nil) } catch { try FileManager.default.removeItem(at: url) }
86 }
87 self.workspace = workspace
88 agenda = AgendaModel(workspace: workspace)
89 failure = nil
90 } catch {
91 workspace = nil
92 agenda = nil
93 failure = error.localizedDescription
94 }
95 configFolder = folder
96 configProblems = problems
97 applySettings(colors)
98 shareTemplates()
99 watchConfig()
100 // `org-clock-out-when-done`, and the reminder when the Effort runs out.
101 clock.notifications = SystemReminderCenter()
102 session.textChanged = { [weak self] path in
103 guard let self else { return }
104 _ = self.clock.textChanged(path, self.session)
105 }
106 // A new Dynamic Type size restyles editors and the reader.
107 sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
108 MainActor.assumeIsolated { self?.settingsVersion += 1 }
109 }
110 }
111
112 /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
113 func setConfigFolder(_ url: URL?) {
114 var problem: String?
115 if let url {
116 ConfigFolder.set(url)
117 problem = Self.createConfig(in: url)
118 } else {
119 ConfigFolder.clear()
120 // What the folder set no longer applies.
121 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
122 for width in KeyBarLayout.Width.allCases { KeyBarLayout.store(nil, width, in: .standard) }
123 }
124 configFolder = url
125 _ = reloadConfig(after: problem)
126 watchConfig()
127 }
128
129 func reloadConfig() {
130 let interval = Perf.begin("config.reload")
131 defer { interval.end() }
132 UserConfig.directoryOverride = configFolder
133 let (problems, colors) = Self.readConfig(configFolder)
134 configProblems = problems
135 applySettings(colors)
136 shareTemplates()
137 }
138
139 private func applySettings(_ colors: ThemeSpec) {
140 theme = OrgPreferences.theme(colors)
141 let markup = OrgPreferences.showMarkup()
142 if markup != configShowMarkup {
143 configShowMarkup = markup
144 showMarkup = markup
145 }
146 let preset = KeymapPreset(rawValue: UserDefaults.standard.string(forKey: "keymap") ?? "") ?? .emacs
147 let loaded = KeymapLoader.load(preset, userFile: UserConfig.file("keymap.toml"))
148 keymap = loaded.keymap
149 modalKeys = preset.isModal
150 configProblems += loaded.problems.map { "keymap.toml: " + $0 }
151 configProblems += MacroFile.load().map { "\(NamedMacros.fileName): " + $0 }
152 SnippetLibrary.shared.reload(from: UserConfig.file(Snippets.fileName), read: configFolder == nil ? { try? String(contentsOf: $0, encoding: .utf8) } : Self.read)
153 configProblems += SnippetLibrary.shared.problems
154 configProblems += KeyBar.problems()
155 let settings = OrgPreferences.orgSettings()
156 session.defaults = settings
157 session.options = OrgPreferences.options()
158 session.options.snippets = SnippetLibrary.shared.snippets
159 workspace?.settings = .with(todoKeywords: settings)
160 if let agenda {
161 agenda.span = OrgPreferences.agendaSpan()
162 agenda.startOffset = OrgPreferences.agendaStartOffset()
163 agenda.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
164 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
165 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
166 agenda.agendaFiles = OrgPreferences.agendaFiles()
167 agenda.options = OrgPreferences.agendaOptions(agenda.options)
168 agenda.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() ? calendarEvents : nil
169 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
170 agenda.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() ? reminderLists : nil
171 agenda.reminderListNames = OrgPreferences.agendaReminderLists()
172 }
173 settingsVersion += 1
174 }
175
176 /// The folder's `config.toml`, read in coordination with the app that syncs it.
177 func configText() -> String? {
178 configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
179 }
180
181 /// Writes the folder's `config.toml` and applies it. False, with the reason first in
182 /// `configProblems`, when the file can't be written or what it holds can't be read.
183 @discardableResult
184 func saveConfig(_ text: String) -> Bool {
185 guard let configFolder else { return false }
186 return reloadConfig(after: Self.updateConfig(in: configFolder) { _ in text })
187 }
188
189 /// Changes the folder's `config.toml`; returns the problem when it can't be read or written.
190 private static func updateConfig(in folder: URL, _ change: (String) -> String) -> String? {
191 do {
192 try UserFile.update(folder.appendingPathComponent("config.toml"), coordinated: true, change)
193 return nil
194 } catch {
195 return "config.toml wasn't changed: \(error.localizedDescription)"
196 }
197 }
198
199 /// Applies the folder's settings, with the `problem` of the write before it first.
200 private func reloadConfig(after problem: String?) -> Bool {
201 reloadConfig()
202 if let problem { configProblems.insert(problem, at: 0) }
203 return problem == nil
204 }
205
206 /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
207 /// the Mac's Settings write it, else in this device's settings.
208 func set(_ defaultsKey: String, to value: TOML.Value) {
209 guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
210 var problem: String?
211 if let configFolder {
212 problem = Self.updateConfig(in: configFolder) { UserConfig.setting($0, section: setting.section, key: setting.key, to: value) }
213 } else {
214 switch value {
215 case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
216 case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
217 case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
218 case .array: break
219 }
220 }
221 _ = reloadConfig(after: problem)
222 }
223
224 /// Sets the key bar's buttons for `width`, or with nil its default, as `set` does.
225 func setKeyBar(_ ids: [String]?, _ width: KeyBarLayout.Width) {
226 var problem: String?
227 if let configFolder {
228 problem = Self.updateConfig(in: configFolder) { text in
229 guard let ids else { return UserConfig.removingSetting(text, section: KeyBarLayout.table, key: width.rawValue) }
230 return UserConfig.setting(text, section: KeyBarLayout.table, key: width.rawValue, to: .array(ids.map(TOML.Value.string)))
231 }
232 } else {
233 KeyBarLayout.store(ids, width, in: .standard)
234 }
235 _ = reloadConfig(after: problem)
236 }
237
238 /// The capture templates, for the share extension to offer.
239 private func shareTemplates() {
240 try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
241 }
242
243 /// Edits to the folder's files, synced from the Mac, apply as they arrive.
244 private func watchConfig() {
245 presenter?.stop()
246 presenter = nil
247 guard let configFolder else { return }
248 let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
249 Task { @MainActor [weak self] in self?.reloadConfig() }
250 }
251 presenter.start()
252 self.presenter = presenter
253 }
254
255 /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
256 /// colors.
257 /// Writes `config.toml` with every setting at its default when the folder has none; returns
258 /// the problem when it can't be written.
259 private static func createConfig(in folder: URL) -> String? {
260 let file = folder.appendingPathComponent("config.toml")
261 var error: NSError?
262 var failure: Error?
263 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
264 guard !FileManager.default.fileExists(atPath: url.path) else { return }
265 do { try UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8) } catch { failure = error }
266 }
267 return (error ?? failure).map { "config.toml wasn't created: \($0.localizedDescription)" }
268 }
269
270 private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
271 let defaults = UserDefaults.standard
272 guard let folder else {
273 let (base, problems) = ThemeSpec.base(light: defaults.string(forKey: "themeLight"), dark: defaults.string(forKey: "themeDark"))
274 return (problems, base)
275 }
276 guard let text = read(folder.appendingPathComponent("config.toml")) else {
277 return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
278 }
279 let problems = UserConfig.apply(text, to: defaults)
280 guard let theme = UserConfig.theme(
281 config: text, themeFile: defaults.string(forKey: "themeFile"),
282 lightTheme: defaults.string(forKey: "themeLight"), darkTheme: defaults.string(forKey: "themeDark"), in: folder, read: read
283 ) else {
284 return (problems, .default)
285 }
286 return (problems + theme.problems, theme.theme)
287 }
288
289 /// A file of the folder, read in coordination with the app that syncs it.
290 private static func read(_ file: URL) -> String? {
291 var text: String?
292 var error: NSError?
293 NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
294 text = try? String(contentsOf: url, encoding: .utf8)
295 }
296 return text
297 }
298
299 /// Notifications for the next week's timed entries, at most 64, as iOS allows.
300 func updateReminders() async {
301 let interval = Perf.begin("reminders.update")
302 defer { interval.end() }
303 guard let workspace else { return }
304 guard OrgPreferences.reminders() else {
305 await scheduler.clear()
306 return
307 }
308 guard !workspace.files.isEmpty else { return }
309 // The agenda's cache and options, so files it has read aren't read again.
310 let agenda = AgendaModel(workspace: workspace, cache: self.agenda?.cache ?? AgendaSourceCache())
311 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
312 if let options = self.agenda?.options { agenda.options = options }
313 let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
314 await scheduler.reconcile(reminders)
315 }
316
317 /// The widgets' agenda: today and the next days in the app group's container, with the
318 /// widgets reloaded when it changed; their habits and capture templates; and the icon's
319 /// overdue badge.
320 func updateWidgets() async {
321 let interval = Perf.begin("widgets.update")
322 defer { interval.end() }
323 guard let workspace else { return }
324 let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
325 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
326 days.startOnWeekday = nil
327 days.hiddenFolders = HiddenFolders.shared.all
328 if let agenda {
329 days.includeSubfolders = agenda.includeSubfolders
330 days.excludeArchives = agenda.excludeArchives
331 days.options = agenda.options
332 days.options.logMode = false
333 days.calendarEvents = agenda.calendarEvents
334 days.calendarNames = agenda.calendarNames
335 days.reminderLists = agenda.reminderLists
336 days.reminderListNames = agenda.reminderListNames
337 }
338 await days.refresh(open: session.openTexts)
339 let groups = days.groups()
340 let locked = !ProAccess.shared.isUnlocked
341 let wasLocked = widgetsLocked
342 widgetsLocked = locked
343 guard !locked else {
344 // Widgets read the flag and show that they need Pro.
345 WatchLink.shared.send(.locked(generated: Date()))
346 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
347 if AgendaSnapshot.reloadsWidgets(locked: true, wasLocked: wasLocked, snapshotChanged: false) { WidgetCenter.shared.reloadAllTimelines() }
348 return
349 }
350 WatchLink.shared.send(WatchAgenda(groups: groups, today: days.today, clock: clock.running, lastClocked: clock.history.first?.title, generated: Date()))
351 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
352 if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") }
353 _ = try? TemplateList(templates: CaptureTemplates.load().templates.map { .init(key: $0.key, name: $0.name) }).write()
354 guard let file = AgendaSnapshot.file() else { return }
355 let snapshot = AgendaSnapshot(groups: groups, today: days.today, theme: theme, generated: Date())
356 let changed = (try? snapshot.write(to: file)) == true
357 if AgendaSnapshot.reloadsWidgets(locked: false, wasLocked: wasLocked, snapshotChanged: changed) { WidgetCenter.shared.reloadAllTimelines() }
358 }
359
360 /// Today's count on the icon, and each later day's set for its midnight by a notification
361 /// that only changes the badge.
362 private func updateBadge(_ counts: [Int]) async {
363 let center = UNUserNotificationCenter.current()
364 // Onboarding asks first.
365 guard await badgesEnabled(asking: UserDefaults.standard.bool(forKey: OnboardingScreen.doneKey)) else { return }
366 try? await center.setBadgeCount(counts.first ?? 0)
367 center.removePendingNotificationRequests(withIdentifiers: (1..<AgendaSnapshot.dayCount).map(Self.badgeID))
368 let today = Calendar.current.startOfDay(for: Date())
369 for (offset, count) in counts.enumerated().dropFirst() {
370 guard let midnight = Calendar.current.date(byAdding: .day, value: offset, to: today) else { continue }
371 let content = UNMutableNotificationContent()
372 content.badge = NSNumber(value: count)
373 let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: midnight)
374 let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
375 try? await center.add(UNNotificationRequest(identifier: Self.badgeID(offset), content: content, trigger: trigger))
376 }
377 }
378
379 static func badgeID(_ offset: Int) -> String { "badge.\(offset)" }
380
381 /// Whether iOS shows the icon's badge. Asking adds badges to the app's notification
382 /// settings, which an earlier grant without them leaves out; iOS prompts only the first time.
383 func badgesEnabled(asking: Bool) async -> Bool {
384 let center = UNUserNotificationCenter.current()
385 let settings = await center.notificationSettings()
386 if settings.badgeSetting == .enabled { return true }
387 guard asking, settings.authorizationStatus != .denied else { return false }
388 _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge])
389 return await center.notificationSettings().badgeSetting == .enabled
390 }
391}
392#endif