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