Sources/OrgApp/AgendaModel.swift

19641366e5de9103a7d88bf80436ab2aebc03cf5
orgstar/Sources/OrgApp/AgendaModel.swift

308 lines · 16450 bytes

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