Sources/OrgstarMobile/MobileModel.swift

2d7bde2d9a815f914b1250e74c47c6a07f677f23
orgstar/Sources/OrgstarMobile/MobileModel.swift

260 lines · 11664 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    /// The folder's `config.toml`, read in coordination with the app that syncs it.
133    func configText() -> String? {
134        configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
135    }
136
137    /// Writes the folder's `config.toml` and applies it.
138    func saveConfig(_ text: String) {
139        guard let configFolder else { return }
140        var error: NSError?
141        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: configFolder.appendingPathComponent("config.toml"), options: [], error: &error) { url in
142            try? text.write(to: url, atomically: true, encoding: .utf8)
143        }
144        reloadConfig()
145    }
146
147    /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
148    /// the Mac's Settings write it, else in this device's settings.
149    func set(_ defaultsKey: String, to value: TOML.Value) {
150        guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
151        if let configFolder {
152            let file = configFolder.appendingPathComponent("config.toml")
153            var error: NSError?
154            NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
155                let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
156                try? UserConfig.setting(text, section: setting.section, key: setting.key, to: value).write(to: url, atomically: true, encoding: .utf8)
157            }
158        } else {
159            switch value {
160            case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
161            case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
162            case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
163            }
164        }
165        reloadConfig()
166    }
167
168    /// The capture templates, for the share extension to offer.
169    private func shareTemplates() {
170        try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
171    }
172
173    /// Edits to the folder's files, synced from the Mac, apply as they arrive.
174    private func watchConfig() {
175        presenter?.stop()
176        presenter = nil
177        guard let configFolder else { return }
178        let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
179            Task { @MainActor [weak self] in self?.reloadConfig() }
180        }
181        presenter.start()
182        self.presenter = presenter
183    }
184
185    private static func resolveBookmark() -> URL? {
186        guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
187        var stale = false
188        guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
189        _ = url.startAccessingSecurityScopedResource()
190        if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
191        return url
192    }
193
194    /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
195    /// colors.
196    /// Writes `config.toml` with every setting at its default when the folder has none.
197    private static func createConfig(in folder: URL) {
198        let file = folder.appendingPathComponent("config.toml")
199        var error: NSError?
200        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
201            guard !FileManager.default.fileExists(atPath: url.path) else { return }
202            try? UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8)
203        }
204    }
205
206    private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
207        guard let folder else { return ([], .default) }
208        guard let text = read(folder.appendingPathComponent("config.toml")) else {
209            return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
210        }
211        let problems = UserConfig.apply(text, to: .standard)
212        guard let theme = UserConfig.theme(config: text, themeFile: UserDefaults.standard.string(forKey: "themeFile"), in: folder, read: read) else {
213            return (problems, .default)
214        }
215        return (problems + theme.problems, theme.theme)
216    }
217
218    /// A file of the folder, read in coordination with the app that syncs it.
219    private static func read(_ file: URL) -> String? {
220        var text: String?
221        var error: NSError?
222        NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
223            text = try? String(contentsOf: url, encoding: .utf8)
224        }
225        return text
226    }
227
228    /// Notifications for the next week's timed entries, at most 64, as iOS allows.
229    func updateReminders() async {
230        guard let workspace else { return }
231        guard OrgPreferences.reminders() else {
232            await scheduler.clear()
233            return
234        }
235        guard !workspace.files.isEmpty else { return }
236        let agenda = AgendaModel(workspace: workspace)
237        agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
238        let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
239        await scheduler.reconcile(reminders)
240    }
241
242    /// The widgets' agenda: today and the next days in the app group's container, with the
243    /// widgets reloaded when it changed.
244    func updateWidgets() async {
245        guard let workspace, let file = AgendaSnapshot.file() else { return }
246        let days = AgendaModel(workspace: workspace)
247        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
248        if let agenda {
249            days.includeSubfolders = agenda.includeSubfolders
250            days.options = agenda.options
251            days.options.logMode = false
252            days.calendarEvents = agenda.calendarEvents
253            days.calendarNames = agenda.calendarNames
254        }
255        await days.refresh(open: session.openTexts)
256        let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
257        if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
258    }
259}
260#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form