Sources/Orgstar/ClockViews.swift
268 lines · 10678 bytes
1import AppKit
2import CoreGraphics
3import OrgApp
4import OrgCore
5import OrgEditorAppKit
6import SwiftUI
7
8/// Elapsed time of the running clock, `H:MM`.
9func clockElapsed(_ running: ClockModel.Running, now: Date) -> String {
10 let minutes = max(0, Int(now.timeIntervalSince(running.startedAt) / 60))
11 return String(format: "%d:%02d", minutes / 60, minutes % 60)
12}
13
14/// What the menu bar item shows.
15struct ClockMenuState: Equatable {
16 let running: ClockModel.Running?
17 let history: [ClockTask]
18 /// `menu-bar-item`: the item stays when no clock runs.
19 var always = false
20 /// Today's agenda, overdue entries first.
21 var today: [AgendaSnapshot.Row] = []
22}
23
24/// `org-user-idle-seconds` on macOS: time since the last keyboard or mouse input anywhere.
25enum ClockIdle {
26 static func seconds() -> Double {
27 // `kCGAnyInputEventType`.
28 CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: CGEventType(rawValue: ~0)!)
29 }
30}
31
32/// The clock history in a menu: clocking in to an entry runs `app.clock.history.N`.
33struct RecentClocks: View {
34 let clock: ClockModel
35 let run: (String) -> Void
36
37 var body: some View {
38 if !clock.history.isEmpty {
39 Section("Recent Entries") {
40 ForEach(Array(clock.history.enumerated()), id: \.offset) { index, task in
41 Button(task.title) { run("app.clock.history.\(index)") }
42 .help("Clock in to \(task.title) in \((task.path as NSString).lastPathComponent)")
43 }
44 }
45 }
46 }
47}
48
49/// Org ▸ Clock: the clock commands, with their keys, and the recent entries.
50struct ClockMenu: View {
51 let commands: AppCommands
52 let clock: ClockModel
53
54 var body: some View {
55 Menu("Clock") {
56 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.clock.") }, id: \.id) { command in
57 Button {
58 commands.run(command.id)
59 } label: {
60 Text(command.localizedTitle)
61 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
62 }
63 }
64 RecentClocks(clock: clock) { commands.run($0) }
65 }
66 }
67}
68
69/// The menu bar item: while a clock runs, the elapsed time and the clock commands; with
70/// `always`, there all the time, with capture, the agenda and today's entries too.
71@MainActor
72final class ClockStatusItem: NSObject {
73 /// Today's entries the menu lists before "more".
74 static let rowLimit = 12
75
76 private var item: NSStatusItem?
77 private var timer: Timer?
78 private var running: ClockModel.Running?
79 private let run: (String) -> Void
80 private let jump: (String, Int) -> Void
81
82 init(run: @escaping (String) -> Void, jump: @escaping (String, Int) -> Void) {
83 self.run = run
84 self.jump = jump
85 }
86
87 func update(_ state: ClockMenuState) {
88 running = state.running
89 guard state.running != nil || state.always else {
90 timer?.invalidate()
91 timer = nil
92 if let item { NSStatusBar.system.removeStatusItem(item) }
93 item = nil
94 return
95 }
96 if item == nil {
97 item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
98 timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] _ in
99 MainActor.assumeIsolated { self?.refresh() }
100 }
101 }
102 let menu = NSMenu()
103 if state.always {
104 add(String(localized: "Capture…"), "app.capture", to: menu)
105 add(String(localized: "Agenda"), "app.agenda", to: menu)
106 menu.addItem(.separator())
107 menu.addItem(NSMenuItem.sectionHeader(title: String(localized: "Today")))
108 let rows = state.today.filter { !$0.isDone }
109 if rows.isEmpty { menu.addItem(withTitle: String(localized: "Nothing scheduled"), action: nil, keyEquivalent: "") }
110 for row in rows.prefix(Self.rowLimit) {
111 let title = [row.gutter, row.todo ?? "", row.title].filter { !$0.isEmpty }.joined(separator: " ")
112 let entry = NSMenuItem(title: title, action: row.link == nil ? nil : #selector(open(_:)), keyEquivalent: "")
113 entry.target = self
114 entry.representedObject = row.link
115 menu.addItem(entry)
116 }
117 if rows.count > Self.rowLimit { add(String(localized: "\(rows.count - Self.rowLimit) more…"), "app.agenda", to: menu) }
118 menu.addItem(.separator())
119 }
120 var commands = [("Clock In to Recent Entry…", "app.clock.in-recent"), ("Clock Report", "app.clock.report")]
121 if let running = state.running {
122 menu.addItem(withTitle: running.heading, action: nil, keyEquivalent: "")
123 menu.addItem(.separator())
124 commands.insert(contentsOf: [("Clock Out", "app.clock.out"), ("Cancel Clock", "app.clock.cancel"), ("Go to Clocked Entry", "app.clock.goto")], at: 0)
125 }
126 for (title, id) in commands { add(title, id, to: menu) }
127 let recent = state.history.map(\.title)
128 if !recent.isEmpty {
129 menu.addItem(.separator())
130 menu.addItem(NSMenuItem.sectionHeader(title: "Recent Entries"))
131 for (index, title) in recent.enumerated() { add(title, "app.clock.history.\(index)", to: menu) }
132 }
133 if state.always {
134 menu.addItem(.separator())
135 let show = NSMenuItem(title: String(localized: "Open orgstar"), action: #selector(activate), keyEquivalent: "")
136 show.target = self
137 menu.addItem(show)
138 }
139 item?.menu = menu
140 refresh()
141 }
142
143 private func add(_ title: String, _ id: String, to menu: NSMenu) {
144 let entry = NSMenuItem(title: title, action: #selector(choose(_:)), keyEquivalent: "")
145 entry.target = self
146 entry.representedObject = id
147 menu.addItem(entry)
148 }
149
150 private func refresh() {
151 guard let button = item?.button else { return }
152 if let running {
153 button.image = nil
154 button.title = "⏱ " + clockElapsed(running, now: Date())
155 } else {
156 button.image = NSImage(systemSymbolName: "star", accessibilityDescription: "orgstar")
157 button.title = ""
158 }
159 }
160
161 @objc private func choose(_ sender: NSMenuItem) {
162 if let id = sender.representedObject as? String {
163 NSApp.activate()
164 run(id)
165 }
166 }
167
168 @objc private func open(_ sender: NSMenuItem) {
169 if case .entry(let path, let offset)? = sender.representedObject as? AppLink {
170 NSApp.activate()
171 jump(path, offset)
172 }
173 }
174
175 @objc private func activate() {
176 NSApp.activate()
177 }
178}
179
180/// Clocked time per day and heading (`ClockReport.timeReport`) for chosen files and dates.
181struct ClockReportView: View {
182 let workspace: WorkspaceModel
183 /// Open buffers are read as they are, unsaved edits included, as the agenda reads them.
184 let session: DocumentSession
185 @State private var start = Calendar.current.date(byAdding: .day, value: -6, to: Date()) ?? Date()
186 @State private var end = Date()
187 @State private var limit = false
188 @State private var selected: Set<String> = []
189 @State private var report = ""
190
191 private var candidates: [FileEntry] { workspace.files.filter { $0.kind == .org } }
192
193 var body: some View {
194 HSplitView {
195 List(candidates, selection: $selected) { file in
196 Text(file.relativePath).tag(file.path)
197 }
198 .frame(minWidth: 180, idealWidth: 220, maxWidth: 320)
199 VStack(alignment: .leading, spacing: 8) {
200 HStack {
201 Toggle("From", isOn: $limit)
202 DatePicker("", selection: $start, displayedComponents: .date).labelsHidden().disabled(!limit)
203 Text("to")
204 DatePicker("", selection: $end, displayedComponents: .date).labelsHidden().disabled(!limit)
205 Spacer()
206 Button("Copy") {
207 NSPasteboard.general.clearContents()
208 NSPasteboard.general.setString(report, forType: .string)
209 }
210 Button("Save…", action: saveReport)
211 }
212 ScrollView([.horizontal, .vertical]) {
213 Text(report.isEmpty ? "Choose files with clocked time." : report)
214 .font(.body.monospaced())
215 .textSelection(.enabled)
216 .fixedSize()
217 .padding(4)
218 }
219 .defaultScrollAnchor(.topLeading)
220 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
221 }
222 .padding(12)
223 }
224 .navigationTitle("Clock Report")
225 .onAppear {
226 if selected.isEmpty {
227 selected = Set(candidates.filter { text(of: $0.path)?.contains("CLOCK: [") ?? false }.map(\.path))
228 }
229 compute()
230 }
231 .onChange(of: selected) { compute() }
232 .onChange(of: session.editVersion) { compute() }
233 .onChange(of: session.dirtyPaths) { compute() }
234 .onChange(of: start) { compute() }
235 .onChange(of: end) { compute() }
236 .onChange(of: limit) { compute() }
237 }
238
239 private func day(_ date: Date) -> String {
240 let c = Calendar.current.dateComponents([.year, .month, .day], from: date)
241 return String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
242 }
243
244 /// The file's text: its open buffer, else the file on disk.
245 private func text(of path: String) -> String? {
246 session.openTexts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8))
247 }
248
249 private func compute() {
250 var entries: [ClockReport.Entry] = []
251 for path in selected.sorted() {
252 guard let text = text(of: path) else { continue }
253 entries += ClockReport.entries(text, settings: workspace.settings.org)
254 }
255 report = selected.isEmpty ? "" : ClockReport.timeReport(entries, start: limit ? day(start) : nil, end: limit ? day(end) : nil)
256 }
257
258 private func saveReport() {
259 let panel = NSSavePanel()
260 panel.nameFieldStringValue = "time-report.org"
261 guard panel.runModal() == .OK, let url = panel.url else { return }
262 do {
263 try report.write(to: url, atomically: true, encoding: .utf8)
264 } catch {
265 NSAlert(error: error).runModal()
266 }
267 }
268}