krz/orgstar

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

Sources/OrgApp/AgendaModel.swift

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

140 lines · 6583 bytes

  1import Foundation
  2import Observation
  3import OrgCore
  4import OrgIndex
  5
  6/// The day/week agenda over the workspace's agenda files. Sources are read from disk and
  7/// cached by modification date and size; the open file's come from its buffer, so the agenda
  8/// shows unsaved edits.
  9@MainActor
 10@Observable
 11public final class AgendaModel {
 12    public private(set) var days: [AgendaDay] = []
 13    /// The entries of a TODO list or match view.
 14    public private(set) var list: [AgendaItem] = []
 15    public var mode: AgendaMode = .agenda(span: nil, startOffset: nil)
 16    /// The first day shown, as `Days` numbers it; nil follows today.
 17    public var start: Int?
 18    public var span = 10
 19    /// Where the view starts relative to today, as Doom's `org-agenda-start-day "-3d"`.
 20    public var startOffset = -3
 21    /// Files below the top level of each folder are agenda files too.
 22    public var includeSubfolders = false
 23    public var options = AgendaOptions()
 24    public private(set) var isComputing = false
 25
 26    private let workspace: WorkspaceModel
 27    @ObservationIgnored private var cache: [String: (mtime: Date, size: Int, source: AgendaSource)] = [:]
 28    @ObservationIgnored private var generation = 0
 29
 30    public init(workspace: WorkspaceModel) {
 31        self.workspace = workspace
 32    }
 33
 34    /// Org files directly in each folder (or below it, with `includeSubfolders`), by path, as
 35    /// Emacs lists a directory in `org-agenda-files`.
 36    public var files: [String] {
 37        workspace.files
 38            .filter { $0.kind == .org && (includeSubfolders || !$0.relativePath.contains("/")) }
 39            .map(\.path)
 40            .sorted()
 41    }
 42
 43    /// Recomputes the days. `open` is the open file's path and text.
 44    public func refresh(open: (path: String, text: String)?, now: Date = Date(), calendar: Calendar = .current) async {
 45        generation += 1
 46        let id = generation
 47        isComputing = true
 48        let today = Days.absolute(now, calendar: calendar)
 49        let clock = calendar.dateComponents([.hour, .minute], from: now)
 50        var span = self.span
 51        var startOffset = self.startOffset
 52        if case .agenda(let viewSpan, let viewStart) = mode {
 53            span = viewSpan ?? span
 54            startOffset = viewStart ?? startOffset
 55        }
 56        let first = start ?? today + startOffset
 57        let options = self.options
 58        let mode = self.mode
 59        let all = await sources(open: open)
 60        let result = await Task.detached {
 61            var days: [AgendaDay] = []
 62            var list: [AgendaItem] = []
 63            switch mode {
 64            case .agenda:
 65                days = Agenda.list(all, start: first, days: span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: options)
 66            case .todo(let keywords):
 67                list = Agenda.todoList(all, keywords: keywords)
 68            case .match(let match, let todoOnly):
 69                list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar)
 70            }
 71            return (days, list)
 72        }.value
 73        guard id == generation else { return }
 74        days = result.0
 75        list = result.1
 76        isComputing = false
 77    }
 78
 79    /// Reminders for the timed entries of the next `days` days.
 80    public func reminders(open: (path: String, text: String)?, now: Date = Date(), calendar: Calendar = .current, days: Int = 7, lead: Int = 12) async -> [Reminder] {
 81        let all = await sources(open: open)
 82        return await Task.detached { Reminders.upcoming(all, now: now, calendar: calendar, days: days, lead: lead) }.value
 83    }
 84
 85    /// Entries for the table and kanban views, and the keywords their files use.
 86    public func board(open: (path: String, text: String)?, match: String) async -> (entries: [BoardEntry], keywords: [String]) {
 87        let all = await sources(open: open)
 88        return await Task.detached { (Board.entries(all, match: match), Board.keywords(all)) }.value
 89    }
 90
 91    /// The agenda files' sources: the open file's from its text, the others from the cache
 92    /// while their modification date and size are unchanged.
 93    private func sources(open: (path: String, text: String)?) async -> [AgendaSource] {
 94        let defaults = workspace.settings.org
 95        var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
 96        for path in files {
 97            if let open, open.path == path {
 98                reads.append((path, nil, .distantPast, -1, open.text))
 99                continue
100            }
101            let attributes = try? FileManager.default.attributesOfItem(atPath: path)
102            let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
103            let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
104            let cached = cache[path].flatMap { $0.mtime == mtime && $0.size == size ? $0.source : nil }
105            reads.append((path, cached, mtime, size, nil))
106        }
107        let loaded = await Task.detached {
108            var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
109            for read in reads {
110                if let cached = read.cached {
111                    sources.append((read.path, read.mtime, read.size, cached, true))
112                } else if let text = read.text {
113                    sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults), false))
114                } else if let data = FileManager.default.contents(atPath: read.path) {
115                    let text = SourceText(bytes: [UInt8](data)).text
116                    sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults), true))
117                }
118            }
119            return sources
120        }.value
121        for source in loaded where source.fromDisk {
122            cache[source.path] = (source.mtime, source.size, source.source)
123        }
124        return loaded.map(\.source)
125    }
126
127    public func showToday() { start = nil }
128
129    /// Moves the view by a whole span, forward or back.
130    public func shift(forward: Bool, now: Date = Date(), calendar: Calendar = .current) {
131        var span = self.span
132        var startOffset = self.startOffset
133        if case .agenda(let viewSpan, let viewStart) = mode {
134            span = viewSpan ?? span
135            startOffset = viewStart ?? startOffset
136        }
137        let current = start ?? Days.absolute(now, calendar: calendar) + startOffset
138        start = current + (forward ? span : -span)
139    }
140}