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