Sources/OrgApp/AgendaModel.swift

232 lines · 11911 bytes

  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    public var mode: AgendaMode = .agenda(span: nil, startOffset: nil)
 27    /// The first day shown, as `Days` numbers it; nil follows today.
 28    public var start: Int?
 29    public var span = 10
 30    /// Where the view starts relative to today, as `org-agenda-start-day` (`"-3d"` is -3).
 31    public var startOffset = 0
 32    /// Files below the top level of each folder are agenda files too.
 33    public var includeSubfolders = false
 34    public var options = AgendaOptions()
 35    public private(set) var isComputing = false
 36    /// Calendar events over the days shown, from `calendarEvents` (nil reads none) and the
 37    /// calendars in `calendarNames` (all when empty).
 38    public private(set) var events: [AgendaEvent] = []
 39    public var calendarEvents: CalendarEvents?
 40    public var calendarNames: [String] = []
 41    /// Today and the calendar of the last refresh.
 42    public private(set) var today = Days.absolute(Date(), calendar: .current)
 43    @ObservationIgnored private var calendar = Calendar.current
 44
 45    private let workspace: WorkspaceModel
 46    @ObservationIgnored public let cache: AgendaSourceCache
 47    @ObservationIgnored private var generation = 0
 48
 49    public init(workspace: WorkspaceModel, cache: AgendaSourceCache = AgendaSourceCache()) {
 50        self.workspace = workspace
 51        self.cache = cache
 52    }
 53
 54    /// Org files directly in each folder (or below it, with `includeSubfolders`), by path, as
 55    /// Emacs lists a directory in `org-agenda-files`.
 56    public var files: [String] {
 57        workspace.files
 58            // Dotfiles stay out, as `org-agenda-file-regexp` leaves them out.
 59            .filter { $0.kind == .org && !$0.name.hasPrefix(".") && (includeSubfolders || !$0.relativePath.contains("/")) }
 60            .map(\.path)
 61            .sorted()
 62    }
 63
 64    /// Recomputes the days. `open` is the open buffers' text by path.
 65    public func refresh(open: [String: String], now: Date = Date(), calendar: Calendar = .current) async {
 66        let interval = Perf.begin("agenda.refresh")
 67        defer { interval.end("\(files.count) files") }
 68        generation += 1
 69        let id = generation
 70        isComputing = true
 71        let today = Days.absolute(now, calendar: calendar)
 72        let clock = calendar.dateComponents([.hour, .minute], from: now)
 73        var span = self.span
 74        var startOffset = self.startOffset
 75        if case .agenda(let viewSpan, let viewStart) = mode {
 76            span = viewSpan ?? span
 77            startOffset = viewStart ?? startOffset
 78        }
 79        let first = start ?? today + startOffset
 80        let options = self.options
 81        let mode = self.mode
 82        let provider = calendarEvents
 83        let names = calendarNames
 84        let all = await sources(open: open)
 85        let result = await Task.detached {
 86            var days: [AgendaDay] = []
 87            var list: [AgendaItem] = []
 88            var events: [AgendaEvent] = []
 89            switch mode {
 90            case .agenda:
 91                days = Agenda.list(all, start: first, days: span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: options)
 92                if let provider {
 93                    let from = Self.date(first, calendar: calendar)
 94                    events = provider.events(from: from, to: Self.date(first + span, calendar: calendar), chosen: names)
 95                }
 96            case .todo(let keywords):
 97                list = Agenda.todoList(all, keywords: keywords, options: options)
 98            case .match(let match, let todoOnly):
 99                list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: options)
100            case .search(let string, let todoOnly):
101                list = Agenda.textSearch(all, string: string, todoOnly: todoOnly, options: options)
102            }
103            return (days, list, events)
104        }.value
105        guard id == generation else { return }
106        // Unchanged results leave the views alone: a new value redraws the whole list.
107        if days != result.0 { days = result.0 }
108        if list != result.1 { list = result.1 }
109        if events != result.2 { events = result.2 }
110        if self.today != today { self.today = today }
111        if self.calendar != calendar { self.calendar = calendar }
112        isComputing = false
113    }
114
115    /// Reminders for the timed entries of the next `days` days.
116    public func reminders(open: [String: String], now: Date = Date(), calendar: Calendar = .current, days: Int = 7, lead: Int = 12) async -> [Reminder] {
117        let all = await sources(open: open)
118        return await Task.detached { Reminders.upcoming(all, now: now, calendar: calendar, days: days, lead: lead) }.value
119    }
120
121    /// The habits of the agenda files, file by file.
122    public func habits(open: [String: String]) async -> [HabitSnapshot.Entry] {
123        await sources(open: open).flatMap { source in
124            source.habits.map { HabitSnapshot.Entry(title: $0.title, path: source.path, offset: $0.offset, habit: $0.habit) }
125        }
126    }
127
128    /// Entries for the table and kanban views, and the keywords their files use.
129    public func board(open: [String: String], match: String) async -> (entries: [BoardEntry], keywords: [String]) {
130        let all = await sources(open: open)
131        return await Task.detached { (Board.entries(all, match: match), Board.keywords(all)) }.value
132    }
133
134    /// The agenda files' sources: the open file's from its text, the others from the cache
135    /// while they and the settings are unchanged.
136    private func sources(open: [String: String]) async -> [AgendaSource] {
137        let interval = Perf.begin("agenda.sources")
138        defer { interval.end("\(files.count) files") }
139        let defaults = workspace.settings.org
140        let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
141        var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
142        for path in files {
143            if let text = open[path] {
144                // The same text parsed before, as the buffer or as the file on disk.
145                func reusable(_ source: AgendaSource?, _ parsedWith: OrgSettings?, _ parsedBlocking: Bool?) -> AgendaSource? {
146                    guard let source, parsedWith == defaults, parsedBlocking == blocking, !source.readsSetupFiles, source.text == text else { return nil }
147                    return source
148                }
149                let fromOpen = cache.open[path]
150                let fromDisk = cache.entries[path]
151                let cached = reusable(fromOpen?.source, fromOpen?.defaults, fromOpen?.blocking) ?? reusable(fromDisk?.source, fromDisk?.defaults, fromDisk?.blocking)
152                reads.append((path, cached, .distantPast, -1, text))
153                continue
154            }
155            let attributes = try? FileManager.default.attributesOfItem(atPath: path)
156            let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
157            let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
158            // A file reading setup files is read again: they may have changed.
159            let cached = cache.entries[path].flatMap { entry in
160                entry.mtime == mtime && entry.size == size && entry.defaults == defaults && entry.blocking == blocking && !entry.source.readsSetupFiles ? entry.source : nil
161            }
162            reads.append((path, cached, mtime, size, nil))
163        }
164        let loaded = await Task.detached {
165            var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
166            for read in reads {
167                if let cached = read.cached {
168                    sources.append((read.path, read.mtime, read.size, cached, read.text == nil))
169                } else if let text = read.text {
170                    sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: read.path, read: OrgSettings.readFile), checksBlocking: blocking), false))
171                } else if let data = FileManager.default.contents(atPath: read.path) {
172                    let text = SourceText(bytes: [UInt8](data)).text
173                    sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: read.path, read: OrgSettings.readFile), checksBlocking: blocking), true))
174                }
175            }
176            return sources
177        }.value
178        for source in loaded {
179            if source.fromDisk {
180                cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source)
181            } else {
182                cache.open[source.path] = (defaults, blocking, source.source)
183            }
184        }
185        return loaded.map(\.source)
186    }
187
188    /// The days as rows with the events, empty days hidden unless `showAllDates`; see
189    /// `AgendaRows.groups`.
190    public func groups(showAllDates: Bool = false, keep: (AgendaItem) -> Bool = { _ in true }) -> [AgendaDayGroup] {
191        AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
192    }
193
194    /// `groups` with `filter`, kept while the days, events and arguments are the same, as
195    /// views ask on every redraw.
196    public func groups(showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] {
197        let key = GroupsKey(days: days, events: events, today: today, showAllDates: showAllDates, filter: filter)
198        if let groupsMemo, groupsMemo.key == key { return groupsMemo.groups }
199        let groups = groups(showAllDates: showAllDates, keep: filter.keeps)
200        groupsMemo = (key, groups)
201        return groups
202    }
203
204    private struct GroupsKey: Equatable {
205        let days: [AgendaDay]
206        let events: [AgendaEvent]
207        let today: Int
208        let showAllDates: Bool
209        let filter: AgendaFilter
210    }
211
212    @ObservationIgnored private var groupsMemo: (key: GroupsKey, groups: [AgendaDayGroup])?
213
214    nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
215        let d = Days.date(day)
216        return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
217    }
218
219    public func showToday() { start = nil }
220
221    /// Moves the view by a whole span, forward or back.
222    public func shift(forward: Bool, now: Date = Date(), calendar: Calendar = .current) {
223        var span = self.span
224        var startOffset = self.startOffset
225        if case .agenda(let viewSpan, let viewStart) = mode {
226            span = viewSpan ?? span
227            startOffset = viewStart ?? startOffset
228        }
229        let current = start ?? Days.absolute(now, calendar: calendar) + startOffset
230        start = current + (forward ? span : -span)
231    }
232}