Sources/OrgApp/AgendaModel.swift

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