Sources/OrgstarMobile/MobileModel.swift

5090f3e3e1c88646fa8a0e07bb75647c5cfa2495
orgstar/Sources/OrgstarMobile/MobileModel.swift

328 lines · 16008 bytes

  1#if os(iOS)
  2import Foundation
  3import Observation
  4import OrgApp
  5import OrgCore
  6import OrgIndex
  7import OrgPresentation
  8import OrgWorkspace
  9import UIKit
 10import UserNotifications
 11import WidgetKit
 12
 13/// The app's models, and the settings from the configuration folder: a folder you choose
 14/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
 15@MainActor
 16@Observable
 17final class MobileModel {
 18    /// One per process: Shortcuts runs the capture action without a window.
 19    static let shared = MobileModel()
 20
 21    let workspace: WorkspaceModel?
 22    let failure: String?
 23    let session = DocumentSession()
 24    let agenda: AgendaModel?
 25    let scheduler = ReminderScheduler(center: SystemReminderCenter())
 26    let clock = ClockModel()
 27    let clockPrompts = ClockPrompter()
 28    let spotlight = SpotlightIndexer()
 29    /// Captures from the share extension; nil without the app group.
 30    let inbox = CaptureInbox()
 31    private(set) var configFolder: URL?
 32    private(set) var configProblems: [String] = []
 33    /// An entry to show, from a tapped reminder.
 34    var openRequest: ReaderRoute?
 35    /// Agenda days to show, from a followed timestamp: the first (a `Days` number) and how many.
 36    var agendaRequest: AgendaDays?
 37    /// A capture to show, from the agenda or the capture control.
 38    var captureRequest: CaptureRequest?
 39    /// Calendar's events for the agenda, with `calendar-events`.
 40    let calendarEvents = CalendarEvents()
 41
 42    struct AgendaDays: Equatable {
 43        let start: Int
 44        let count: Int
 45    }
 46    /// Bumped when settings apply, so views that read them update.
 47    private(set) var settingsVersion = 0
 48    /// The `keymap` preset with the folder's `keymap.toml` on it, for a hardware keyboard, and
 49    /// whether it is Doom's modal one.
 50    private(set) var keymap = KeymapPreset.emacs.keymap
 51    private(set) var modalKeys = false
 52    /// The theme from `config.toml` and its theme file, with the type settings.
 53    private(set) var theme = ThemeSpec.default
 54    /// `show-markup`, toggled in the editor; the folder's value applies when it changes.
 55    var showMarkup = false
 56    /// `org-stored-links`, most recent first; kept while the app runs, as in Emacs.
 57    var storedLinks: [StoredLink] = []
 58    @ObservationIgnored private var configShowMarkup: Bool?
 59    @ObservationIgnored private var presenter: FolderPresenter?
 60    @ObservationIgnored private var sizeObserver: NSObjectProtocol?
 61
 62    private static let bookmarkKey = "configFolderBookmark"
 63
 64    private init() {
 65        // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
 66        let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
 67        UserConfig.directoryOverride = folder
 68        let (problems, colors) = Self.readConfig(folder)
 69        let settings = OrgPreferences.orgSettings()
 70        do {
 71            let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
 72            // Recently Deleted where the folder's provider keeps one (iCloud Drive); otherwise gone.
 73            workspace.trasher = { url in
 74                do { try FileManager.default.trashItem(at: url, resultingItemURL: nil) } catch { try FileManager.default.removeItem(at: url) }
 75            }
 76            self.workspace = workspace
 77            agenda = AgendaModel(workspace: workspace)
 78            failure = nil
 79        } catch {
 80            workspace = nil
 81            agenda = nil
 82            failure = error.localizedDescription
 83        }
 84        configFolder = folder
 85        configProblems = problems
 86        applySettings(colors)
 87        shareTemplates()
 88        watchConfig()
 89        // `org-clock-out-when-done`, and the reminder when the Effort runs out.
 90        clock.notifications = SystemReminderCenter()
 91        session.textChanged = { [weak self] path in
 92            guard let self else { return }
 93            _ = self.clock.textChanged(path, self.session)
 94        }
 95        clock.remindAtEffort(session)
 96        // A new Dynamic Type size restyles editors and the reader.
 97        sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
 98            MainActor.assumeIsolated { self?.settingsVersion += 1 }
 99        }
100    }
101
102    /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
103    func setConfigFolder(_ url: URL?) {
104        if let url {
105            _ = url.startAccessingSecurityScopedResource()
106            if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
107            Self.createConfig(in: url)
108        } else {
109            UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
110            // What the folder set no longer applies.
111            for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
112        }
113        configFolder = url
114        reloadConfig()
115        watchConfig()
116    }
117
118    func reloadConfig() {
119        let interval = Perf.begin("config.reload")
120        defer { interval.end() }
121        UserConfig.directoryOverride = configFolder
122        let (problems, colors) = Self.readConfig(configFolder)
123        configProblems = problems
124        applySettings(colors)
125        shareTemplates()
126    }
127
128    private func applySettings(_ colors: ThemeSpec) {
129        theme = OrgPreferences.theme(colors)
130        let markup = OrgPreferences.showMarkup()
131        if markup != configShowMarkup {
132            configShowMarkup = markup
133            showMarkup = markup
134        }
135        let preset = KeymapPreset(rawValue: UserDefaults.standard.string(forKey: "keymap") ?? "") ?? .emacs
136        let loaded = KeymapLoader.load(preset, userFile: UserConfig.file("keymap.toml"))
137        keymap = loaded.keymap
138        modalKeys = preset.isModal
139        configProblems += loaded.problems.map { "keymap.toml: " + $0 }
140        let settings = OrgPreferences.orgSettings()
141        session.defaults = settings
142        session.options = OrgPreferences.options()
143        workspace?.settings = .with(todoKeywords: settings)
144        if let agenda {
145            agenda.span = OrgPreferences.agendaSpan()
146            agenda.startOffset = OrgPreferences.agendaStartOffset()
147            agenda.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
148            agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
149            agenda.options = OrgPreferences.agendaOptions(agenda.options)
150            agenda.calendarEvents = OrgPreferences.calendarEvents() ? calendarEvents : nil
151            agenda.calendarNames = OrgPreferences.calendarEventCalendars()
152        }
153        settingsVersion += 1
154    }
155
156    /// The folder's `config.toml`, read in coordination with the app that syncs it.
157    func configText() -> String? {
158        configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
159    }
160
161    /// Writes the folder's `config.toml` and applies it.
162    func saveConfig(_ text: String) {
163        guard let configFolder else { return }
164        var error: NSError?
165        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: configFolder.appendingPathComponent("config.toml"), options: [], error: &error) { url in
166            try? text.write(to: url, atomically: true, encoding: .utf8)
167        }
168        reloadConfig()
169    }
170
171    /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
172    /// the Mac's Settings write it, else in this device's settings.
173    func set(_ defaultsKey: String, to value: TOML.Value) {
174        guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
175        if let configFolder {
176            let file = configFolder.appendingPathComponent("config.toml")
177            var error: NSError?
178            NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
179                let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
180                try? UserConfig.setting(text, section: setting.section, key: setting.key, to: value).write(to: url, atomically: true, encoding: .utf8)
181            }
182        } else {
183            switch value {
184            case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
185            case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
186            case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
187            }
188        }
189        reloadConfig()
190    }
191
192    /// The capture templates, for the share extension to offer.
193    private func shareTemplates() {
194        try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
195    }
196
197    /// Edits to the folder's files, synced from the Mac, apply as they arrive.
198    private func watchConfig() {
199        presenter?.stop()
200        presenter = nil
201        guard let configFolder else { return }
202        let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
203            Task { @MainActor [weak self] in self?.reloadConfig() }
204        }
205        presenter.start()
206        self.presenter = presenter
207    }
208
209    private static func resolveBookmark() -> URL? {
210        guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
211        var stale = false
212        guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
213        _ = url.startAccessingSecurityScopedResource()
214        if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
215        return url
216    }
217
218    /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
219    /// colors.
220    /// Writes `config.toml` with every setting at its default when the folder has none.
221    private static func createConfig(in folder: URL) {
222        let file = folder.appendingPathComponent("config.toml")
223        var error: NSError?
224        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
225            guard !FileManager.default.fileExists(atPath: url.path) else { return }
226            try? UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8)
227        }
228    }
229
230    private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
231        guard let folder else { return ([], .default) }
232        guard let text = read(folder.appendingPathComponent("config.toml")) else {
233            return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
234        }
235        let problems = UserConfig.apply(text, to: .standard)
236        guard let theme = UserConfig.theme(config: text, themeFile: UserDefaults.standard.string(forKey: "themeFile"), in: folder, read: read) else {
237            return (problems, .default)
238        }
239        return (problems + theme.problems, theme.theme)
240    }
241
242    /// A file of the folder, read in coordination with the app that syncs it.
243    private static func read(_ file: URL) -> String? {
244        var text: String?
245        var error: NSError?
246        NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
247            text = try? String(contentsOf: url, encoding: .utf8)
248        }
249        return text
250    }
251
252    /// Notifications for the next week's timed entries, at most 64, as iOS allows.
253    func updateReminders() async {
254        let interval = Perf.begin("reminders.update")
255        defer { interval.end() }
256        guard let workspace else { return }
257        guard OrgPreferences.reminders() else {
258            await scheduler.clear()
259            return
260        }
261        guard !workspace.files.isEmpty else { return }
262        // The agenda's cache and options, so files it has read aren't read again.
263        let agenda = AgendaModel(workspace: workspace, cache: self.agenda?.cache ?? AgendaSourceCache())
264        agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
265        if let options = self.agenda?.options { agenda.options = options }
266        let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
267        await scheduler.reconcile(reminders)
268    }
269
270    /// The widgets' agenda: today and the next days in the app group's container, with the
271    /// widgets reloaded when it changed; their habits and capture templates; and the icon's
272    /// overdue badge.
273    func updateWidgets() async {
274        let interval = Perf.begin("widgets.update")
275        defer { interval.end() }
276        guard let workspace else { return }
277        let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
278        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
279        days.startOnWeekday = nil
280        if let agenda {
281            days.includeSubfolders = agenda.includeSubfolders
282            days.options = agenda.options
283            days.options.logMode = false
284            days.calendarEvents = agenda.calendarEvents
285            days.calendarNames = agenda.calendarNames
286        }
287        await days.refresh(open: session.openTexts)
288        let groups = days.groups()
289        await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
290        if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") }
291        _ = try? TemplateList(templates: CaptureTemplates.load().templates.map { .init(key: $0.key, name: $0.name) }).write()
292        guard let file = AgendaSnapshot.file() else { return }
293        let snapshot = AgendaSnapshot(groups: groups, today: days.today, theme: theme, generated: Date())
294        if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
295    }
296
297    /// Today's count on the icon, and each later day's set for its midnight by a notification
298    /// that only changes the badge.
299    private func updateBadge(_ counts: [Int]) async {
300        let center = UNUserNotificationCenter.current()
301        guard await badgesEnabled(asking: true) else { return }
302        try? await center.setBadgeCount(counts.first ?? 0)
303        center.removePendingNotificationRequests(withIdentifiers: (1..<AgendaSnapshot.dayCount).map(Self.badgeID))
304        let today = Calendar.current.startOfDay(for: Date())
305        for (offset, count) in counts.enumerated().dropFirst() {
306            guard let midnight = Calendar.current.date(byAdding: .day, value: offset, to: today) else { continue }
307            let content = UNMutableNotificationContent()
308            content.badge = NSNumber(value: count)
309            let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: midnight)
310            let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
311            try? await center.add(UNNotificationRequest(identifier: Self.badgeID(offset), content: content, trigger: trigger))
312        }
313    }
314
315    static func badgeID(_ offset: Int) -> String { "badge.\(offset)" }
316
317    /// Whether iOS shows the icon's badge. Asking adds badges to the app's notification
318    /// settings, which an earlier grant without them leaves out; iOS prompts only the first time.
319    func badgesEnabled(asking: Bool) async -> Bool {
320        let center = UNUserNotificationCenter.current()
321        let settings = await center.notificationSettings()
322        if settings.badgeSetting == .enabled { return true }
323        guard asking, settings.authorizationStatus != .denied else { return false }
324        _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge])
325        return await center.notificationSettings().badgeSetting == .enabled
326    }
327}
328#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