Sources/OrgstarMobile/MobileModel.swift
135 lines · 5452 bytes
1#if os(iOS)
2import Foundation
3import Observation
4import OrgApp
5import OrgCore
6import OrgIndex
7import OrgWorkspace
8
9/// The app's models, and the settings from the configuration folder: a folder you choose
10/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
11@MainActor
12@Observable
13final class MobileModel {
14 let workspace: WorkspaceModel?
15 let failure: String?
16 let session = DocumentSession()
17 let agenda: AgendaModel?
18 let scheduler = ReminderScheduler(center: SystemReminderCenter())
19 let clock = ClockModel()
20 let spotlight = SpotlightIndexer()
21 private(set) var configFolder: URL?
22 private(set) var configProblems: [String] = []
23 /// An entry to show, from a tapped reminder.
24 var openRequest: ReaderRoute?
25 /// Bumped when settings apply, so views that read them update.
26 private(set) var settingsVersion = 0
27 @ObservationIgnored private var presenter: FolderPresenter?
28
29 private static let bookmarkKey = "configFolderBookmark"
30
31 init() {
32 // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
33 let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
34 UserConfig.directoryOverride = folder
35 let problems = Self.readConfig(folder)
36 let settings = OrgPreferences.orgSettings()
37 do {
38 let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
39 self.workspace = workspace
40 agenda = AgendaModel(workspace: workspace)
41 failure = nil
42 } catch {
43 workspace = nil
44 agenda = nil
45 failure = error.localizedDescription
46 }
47 configFolder = folder
48 configProblems = problems
49 applySettings()
50 watchConfig()
51 }
52
53 /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
54 func setConfigFolder(_ url: URL?) {
55 if let url {
56 _ = url.startAccessingSecurityScopedResource()
57 if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
58 } else {
59 UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
60 // What the folder set no longer applies.
61 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
62 }
63 configFolder = url
64 reloadConfig()
65 watchConfig()
66 }
67
68 func reloadConfig() {
69 UserConfig.directoryOverride = configFolder
70 configProblems = Self.readConfig(configFolder)
71 applySettings()
72 }
73
74 private func applySettings() {
75 let settings = OrgPreferences.orgSettings()
76 session.defaults = settings
77 session.options = OrgPreferences.options()
78 workspace?.settings = .with(todoKeywords: settings)
79 if let agenda {
80 agenda.span = OrgPreferences.agendaSpan()
81 agenda.startOffset = OrgPreferences.agendaStartOffset()
82 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
83 }
84 settingsVersion += 1
85 }
86
87 /// Edits to the folder's files, synced from the Mac, apply as they arrive.
88 private func watchConfig() {
89 presenter?.stop()
90 presenter = nil
91 guard let configFolder else { return }
92 let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
93 Task { @MainActor [weak self] in self?.reloadConfig() }
94 }
95 presenter.start()
96 self.presenter = presenter
97 }
98
99 private static func resolveBookmark() -> URL? {
100 guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
101 var stale = false
102 guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
103 _ = url.startAccessingSecurityScopedResource()
104 if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
105 return url
106 }
107
108 /// Applies the folder's `config.toml` to the settings; returns its problems.
109 private static func readConfig(_ folder: URL?) -> [String] {
110 guard let folder else { return [] }
111 let file = folder.appendingPathComponent("config.toml")
112 var text: String?
113 var error: NSError?
114 NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
115 text = try? String(contentsOf: url, encoding: .utf8)
116 }
117 guard let text else { return ["No config.toml in \(folder.lastPathComponent); the defaults apply."] }
118 return UserConfig.apply(text, to: .standard)
119 }
120
121 /// Notifications for the next week's timed entries, at most 64, as iOS allows.
122 func updateReminders() async {
123 guard let workspace else { return }
124 guard OrgPreferences.reminders() else {
125 await scheduler.clear()
126 return
127 }
128 guard !workspace.files.isEmpty else { return }
129 let agenda = AgendaModel(workspace: workspace)
130 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
131 let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
132 await scheduler.reconcile(reminders)
133 }
134}
135#endif