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