Sources/OrgApp/ClockModel.swift
675 lines · 35702 bytes
1import Foundation
2import Observation
3import OrgCore
4
5/// The running clock and the clock history, kept across launches as Org keeps them with
6/// `org-clock-persist`, and the commands that start, stop and resolve clocks.
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 /// An open `CLOCK:` line: the running clock, or one left dangling.
19 public struct OpenClock: Equatable, Sendable {
20 public let path: String
21 public let start: String
22 public let startedAt: Date
23 public let heading: String
24 }
25
26 /// What a question about a clock led to: messages, and where to look (`j`).
27 public struct Outcome {
28 public var messages: [String] = []
29 public var jump: (path: String, offset: Int)?
30 }
31
32 /// Asks a question in the echo area or a sheet; nil when it is cancelled.
33 public typealias Ask = @MainActor (Prompt) async -> String?
34
35 private struct Saved: Codable {
36 var running: Running?
37 var history: [ClockTask]
38 }
39
40 public private(set) var running: Running?
41 /// `org-clock-history`, most recent first.
42 public private(set) var history: [ClockTask] = []
43 /// `org-clock-default-task`, for the session.
44 public private(set) var defaultTask: ClockTask?
45 /// `org-clock-interrupted-task`.
46 public private(set) var interruptedTask: ClockTask?
47 /// `org-clock-leftover-time`: where a clock resolved with `K`, `S` or `T` stopped.
48 public private(set) var leftover: Date?
49 /// A clock question is open (`org-clock-resolving-clocks`).
50 public private(set) var isResolving = false
51 /// Where the effort reminder goes (`org-clock-notify-once-if-expired`); nil sets none.
52 @ObservationIgnored public var notifications: ReminderCenter?
53 /// The clocked entry's heading line as last seen, and its keyword, for
54 /// `org-clock-out-when-done`.
55 @ObservationIgnored private var watched: (line: String, keyword: String?)?
56 /// The open clocks `sync` has seen, by path and start: only new ones start running.
57 @ObservationIgnored private var seenOpen: Set<String> = []
58 private let file: URL
59 private let defaults: UserDefaults
60
61 public init(file: URL = WorkspaceModel.defaultDirectory.appendingPathComponent("clock.json"), defaults: UserDefaults = .standard) {
62 self.file = file
63 self.defaults = defaults
64 guard let data = try? Data(contentsOf: file) else { return }
65 if let running = try? JSONDecoder().decode(Running.self, from: data) {
66 self.running = running
67 } else if let saved = try? JSONDecoder().decode(Saved.self, from: data) {
68 running = saved.running
69 history = saved.history
70 }
71 }
72
73 private func save() {
74 try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
75 if running != nil || !history.isEmpty, let data = try? JSONEncoder().encode(Saved(running: running, history: history)) {
76 try? data.write(to: file, options: .atomic)
77 } else {
78 try? FileManager.default.removeItem(at: file)
79 }
80 }
81
82 // MARK: - Clocking in and out
83
84 /// `org-clock-in` at the heading under the caret, clocking out a running clock first.
85 public func clockIn(_ session: DocumentSession, now: Date = Date()) -> String {
86 guard let path = session.path, session.document != nil else { return "No file is open." }
87 return clockIn(session, path: path, at: session.caret, now: now)
88 }
89
90 /// `org-clock-in` at the heading containing `offset` in `path`.
91 public func clockIn(_ session: DocumentSession, path: String, at offset: Int, now: Date = Date()) -> String {
92 guard let text = Self.text(path, session) else { return "Can't read \(path)" }
93 let headings = DocumentModel(tree: OrgParser.parse(text)).headings
94 guard let index = headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) else { return "Before first headline" }
95 let entry = headings[index]
96 var offset = offset
97 var heading = entry.headingRange.lowerBound
98 if let running {
99 if isRunning(path: path, heading: heading, session) { return "Clock continues in \"\(running.heading)\"" }
100 let interrupted = runningTask(session)
101 let message = clockOut(session, now: now)
102 if self.running != nil { return message }
103 interruptedTask = interrupted
104 // Clocking out may have moved the entry.
105 let target = ClockTask(path: path, title: entry.title, ordinal: index, id: entry.id)
106 guard let moved = Self.text(path, session).flatMap(target.locate) else { return "Can't find \(entry.title) after clocking out." }
107 offset += moved - heading
108 heading = moved
109 } else {
110 interruptedTask = nil
111 }
112 switch session.perform(ClockIn(), path: path, at: offset, expect: nil, now: now) {
113 case .commit:
114 guard let updated = Self.text(path, session), let start = ClockIn.runningStart(in: updated, near: heading) else {
115 return "The clock line wasn't found after clocking in."
116 }
117 running = Running(path: path, start: start, heading: entry.title, startedAt: now)
118 if let task = ClockTask.at(heading, in: updated, path: path) { push(task, session) }
119 save()
120 watched = clockedHeading(path, session)
121 remindAtEffort(session, now: now)
122 return "Clock starts at [\(start)]"
123 case .failed(let message):
124 return message
125 default:
126 return "Can't clock in here."
127 }
128 }
129
130 /// `org-clock-out`, or `org-clock-cancel` with `cancel`.
131 public func clockOut(_ session: DocumentSession, cancel: Bool = false, now: Date = Date()) -> String {
132 guard let clock = running else { return "No active clock" }
133 notifications?.remove([Self.effortReminderID])
134 switch session.perform(ClockOut(start: clock.start, cancel: cancel), path: clock.path, at: 0, expect: nil, now: now) {
135 case .commit:
136 running = nil
137 watched = nil
138 save()
139 if cancel { return "Clock canceled" }
140 let minutes = Int(now.timeIntervalSince(clock.startedAt) / 60)
141 let removed = Self.text(clock.path, session).map { !$0.contains("CLOCK: [\(clock.start)]") } ?? false
142 return String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60) + (removed ? " => LINE REMOVED" : "")
143 case .failed(let message):
144 if message == "Clock start time is gone" || message == "No active clock" {
145 running = nil
146 save()
147 }
148 return message
149 default:
150 return "Can't clock out."
151 }
152 }
153
154 /// A template's `clock-in` once its entry is filed: `org-clock-in` at the entry as when
155 /// capture began, dangling clocks resolved first, and, without `clock-keep`, clocked out
156 /// now, the clock it interrupted resuming with `clock-resume`.
157 public func captured(
158 _ entry: (path: String, offset: Int), options: CaptureTemplate.Options, session: DocumentSession, paths: [String], ask: Ask,
159 opened: Date, now: Date = Date()
160 ) async -> Outcome {
161 guard options.clockIn else { return Outcome() }
162 let previous = running == nil ? nil : runningTask(session)
163 var outcome = await clockIn(session, target: .entry(path: entry.path, offset: entry.offset), paths: paths, ask: ask, now: { opened })
164 if !options.clockKeep {
165 outcome.messages.append(clockOut(session, now: now))
166 if options.clockResume, let previous {
167 let resumed = await clockIn(session, target: .task(previous), paths: paths, ask: ask, now: { now })
168 outcome.messages += resumed.messages
169 if let jump = resumed.jump { outcome.jump = jump }
170 }
171 }
172 return outcome
173 }
174
175 // MARK: - Done and effort
176
177 /// The heading line above the running clock's line in `text`.
178 private func clockedHeadingLine(_ text: String) -> String? {
179 guard let clock = running else { return nil }
180 let ns = text as NSString
181 var end = ns.range(of: "CLOCK: [\(clock.start)]").location
182 guard end != NSNotFound else { return nil }
183 while end > 0 {
184 let newline = ns.range(of: "\n", options: .backwards, range: NSRange(location: 0, length: end)).location
185 let start = newline == NSNotFound ? 0 : newline + 1
186 let line = ns.substring(with: ns.lineRange(for: NSRange(location: start, length: 0))).trimmingCharacters(in: .newlines)
187 if line.range(of: "^\\*+ ", options: .regularExpression) != nil { return line }
188 guard newline != NSNotFound else { return nil }
189 end = newline
190 }
191 return nil
192 }
193
194 /// The clocked entry's heading line and keyword.
195 private func clockedHeading(_ path: String, _ session: DocumentSession) -> (line: String, keyword: String?)? {
196 guard let text = Self.text(path, session), let heading = clockedHeadingLine(text) else { return nil }
197 let settings = OrgParser.parse(text, defaults: session.defaults).settings
198 let word = String(heading.drop { $0 == "*" }.drop { $0 == " " }.prefix { !$0.isWhitespace })
199 let keywords = settings.todoSequences.flatMap { $0.active + $0.done }.map(\.name)
200 return (heading, keywords.contains(word) ? word : nil)
201 }
202
203 /// `org-clock-out-if-current`: clocks out when the clocked entry's keyword became one of
204 /// `org-clock-out-when-done`'s (any done keyword for `t`). Returns the message.
205 public func textChanged(_ path: String, _ session: DocumentSession, now: Date = Date()) -> String? {
206 guard let clock = running, clock.path == path, let states = OrgPreferences.clockOutWhenDone(defaults),
207 let text = Self.text(path, session), let line = clockedHeadingLine(text), line != watched?.line,
208 let current = clockedHeading(path, session) else { return nil }
209 let before = watched
210 watched = current
211 guard let before else { return nil }
212 let settings = OrgParser.parse(text, defaults: session.defaults).settings
213 func stops(_ keyword: String?) -> Bool {
214 guard let keyword else { return false }
215 return states.isEmpty ? settings.isDone(keyword) : states.contains(keyword)
216 }
217 guard stops(current.keyword), !stops(before.keyword) else { return nil }
218 return clockOut(session, now: now)
219 }
220
221 static let effortReminderID = "orgstar-effort"
222
223 /// The running clock's entry: its Effort in minutes, and the minutes clocked on it before
224 /// this clock (`org-clock-sum-current-item` from `org-clock-get-sum-start`).
225 public func effort(_ session: DocumentSession, now: Date = Date(), calendar: Calendar = .current) -> (effort: Int, clocked: Int, value: String)? {
226 guard let clock = running, let text = Self.text(clock.path, session) else { return nil }
227 let line = (text as NSString).range(of: "CLOCK: [\(clock.start)]")
228 guard line.location != NSNotFound else { return nil }
229 let model = DocumentModel(tree: OrgParser.parse(text, defaults: session.defaults))
230 guard let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= line.location }),
231 let value = model.headings[index].properties.last(where: { $0.key.uppercased() == "EFFORT" })?.value,
232 let effort = ColumnView.minutes(value), effort > 0 else { return nil }
233 let own = { (key: String) in model.headings[index].properties.last { $0.key.uppercased() == key }?.value }
234 func day(_ p: Timestamp.Point) -> Date? { calendar.date(from: DateComponents(year: p.year, month: p.month, day: p.day, hour: p.hour ?? 0, minute: p.minute ?? 0)) }
235 let since: Date? = switch own("CLOCK_MODELINE_TOTAL") ?? "auto" {
236 case "current": .distantFuture
237 case "today": calendar.startOfDay(for: now)
238 case "all": nil
239 default: own("LAST_REPEAT").flatMap { stamp in Timestamp.parse(stamp).flatMap { day($0.start) } }
240 }
241 let level = model.headings[index].level
242 var subtree = [index]
243 for i in (index + 1)..<model.headings.count {
244 guard model.headings[i].level > level else { break }
245 subtree.append(i)
246 }
247 let clocked = subtree.flatMap { model.headings[$0].clocks }.filter { clock in
248 guard clock.end != nil else { return false }
249 guard let since else { return true }
250 return day(clock.start).map { $0 >= since } ?? false
251 }.compactMap(\.minutes).reduce(0, +)
252 return (Int(effort), clocked, value)
253 }
254
255 /// A notification when the running clock passes the entry's Effort, as
256 /// `org-clock-notify-once-if-expired` shows: "Task `…' should be finished by now. (1:00)".
257 public func remindAtEffort(_ session: DocumentSession, now: Date = Date()) {
258 guard let notifications else { return }
259 notifications.remove([Self.effortReminderID])
260 guard let clock = running, let status = effort(session, now: now) else { return }
261 let due = clock.startedAt.addingTimeInterval(Double((status.effort - status.clocked) * 60))
262 let fire = max(due, now.addingTimeInterval(1))
263 let location = location(session)
264 let reminder = Reminder(id: Self.effortReminderID, fireDate: fire, eventDate: fire, title: "Effort used up",
265 body: "Task `\(clock.heading)' should be finished by now. (\(status.value))",
266 path: clock.path, offset: location?.offset ?? 0)
267 Task {
268 guard await notifications.authorize() else { return }
269 try? await notifications.add(reminder)
270 }
271 }
272
273 static func text(_ path: String, _ session: DocumentSession) -> String? {
274 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
275 }
276
277 /// The clocked entry's heading, for the `clock` capture target.
278 public func entry(_ session: DocumentSession) -> (path: String, offset: Int)? {
279 guard let line = location(session), let text = Self.text(line.path, session) else { return nil }
280 let heading = DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= line.offset }
281 return heading.map { (line.path, $0.headingRange.lowerBound) }
282 }
283
284 /// Where the running clock's line is, for `org-clock-goto`.
285 public func location(_ session: DocumentSession) -> (path: String, offset: Int)? {
286 guard let clock = running else { return nil }
287 return lineLocation(path: clock.path, start: clock.start, session)
288 }
289
290 private func lineLocation(path: String, start: String, _ session: DocumentSession) -> (path: String, offset: Int)? {
291 guard let text = Self.text(path, session) else { return nil }
292 let range = (text as NSString).range(of: "CLOCK: [\(start)]")
293 return range.location == NSNotFound ? (path, 0) : (path, range.location)
294 }
295
296 /// The running clock's entry.
297 private func runningTask(_ session: DocumentSession) -> ClockTask? {
298 guard let line = location(session), let text = Self.text(line.path, session) else { return nil }
299 return ClockTask.at(line.offset, in: text, path: line.path)
300 }
301
302 private func isRunning(path: String, heading: Int, _ session: DocumentSession) -> Bool {
303 guard running?.path == path, let current = entry(session) else { return false }
304 return current.offset == heading
305 }
306
307 // MARK: - History
308
309 private func push(_ task: ClockTask, _ session: DocumentSession) {
310 history = ClockHistory.push(task, onto: history, length: OrgPreferences.clockHistoryLength(defaults)) { Self.text($0, session) }
311 }
312
313 /// Where a remembered entry's heading is now.
314 public func locate(_ task: ClockTask, _ session: DocumentSession) -> (path: String, offset: Int)? {
315 Self.text(task.path, session).flatMap { task.locate(in: $0) }.map { (task.path, $0) }
316 }
317
318 /// `org-clock-mark-default-task` for the heading under the caret.
319 public func markDefault(_ session: DocumentSession) -> String {
320 guard let path = session.path, session.document != nil else { return "No file is open." }
321 return markDefault(session, path: path, at: session.caret)
322 }
323
324 /// `org-clock-mark-default-task` for the heading containing `offset` in `path`.
325 public func markDefault(_ session: DocumentSession, path: String, at offset: Int) -> String {
326 guard let text = Self.text(path, session) else { return "Can't read \(path)" }
327 guard let task = ClockTask.at(offset, in: text, path: path) else { return "Before first headline" }
328 defaultTask = task
329 return "Default clock task: \(task.title)"
330 }
331
332 /// `org-clock-select-task`'s entries, or nil with no recent clock.
333 public func selection(_ session: DocumentSession) -> [ClockHistory.Choice]? {
334 ClockHistory.selection(
335 defaultTask: defaultTask, interrupted: interruptedTask, current: running == nil ? nil : runningTask(session), history: history
336 ) { Self.text($0, session) }
337 }
338
339 /// `org-clock-select-task`: the chosen entry, nil when the question is left with `q`,
340 /// `x` or Escape, or an error message.
341 public func chooseTask(_ session: DocumentSession, prompt: String, ask: Ask) async -> Result<ClockTask?, ClockResolution.Failure> {
342 guard let choices = selection(session) else { return .failure(.init(message: "No recent clock")) }
343 guard let answer = await ask(Prompt(key: "clock-task", message: prompt, fast: ClockHistory.fastSelection(choices))),
344 let key = answer.first, key != "q", key != "x" else { return .success(nil) }
345 guard let choice = choices.first(where: { $0.key == key }) else { return .failure(.init(message: "Invalid task choice \(key)")) }
346 return .success(choice.task)
347 }
348
349 /// `org-clock-goto`: the running clock, else the most recent entry clocked.
350 public func goto(_ session: DocumentSession) -> (location: (path: String, offset: Int)?, message: String?) {
351 if let location = location(session) { return (location, nil) }
352 if let recent = history.first, let location = locate(recent, session) {
353 return (location, "No running clock, this is the most recently clocked task")
354 }
355 return (nil, "No active or recent clock task")
356 }
357
358 /// `org-clock-goto` with a prefix argument: an entry from the selection.
359 public func gotoRecent(_ session: DocumentSession, ask: Ask) async -> (location: (path: String, offset: Int)?, message: String?) {
360 switch await chooseTask(session, prompt: "Select task to go to: ", ask: ask) {
361 case .failure(let failure): return (nil, failure.message)
362 case .success(nil): return (nil, "No task selected")
363 case .success(let task?):
364 guard let location = locate(task, session) else { return (nil, "\(task.title) isn't in \((task.path as NSString).lastPathComponent) any more") }
365 return (location, nil)
366 }
367 }
368
369 // MARK: - Clocking in with questions
370
371 /// Where an interactive clock-in goes.
372 public enum Target {
373 /// The heading under the caret (`org-clock-in`).
374 case caret
375 /// An entry chosen from the selection (`org-clock-in` with a prefix argument).
376 case select
377 /// The most recent entry (`org-clock-in-last`).
378 case last
379 /// A remembered entry.
380 case task(ClockTask)
381 /// The heading containing `offset` in `path` (the agenda's `org-agenda-clock-in`, a
382 /// capture template's `clock-in`).
383 case entry(path: String, offset: Int)
384 }
385
386 /// `org-clock-in` as a command: dangling clocks in `paths` are resolved first when no
387 /// clock runs (`org-clock-auto-clock-resolution` `when-no-clock-is-running`), and a clock
388 /// stopped with `K`, `S` or `T` offers its time as the start.
389 public func clockIn(_ session: DocumentSession, target: Target, paths: [String], ask: Ask, now: () -> Date = Date.init) async -> Outcome {
390 var outcome = Outcome()
391 if case .last = target, history.isEmpty {
392 outcome.messages.append("No last clock")
393 return outcome
394 }
395 var target = target
396 // Resolving may edit the entry's file, so its heading is found again afterwards.
397 if case .entry(let path, let offset) = target {
398 guard let text = Self.text(path, session) else {
399 outcome.messages.append("Can't read \(path)")
400 return outcome
401 }
402 guard let task = ClockTask.at(offset, in: text, path: path) else {
403 outcome.messages.append("Before first headline")
404 return outcome
405 }
406 target = .task(task)
407 }
408 let wasRunning = running != nil
409 let stopped = leftover
410 if !wasRunning {
411 leftover = nil
412 for clock in openClocks(session, paths: paths) {
413 let minutes = Int(now().timeIntervalSince(clock.startedAt) / 60)
414 let result = await resolve(
415 clock, description: "Dangling clock started \(minutes) mins ago", lastValid: clock.startedAt, clockingIn: true, session, ask: ask, now: now
416 )
417 outcome.messages += result.messages
418 if let jump = result.jump { outcome.jump = jump }
419 }
420 }
421 let location: (path: String, offset: Int)
422 switch target {
423 case .caret:
424 guard let path = session.path, session.document != nil else {
425 outcome.messages.append("No file is open.")
426 return outcome
427 }
428 location = (path, session.caret)
429 case .select:
430 switch await chooseTask(session, prompt: "Clock-in on task: ", ask: ask) {
431 case .failure(let failure):
432 outcome.messages.append(failure.message)
433 return outcome
434 case .success(nil):
435 outcome.messages.append("Abort")
436 return outcome
437 case .success(let task?):
438 guard let found = locate(task, session) else {
439 outcome.messages.append("\(task.title) isn't in \((task.path as NSString).lastPathComponent) any more")
440 return outcome
441 }
442 location = found
443 }
444 case .last, .task, .entry:
445 let task: ClockTask
446 if case .task(let chosen) = target { task = chosen } else { task = history[0] }
447 guard let found = locate(task, session) else {
448 outcome.messages.append("\(task.title) isn't in \((task.path as NSString).lastPathComponent) any more")
449 return outcome
450 }
451 location = found
452 }
453 var start = now()
454 if let stopped, !isRunning(path: location.path, heading: headingStart(location, session) ?? -1, session) {
455 let minutes = Int(start.timeIntervalSince(stopped) / 60)
456 let answer = await ask(Prompt(
457 key: "clock-leftover", message: "You stopped another clock \(minutes) mins ago; start this one from then? (y or n) ",
458 fast: FastSelection(items: [.option(key: "y", name: "yes"), .option(key: "n", name: "no")], multiple: false)
459 ))
460 if answer == "y" { start = stopped }
461 }
462 let message = clockIn(session, path: location.path, at: location.offset, now: start)
463 if case .last = target, !wasRunning, let running {
464 outcome.messages.append("Clocking back: \(running.heading) (in \((running.path as NSString).lastPathComponent))")
465 } else {
466 outcome.messages.append(message)
467 }
468 return outcome
469 }
470
471 private func headingStart(_ location: (path: String, offset: Int), _ session: DocumentSession) -> Int? {
472 guard let text = Self.text(location.path, session) else { return nil }
473 return DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= location.offset }?.headingRange.lowerBound
474 }
475
476 // MARK: - Clocks started and stopped elsewhere
477
478 /// Brings the running clock in line with the open `CLOCK:` lines of `paths`, so that a
479 /// clock started or stopped in Emacs, or on another device, is the one orgstar knows: the
480 /// running clock ends when its line was closed or removed, and with none running, the most
481 /// recently started of the open clocks not seen before becomes the running one. Others stay
482 /// dangling, for `org-resolve-clocks` at the next clock in. Returns a message when
483 /// something changed.
484 @discardableResult
485 public func sync(_ session: DocumentSession, paths: [String]) -> String? {
486 guard !isResolving else { return nil }
487 let open = openClocks(session, paths: paths)
488 let fresh = open.filter { !seenOpen.contains($0.path + "\u{0}" + $0.start) }
489 seenOpen.formUnion(open.map { $0.path + "\u{0}" + $0.start })
490 if let running {
491 guard paths.contains(running.path) || session.openDocuments.contains(where: { $0.path == running.path }) else { return nil }
492 // Its line was closed or removed elsewhere; a file that can't be read says nothing.
493 guard !open.contains(where: isActive), Self.text(running.path, session) != nil else { return nil }
494 notifications?.remove([Self.effortReminderID])
495 self.running = nil
496 watched = nil
497 save()
498 return "The clock in \"\(running.heading)\" was stopped elsewhere"
499 }
500 guard let newest = fresh.max(by: { $0.startedAt < $1.startedAt }) else { return nil }
501 running = Running(path: newest.path, start: newest.start, heading: newest.heading, startedAt: newest.startedAt)
502 if let text = Self.text(newest.path, session), case let offset = (text as NSString).range(of: "CLOCK: [\(newest.start)]").location, offset != NSNotFound {
503 let heading = DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= offset }?.headingRange.lowerBound
504 if let heading, let task = ClockTask.at(heading, in: text, path: newest.path) { push(task, session) }
505 }
506 save()
507 watched = clockedHeading(newest.path, session)
508 return "Clock running in \"\(newest.heading)\" since [\(newest.start)]"
509 }
510
511 // MARK: - Resolving clocks
512
513 /// `org-find-open-clocks` over `paths` and the open org buffers.
514 public func openClocks(_ session: DocumentSession, paths: [String]) -> [OpenClock] {
515 // A file open under another spelling of its path is read from its buffer.
516 func resolved(_ path: String) -> String { URL(fileURLWithPath: path).resolvingSymlinksInPath().path }
517 var open: [String: String] = [:]
518 for document in session.openDocuments { open[resolved(document.path)] = document.path }
519 var seen = Set<String>()
520 let all = (session.openDocuments.map(\.path).filter { $0.hasSuffix(".org") } + paths.map { open[resolved($0)] ?? $0 })
521 .filter { seen.insert(resolved($0)).inserted }
522 var clocks: [OpenClock] = []
523 for path in all {
524 guard let text = Self.text(path, session), text.contains("CLOCK: [") else { continue }
525 let open = ClockResolution.openClocks(in: text)
526 guard !open.isEmpty else { continue }
527 let headings = DocumentModel(tree: OrgParser.parse(text)).headings
528 for clock in open {
529 guard let startedAt = ClockResolution.date(of: clock.start) else { continue }
530 let heading = headings.last { $0.headingRange.lowerBound <= clock.offset }?.title ?? ""
531 clocks.append(OpenClock(path: path, start: clock.start, startedAt: startedAt, heading: heading))
532 }
533 }
534 return clocks
535 }
536
537 private func isActive(_ clock: OpenClock) -> Bool {
538 running?.path == clock.path && running?.start == clock.start
539 }
540
541 /// `org-resolve-clocks`: every open clock in `paths`, the running one included.
542 public func resolveOpenClocks(_ session: DocumentSession, paths: [String], ask: Ask, now: () -> Date = Date.init) async -> Outcome {
543 var outcome = Outcome()
544 let clocks = openClocks(session, paths: paths)
545 guard !clocks.isEmpty else {
546 outcome.messages.append("No open clocks")
547 return outcome
548 }
549 for clock in clocks {
550 let minutes = Int(now().timeIntervalSince(clock.startedAt) / 60)
551 let result = await resolve(
552 clock, description: "Dangling clock started \(minutes) mins ago", lastValid: clock.startedAt, clockingIn: false, session, ask: ask, now: now
553 )
554 outcome.messages += result.messages
555 if let jump = result.jump { outcome.jump = jump }
556 }
557 return outcome
558 }
559
560 /// `org-resolve-clocks-if-idle`: the running clock after the user was idle since `idleSince`.
561 public func resolveIdle(_ session: DocumentSession, idleSince: Date, ask: Ask, now: () -> Date = Date.init) async -> Outcome {
562 guard let running, !isResolving else { return Outcome() }
563 let clock = OpenClock(path: running.path, start: running.start, startedAt: running.startedAt, heading: running.heading)
564 let minutes = now().timeIntervalSince(idleSince) / 60
565 return await resolve(
566 clock, description: String(format: "Clocked in & idle for %.1f mins", minutes), lastValid: idleSince, clockingIn: false, session, ask: ask, now: now
567 )
568 }
569
570 /// `org-clock-resolve`: asks what to do with `clock`'s time since `lastValid` and does it.
571 func resolve(
572 _ clock: OpenClock, description: String, lastValid: Date, clockingIn: Bool, _ session: DocumentSession, ask: Ask, now: () -> Date
573 ) async -> Outcome {
574 var outcome = Outcome()
575 // An earlier answer may have closed it.
576 guard let text = Self.text(clock.path, session), ClockResolution.openClocks(in: text).contains(where: { $0.start == clock.start }) else {
577 return outcome
578 }
579 isResolving = true
580 defer { isResolving = false }
581 var key: Character = "q"
582 while true {
583 guard let answer = await ask(Prompt(key: "clock-resolve", message: description + ClockResolution.keyHint, fast: ClockResolution.menu)) else {
584 return outcome
585 }
586 if let c = answer.first, ClockResolution.keys.contains(c) {
587 key = c
588 break
589 }
590 }
591 var minutes: Int?
592 var defaultMinutes: Int?
593 switch ClockResolution.input(for: key) {
594 case .minutes(let prompt):
595 let fallback = ClockResolution.defaultMinutes(lastValid: lastValid, now: now())
596 defaultMinutes = fallback
597 while minutes == nil {
598 guard let answer = await ask(Prompt(key: "clock-minutes", message: "\(prompt) (default \(fallback)): ")) else { return outcome }
599 let trimmed = answer.trimmingCharacters(in: .whitespaces)
600 minutes = trimmed.isEmpty ? fallback : Int(trimmed)
601 }
602 case .date:
603 guard let answer = await ask(Prompt(key: "clock-date", message: "Date+time: ", date: .init(defaultDate: nil))) else { return outcome }
604 let calendar = Calendar.current
605 let read = ReadDate.read(answer, default: nil, now: now(), calendar: calendar)
606 guard let date = calendar.date(from: read.components(calendar)) else { return outcome }
607 minutes = ClockResolution.minutes(from: lastValid, to: date)
608 defaultMinutes = ClockResolution.defaultMinutes(lastValid: lastValid, now: now())
609 case nil:
610 break
611 }
612 let plan: ClockResolution.Plan
613 do {
614 plan = try ClockResolution.plan(
615 key: key, minutes: minutes, start: clock.startedAt, lastValid: lastValid, now: now(), active: isActive(clock),
616 clockingIn: clockingIn, defaultMinutes: defaultMinutes
617 )
618 } catch {
619 outcome.messages.append((error as? ClockResolution.Failure)?.message ?? "\(error)")
620 return outcome
621 }
622 outcome.messages = apply(plan, to: clock, session)
623 if plan.jump { outcome.jump = lineLocation(path: clock.path, start: clock.start, session) }
624 return outcome
625 }
626
627 /// Carries out `plan` on `clock`'s line.
628 func apply(_ plan: ClockResolution.Plan, to clock: OpenClock, _ session: DocumentSession) -> [String] {
629 var messages: [String] = []
630 let active = isActive(clock)
631 let task = lineLocation(path: clock.path, start: clock.start, session).flatMap { line in
632 Self.text(clock.path, session).flatMap { ClockTask.at(line.offset, in: $0, path: clock.path) }
633 }
634 for step in plan.steps {
635 switch step {
636 case .cancel:
637 if active {
638 messages.append(clockOut(session, cancel: true))
639 } else {
640 messages.append(perform(ClockOut(start: clock.start, cancel: true), clock, session, now: Date()) ?? "Clock canceled")
641 }
642 case .clockOut(let time):
643 if active {
644 messages.append(clockOut(session, now: time))
645 } else {
646 let minutes = Int(time.timeIntervalSince(clock.startedAt) / 60)
647 messages.append(perform(ClockOut(start: clock.start), clock, session, now: time)
648 ?? String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60))
649 }
650 case .clockIn(let time):
651 guard let task, let location = locate(task, session) else { continue }
652 messages.append(clockIn(session, path: location.path, at: location.offset, now: time))
653 case .resume:
654 if running != nil { messages.append(clockOut(session, now: Date())) }
655 running = Running(path: clock.path, start: clock.start, heading: clock.heading, startedAt: clock.startedAt)
656 if let task { push(task, session) }
657 save()
658 watched = clockedHeading(clock.path, session)
659 remindAtEffort(session)
660 messages.append("Clock starts at [\(clock.start)]")
661 }
662 }
663 if plan.setsLeftover { leftover = plan.leftover }
664 return messages
665 }
666
667 /// Runs a clock command on a clock that isn't the running one; nil when it worked.
668 private func perform(_ command: ClockOut, _ clock: OpenClock, _ session: DocumentSession, now: Date) -> String? {
669 switch session.perform(command, path: clock.path, at: 0, expect: nil, now: now) {
670 case .commit: return nil
671 case .failed(let message): return message
672 default: return "Can't change the clock."
673 }
674 }
675}