Sources/OrgstarMobile/MobileModel.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgstarMobile/MobileModel.swift history · blame · raw

319 lines · 15443 bytes

  1#if os(iOS)
  2import Foundation
  3import Observation
  4import OrgApp
  5import OrgCore
  6import OrgIndex
  7import OrgPresentation
  8import OrgWorkspace
  9import UIKit
 10import UserNotifications
 11import WidgetKit
 12
 13/// The app's models, and the settings from the configuration folder: a folder you choose
 14/// (a synced copy of the Mac's `~/.config/orgstar`) with `config.toml` and `capture.toml`.
 15@MainActor
 16@Observable
 17final class MobileModel {
 18    /// One per process: Shortcuts runs the capture action without a window.
 19    static let shared = MobileModel()
 20
 21    let workspace: WorkspaceModel?
 22    let failure: String?
 23    let session = DocumentSession()
 24    let agenda: AgendaModel?
 25    let scheduler = ReminderScheduler(center: SystemReminderCenter())
 26    let clock = ClockModel()
 27    let clockPrompts = ClockPrompter()
 28    let spotlight = SpotlightIndexer()
 29    /// Captures from the share extension; nil without the app group.
 30    let inbox = CaptureInbox()
 31    private(set) var configFolder: URL?
 32    private(set) var configProblems: [String] = []
 33    /// An entry to show, from a tapped reminder.
 34    var openRequest: ReaderRoute?
 35    /// Agenda days to show, from a followed timestamp: the first (a `Days` number) and how many.
 36    var agendaRequest: AgendaDays?
 37    /// A capture to show, from the agenda or the capture control.
 38    var captureRequest: CaptureRequest?
 39    /// Calendar's events for the agenda, with `calendar-events`.
 40    let calendarEvents = CalendarEvents()
 41
 42    struct AgendaDays: Equatable {
 43        let start: Int
 44        let count: Int
 45    }
 46    /// Bumped when settings apply, so views that read them update.
 47    private(set) var settingsVersion = 0
 48    /// The theme from `config.toml` and its theme file, with the type settings.
 49    private(set) var theme = ThemeSpec.default
 50    /// `show-markup`, toggled in the editor; the folder's value applies when it changes.
 51    var showMarkup = false
 52    /// `org-stored-links`, most recent first; kept while the app runs, as in Emacs.
 53    var storedLinks: [StoredLink] = []
 54    @ObservationIgnored private var configShowMarkup: Bool?
 55    @ObservationIgnored private var presenter: FolderPresenter?
 56    @ObservationIgnored private var sizeObserver: NSObjectProtocol?
 57
 58    private static let bookmarkKey = "configFolderBookmark"
 59
 60    private init() {
 61        // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
 62        let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
 63        UserConfig.directoryOverride = folder
 64        let (problems, colors) = Self.readConfig(folder)
 65        let settings = OrgPreferences.orgSettings()
 66        do {
 67            let workspace = try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: settings))
 68            // Recently Deleted where the folder's provider keeps one (iCloud Drive); otherwise gone.
 69            workspace.trasher = { url in
 70                do { try FileManager.default.trashItem(at: url, resultingItemURL: nil) } catch { try FileManager.default.removeItem(at: url) }
 71            }
 72            self.workspace = workspace
 73            agenda = AgendaModel(workspace: workspace)
 74            failure = nil
 75        } catch {
 76            workspace = nil
 77            agenda = nil
 78            failure = error.localizedDescription
 79        }
 80        configFolder = folder
 81        configProblems = problems
 82        applySettings(colors)
 83        shareTemplates()
 84        watchConfig()
 85        // `org-clock-out-when-done`, and the reminder when the Effort runs out.
 86        clock.notifications = SystemReminderCenter()
 87        session.textChanged = { [weak self] path in
 88            guard let self else { return }
 89            _ = self.clock.textChanged(path, self.session)
 90        }
 91        clock.remindAtEffort(session)
 92        // A new Dynamic Type size restyles editors and the reader.
 93        sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
 94            MainActor.assumeIsolated { self?.settingsVersion += 1 }
 95        }
 96    }
 97
 98    /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
 99    func setConfigFolder(_ url: URL?) {
100        if let url {
101            _ = url.startAccessingSecurityScopedResource()
102            if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
103            Self.createConfig(in: url)
104        } else {
105            UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
106            // What the folder set no longer applies.
107            for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
108        }
109        configFolder = url
110        reloadConfig()
111        watchConfig()
112    }
113
114    func reloadConfig() {
115        let interval = Perf.begin("config.reload")
116        defer { interval.end() }
117        UserConfig.directoryOverride = configFolder
118        let (problems, colors) = Self.readConfig(configFolder)
119        configProblems = problems
120        applySettings(colors)
121        shareTemplates()
122    }
123
124    private func applySettings(_ colors: ThemeSpec) {
125        theme = OrgPreferences.theme(colors)
126        let markup = OrgPreferences.showMarkup()
127        if markup != configShowMarkup {
128            configShowMarkup = markup
129            showMarkup = markup
130        }
131        let settings = OrgPreferences.orgSettings()
132        session.defaults = settings
133        session.options = OrgPreferences.options()
134        workspace?.settings = .with(todoKeywords: settings)
135        if let agenda {
136            agenda.span = OrgPreferences.agendaSpan()
137            agenda.startOffset = OrgPreferences.agendaStartOffset()
138            agenda.startOnWeekday = OrgPreferences.agendaStartOnWeekday()
139            agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
140            agenda.options = OrgPreferences.agendaOptions(agenda.options)
141            agenda.calendarEvents = OrgPreferences.calendarEvents() ? calendarEvents : nil
142            agenda.calendarNames = OrgPreferences.calendarEventCalendars()
143        }
144        settingsVersion += 1
145    }
146
147    /// The folder's `config.toml`, read in coordination with the app that syncs it.
148    func configText() -> String? {
149        configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) }
150    }
151
152    /// Writes the folder's `config.toml` and applies it.
153    func saveConfig(_ text: String) {
154        guard let configFolder else { return }
155        var error: NSError?
156        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: configFolder.appendingPathComponent("config.toml"), options: [], error: &error) { url in
157            try? text.write(to: url, atomically: true, encoding: .utf8)
158        }
159        reloadConfig()
160    }
161
162    /// Changes a setting from the app: in the folder's config.toml when there is a folder, as
163    /// the Mac's Settings write it, else in this device's settings.
164    func set(_ defaultsKey: String, to value: TOML.Value) {
165        guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return }
166        if let configFolder {
167            let file = configFolder.appendingPathComponent("config.toml")
168            var error: NSError?
169            NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
170                let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
171                try? UserConfig.setting(text, section: setting.section, key: setting.key, to: value).write(to: url, atomically: true, encoding: .utf8)
172            }
173        } else {
174            switch value {
175            case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey)
176            case .string(let s): UserDefaults.standard.set(s, forKey: defaultsKey)
177            case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey)
178            }
179        }
180        reloadConfig()
181    }
182
183    /// The capture templates, for the share extension to offer.
184    private func shareTemplates() {
185        try? inbox?.setTemplates(CaptureTemplates.load().templates.map { CaptureInbox.Template(key: $0.key, name: $0.name) })
186    }
187
188    /// Edits to the folder's files, synced from the Mac, apply as they arrive.
189    private func watchConfig() {
190        presenter?.stop()
191        presenter = nil
192        guard let configFolder else { return }
193        let presenter = FolderPresenter(root: configFolder) { [weak self] _ in
194            Task { @MainActor [weak self] in self?.reloadConfig() }
195        }
196        presenter.start()
197        self.presenter = presenter
198    }
199
200    private static func resolveBookmark() -> URL? {
201        guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
202        var stale = false
203        guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
204        _ = url.startAccessingSecurityScopedResource()
205        if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
206        return url
207    }
208
209    /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
210    /// colors.
211    /// Writes `config.toml` with every setting at its default when the folder has none.
212    private static func createConfig(in folder: URL) {
213        let file = folder.appendingPathComponent("config.toml")
214        var error: NSError?
215        NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in
216            guard !FileManager.default.fileExists(atPath: url.path) else { return }
217            try? UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8)
218        }
219    }
220
221    private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
222        guard let folder else { return ([], .default) }
223        guard let text = read(folder.appendingPathComponent("config.toml")) else {
224            return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
225        }
226        let problems = UserConfig.apply(text, to: .standard)
227        guard let theme = UserConfig.theme(config: text, themeFile: UserDefaults.standard.string(forKey: "themeFile"), in: folder, read: read) else {
228            return (problems, .default)
229        }
230        return (problems + theme.problems, theme.theme)
231    }
232
233    /// A file of the folder, read in coordination with the app that syncs it.
234    private static func read(_ file: URL) -> String? {
235        var text: String?
236        var error: NSError?
237        NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: file, options: [], error: &error) { url in
238            text = try? String(contentsOf: url, encoding: .utf8)
239        }
240        return text
241    }
242
243    /// Notifications for the next week's timed entries, at most 64, as iOS allows.
244    func updateReminders() async {
245        let interval = Perf.begin("reminders.update")
246        defer { interval.end() }
247        guard let workspace else { return }
248        guard OrgPreferences.reminders() else {
249            await scheduler.clear()
250            return
251        }
252        guard !workspace.files.isEmpty else { return }
253        // The agenda's cache and options, so files it has read aren't read again.
254        let agenda = AgendaModel(workspace: workspace, cache: self.agenda?.cache ?? AgendaSourceCache())
255        agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
256        if let options = self.agenda?.options { agenda.options = options }
257        let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
258        await scheduler.reconcile(reminders)
259    }
260
261    /// The widgets' agenda: today and the next days in the app group's container, with the
262    /// widgets reloaded when it changed; their habits and capture templates; and the icon's
263    /// overdue badge.
264    func updateWidgets() async {
265        let interval = Perf.begin("widgets.update")
266        defer { interval.end() }
267        guard let workspace else { return }
268        let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
269        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
270        days.startOnWeekday = nil
271        if let agenda {
272            days.includeSubfolders = agenda.includeSubfolders
273            days.options = agenda.options
274            days.options.logMode = false
275            days.calendarEvents = agenda.calendarEvents
276            days.calendarNames = agenda.calendarNames
277        }
278        await days.refresh(open: session.openTexts)
279        let groups = days.groups()
280        await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
281        if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") }
282        _ = try? TemplateList(templates: CaptureTemplates.load().templates.map { .init(key: $0.key, name: $0.name) }).write()
283        guard let file = AgendaSnapshot.file() else { return }
284        let snapshot = AgendaSnapshot(groups: groups, today: days.today, theme: theme, generated: Date())
285        if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
286    }
287
288    /// Today's count on the icon, and each later day's set for its midnight by a notification
289    /// that only changes the badge.
290    private func updateBadge(_ counts: [Int]) async {
291        let center = UNUserNotificationCenter.current()
292        guard await badgesEnabled(asking: true) else { return }
293        try? await center.setBadgeCount(counts.first ?? 0)
294        center.removePendingNotificationRequests(withIdentifiers: (1..<AgendaSnapshot.dayCount).map(Self.badgeID))
295        let today = Calendar.current.startOfDay(for: Date())
296        for (offset, count) in counts.enumerated().dropFirst() {
297            guard let midnight = Calendar.current.date(byAdding: .day, value: offset, to: today) else { continue }
298            let content = UNMutableNotificationContent()
299            content.badge = NSNumber(value: count)
300            let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: midnight)
301            let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
302            try? await center.add(UNNotificationRequest(identifier: Self.badgeID(offset), content: content, trigger: trigger))
303        }
304    }
305
306    static func badgeID(_ offset: Int) -> String { "badge.\(offset)" }
307
308    /// Whether iOS shows the icon's badge. Asking adds badges to the app's notification
309    /// settings, which an earlier grant without them leaves out; iOS prompts only the first time.
310    func badgesEnabled(asking: Bool) async -> Bool {
311        let center = UNUserNotificationCenter.current()
312        let settings = await center.notificationSettings()
313        if settings.badgeSetting == .enabled { return true }
314        guard asking, settings.authorizationStatus != .denied else { return false }
315        _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge])
316        return await center.notificationSettings().badgeSetting == .enabled
317    }
318}
319#endif