Sources/OrgstarMobile/MobileModel.swift

c4d5cb219ab6fe95c4d840f835a207f3da933181
orgstar/Sources/OrgstarMobile/MobileModel.swift

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