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