Sources/OrgstarMobile/MobileModel.swift
371 lines · 18503 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 }
123 configFolder = url
124 _ = reloadConfig(after: problem)
125 watchConfig()
126 }
127
128 func reloadConfig() {
129 let interval = Perf.begin("config.reload")
130 defer { interval.end() }
131 UserConfig.directoryOverride = configFolder
132 let (problems, colors) = Self.readConfig(configFolder)
133 configProblems = problems
134 applySettings(colors)
135 shareTemplates()
136 }
137
138 private func applySettings(_ colors: ThemeSpec) {
139 theme = OrgPreferences.theme(colors)
140 let markup = OrgPreferences.showMarkup()
141 if markup != configShowMarkup {
142 configShowMarkup = markup
143 showMarkup = markup
144 }
145 let preset = KeymapPreset(rawValue: UserDefaults.standard.string(forKey: "keymap") ?? "") ?? .emacs
146 let loaded = KeymapLoader.load(preset, userFile: UserConfig.file("keymap.toml"))
147 keymap = loaded.keymap
148 modalKeys = preset.isModal
149 configProblems += loaded.problems.map { "keymap.toml: " + $0 }
150 let settings = OrgPreferences.orgSettings()
151 session.defaults = settings
152 session.options = OrgPreferences.options()
153 workspace?.settings = .with(todoKeywords: settings)
154 if let agenda {
155 agenda.span = OrgPreferences.agendaSpan()
156 agenda.startOffset = OrgPreferences.agendaStartOffset()
157 agenda.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
158 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
159 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
160 agenda.agendaFiles = OrgPreferences.agendaFiles()
161 agenda.options = OrgPreferences.agendaOptions(agenda.options)
162 agenda.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() ? calendarEvents : nil
163 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
164 agenda.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() ? reminderLists : nil
165 agenda.reminderListNames = OrgPreferences.agendaReminderLists()
166 }
167 settingsVersion += 1
168 }
169
170 /// The folder's `config.toml`, read in coordination with the app that syncs it.
171 func configText() -> String? {
172 configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
173 }
174
175 /// Writes the folder's `config.toml` and applies it. False, with the reason first in
176 /// `configProblems`, when the file can't be written or what it holds can't be read.
177 @discardableResult
178 func saveConfig(_ text: String) -> Bool {
179 guard let configFolder else { return false }
180 return reloadConfig(after: Self.updateConfig(in: configFolder) { _ in text })
181 }
182
183 /// Changes the folder's `config.toml`; returns the problem when it can't be read or written.
184 private static func updateConfig(in folder: URL, _ change: (String) -> String) -> String? {
185 do {
186 try UserFile.update(folder.appendingPathComponent("config.toml"), coordinated: true, change)
187 return nil
188 } catch {
189 return "config.toml wasn't changed: \(error.localizedDescription)"
190 }
191 }
192
193 /// Applies the folder's settings, with the `problem` of the write before it first.
194 private func reloadConfig(after problem: String?) -> Bool {
195 reloadConfig()
196 if let problem { configProblems.insert(problem, at: 0) }
197 return problem == nil
198 }
199
200 /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
201 /// the Mac's Settings write it, else in this device's settings.
202 func set(_ defaultsKey: String, to value: TOML.Value) {
203 guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
204 var problem: String?
205 if let configFolder {
206 problem = Self.updateConfig(in: configFolder) { UserConfig.setting($0, section: setting.section, key: setting.key, to: value) }
207 } else {
208 switch value {
209 case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
210 case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
211 case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
212 }
213 }
214 _ = reloadConfig(after: problem)
215 }
216
217 /// The capture templates, for the share extension to offer.
218 private func shareTemplates() {
219 try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
220 }
221
222 /// Edits to the folder's files, synced from the Mac, apply as they arrive.
223 private func watchConfig() {
224 presenter?.stop()
225 presenter = nil
226 guard let configFolder else { return }
227 let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
228 Task { @MainActor [weak self] in self?.reloadConfig() }
229 }
230 presenter.start()
231 self.presenter = presenter
232 }
233
234 /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
235 /// colors.
236 /// Writes `config.toml` with every setting at its default when the folder has none; returns
237 /// the problem when it can't be written.
238 private static func createConfig(in folder: URL) -> String? {
239 let file = folder.appendingPathComponent("config.toml")
240 var error: NSError?
241 var failure: Error?
242 NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
243 guard !FileManager.default.fileExists(atPath: url.path) else { return }
244 do { try UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8) } catch { failure = error }
245 }
246 return (error ?? failure).map { "config.toml wasn't created: \($0.localizedDescription)" }
247 }
248
249 private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
250 let defaults = UserDefaults.standard
251 guard let folder else {
252 let (base, problems) = ThemeSpec.base(light: defaults.string(forKey: "themeLight"), dark: defaults.string(forKey: "themeDark"))
253 return (problems, base)
254 }
255 guard let text = read(folder.appendingPathComponent("config.toml")) else {
256 return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
257 }
258 let problems = UserConfig.apply(text, to: defaults)
259 guard let theme = UserConfig.theme(
260 config: text, themeFile: defaults.string(forKey: "themeFile"),
261 lightTheme: defaults.string(forKey: "themeLight"), darkTheme: defaults.string(forKey: "themeDark"), in: folder, read: read
262 ) else {
263 return (problems, .default)
264 }
265 return (problems + theme.problems, theme.theme)
266 }
267
268 /// A file of the folder, read in coordination with the app that syncs it.
269 private static func read(_ file: URL) -> String? {
270 var text: String?
271 var error: NSError?
272 NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
273 text = try? String(contentsOf: url, encoding: .utf8)
274 }
275 return text
276 }
277
278 /// Notifications for the next week's timed entries, at most 64, as iOS allows.
279 func updateReminders() async {
280 let interval = Perf.begin("reminders.update")
281 defer { interval.end() }
282 guard let workspace else { return }
283 guard OrgPreferences.reminders() else {
284 await scheduler.clear()
285 return
286 }
287 guard !workspace.files.isEmpty else { return }
288 // The agenda's cache and options, so files it has read aren't read again.
289 let agenda = AgendaModel(workspace: workspace, cache: self.agenda?.cache ?? AgendaSourceCache())
290 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
291 if let options = self.agenda?.options { agenda.options = options }
292 let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
293 await scheduler.reconcile(reminders)
294 }
295
296 /// The widgets' agenda: today and the next days in the app group's container, with the
297 /// widgets reloaded when it changed; their habits and capture templates; and the icon's
298 /// overdue badge.
299 func updateWidgets() async {
300 let interval = Perf.begin("widgets.update")
301 defer { interval.end() }
302 guard let workspace else { return }
303 let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
304 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
305 days.startOnWeekday = nil
306 days.hiddenFolders = HiddenFolders.shared.all
307 if let agenda {
308 days.includeSubfolders = agenda.includeSubfolders
309 days.excludeArchives = agenda.excludeArchives
310 days.options = agenda.options
311 days.options.logMode = false
312 days.calendarEvents = agenda.calendarEvents
313 days.calendarNames = agenda.calendarNames
314 days.reminderLists = agenda.reminderLists
315 days.reminderListNames = agenda.reminderListNames
316 }
317 await days.refresh(open: session.openTexts)
318 let groups = days.groups()
319 let locked = !ProAccess.shared.isUnlocked
320 let wasLocked = widgetsLocked
321 widgetsLocked = locked
322 guard !locked else {
323 // Widgets read the flag and show that they need Pro.
324 WatchLink.shared.send(.locked(generated: Date()))
325 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
326 if AgendaSnapshot.reloadsWidgets(locked: true, wasLocked: wasLocked, snapshotChanged: false) { WidgetCenter.shared.reloadAllTimelines() }
327 return
328 }
329 WatchLink.shared.send(WatchAgenda(groups: groups, today: days.today, clock: clock.running, lastClocked: clock.history.first?.title, generated: Date()))
330 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
331 if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") }
332 _ = try? TemplateList(templates: CaptureTemplates.load().templates.map { .init(key: $0.key, name: $0.name) }).write()
333 guard let file = AgendaSnapshot.file() else { return }
334 let snapshot = AgendaSnapshot(groups: groups, today: days.today, theme: theme, generated: Date())
335 let changed = (try? snapshot.write(to: file)) == true
336 if AgendaSnapshot.reloadsWidgets(locked: false, wasLocked: wasLocked, snapshotChanged: changed) { WidgetCenter.shared.reloadAllTimelines() }
337 }
338
339 /// Today's count on the icon, and each later day's set for its midnight by a notification
340 /// that only changes the badge.
341 private func updateBadge(_ counts: [Int]) async {
342 let center = UNUserNotificationCenter.current()
343 // Onboarding asks first.
344 guard await badgesEnabled(asking: UserDefaults.standard.bool(forKey: OnboardingScreen.doneKey)) else { return }
345 try? await center.setBadgeCount(counts.first ?? 0)
346 center.removePendingNotificationRequests(withIdentifiers: (1..<AgendaSnapshot.dayCount).map(Self.badgeID))
347 let today = Calendar.current.startOfDay(for: Date())
348 for (offset, count) in counts.enumerated().dropFirst() {
349 guard let midnight = Calendar.current.date(byAdding: .day, value: offset, to: today) else { continue }
350 let content = UNMutableNotificationContent()
351 content.badge = NSNumber(value: count)
352 let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: midnight)
353 let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
354 try? await center.add(UNNotificationRequest(identifier: Self.badgeID(offset), content: content, trigger: trigger))
355 }
356 }
357
358 static func badgeID(_ offset: Int) -> String { "badge.\(offset)" }
359
360 /// Whether iOS shows the icon's badge. Asking adds badges to the app's notification
361 /// settings, which an earlier grant without them leaves out; iOS prompts only the first time.
362 func badgesEnabled(asking: Bool) async -> Bool {
363 let center = UNUserNotificationCenter.current()
364 let settings = await center.notificationSettings()
365 if settings.badgeSetting == .enabled { return true }
366 guard asking, settings.authorizationStatus != .denied else { return false }
367 _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge])
368 return await center.notificationSettings().badgeSetting == .enabled
369 }
370}
371#endif