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