Sources/OrgstarMobile/MobileModel.swift

dd764a1db9c6495c09fa4fc20856a781d84441e4
orgstar/Sources/OrgstarMobile/MobileModel.swift

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