Sources/OrgApp/AgendaModel.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgApp/AgendaModel.swift history · blame · raw

294 lines · 16061 bytes

17 symbols in this file
  1import Foundation
  2import Observation
  3import OrgCore
  4import OrgIndex
  5import OrgPresentation
  6
  7/// Parsed agenda files by path, kept while the file's modification date and size and the
  8/// settings it was parsed with hold. Agenda models over one workspace can share one.
  9@MainActor
 10public final class AgendaSourceCache {
 11    var entries: [String: (mtime: Date, size: Int, defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:]
 12    /// Open buffers' sources, kept while their text is the same.
 13    var open: [String: (defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:]
 14
 15    public init() {}
 16}
 17
 18/// The day/week agenda over the workspace's agenda files. Sources are read from disk and
 19/// cached in `cache`; the open file's come from its buffer, so the agenda shows unsaved edits.
 20@MainActor
 21@Observable
 22public final class AgendaModel {
 23    public private(set) var days: [AgendaDay] = []
 24    /// The entries of a TODO list, match or search view.
 25    public private(set) var list: [AgendaItem] = []
 26    /// A block agenda's views, in order.
 27    public private(set) var blocks: [AgendaBlockResult] = []
 28    public var mode: AgendaMode = .agenda(span: nil, startOffset: nil)
 29    /// The first day shown, as `Days` numbers it; nil follows today.
 30    public var start: Int?
 31    public var span = 10
 32    /// Where the view starts relative to today, as `org-agenda-start-day` (`"-3d"` is -3).
 33    public var startOffset = 0
 34    /// `org-agenda-start-on-weekday`: 7- and 14-day spans start on this weekday (0 is Sunday);
 35    /// nil starts them on the first day.
 36    public var startOnWeekday: Int? = 1
 37    /// Files below the top level of each folder are agenda files too.
 38    public var includeSubfolders = false
 39    /// Files other agenda files archive to are left out.
 40    public var excludeArchives = OrgPreferences.agendaExcludeArchives()
 41    /// Files in these folders (root paths) are left out; see `HiddenFolders`.
 42    public var hiddenFolders: Set<String> = []
 43    /// `org-agenda-files`: when not empty, the agenda reads these instead of the folders' files.
 44    public var agendaFiles = OrgPreferences.agendaFiles()
 45    public var options = AgendaOptions()
 46    /// The settings of the views in `views.toml`, applied while `mode` is theirs.
 47    public var viewSettings: [AgendaMode: AgendaViewSettings] = [:]
 48    public private(set) var isComputing = false
 49    /// Calendar events over the days shown, from `calendarEvents` (nil reads none) and the
 50    /// calendars in `calendarNames` (all when empty).
 51    public private(set) var events: [AgendaEvent] = []
 52    public var calendarEvents: CalendarEvents?
 53    public var calendarNames: [String] = []
 54    /// Reminders due by the last day shown, from `reminderLists` (nil reads none) and the lists
 55    /// in `reminderListNames` (all when empty), among the events.
 56    public var reminderLists: ReminderLists?
 57    public var reminderListNames: [String] = []
 58    /// Today and the calendar of the last refresh.
 59    public private(set) var today = Days.absolute(Date(), calendar: .current)
 60    @ObservationIgnored private var calendar = Calendar.current
 61
 62    private let workspace: WorkspaceModel
 63    @ObservationIgnored public let cache: AgendaSourceCache
 64    @ObservationIgnored private var generation = 0
 65    /// Called with each file's path before it is checked on disk. For tests.
 66    @ObservationIgnored var willStat: (@Sendable (String) -> Void)?
 67
 68    public init(workspace: WorkspaceModel, cache: AgendaSourceCache = AgendaSourceCache()) {
 69        self.workspace = workspace
 70        self.cache = cache
 71    }
 72
 73    /// Org files directly in each folder (or below it, with `includeSubfolders`), by path, as
 74    /// Emacs lists a directory in `org-agenda-files`.
 75    public var files: [String] {
 76        let paths = workspace.agendaFilePaths(list: agendaFiles, includeSubfolders: includeSubfolders)
 77        return hiddenFolders.isEmpty ? paths : paths.filter { !HiddenFolders.hides(hiddenFolders, path: $0) }
 78    }
 79
 80    /// Recomputes the days. `open` is the open buffers' text by path.
 81    public func refresh(open: [String: String], now: Date = Date(), calendar: Calendar = .current) async {
 82        let interval = Perf.begin("agenda.refresh")
 83        defer { interval.end("\(files.count) files") }
 84        generation += 1
 85        let id = generation
 86        isComputing = true
 87        let today = Days.absolute(now, calendar: calendar)
 88        let clock = calendar.dateComponents([.hour, .minute], from: now)
 89        let mode = self.mode
 90        let options = viewSettings[mode]?.apply(to: self.options, view: mode.viewKey) ?? self.options
 91        // What each view computes: the mode, its options, and for days the first and the span.
 92        var jobs: [(mode: AgendaMode, options: AgendaOptions, first: Int, span: Int, header: String)] = []
 93        if case .blocks(let blocks) = mode {
 94            for block in blocks {
 95                let (first, span) = shown(today: today, mode: block.mode, start: nil)
 96                jobs.append((block.mode, block.settings.apply(to: self.options, view: block.mode.viewKey), first, span, block.settings.header ?? block.mode.title))
 97            }
 98        } else {
 99            let (first, span) = shown(today: today)
100            jobs.append((mode, options, first, span, ""))
101        }
102        let provider = calendarEvents
103        let names = calendarNames
104        let all = await sources(open: open)
105        let agendaEnd = jobs.filter { if case .agenda = $0.mode { true } else { false } }.map { $0.first + $0.span }.max()
106        var reminders: [AgendaEvent] = []
107        if let agendaEnd, let reminderLists {
108            reminders = await reminderLists.reminders(before: Self.date(agendaEnd, calendar: calendar), chosen: reminderListNames, calendar: calendar)
109        }
110        let results = await Task.detached {
111            jobs.map { job in
112                var result = AgendaBlockResult(header: job.header, mode: job.mode)
113                switch job.mode {
114                case .agenda:
115                    result.days = Agenda.list(all, start: job.first, days: job.span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: job.options)
116                    if let provider {
117                        let from = Self.date(job.first, calendar: calendar)
118                        result.events = provider.events(from: from, to: Self.date(job.first + job.span, calendar: calendar), chosen: names)
119                    }
120                    result.events += reminders
121                case .todo(let keywords):
122                    result.list = Agenda.todoList(all, keywords: keywords, options: job.options, today: today)
123                case .match(let match, let todoOnly):
124                    result.list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: job.options)
125                case .search(let string, let todoOnly):
126                    result.list = Agenda.textSearch(all, string: string, todoOnly: todoOnly, options: job.options)
127                case .stuck(let definition):
128                    result.list = Agenda.stuckProjects(all, definition ?? job.options.stuckProjects, now: now, calendar: calendar, options: job.options)
129                case .blocks:
130                    break
131                }
132                return result
133            }
134        }.value
135        guard id == generation else { return }
136        // Unchanged results leave the views alone: a new value redraws the whole list.
137        let isBlocks = { if case .blocks = mode { true } else { false } }()
138        let single = isBlocks ? AgendaBlockResult(header: "", mode: mode) : results[0]
139        let blocks = isBlocks ? results : []
140        if days != single.days { days = single.days }
141        if list != single.list { list = single.list }
142        if events != single.events { events = single.events }
143        if self.blocks != blocks { self.blocks = blocks }
144        if self.today != today { self.today = today }
145        if self.calendar != calendar { self.calendar = calendar }
146        isComputing = false
147    }
148
149    /// Reminders for the timed entries of the next `days` days, each with the folder it is in.
150    public func reminders(open: [String: String], now: Date = Date(), calendar: Calendar = .current, days: Int = 7, lead: Int = 12) async -> [Reminder] {
151        let all = await sources(open: open)
152        let roots = workspace.rootPaths
153        return await Task.detached {
154            Reminders.upcoming(all, now: now, calendar: calendar, days: days, lead: lead).map { reminder in
155                var reminder = reminder
156                reminder.folder = roots.first { HiddenFolders.hides([$0], path: reminder.path) }
157                return reminder
158            }
159        }.value
160    }
161
162    /// The habits of the agenda files, file by file.
163    public func habits(open: [String: String]) async -> [HabitSnapshot.Entry] {
164        await sources(open: open).flatMap { source in
165            source.habits.map { HabitSnapshot.Entry(title: $0.title, path: source.path, offset: $0.offset, habit: $0.habit) }
166        }
167    }
168
169    /// Entries for the table and kanban views, and the keywords their files use.
170    public func board(open: [String: String], match: String) async -> (entries: [BoardEntry], keywords: [String]) {
171        let all = await sources(open: open)
172        return await Task.detached { (Board.entries(all, match: match), Board.keywords(all)) }.value
173    }
174
175    /// The agenda files' sources: the open file's from its text, the others from the cache
176    /// while they and the settings are unchanged.
177    private func sources(open: [String: String]) async -> [AgendaSource] {
178        let interval = Perf.begin("agenda.sources")
179        defer { interval.end("\(files.count) files") }
180        let defaults = workspace.settings.org
181        let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
182        let files = files
183        let (openCache, diskCache) = (cache.open, cache.entries)
184        let willStat = willStat
185        let loaded = await Task.detached {
186            var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
187            for path in files {
188                if let text = open[path] {
189                    // The same text parsed before, as the buffer or as the file on disk.
190                    func reusable(_ source: AgendaSource?, _ parsedWith: OrgSettings?, _ parsedBlocking: Bool?) -> AgendaSource? {
191                        guard let source, parsedWith == defaults, parsedBlocking == blocking, !source.readsSetupFiles, source.text == text else { return nil }
192                        return source
193                    }
194                    let fromOpen = openCache[path]
195                    let fromDisk = diskCache[path]
196                    let cached = reusable(fromOpen?.source, fromOpen?.defaults, fromOpen?.blocking) ?? reusable(fromDisk?.source, fromDisk?.defaults, fromDisk?.blocking)
197                    sources.append((path, .distantPast, -1, cached ?? AgendaSource(path: path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile), checksBlocking: blocking), false))
198                    continue
199                }
200                willStat?(path)
201                let attributes = try? FileManager.default.attributesOfItem(atPath: path)
202                let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
203                let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
204                // A file reading setup files is read again: they may have changed.
205                let cached = diskCache[path].flatMap { entry in
206                    entry.mtime == mtime && entry.size == size && entry.defaults == defaults && entry.blocking == blocking && !entry.source.readsSetupFiles ? entry.source : nil
207                }
208                if let cached {
209                    sources.append((path, mtime, size, cached, true))
210                } else if let data = FileManager.default.contents(atPath: path) {
211                    let text = SourceText(bytes: [UInt8](data)).text
212                    sources.append((path, mtime, size, AgendaSource(path: path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile), checksBlocking: blocking), true))
213                }
214            }
215            return sources
216        }.value
217        for source in loaded {
218            if source.fromDisk {
219                cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source)
220            } else {
221                cache.open[source.path] = (defaults, blocking, source.source)
222            }
223        }
224        var sources = loaded.map(\.source)
225        if excludeArchives {
226            let location = OrgPreferences.options().archiveLocation ?? "%s_archive::"
227            let archives = Set(sources.flatMap { $0.archiveFiles(location: location) })
228            sources.removeAll { archives.contains($0.path) }
229        }
230        return sources
231    }
232
233    /// The days as rows with the events, empty days hidden unless `showAllDates`; see
234    /// `AgendaRows.groups`.
235    public func groups(showAllDates: Bool = false, keep: (AgendaItem) -> Bool = { _ in true }) -> [AgendaDayGroup] {
236        AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
237    }
238
239    /// A block's days as rows, as `groups` does for the view's.
240    public func groups(_ block: AgendaBlockResult, showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] {
241        AgendaRows.groups(block.days, events: block.events, today: today, showAllDates: showAllDates, calendar: calendar, keep: filter.keeps)
242    }
243
244    /// `groups` with `filter`, kept while the days, events and arguments are the same, as
245    /// views ask on every redraw.
246    public func groups(showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] {
247        let key = GroupsKey(days: days, events: events, today: today, showAllDates: showAllDates, filter: filter)
248        if let groupsMemo, groupsMemo.key == key { return groupsMemo.groups }
249        let groups = groups(showAllDates: showAllDates, keep: filter.keeps)
250        groupsMemo = (key, groups)
251        return groups
252    }
253
254    private struct GroupsKey: Equatable {
255        let days: [AgendaDay]
256        let events: [AgendaEvent]
257        let today: Int
258        let showAllDates: Bool
259        let filter: AgendaFilter
260    }
261
262    @ObservationIgnored private var groupsMemo: (key: GroupsKey, groups: [AgendaDayGroup])?
263
264    nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
265        let d = Days.date(day)
266        return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
267    }
268
269    public func showToday() { start = nil }
270
271    /// The first day the agenda shows and how many, as `org-agenda-list` works them out: the
272    /// view's span and start, or the settings', with 7- and 14-day spans moved back to
273    /// `startOnWeekday`.
274    public func shown(today: Int) -> (first: Int, span: Int) { shown(today: today, mode: mode, start: start) }
275
276    /// `shown(today:)` for `mode`, from `start` when it isn't nil.
277    func shown(today: Int, mode: AgendaMode, start: Int?) -> (first: Int, span: Int) {
278        var span = self.span
279        var startOffset = self.startOffset
280        if case .agenda(let viewSpan, let viewStart) = mode {
281            span = viewSpan ?? span
282            startOffset = viewStart ?? startOffset
283        }
284        var first = start ?? today + startOffset
285        if span == 7 || span == 14 { first = Days.weekStart(first, on: startOnWeekday) }
286        return (first, span)
287    }
288
289    /// Moves the view by a whole span, forward or back.
290    public func shift(forward: Bool, now: Date = Date(), calendar: Calendar = .current) {
291        let (current, span) = shown(today: Days.absolute(now, calendar: calendar))
292        start = current + (forward ? span : -span)
293    }
294}