Sources/OrgstarMobile/MobileModel.swift

7119821e1398fbe6bc6b8362f2b2f6df5d8001ab
orgstar/Sources/OrgstarMobile/MobileModel.swift

369 lines · 18388 bytes

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