Sources/OrgstarMobile/MobileModel.swift

fbc792eb21866a31f8edcffd23f5105df3be2348
orgstar/Sources/OrgstarMobile/MobileModel.swift

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