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