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