Sources/OrgstarMobile/MobileModel.swift

1d52ac3e828cb73639dc1c0cd5b6c9f0795b14a7
orgstar/Sources/OrgstarMobile/MobileModel.swift history · blame · raw

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