Sources/OrgstarMobile/MobileModel.swift

19641366e5de9103a7d88bf80436ab2aebc03cf5
orgstar/Sources/OrgstarMobile/MobileModel.swift

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