Sources/OrgApp/AgendaModel.swift
240 lines · 12533 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 }
102 return (days, list, events)
103 }.value
104 guard id == generation else { return }
105 // Unchanged results leave the views alone: a new value redraws the whole list.
106 if days != result.0 { days = result.0 }
107 if list != result.1 { list = result.1 }
108 if events != result.2 { events = result.2 }
109 if self.today != today { self.today = today }
110 if self.calendar != calendar { self.calendar = calendar }
111 isComputing = false
112 }
113
114 /// Reminders for the timed entries of the next `days` days.
115 public func reminders(open: [String: String], now: Date = Date(), calendar: Calendar = .current, days: Int = 7, lead: Int = 12) async -> [Reminder] {
116 let all = await sources(open: open)
117 return await Task.detached { Reminders.upcoming(all, now: now, calendar: calendar, days: days, lead: lead) }.value
118 }
119
120 /// The habits of the agenda files, file by file.
121 public func habits(open: [String: String]) async -> [HabitSnapshot.Entry] {
122 await sources(open: open).flatMap { source in
123 source.habits.map { HabitSnapshot.Entry(title: $0.title, path: source.path, offset: $0.offset, habit: $0.habit) }
124 }
125 }
126
127 /// Entries for the table and kanban views, and the keywords their files use.
128 public func board(open: [String: String], match: String) async -> (entries: [BoardEntry], keywords: [String]) {
129 let all = await sources(open: open)
130 return await Task.detached { (Board.entries(all, match: match), Board.keywords(all)) }.value
131 }
132
133 /// The agenda files' sources: the open file's from its text, the others from the cache
134 /// while they and the settings are unchanged.
135 private func sources(open: [String: String]) async -> [AgendaSource] {
136 let interval = Perf.begin("agenda.sources")
137 defer { interval.end("\(files.count) files") }
138 let defaults = workspace.settings.org
139 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
140 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
141 for path in files {
142 if let text = open[path] {
143 // The same text parsed before, as the buffer or as the file on disk.
144 func reusable(_ source: AgendaSource?, _ parsedWith: OrgSettings?, _ parsedBlocking: Bool?) -> AgendaSource? {
145 guard let source, parsedWith == defaults, parsedBlocking == blocking, !source.readsSetupFiles, source.text == text else { return nil }
146 return source
147 }
148 let fromOpen = cache.open[path]
149 let fromDisk = cache.entries[path]
150 let cached = reusable(fromOpen?.source, fromOpen?.defaults, fromOpen?.blocking) ?? reusable(fromDisk?.source, fromDisk?.defaults, fromDisk?.blocking)
151 reads.append((path, cached, .distantPast, -1, text))
152 continue
153 }
154 let attributes = try? FileManager.default.attributesOfItem(atPath: path)
155 let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
156 let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
157 // A file reading setup files is read again: they may have changed.
158 let cached = cache.entries[path].flatMap { entry in
159 entry.mtime == mtime && entry.size == size && entry.defaults == defaults && entry.blocking == blocking && !entry.source.readsSetupFiles ? entry.source : nil
160 }
161 reads.append((path, cached, mtime, size, nil))
162 }
163 let loaded = await Task.detached {
164 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
165 for read in reads {
166 if let cached = read.cached {
167 sources.append((read.path, read.mtime, read.size, cached, read.text == nil))
168 } else if let text = read.text {
169 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))
170 } else if let data = FileManager.default.contents(atPath: read.path) {
171 let text = SourceText(bytes: [UInt8](data)).text
172 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))
173 }
174 }
175 return sources
176 }.value
177 for source in loaded {
178 if source.fromDisk {
179 cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source)
180 } else {
181 cache.open[source.path] = (defaults, blocking, source.source)
182 }
183 }
184 return loaded.map(\.source)
185 }
186
187 /// The days as rows with the events, empty days hidden unless `showAllDates`; see
188 /// `AgendaRows.groups`.
189 public func groups(showAllDates: Bool = false, keep: (AgendaItem) -> Bool = { _ in true }) -> [AgendaDayGroup] {
190 AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
191 }
192
193 /// `groups` with `filter`, kept while the days, events and arguments are the same, as
194 /// views ask on every redraw.
195 public func groups(showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] {
196 let key = GroupsKey(days: days, events: events, today: today, showAllDates: showAllDates, filter: filter)
197 if let groupsMemo, groupsMemo.key == key { return groupsMemo.groups }
198 let groups = groups(showAllDates: showAllDates, keep: filter.keeps)
199 groupsMemo = (key, groups)
200 return groups
201 }
202
203 private struct GroupsKey: Equatable {
204 let days: [AgendaDay]
205 let events: [AgendaEvent]
206 let today: Int
207 let showAllDates: Bool
208 let filter: AgendaFilter
209 }
210
211 @ObservationIgnored private var groupsMemo: (key: GroupsKey, groups: [AgendaDayGroup])?
212
213 nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
214 let d = Days.date(day)
215 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
216 }
217
218 public func showToday() { start = nil }
219
220 /// The first day the agenda shows and how many, as `org-agenda-list` works them out: the
221 /// view's span and start, or the settings', with 7- and 14-day spans moved back to
222 /// `startOnWeekday`.
223 public func shown(today: Int) -> (first: Int, span: Int) {
224 var span = self.span
225 var startOffset = self.startOffset
226 if case .agenda(let viewSpan, let viewStart) = mode {
227 span = viewSpan ?? span
228 startOffset = viewStart ?? startOffset
229 }
230 var first = start ?? today + startOffset
231 if span == 7 || span == 14 { first = Days.weekStart(first, on: startOnWeekday) }
232 return (first, span)
233 }
234
235 /// Moves the view by a whole span, forward or back.
236 public func shift(forward: Bool, now: Date = Date(), calendar: Calendar = .current) {
237 let (current, span) = shown(today: Days.absolute(now, calendar: calendar))
238 start = current + (forward ? span : -span)
239 }
240}