Sources/OrgApp/AgendaModel.swift

d4ccb12cca1f5f07b8acf23dc1cac828bb6a1498
orgstar/Sources/OrgApp/AgendaModel.swift

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