Sources/OrgApp/AgendaModel.swift
179 lines · 9062 bytes
1import Foundation
2import Observation
3import OrgCore
4import OrgIndex
5import OrgPresentation
6
7/// The day/week agenda over the workspace's agenda files. Sources are read from disk and
8/// cached by modification date and size; the open file's come from its buffer, so the agenda
9/// shows unsaved edits.
10@MainActor
11@Observable
12public final class AgendaModel {
13 public private(set) var days: [AgendaDay] = []
14 /// The entries of a TODO list, match or search view.
15 public private(set) var list: [AgendaItem] = []
16 public var mode: AgendaMode = .agenda(span: nil, startOffset: nil)
17 /// The first day shown, as `Days` numbers it; nil follows today.
18 public var start: Int?
19 public var span = 10
20 /// Where the view starts relative to today, as Doom's `org-agenda-start-day "-3d"`.
21 public var startOffset = -3
22 /// Files below the top level of each folder are agenda files too.
23 public var includeSubfolders = false
24 public var options = AgendaOptions()
25 public private(set) var isComputing = false
26 /// Calendar events over the days shown, from `calendarEvents` (nil reads none) and the
27 /// calendars in `calendarNames` (all when empty).
28 public private(set) var events: [AgendaEvent] = []
29 public var calendarEvents: CalendarEvents?
30 public var calendarNames: [String] = []
31 /// Today and the calendar of the last refresh.
32 public private(set) var today = Days.absolute(Date(), calendar: .current)
33 @ObservationIgnored private var calendar = Calendar.current
34
35 private let workspace: WorkspaceModel
36 @ObservationIgnored private var cache: [String: (mtime: Date, size: Int, source: AgendaSource)] = [:]
37 @ObservationIgnored private var generation = 0
38
39 public init(workspace: WorkspaceModel) {
40 self.workspace = workspace
41 }
42
43 /// Org files directly in each folder (or below it, with `includeSubfolders`), by path, as
44 /// Emacs lists a directory in `org-agenda-files`.
45 public var files: [String] {
46 workspace.files
47 // Dotfiles stay out, as `org-agenda-file-regexp` leaves them out.
48 .filter { $0.kind == .org && !$0.name.hasPrefix(".") && (includeSubfolders || !$0.relativePath.contains("/")) }
49 .map(\.path)
50 .sorted()
51 }
52
53 /// Recomputes the days. `open` is the open buffers' text by path.
54 public func refresh(open: [String: String], now: Date = Date(), calendar: Calendar = .current) async {
55 let interval = Perf.begin("agenda.refresh")
56 defer { interval.end("\(files.count) files") }
57 generation += 1
58 let id = generation
59 isComputing = true
60 let today = Days.absolute(now, calendar: calendar)
61 let clock = calendar.dateComponents([.hour, .minute], from: now)
62 var span = self.span
63 var startOffset = self.startOffset
64 if case .agenda(let viewSpan, let viewStart) = mode {
65 span = viewSpan ?? span
66 startOffset = viewStart ?? startOffset
67 }
68 let first = start ?? today + startOffset
69 let options = self.options
70 let mode = self.mode
71 let provider = calendarEvents
72 let names = calendarNames
73 let all = await sources(open: open)
74 let result = await Task.detached {
75 var days: [AgendaDay] = []
76 var list: [AgendaItem] = []
77 var events: [AgendaEvent] = []
78 switch mode {
79 case .agenda:
80 days = Agenda.list(all, start: first, days: span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: options)
81 if let provider {
82 let from = Self.date(first, calendar: calendar)
83 events = provider.events(from: from, to: Self.date(first + span, calendar: calendar), chosen: names)
84 }
85 case .todo(let keywords):
86 list = Agenda.todoList(all, keywords: keywords, options: options)
87 case .match(let match, let todoOnly):
88 list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: options)
89 case .search(let string, let todoOnly):
90 list = Agenda.textSearch(all, string: string, todoOnly: todoOnly, options: options)
91 }
92 return (days, list, events)
93 }.value
94 guard id == generation else { return }
95 days = result.0
96 list = result.1
97 events = result.2
98 self.today = today
99 self.calendar = calendar
100 isComputing = false
101 }
102
103 /// Reminders for the timed entries of the next `days` days.
104 public func reminders(open: [String: String], now: Date = Date(), calendar: Calendar = .current, days: Int = 7, lead: Int = 12) async -> [Reminder] {
105 let all = await sources(open: open)
106 return await Task.detached { Reminders.upcoming(all, now: now, calendar: calendar, days: days, lead: lead) }.value
107 }
108
109 /// Entries for the table and kanban views, and the keywords their files use.
110 public func board(open: [String: String], match: String) async -> (entries: [BoardEntry], keywords: [String]) {
111 let all = await sources(open: open)
112 return await Task.detached { (Board.entries(all, match: match), Board.keywords(all)) }.value
113 }
114
115 /// The agenda files' sources: the open file's from its text, the others from the cache
116 /// while their modification date and size are unchanged.
117 private func sources(open: [String: String]) async -> [AgendaSource] {
118 let interval = Perf.begin("agenda.sources")
119 defer { interval.end("\(files.count) files") }
120 let defaults = workspace.settings.org
121 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
122 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
123 for path in files {
124 if let text = open[path] {
125 reads.append((path, nil, .distantPast, -1, text))
126 continue
127 }
128 let attributes = try? FileManager.default.attributesOfItem(atPath: path)
129 let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
130 let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
131 // A file reading setup files is read again: they may have changed.
132 let cached = cache[path].flatMap { $0.mtime == mtime && $0.size == size && !$0.source.readsSetupFiles && $0.source.checksBlocking == blocking ? $0.source : nil }
133 reads.append((path, cached, mtime, size, nil))
134 }
135 let loaded = await Task.detached {
136 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
137 for read in reads {
138 if let cached = read.cached {
139 sources.append((read.path, read.mtime, read.size, cached, true))
140 } else if let text = read.text {
141 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))
142 } else if let data = FileManager.default.contents(atPath: read.path) {
143 let text = SourceText(bytes: [UInt8](data)).text
144 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))
145 }
146 }
147 return sources
148 }.value
149 for source in loaded where source.fromDisk {
150 cache[source.path] = (source.mtime, source.size, source.source)
151 }
152 return loaded.map(\.source)
153 }
154
155 /// The days as rows with the events, empty days hidden unless `showAllDates`; see
156 /// `AgendaRows.groups`.
157 public func groups(showAllDates: Bool = false, keep: (AgendaItem) -> Bool = { _ in true }) -> [AgendaDayGroup] {
158 AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
159 }
160
161 nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
162 let d = Days.date(day)
163 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
164 }
165
166 public func showToday() { start = nil }
167
168 /// Moves the view by a whole span, forward or back.
169 public func shift(forward: Bool, now: Date = Date(), calendar: Calendar = .current) {
170 var span = self.span
171 var startOffset = self.startOffset
172 if case .agenda(let viewSpan, let viewStart) = mode {
173 span = viewSpan ?? span
174 startOffset = viewStart ?? startOffset
175 }
176 let current = start ?? Days.absolute(now, calendar: calendar) + startOffset
177 start = current + (forward ? span : -span)
178 }
179}