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