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