Sources/OrgApp/ClockModel.swift

265b9d63623b99c4c2b8e8c4d104c57fec553586
orgstar/Sources/OrgApp/ClockModel.swift history · blame · raw

106 lines · 4979 bytes

  1import Foundation
  2import Observation
  3import OrgCore
  4
  5/// The running clock, kept across launches as Emacs keeps `org-clock-marker` for the session,
  6/// and the commands that start and stop it.
  7@MainActor
  8@Observable
  9public final class ClockModel {
 10    public struct Running: Codable, Equatable, Sendable {
 11        public let path: String
 12        /// The stamp in `CLOCK: [start]`.
 13        public let start: String
 14        public let heading: String
 15        public let startedAt: Date
 16    }
 17
 18    public private(set) var running: Running?
 19    private let file: URL
 20
 21    public init(file: URL = WorkspaceModel.defaultDirectory.appendingPathComponent("clock.json")) {
 22        self.file = file
 23        running = (try? JSONDecoder().decode(Running.self, from: Data(contentsOf: file)))
 24    }
 25
 26    private func save() {
 27        try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
 28        if let running, let data = try? JSONEncoder().encode(running) {
 29            try? data.write(to: file, options: .atomic)
 30        } else {
 31            try? FileManager.default.removeItem(at: file)
 32        }
 33    }
 34
 35    /// `org-clock-in` at the heading under the caret, clocking out a running clock first.
 36    public func clockIn(_ session: DocumentSession, now: Date = Date()) -> String {
 37        guard let path = session.path, session.document != nil else { return "No file is open." }
 38        return clockIn(session, path: path, at: session.caret, now: now)
 39    }
 40
 41    /// `org-clock-in` at the heading containing `offset` in `path`.
 42    public func clockIn(_ session: DocumentSession, path: String, at offset: Int, now: Date = Date()) -> String {
 43        guard let text = Self.text(path, session) else { return "Can't read \(path)" }
 44        let tree = OrgParser.parse(text)
 45        guard let entry = DocumentModel(tree: tree).headings.last(where: { $0.headingRange.lowerBound <= offset }) else { return "Before first headline" }
 46        if running != nil {
 47            let message = clockOut(session, now: now)
 48            if running != nil { return message }
 49        }
 50        switch session.perform(ClockIn(), path: path, at: offset, expect: nil, now: now) {
 51        case .commit:
 52            guard let updated = Self.text(path, session), let start = ClockIn.runningStart(in: updated, near: entry.headingRange.lowerBound) else {
 53                return "The clock line wasn't found after clocking in."
 54            }
 55            running = Running(path: path, start: start, heading: entry.title, startedAt: now)
 56            save()
 57            return "Clock starts at [\(start)]"
 58        case .failed(let message):
 59            return message
 60        default:
 61            return "Can't clock in here."
 62        }
 63    }
 64
 65    /// `org-clock-out`, or `org-clock-cancel` with `cancel`.
 66    public func clockOut(_ session: DocumentSession, cancel: Bool = false, now: Date = Date()) -> String {
 67        guard let clock = running else { return "No active clock" }
 68        switch session.perform(ClockOut(start: clock.start, cancel: cancel), path: clock.path, at: 0, expect: nil, now: now) {
 69        case .commit:
 70            running = nil
 71            save()
 72            if cancel { return "Clock canceled" }
 73            let minutes = Int(now.timeIntervalSince(clock.startedAt) / 60)
 74            return String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60)
 75        case .failed(let message):
 76            if message == "Clock start time is gone" || message == "No active clock" {
 77                running = nil
 78                save()
 79            }
 80            return message
 81        default:
 82            return "Can't clock out."
 83        }
 84    }
 85
 86    static func text(_ path: String, _ session: DocumentSession) -> String? {
 87        session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
 88    }
 89
 90    /// The clocked entry's heading, for the `clock` capture target.
 91    public func entry(_ session: DocumentSession) -> (path: String, offset: Int)? {
 92        guard let line = location(session), let text = Self.text(line.path, session) else { return nil }
 93        let heading = DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= line.offset }
 94        return heading.map { (line.path, $0.headingRange.lowerBound) }
 95    }
 96
 97    /// Where the running clock's line is, for `org-clock-goto`.
 98    public func location(_ session: DocumentSession) -> (path: String, offset: Int)? {
 99        guard let clock = running else { return nil }
100        let open = session.openDocuments.first { $0.path == clock.path }?.document.text
101        guard let text = open ?? (try? String(contentsOfFile: clock.path, encoding: .utf8)) else { return nil }
102        let buffer = text as NSString
103        let range = buffer.range(of: "CLOCK: [\(clock.start)]")
104        return range.location == NSNotFound ? (clock.path, 0) : (clock.path, range.location)
105    }
106}