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