Sources/OrgApp/AgendaModel.swift

a866e469a3568bf7a2829a8dd2a56317ced4736e
orgstar/Sources/OrgApp/AgendaModel.swift history · blame · raw

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