Sources/OrgApp/ClockModel.swift
124 lines · 5872 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 /// A template's `clock-in` once its entry is filed: clocked from when capture began and,
87 /// without `clock-keep`, clocked out now, the clock it interrupted resuming with
88 /// `clock-resume`. The messages, in order.
89 public func captured(
90 _ entry: (path: String, offset: Int), options: CaptureTemplate.Options, session: DocumentSession, opened: Date, now: Date = Date()
91 ) -> [String] {
92 guard options.clockIn else { return [] }
93 let previous = self.entry(session)
94 var messages = [clockIn(session, path: entry.path, at: entry.offset, now: opened)]
95 if !options.clockKeep {
96 messages.append(clockOut(session, now: now))
97 if options.clockResume, let previous {
98 messages.append(clockIn(session, path: previous.path, at: previous.offset, now: now))
99 }
100 }
101 return messages
102 }
103
104 static func text(_ path: String, _ session: DocumentSession) -> String? {
105 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
106 }
107
108 /// The clocked entry's heading, for the `clock` capture target.
109 public func entry(_ session: DocumentSession) -> (path: String, offset: Int)? {
110 guard let line = location(session), let text = Self.text(line.path, session) else { return nil }
111 let heading = DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= line.offset }
112 return heading.map { (line.path, $0.headingRange.lowerBound) }
113 }
114
115 /// Where the running clock's line is, for `org-clock-goto`.
116 public func location(_ session: DocumentSession) -> (path: String, offset: Int)? {
117 guard let clock = running else { return nil }
118 let open = session.openDocuments.first { $0.path == clock.path }?.document.text
119 guard let text = open ?? (try? String(contentsOfFile: clock.path, encoding: .utf8)) else { return nil }
120 let buffer = text as NSString
121 let range = buffer.range(of: "CLOCK: [\(clock.start)]")
122 return range.location == NSNotFound ? (clock.path, 0) : (clock.path, range.location)
123 }
124}