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