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