Sources/OrgstarMobile/MobileModel.swift

071e94ac597ceadb3ee079a0401d882f11c45a76
orgstar/Sources/OrgstarMobile/MobileModel.swift

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