Sources/OrgstarMobile/MobileModel.swift

4d8e517de5aef10e915fb482735feba5435a4a21
orgstar/Sources/OrgstarMobile/MobileModel.swift

413 lines · 21147 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        configProblems += configFolder.map { UserCommandFile.load(folder: $0, read: Self.read) } ?? UserCommandFile.load(folder: UserConfig.directory)
167        SnippetLibrary.shared.reload(from: UserConfig.file(Snippets.fileName), read: configFolder == nil ? { try? String(contentsOf: $0, encoding: .utf8) } : Self.read)
168        configProblems += SnippetLibrary.shared.problems
169        configProblems += KeyBar.problems()
170        let settings = OrgPreferences.orgSettings()
171        session.defaults = settings
172        session.options = OrgPreferences.options()
173        session.encryptsTaggedEntries = OrgPreferences.cryptBeforeSave()
174        session.cryptTag = OrgPreferences.cryptTag()
175        session.options.snippets = SnippetLibrary.shared.snippets
176        workspace?.settings = .with(todoKeywords: settings)
177        if let agenda {
178            agenda.span = OrgPreferences.agendaSpan()
179            agenda.startOffset = OrgPreferences.agendaStartOffset()
180            agenda.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
181            agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
182            agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
183            agenda.agendaFiles = OrgPreferences.agendaFiles()
184            agenda.options = OrgPreferences.agendaOptions(agenda.options)
185            agenda.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() ? calendarEvents : nil
186            agenda.calendarNames = OrgPreferences.calendarEventCalendars()
187            agenda.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() ? reminderLists : nil
188            agenda.reminderListNames = OrgPreferences.agendaReminderLists()
189        }
190        settingsVersion += 1
191    }
192
193    /// The folder's `config.toml`, read in coordination with the app that syncs it.
194    func configText() -> String? {
195        configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
196    }
197
198    /// Writes the folder's `config.toml` and applies it. False, with the reason first in
199    /// `configProblems`, when the file can't be written or what it holds can't be read.
200    @discardableResult
201    func saveConfig(_ text: String) -> Bool {
202        guard let configFolder else { return false }
203        return reloadConfig(after: Self.updateConfig(in: configFolder) { _ in text })
204    }
205
206    /// Changes the folder's `config.toml`; returns the problem when it can't be read or written.
207    private static func updateConfig(in folder: URL, _ change: (String) -> String) -> String? {
208        do {
209            try UserFile.update(folder.appendingPathComponent("config.toml"), coordinated: true, change)
210            return nil
211        } catch {
212            return "config.toml wasn't changed: \(error.localizedDescription)"
213        }
214    }
215
216    /// Applies the folder's settings, with the `problem` of the write before it first.
217    private func reloadConfig(after problem: String?) -> Bool {
218        reloadConfig()
219        if let problem { configProblems.insert(problem, at: 0) }
220        return problem == nil
221    }
222
223    /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
224    /// the Mac's Settings write it, else in this device's settings.
225    func set(_ defaultsKey: String, to value: TOML.Value) {
226        guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
227        var problem: String?
228        if let configFolder {
229            problem = Self.updateConfig(in: configFolder) { UserConfig.setting($0, section: setting.section, key: setting.key, to: value) }
230        } else {
231            switch value {
232            case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
233            case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
234            case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
235            case .array: break
236            }
237        }
238        _ = reloadConfig(after: problem)
239    }
240
241    /// Sets the key bar's buttons for `width`, or with nil its default, as `set` does.
242    func setKeyBar(_ ids: [String]?, _ width: KeyBarLayout.Width) {
243        var problem: String?
244        if let configFolder {
245            problem = Self.updateConfig(in: configFolder) { text in
246                guard let ids else { return UserConfig.removingSetting(text, section: KeyBarLayout.table, key: width.rawValue) }
247                return UserConfig.setting(text, section: KeyBarLayout.table, key: width.rawValue, to: .array(ids.map(TOML.Value.string)))
248            }
249        } else {
250            KeyBarLayout.store(ids, width, in: .standard)
251        }
252        _ = reloadConfig(after: problem)
253    }
254
255    /// The capture templates, for the share extension to offer.
256    private func shareTemplates() {
257        try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
258    }
259
260    /// Edits to the folder's files, synced from the Mac, apply as they arrive.
261    private func watchConfig() {
262        presenter?.stop()
263        presenter = nil
264        guard let configFolder else { return }
265        let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
266            Task { @MainActor [weak self] in self?.reloadConfig() }
267        }
268        presenter.start()
269        self.presenter = presenter
270    }
271
272    /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
273    /// colors.
274    /// Writes `config.toml` with every setting at its default when the folder has none; returns
275    /// the problem when it can't be written.
276    private static func createConfig(in folder: URL) -> String? {
277        let file = folder.appendingPathComponent("config.toml")
278        var error: NSError?
279        var failure: Error?
280        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
281            guard !FileManager.default.fileExists(atPath: url.path) else { return }
282            do { try UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8) } catch { failure = error }
283        }
284        return (error ?? failure).map { "config.toml wasn't created: \($0.localizedDescription)" }
285    }
286
287    private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
288        let defaults = UserDefaults.standard
289        guard let folder else {
290            let (base, problems) = ThemeSpec.base(light: defaults.string(forKey: "themeLight"), dark: defaults.string(forKey: "themeDark"))
291            return (problems, base)
292        }
293        guard let text = read(folder.appendingPathComponent("config.toml")) else {
294            return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
295        }
296        let problems = UserConfig.apply(text, to: defaults)
297        guard let theme = UserConfig.theme(
298            config: text, themeFile: defaults.string(forKey: "themeFile"),
299            lightTheme: defaults.string(forKey: "themeLight"), darkTheme: defaults.string(forKey: "themeDark"), in: folder, read: read
300        ) else {
301            return (problems, .default)
302        }
303        return (problems + theme.problems, theme.theme)
304    }
305
306    /// A file of the folder, read in coordination with the app that syncs it.
307    private static func read(_ file: URL) -> String? {
308        var text: String?
309        var error: NSError?
310        NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
311            text = try? String(contentsOf: url, encoding: .utf8)
312        }
313        return text
314    }
315
316    /// Notifications for the next week's timed entries, at most 64, as iOS allows.
317    func updateReminders() async {
318        let interval = Perf.begin("reminders.update")
319        defer { interval.end() }
320        guard let workspace else { return }
321        guard OrgPreferences.reminders() else {
322            await scheduler.clear()
323            return
324        }
325        guard !workspace.files.isEmpty else { return }
326        // The agenda's cache and options, so files it has read aren't read again.
327        let agenda = AgendaModel(workspace: workspace, cache: self.agenda?.cache ?? AgendaSourceCache())
328        agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
329        if let options = self.agenda?.options { agenda.options = options }
330        let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
331        await scheduler.reconcile(reminders)
332    }
333
334    /// The widgets' agenda: today and the next days in the app group's container, with the
335    /// widgets reloaded when it changed; their habits and capture templates; and the icon's
336    /// overdue badge.
337    func updateWidgets() async {
338        let interval = Perf.begin("widgets.update")
339        defer { interval.end() }
340        guard let workspace else { return }
341        let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
342        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
343        days.startOnWeekday = nil
344        days.hiddenFolders = HiddenFolders.shared.all
345        if let agenda {
346            days.includeSubfolders = agenda.includeSubfolders
347            days.excludeArchives = agenda.excludeArchives
348            days.options = agenda.options
349            days.options.logMode = false
350            days.calendarEvents = agenda.calendarEvents
351            days.calendarNames = agenda.calendarNames
352            days.reminderLists = agenda.reminderLists
353            days.reminderListNames = agenda.reminderListNames
354        }
355        await days.refresh(open: session.openTexts)
356        let groups = days.groups()
357        let locked = !ProAccess.shared.isUnlocked
358        let wasLocked = widgetsLocked
359        widgetsLocked = locked
360        guard !locked else {
361            // Widgets read the flag and show that they need Pro.
362            WatchLink.shared.send(.locked(generated: Date()))
363            await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
364            if AgendaSnapshot.reloadsWidgets(locked: true, wasLocked: wasLocked, snapshotChanged: false) { WidgetCenter.shared.reloadAllTimelines() }
365            return
366        }
367        let cards = await FlashcardReview.cards(workspace: workspace, session: session)
368        var watch = WatchAgenda(groups: groups, today: days.today, clock: clock.running, lastClocked: clock.history.first?.title, generated: Date())
369        watch.cards = WatchAgenda.Card.review(Flashcards.due(cards, at: Date()))
370        WatchLink.shared.send(watch)
371        if (try? FlashcardSnapshot(cards: cards.map(\.card)).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.flashcards") }
372        await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
373        if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") }
374        _ = try? TemplateList(templates: CaptureTemplates.load().templates.map { .init(key: $0.key, name: $0.name) }).write()
375        guard let file = AgendaSnapshot.file() else { return }
376        let snapshot = AgendaSnapshot(groups: groups, today: days.today, theme: theme, generated: Date())
377        let changed = (try? snapshot.write(to: file)) == true
378        if AgendaSnapshot.reloadsWidgets(locked: false, wasLocked: wasLocked, snapshotChanged: changed) { WidgetCenter.shared.reloadAllTimelines() }
379    }
380
381    /// Today's count on the icon, and each later day's set for its midnight by a notification
382    /// that only changes the badge.
383    private func updateBadge(_ counts: [Int]) async {
384        let center = UNUserNotificationCenter.current()
385        // Onboarding asks first.
386        guard await badgesEnabled(asking: UserDefaults.standard.bool(forKey: OnboardingScreen.doneKey)) else { return }
387        try? await center.setBadgeCount(counts.first ?? 0)
388        center.removePendingNotificationRequests(withIdentifiers: (1..<AgendaSnapshot.dayCount).map(Self.badgeID))
389        let today = Calendar.current.startOfDay(for: Date())
390        for (offset, count) in counts.enumerated().dropFirst() {
391            guard let midnight = Calendar.current.date(byAdding: .day, value: offset, to: today) else { continue }
392            let content = UNMutableNotificationContent()
393            content.badge = NSNumber(value: count)
394            let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: midnight)
395            let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
396            try? await center.add(UNNotificationRequest(identifier: Self.badgeID(offset), content: content, trigger: trigger))
397        }
398    }
399
400    static func badgeID(_ offset: Int) -> String { "badge.\(offset)" }
401
402    /// Whether iOS shows the icon's badge. Asking adds badges to the app's notification
403    /// settings, which an earlier grant without them leaves out; iOS prompts only the first time.
404    func badgesEnabled(asking: Bool) async -> Bool {
405        let center = UNUserNotificationCenter.current()
406        let settings = await center.notificationSettings()
407        if settings.badgeSetting == .enabled { return true }
408        guard asking, settings.authorizationStatus != .denied else { return false }
409        _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge])
410        return await center.notificationSettings().badgeSetting == .enabled
411    }
412}
413#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