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