Sources/OrgstarMobile/MobileModel.swift

49cb8f339ff4526b33437e3b9ccc1aa62b1271ae
orgstar/Sources/OrgstarMobile/MobileModel.swift history · blame · raw

245 lines · 11008 bytes

  1#if os(iOS)
  2import Foundation
  3import Observation
  4import OrgApp
  5import OrgCore
  6import OrgIndex
  7import OrgPresentation
  8import OrgWorkspace
  9import UIKit
 10import WidgetKit
 11
 12/// The app's models, and the settings from the configuration folder: a folder you choose
 13/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
 14@MainActor
 15@Observable
 16final class MobileModel {
 17    /// One per process: Shortcuts runs the capture action without a window.
 18    static let shared = MobileModel()
 19
 20    let workspace: WorkspaceModel?
 21    let failure: String?
 22    let session = DocumentSession()
 23    let agenda: AgendaModel?
 24    let scheduler = ReminderScheduler(center: SystemReminderCenter())
 25    let clock = ClockModel()
 26    let clockPrompts = ClockPrompter()
 27    let spotlight = SpotlightIndexer()
 28    /// Captures from the share extension; nil without the app group.
 29    let inbox = CaptureInbox()
 30    private(set) var configFolder: URL?
 31    private(set) var configProblems: [String] = []
 32    /// An entry to show, from a tapped reminder.
 33    var openRequest: ReaderRoute?
 34    /// Agenda days to show, from a followed timestamp: the first (a `Days` number) and how many.
 35    var agendaRequest: AgendaDays?
 36    /// A capture to show, from the agenda.
 37    var captureRequest: CaptureRequest?
 38    /// Calendar's events for the agenda, with `calendar-events`.
 39    let calendarEvents = CalendarEvents()
 40
 41    struct AgendaDays: Equatable {
 42        let start: Int
 43        let count: Int
 44    }
 45    /// Bumped when settings apply, so views that read them update.
 46    private(set) var settingsVersion = 0
 47    /// The theme from `config.toml` and its theme file, with the type settings.
 48    private(set) var theme = ThemeSpec.default
 49    /// `show-markup`, toggled in the editor; the folder's value applies when it changes.
 50    var showMarkup = false
 51    /// `org-stored-links`, most recent first; kept while the app runs, as in Emacs.
 52    var storedLinks: [StoredLink] = []
 53    @ObservationIgnored private var configShowMarkup: Bool?
 54    @ObservationIgnored private var presenter: FolderPresenter?
 55    @ObservationIgnored private var sizeObserver: NSObjectProtocol?
 56
 57    private static let bookmarkKey = "configFolderBookmark"
 58
 59    private init() {
 60        // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
 61        let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
 62        UserConfig.directoryOverride = folder
 63        let (problems, colors) = Self.readConfig(folder)
 64        let settings = OrgPreferences.orgSettings()
 65        do {
 66            let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
 67            self.workspace = workspace
 68            agenda = AgendaModel(workspace: workspace)
 69            failure = nil
 70        } catch {
 71            workspace = nil
 72            agenda = nil
 73            failure = error.localizedDescription
 74        }
 75        configFolder = folder
 76        configProblems = problems
 77        applySettings(colors)
 78        shareTemplates()
 79        watchConfig()
 80        // A new Dynamic Type size restyles editors and the reader.
 81        sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
 82            MainActor.assumeIsolated { self?.settingsVersion += 1 }
 83        }
 84    }
 85
 86    /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
 87    func setConfigFolder(_ url: URL?) {
 88        if let url {
 89            _ = url.startAccessingSecurityScopedResource()
 90            if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
 91            Self.createConfig(in: url)
 92        } else {
 93            UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
 94            // What the folder set no longer applies.
 95            for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
 96        }
 97        configFolder = url
 98        reloadConfig()
 99        watchConfig()
100    }
101
102    func reloadConfig() {
103        UserConfig.directoryOverride = configFolder
104        let (problems, colors) = Self.readConfig(configFolder)
105        configProblems = problems
106        applySettings(colors)
107        shareTemplates()
108    }
109
110    private func applySettings(_ colors: ThemeSpec) {
111        theme = OrgPreferences.theme(colors)
112        let markup = OrgPreferences.showMarkup()
113        if markup != configShowMarkup {
114            configShowMarkup = markup
115            showMarkup = markup
116        }
117        let settings = OrgPreferences.orgSettings()
118        session.defaults = settings
119        session.options = OrgPreferences.options()
120        workspace?.settings = .with(todoKeywords: settings)
121        if let agenda {
122            agenda.span = OrgPreferences.agendaSpan()
123            agenda.startOffset = OrgPreferences.agendaStartOffset()
124            agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
125            agenda.options = OrgPreferences.agendaOptions(agenda.options)
126            agenda.calendarEvents = OrgPreferences.calendarEvents() ? calendarEvents : nil
127            agenda.calendarNames = OrgPreferences.calendarEventCalendars()
128        }
129        settingsVersion += 1
130    }
131
132    /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
133    /// the Mac's Settings write it, else in this device's settings.
134    func set(_ defaultsKey: String, to value: TOML.Value) {
135        guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
136        if let configFolder {
137            let file = configFolder.appendingPathComponent("config.toml")
138            var error: NSError?
139            NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
140                let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
141                try? UserConfig.setting(text, section: setting.section, key: setting.key, to: value).write(to: url, atomically: true, encoding: .utf8)
142            }
143        } else {
144            switch value {
145            case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
146            case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
147            case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
148            }
149        }
150        reloadConfig()
151    }
152
153    /// The capture templates, for the share extension to offer.
154    private func shareTemplates() {
155        try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
156    }
157
158    /// Edits to the folder's files, synced from the Mac, apply as they arrive.
159    private func watchConfig() {
160        presenter?.stop()
161        presenter = nil
162        guard let configFolder else { return }
163        let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
164            Task { @MainActor [weak self] in self?.reloadConfig() }
165        }
166        presenter.start()
167        self.presenter = presenter
168    }
169
170    private static func resolveBookmark() -> URL? {
171        guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
172        var stale = false
173        guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
174        _ = url.startAccessingSecurityScopedResource()
175        if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
176        return url
177    }
178
179    /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
180    /// colors.
181    /// Writes `config.toml` with every setting at its default when the folder has none.
182    private static func createConfig(in folder: URL) {
183        let file = folder.appendingPathComponent("config.toml")
184        var error: NSError?
185        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
186            guard !FileManager.default.fileExists(atPath: url.path) else { return }
187            try? UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8)
188        }
189    }
190
191    private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
192        guard let folder else { return ([], .default) }
193        guard let text = read(folder.appendingPathComponent("config.toml")) else {
194            return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
195        }
196        let problems = UserConfig.apply(text, to: .standard)
197        guard let theme = UserConfig.theme(config: text, themeFile: UserDefaults.standard.string(forKey: "themeFile"), in: folder, read: read) else {
198            return (problems, .default)
199        }
200        return (problems + theme.problems, theme.theme)
201    }
202
203    /// A file of the folder, read in coordination with the app that syncs it.
204    private static func read(_ file: URL) -> String? {
205        var text: String?
206        var error: NSError?
207        NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
208            text = try? String(contentsOf: url, encoding: .utf8)
209        }
210        return text
211    }
212
213    /// Notifications for the next week's timed entries, at most 64, as iOS allows.
214    func updateReminders() async {
215        guard let workspace else { return }
216        guard OrgPreferences.reminders() else {
217            await scheduler.clear()
218            return
219        }
220        guard !workspace.files.isEmpty else { return }
221        let agenda = AgendaModel(workspace: workspace)
222        agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
223        let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
224        await scheduler.reconcile(reminders)
225    }
226
227    /// The widgets' agenda: today and the next days in the app group's container, with the
228    /// widgets reloaded when it changed.
229    func updateWidgets() async {
230        guard let workspace, let file = AgendaSnapshot.file() else { return }
231        let days = AgendaModel(workspace: workspace)
232        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
233        if let agenda {
234            days.includeSubfolders = agenda.includeSubfolders
235            days.options = agenda.options
236            days.options.logMode = false
237            days.calendarEvents = agenda.calendarEvents
238            days.calendarNames = agenda.calendarNames
239        }
240        await days.refresh(open: session.openTexts)
241        let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
242        if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
243    }
244}
245#endif