Sources/OrgstarMobile/MobileModel.swift

1569d791fbc3c0618d100bc101222d3bfc5f56d9
orgstar/Sources/OrgstarMobile/MobileModel.swift history · blame · raw

184 lines · 7698 bytes

  1#if os(iOS)
  2import Foundation
  3import Observation
  4import OrgApp
  5import OrgCore
  6import OrgIndex
  7import OrgPresentation
  8import OrgWorkspace
  9import UIKit
 10
 11/// The app's models, and the settings from the configuration folder: a folder you choose
 12/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
 13@MainActor
 14@Observable
 15final class MobileModel {
 16    /// One per process: Shortcuts runs the capture action without a window.
 17    static let shared = MobileModel()
 18
 19    let workspace: WorkspaceModel?
 20    let failure: String?
 21    let session = DocumentSession()
 22    let agenda: AgendaModel?
 23    let scheduler = ReminderScheduler(center: SystemReminderCenter())
 24    let clock = ClockModel()
 25    let spotlight = SpotlightIndexer()
 26    /// Captures from the share extension; nil without the app group.
 27    let inbox = CaptureInbox()
 28    private(set) var configFolder: URL?
 29    private(set) var configProblems: [String] = []
 30    /// An entry to show, from a tapped reminder.
 31    var openRequest: ReaderRoute?
 32    /// Agenda days to show, from a followed timestamp: the first (a `Days` number) and how many.
 33    var agendaRequest: AgendaDays?
 34
 35    struct AgendaDays: Equatable {
 36        let start: Int
 37        let count: Int
 38    }
 39    /// Bumped when settings apply, so views that read them update.
 40    private(set) var settingsVersion = 0
 41    /// The theme from `config.toml` and its theme file, with the type settings.
 42    private(set) var theme = ThemeSpec.default
 43    /// `show-markup`, toggled in the editor; the folder's value applies when it changes.
 44    var showMarkup = false
 45    @ObservationIgnored private var configShowMarkup: Bool?
 46    @ObservationIgnored private var presenter: FolderPresenter?
 47    @ObservationIgnored private var sizeObserver: NSObjectProtocol?
 48
 49    private static let bookmarkKey = "configFolderBookmark"
 50
 51    private init() {
 52        // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
 53        let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
 54        UserConfig.directoryOverride = folder
 55        let (problems, colors) = Self.readConfig(folder)
 56        let settings = OrgPreferences.orgSettings()
 57        do {
 58            let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
 59            self.workspace = workspace
 60            agenda = AgendaModel(workspace: workspace)
 61            failure = nil
 62        } catch {
 63            workspace = nil
 64            agenda = nil
 65            failure = error.localizedDescription
 66        }
 67        configFolder = folder
 68        configProblems = problems
 69        applySettings(colors)
 70        shareTemplates()
 71        watchConfig()
 72        // A new Dynamic Type size restyles editors and the reader.
 73        sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
 74            MainActor.assumeIsolated { self?.settingsVersion += 1 }
 75        }
 76    }
 77
 78    /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
 79    func setConfigFolder(_ url: URL?) {
 80        if let url {
 81            _ = url.startAccessingSecurityScopedResource()
 82            if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
 83        } else {
 84            UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
 85            // What the folder set no longer applies.
 86            for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
 87        }
 88        configFolder = url
 89        reloadConfig()
 90        watchConfig()
 91    }
 92
 93    func reloadConfig() {
 94        UserConfig.directoryOverride = configFolder
 95        let (problems, colors) = Self.readConfig(configFolder)
 96        configProblems = problems
 97        applySettings(colors)
 98        shareTemplates()
 99    }
100
101    private func applySettings(_ colors: ThemeSpec) {
102        theme = OrgPreferences.theme(colors)
103        let markup = OrgPreferences.showMarkup()
104        if markup != configShowMarkup {
105            configShowMarkup = markup
106            showMarkup = markup
107        }
108        let settings = OrgPreferences.orgSettings()
109        session.defaults = settings
110        session.options = OrgPreferences.options()
111        workspace?.settings = .with(todoKeywords: settings)
112        if let agenda {
113            agenda.span = OrgPreferences.agendaSpan()
114            agenda.startOffset = OrgPreferences.agendaStartOffset()
115            agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
116        }
117        settingsVersion += 1
118    }
119
120    /// The capture templates, for the share extension to offer.
121    private func shareTemplates() {
122        try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
123    }
124
125    /// Edits to the folder's files, synced from the Mac, apply as they arrive.
126    private func watchConfig() {
127        presenter?.stop()
128        presenter = nil
129        guard let configFolder else { return }
130        let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
131            Task { @MainActor [weak self] in self?.reloadConfig() }
132        }
133        presenter.start()
134        self.presenter = presenter
135    }
136
137    private static func resolveBookmark() -> URL? {
138        guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
139        var stale = false
140        guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
141        _ = url.startAccessingSecurityScopedResource()
142        if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
143        return url
144    }
145
146    /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
147    /// colors.
148    private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
149        guard let folder else { return ([], .default) }
150        guard let text = read(folder.appendingPathComponent("config.toml")) else {
151            return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
152        }
153        let problems = UserConfig.apply(text, to: .standard)
154        guard let theme = UserConfig.theme(config: text, themeFile: UserDefaults.standard.string(forKey: "themeFile"), in: folder, read: read) else {
155            return (problems, .default)
156        }
157        return (problems + theme.problems, theme.theme)
158    }
159
160    /// A file of the folder, read in coordination with the app that syncs it.
161    private static func read(_ file: URL) -> String? {
162        var text: String?
163        var error: NSError?
164        NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
165            text = try? String(contentsOf: url, encoding: .utf8)
166        }
167        return text
168    }
169
170    /// Notifications for the next week's timed entries, at most 64, as iOS allows.
171    func updateReminders() async {
172        guard let workspace else { return }
173        guard OrgPreferences.reminders() else {
174            await scheduler.clear()
175            return
176        }
177        guard !workspace.files.isEmpty else { return }
178        let agenda = AgendaModel(workspace: workspace)
179        agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
180        let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
181        await scheduler.reconcile(reminders)
182    }
183}
184#endif