krz/orgstar

A native macOS editor for org-mode files. editor org-mode swift

Sources/OrgApp/AgendaModel.swift

3a3dedba062790e1580c66d38606eda4b02cb501
orgstar/Sources/OrgApp/AgendaModel.swift history · blame · raw

172 lines · 8461 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 or match 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        generation += 1
 56        let id = generation
 57        isComputing = true
 58        let today = Days.absolute(now, calendar: calendar)
 59        let clock = calendar.dateComponents([.hour, .minute], from: now)
 60        var span = self.span
 61        var startOffset = self.startOffset
 62        if case .agenda(let viewSpan, let viewStart) = mode {
 63            span = viewSpan ?? span
 64            startOffset = viewStart ?? startOffset
 65        }
 66        let first = start ?? today + startOffset
 67        let options = self.options
 68        let mode = self.mode
 69        let provider = calendarEvents
 70        let names = calendarNames
 71        let all = await sources(open: open)
 72        let result = await Task.detached {
 73            var days: [AgendaDay] = []
 74            var list: [AgendaItem] = []
 75            var events: [AgendaEvent] = []
 76            switch mode {
 77            case .agenda:
 78                days = Agenda.list(all, start: first, days: span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: options)
 79                if let provider {
 80                    let from = Self.date(first, calendar: calendar)
 81                    events = provider.events(from: from, to: Self.date(first + span, calendar: calendar), chosen: names)
 82                }
 83            case .todo(let keywords):
 84                list = Agenda.todoList(all, keywords: keywords, options: options)
 85            case .match(let match, let todoOnly):
 86                list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: options)
 87            }
 88            return (days, list, events)
 89        }.value
 90        guard id == generation else { return }
 91        days = result.0
 92        list = result.1
 93        events = result.2
 94        self.today = today
 95        self.calendar = calendar
 96        isComputing = false
 97    }
 98
 99    /// Reminders for the timed entries of the next `days` days.
100    public func reminders(open: [String: String], now: Date = Date(), calendar: Calendar = .current, days: Int = 7, lead: Int = 12) async -> [Reminder] {
101        let all = await sources(open: open)
102        return await Task.detached { Reminders.upcoming(all, now: now, calendar: calendar, days: days, lead: lead) }.value
103    }
104
105    /// Entries for the table and kanban views, and the keywords their files use.
106    public func board(open: [String: String], match: String) async -> (entries: [BoardEntry], keywords: [String]) {
107        let all = await sources(open: open)
108        return await Task.detached { (Board.entries(all, match: match), Board.keywords(all)) }.value
109    }
110
111    /// The agenda files' sources: the open file's from its text, the others from the cache
112    /// while their modification date and size are unchanged.
113    private func sources(open: [String: String]) async -> [AgendaSource] {
114        let defaults = workspace.settings.org
115        var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
116        for path in files {
117            if let text = open[path] {
118                reads.append((path, nil, .distantPast, -1, text))
119                continue
120            }
121            let attributes = try? FileManager.default.attributesOfItem(atPath: path)
122            let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
123            let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
124            // A file reading setup files is read again: they may have changed.
125            let cached = cache[path].flatMap { $0.mtime == mtime && $0.size == size && !$0.source.readsSetupFiles ? $0.source : nil }
126            reads.append((path, cached, mtime, size, nil))
127        }
128        let loaded = await Task.detached {
129            var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
130            for read in reads {
131                if let cached = read.cached {
132                    sources.append((read.path, read.mtime, read.size, cached, true))
133                } else if let text = read.text {
134                    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)), false))
135                } else if let data = FileManager.default.contents(atPath: read.path) {
136                    let text = SourceText(bytes: [UInt8](data)).text
137                    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)), true))
138                }
139            }
140            return sources
141        }.value
142        for source in loaded where source.fromDisk {
143            cache[source.path] = (source.mtime, source.size, source.source)
144        }
145        return loaded.map(\.source)
146    }
147
148    /// The days as rows with the events, empty days hidden unless `showAllDates`; see
149    /// `AgendaRows.groups`.
150    public func groups(showAllDates: Bool = false, keep: (AgendaItem) -> Bool = { _ in true }) -> [AgendaDayGroup] {
151        AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
152    }
153
154    nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
155        let d = Days.date(day)
156        return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
157    }
158
159    public func showToday() { start = nil }
160
161    /// Moves the view by a whole span, forward or back.
162    public func shift(forward: Bool, now: Date = Date(), calendar: Calendar = .current) {
163        var span = self.span
164        var startOffset = self.startOffset
165        if case .agenda(let viewSpan, let viewStart) = mode {
166            span = viewSpan ?? span
167            startOffset = viewStart ?? startOffset
168        }
169        let current = start ?? Days.absolute(now, calendar: calendar) + startOffset
170        start = current + (forward ? span : -span)
171    }
172}