Sources/OrgstarMobile/MobileModel.swift

9c8e4f9667c239dbcda0a122d127aa0620db4d35
orgstar/Sources/OrgstarMobile/MobileModel.swift

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