Sources/OrgApp/ClockModel.swift
708 lines · 37812 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.map { Self.shareable($0, session) }
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: session.shareableTitle(entry.title, path: path, heading: heading), 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 // The history is kept in the clock's file and shown by the widgets.
311 history = ClockHistory.push(task, onto: history, length: OrgPreferences.clockHistoryLength(defaults)) { Self.text($0, session) }
312 .map { Self.shareable($0, session) }
313 }
314
315 /// `task` with a placeholder title when its heading is encrypted on disk.
316 static func shareable(_ task: ClockTask, _ session: DocumentSession) -> ClockTask {
317 guard task.titleHidden != true, let heading = text(task.path, session).flatMap(task.locate) else { return task }
318 let shown = session.shareableTitle(task.title, path: task.path, heading: heading)
319 return shown == task.title ? task : task.hiding(shown)
320 }
321
322 /// Where a remembered entry's heading is now.
323 public func locate(_ task: ClockTask, _ session: DocumentSession) -> (path: String, offset: Int)? {
324 Self.text(task.path, session).flatMap { task.locate(in: $0) }.map { (task.path, $0) }
325 }
326
327 /// `org-clock-mark-default-task` for the heading under the caret.
328 public func markDefault(_ session: DocumentSession) -> String {
329 guard let path = session.path, session.document != nil else { return "No file is open." }
330 return markDefault(session, path: path, at: session.caret)
331 }
332
333 /// `org-clock-mark-default-task` for the heading containing `offset` in `path`.
334 public func markDefault(_ session: DocumentSession, path: String, at offset: Int) -> String {
335 guard let text = Self.text(path, session) else { return "Can't read \(path)" }
336 guard let task = ClockTask.at(offset, in: text, path: path) else { return "Before first headline" }
337 defaultTask = Self.shareable(task, session)
338 return "Default clock task: \(task.title)"
339 }
340
341 /// `org-clock-select-task`'s entries, or nil with no recent clock.
342 public func selection(_ session: DocumentSession) -> [ClockHistory.Choice]? {
343 ClockHistory.selection(
344 defaultTask: defaultTask, interrupted: interruptedTask, current: running == nil ? nil : runningTask(session), history: history
345 ) { Self.text($0, session) }
346 }
347
348 /// `org-clock-select-task`: the chosen entry, nil when the question is left with `q`,
349 /// `x` or Escape, or an error message.
350 public func chooseTask(_ session: DocumentSession, prompt: String, ask: Ask) async -> Result<ClockTask?, ClockResolution.Failure> {
351 guard let choices = selection(session) else { return .failure(.init(message: "No recent clock")) }
352 guard let answer = await ask(Prompt(key: "clock-task", message: prompt, fast: ClockHistory.fastSelection(choices))),
353 let key = answer.first, key != "q", key != "x" else { return .success(nil) }
354 guard let choice = choices.first(where: { $0.key == key }) else { return .failure(.init(message: "Invalid task choice \(key)")) }
355 return .success(choice.task)
356 }
357
358 /// `org-clock-goto`: the running clock, else the most recent entry clocked.
359 public func goto(_ session: DocumentSession) -> (location: (path: String, offset: Int)?, message: String?) {
360 if let location = location(session) { return (location, nil) }
361 if let recent = history.first, let location = locate(recent, session) {
362 return (location, "No running clock, this is the most recently clocked task")
363 }
364 return (nil, "No active or recent clock task")
365 }
366
367 /// `org-clock-goto` with a prefix argument: an entry from the selection.
368 public func gotoRecent(_ session: DocumentSession, ask: Ask) async -> (location: (path: String, offset: Int)?, message: String?) {
369 switch await chooseTask(session, prompt: "Select task to go to: ", ask: ask) {
370 case .failure(let failure): return (nil, failure.message)
371 case .success(nil): return (nil, "No task selected")
372 case .success(let task?):
373 guard let location = locate(task, session) else { return (nil, "\(task.title) isn't in \((task.path as NSString).lastPathComponent) any more") }
374 return (location, nil)
375 }
376 }
377
378 // MARK: - Clocking in with questions
379
380 /// Where an interactive clock-in goes.
381 public enum Target {
382 /// The heading under the caret (`org-clock-in`).
383 case caret
384 /// An entry chosen from the selection (`org-clock-in` with a prefix argument).
385 case select
386 /// The most recent entry (`org-clock-in-last`).
387 case last
388 /// A remembered entry.
389 case task(ClockTask)
390 /// The heading containing `offset` in `path` (the agenda's `org-agenda-clock-in`, a
391 /// capture template's `clock-in`).
392 case entry(path: String, offset: Int)
393 }
394
395 /// `org-clock-in` as a command: dangling clocks in `paths` are resolved first when no
396 /// clock runs (`org-clock-auto-clock-resolution` `when-no-clock-is-running`), and a clock
397 /// stopped with `K`, `S` or `T` offers its time as the start.
398 public func clockIn(_ session: DocumentSession, target: Target, paths: [String], ask: Ask, now: () -> Date = Date.init) async -> Outcome {
399 var outcome = Outcome()
400 if case .last = target, history.isEmpty {
401 outcome.messages.append("No last clock")
402 return outcome
403 }
404 var target = target
405 // Resolving may edit the entry's file, so its heading is found again afterwards.
406 if case .entry(let path, let offset) = target {
407 guard let text = Self.text(path, session) else {
408 outcome.messages.append("Can't read \(path)")
409 return outcome
410 }
411 guard let task = ClockTask.at(offset, in: text, path: path) else {
412 outcome.messages.append("Before first headline")
413 return outcome
414 }
415 target = .task(task)
416 }
417 let wasRunning = running != nil
418 let stopped = leftover
419 if !wasRunning {
420 leftover = nil
421 for clock in openClocks(session, paths: paths) {
422 let minutes = Int(now().timeIntervalSince(clock.startedAt) / 60)
423 let result = await resolve(
424 clock, description: "Dangling clock started \(minutes) mins ago", lastValid: clock.startedAt, clockingIn: true, session, ask: ask, now: now
425 )
426 outcome.messages += result.messages
427 if let jump = result.jump { outcome.jump = jump }
428 }
429 }
430 let location: (path: String, offset: Int)
431 switch target {
432 case .caret:
433 guard let path = session.path, session.document != nil else {
434 outcome.messages.append("No file is open.")
435 return outcome
436 }
437 location = (path, session.caret)
438 case .select:
439 switch await chooseTask(session, prompt: "Clock-in on task: ", ask: ask) {
440 case .failure(let failure):
441 outcome.messages.append(failure.message)
442 return outcome
443 case .success(nil):
444 outcome.messages.append("Abort")
445 return outcome
446 case .success(let task?):
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 case .last, .task, .entry:
454 let task: ClockTask
455 if case .task(let chosen) = target { task = chosen } else { task = history[0] }
456 guard let found = locate(task, session) else {
457 outcome.messages.append("\(task.title) isn't in \((task.path as NSString).lastPathComponent) any more")
458 return outcome
459 }
460 location = found
461 }
462 var start = now()
463 if let stopped, !isRunning(path: location.path, heading: headingStart(location, session) ?? -1, session) {
464 let minutes = Int(start.timeIntervalSince(stopped) / 60)
465 let answer = await ask(Prompt(
466 key: "clock-leftover", message: "You stopped another clock \(minutes) mins ago; start this one from then? (y or n) ",
467 fast: FastSelection(items: [.option(key: "y", name: "yes"), .option(key: "n", name: "no")], multiple: false)
468 ))
469 if answer == "y" { start = stopped }
470 }
471 let message = clockIn(session, path: location.path, at: location.offset, now: start)
472 if case .last = target, !wasRunning, let running {
473 outcome.messages.append("Clocking back: \(running.heading) (in \((running.path as NSString).lastPathComponent))")
474 } else {
475 outcome.messages.append(message)
476 }
477 return outcome
478 }
479
480 private func headingStart(_ location: (path: String, offset: Int), _ session: DocumentSession) -> Int? {
481 guard let text = Self.text(location.path, session) else { return nil }
482 return DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= location.offset }?.headingRange.lowerBound
483 }
484
485 // MARK: - Clocks started and stopped elsewhere
486
487 /// Brings the running clock in line with the open `CLOCK:` lines of `paths`, so that a
488 /// clock started or stopped in Emacs, or on another device, is the one orgstar knows: the
489 /// running clock ends when its line was closed or removed, and with none running, the most
490 /// recently started of the open clocks not seen before becomes the running one. Others stay
491 /// dangling, for `org-resolve-clocks` at the next clock in. Returns a message when
492 /// something changed.
493 @discardableResult
494 public func sync(_ session: DocumentSession, paths: [String]) -> String? {
495 guard !isResolving else { return nil }
496 let open = openClocks(session, paths: paths)
497 let fresh = open.filter { !seenOpen.contains($0.path + "\u{0}" + $0.start) }
498 seenOpen.formUnion(open.map { $0.path + "\u{0}" + $0.start })
499 if let running {
500 guard paths.contains(running.path) || session.openDocuments.contains(where: { $0.path == running.path }) else { return nil }
501 // Its line was closed or removed elsewhere; a file that can't be read says nothing.
502 guard !open.contains(where: isActive), Self.text(running.path, session) != nil else { return nil }
503 notifications?.remove([Self.effortReminderID])
504 self.running = nil
505 watched = nil
506 save()
507 return "The clock in \"\(running.heading)\" was stopped elsewhere"
508 }
509 guard let newest = fresh.max(by: { $0.startedAt < $1.startedAt }) else { return nil }
510 running = Running(path: newest.path, start: newest.start, heading: newest.heading, startedAt: newest.startedAt)
511 if let text = Self.text(newest.path, session), case let offset = (text as NSString).range(of: "CLOCK: [\(newest.start)]").location, offset != NSNotFound {
512 let heading = DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= offset }?.headingRange.lowerBound
513 if let heading, let task = ClockTask.at(heading, in: text, path: newest.path) { push(task, session) }
514 }
515 save()
516 watched = clockedHeading(newest.path, session)
517 return "Clock running in \"\(newest.heading)\" since [\(newest.start)]"
518 }
519
520 // MARK: - Resolving clocks
521
522 /// `org-find-open-clocks` over `paths` and the open org buffers.
523 public func openClocks(_ session: DocumentSession, paths: [String]) -> [OpenClock] {
524 // A file open under another spelling of its path is read from its buffer.
525 func resolved(_ path: String) -> String { URL(fileURLWithPath: path).resolvingSymlinksInPath().path }
526 var open: [String: String] = [:]
527 for document in session.openDocuments { open[resolved(document.path)] = document.path }
528 var seen = Set<String>()
529 let all = (session.openDocuments.map(\.path).filter { $0.hasSuffix(".org") } + paths.map { open[resolved($0)] ?? $0 })
530 .filter { seen.insert(resolved($0)).inserted }
531 var clocks: [OpenClock] = []
532 for path in all {
533 guard let text = Self.text(path, session), text.contains("CLOCK: [") else { continue }
534 let open = ClockResolution.openClocks(in: text)
535 guard !open.isEmpty else { continue }
536 let headings = DocumentModel(tree: OrgParser.parse(text)).headings
537 for clock in open {
538 guard let startedAt = ClockResolution.date(of: clock.start) else { continue }
539 let entry = headings.last { $0.headingRange.lowerBound <= clock.offset }
540 let heading = entry.map { session.shareableTitle($0.title, path: path, heading: $0.headingRange.lowerBound) } ?? ""
541 clocks.append(OpenClock(path: path, start: clock.start, startedAt: startedAt, heading: heading))
542 }
543 }
544 return clocks
545 }
546
547 private func isActive(_ clock: OpenClock) -> Bool {
548 running?.path == clock.path && running?.start == clock.start
549 }
550
551 /// `org-resolve-clocks`: every open clock in `paths`, the running one included.
552 public func resolveOpenClocks(_ session: DocumentSession, paths: [String], ask: Ask, now: () -> Date = Date.init) async -> Outcome {
553 var outcome = Outcome()
554 let clocks = openClocks(session, paths: paths)
555 guard !clocks.isEmpty else {
556 outcome.messages.append("No open clocks")
557 return outcome
558 }
559 for clock in clocks {
560 let minutes = Int(now().timeIntervalSince(clock.startedAt) / 60)
561 let result = await resolve(
562 clock, description: "Dangling clock started \(minutes) mins ago", lastValid: clock.startedAt, clockingIn: false, session, ask: ask, now: now
563 )
564 outcome.messages += result.messages
565 if let jump = result.jump { outcome.jump = jump }
566 }
567 return outcome
568 }
569
570 /// `org-resolve-clocks-if-idle`: the running clock after the user was idle since `idleSince`.
571 public func resolveIdle(_ session: DocumentSession, idleSince: Date, ask: Ask, now: () -> Date = Date.init) async -> Outcome {
572 guard let running, !isResolving else { return Outcome() }
573 let clock = OpenClock(path: running.path, start: running.start, startedAt: running.startedAt, heading: running.heading)
574 let minutes = now().timeIntervalSince(idleSince) / 60
575 return await resolve(
576 clock, description: String(format: "Clocked in & idle for %.1f mins", minutes), lastValid: idleSince, clockingIn: false, session, ask: ask, now: now
577 )
578 }
579
580 /// When every window of the app went to the background, for `cameBack`.
581 @ObservationIgnored private var awayAt: Date?
582
583 /// iOS: the app, all its windows, went to the background at `now`.
584 public func wentAway(at now: Date = Date()) { awayAt = now }
585
586 /// iOS: a window became active. Since when the user was idle, the first time after the
587 /// whole app was away; nil when a window came back while another was in use.
588 public func cameBack(now: Date = Date(), idleMinutes: Int) -> Date? {
589 defer { awayAt = nil }
590 guard let awayAt else { return nil }
591 return Self.idleSince(backgrounded: awayAt, now: now, running: running, idleMinutes: idleMinutes)
592 }
593
594 /// Where iOS has no idle time: since when the user was away, for `resolveIdle`, when the
595 /// app was in the background from `backgrounded` to `now` with `running` going for more
596 /// than `idleMinutes` of that time (`org-clock-idle-time`, 0 for never).
597 public nonisolated static func idleSince(backgrounded: Date, now: Date, running: Running?, idleMinutes: Int) -> Date? {
598 guard idleMinutes > 0, let running else { return nil }
599 let since = max(backgrounded, running.startedAt)
600 return now.timeIntervalSince(since) > Double(idleMinutes * 60) ? since : nil
601 }
602
603 /// `org-clock-resolve`: asks what to do with `clock`'s time since `lastValid` and does it.
604 func resolve(
605 _ clock: OpenClock, description: String, lastValid: Date, clockingIn: Bool, _ session: DocumentSession, ask: Ask, now: () -> Date
606 ) async -> Outcome {
607 var outcome = Outcome()
608 // An earlier answer may have closed it.
609 guard let text = Self.text(clock.path, session), ClockResolution.openClocks(in: text).contains(where: { $0.start == clock.start }) else {
610 return outcome
611 }
612 isResolving = true
613 defer { isResolving = false }
614 var key: Character = "q"
615 while true {
616 guard let answer = await ask(Prompt(key: "clock-resolve", message: description + ClockResolution.keyHint, fast: ClockResolution.menu)) else {
617 return outcome
618 }
619 if let c = answer.first, ClockResolution.keys.contains(c) {
620 key = c
621 break
622 }
623 }
624 var minutes: Int?
625 var defaultMinutes: Int?
626 switch ClockResolution.input(for: key) {
627 case .minutes(let prompt):
628 let fallback = ClockResolution.defaultMinutes(lastValid: lastValid, now: now())
629 defaultMinutes = fallback
630 while minutes == nil {
631 guard let answer = await ask(Prompt(key: "clock-minutes", message: "\(prompt) (default \(fallback)): ")) else { return outcome }
632 let trimmed = answer.trimmingCharacters(in: .whitespaces)
633 minutes = trimmed.isEmpty ? fallback : Int(trimmed)
634 }
635 case .date:
636 guard let answer = await ask(Prompt(key: "clock-date", message: "Date+time: ", date: .init(defaultDate: nil))) else { return outcome }
637 let calendar = Calendar.current
638 let read = ReadDate.read(answer, default: nil, now: now(), calendar: calendar)
639 guard let date = calendar.date(from: read.components(calendar)) else { return outcome }
640 minutes = ClockResolution.minutes(from: lastValid, to: date)
641 defaultMinutes = ClockResolution.defaultMinutes(lastValid: lastValid, now: now())
642 case nil:
643 break
644 }
645 let plan: ClockResolution.Plan
646 do {
647 plan = try ClockResolution.plan(
648 key: key, minutes: minutes, start: clock.startedAt, lastValid: lastValid, now: now(), active: isActive(clock),
649 clockingIn: clockingIn, defaultMinutes: defaultMinutes
650 )
651 } catch {
652 outcome.messages.append((error as? ClockResolution.Failure)?.message ?? "\(error)")
653 return outcome
654 }
655 outcome.messages = apply(plan, to: clock, session)
656 if plan.jump { outcome.jump = lineLocation(path: clock.path, start: clock.start, session) }
657 return outcome
658 }
659
660 /// Carries out `plan` on `clock`'s line.
661 func apply(_ plan: ClockResolution.Plan, to clock: OpenClock, _ session: DocumentSession) -> [String] {
662 var messages: [String] = []
663 let active = isActive(clock)
664 let task = lineLocation(path: clock.path, start: clock.start, session).flatMap { line in
665 Self.text(clock.path, session).flatMap { ClockTask.at(line.offset, in: $0, path: clock.path) }
666 }
667 for step in plan.steps {
668 switch step {
669 case .cancel:
670 if active {
671 messages.append(clockOut(session, cancel: true))
672 } else {
673 messages.append(perform(ClockOut(start: clock.start, cancel: true), clock, session, now: Date()) ?? "Clock canceled")
674 }
675 case .clockOut(let time):
676 if active {
677 messages.append(clockOut(session, now: time))
678 } else {
679 let minutes = Int(time.timeIntervalSince(clock.startedAt) / 60)
680 messages.append(perform(ClockOut(start: clock.start), clock, session, now: time)
681 ?? String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60))
682 }
683 case .clockIn(let time):
684 guard let task, let location = locate(task, session) else { continue }
685 messages.append(clockIn(session, path: location.path, at: location.offset, now: time))
686 case .resume:
687 if running != nil { messages.append(clockOut(session, now: Date())) }
688 running = Running(path: clock.path, start: clock.start, heading: clock.heading, startedAt: clock.startedAt)
689 if let task { push(task, session) }
690 save()
691 watched = clockedHeading(clock.path, session)
692 remindAtEffort(session)
693 messages.append("Clock starts at [\(clock.start)]")
694 }
695 }
696 if plan.setsLeftover { leftover = plan.leftover }
697 return messages
698 }
699
700 /// Runs a clock command on a clock that isn't the running one; nil when it worked.
701 private func perform(_ command: ClockOut, _ clock: OpenClock, _ session: DocumentSession, now: Date) -> String? {
702 switch session.perform(command, path: clock.path, at: 0, expect: nil, now: now) {
703 case .commit: return nil
704 case .failed(let message): return message
705 default: return "Can't change the clock."
706 }
707 }
708}