Sources/Orgstar/ClockViews.swift

62e3c7dafd265558ed379cccd7ca5877f42fafec
orgstar/Sources/Orgstar/ClockViews.swift

269 lines · 10808 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 = NSImage(systemSymbolName: "clock", accessibilityDescription: String(localized: "Clocked in"))
154            button.imagePosition = .imageLeading
155            button.title = clockElapsed(running, now: Date())
156        } else {
157            button.image = NSImage(systemSymbolName: "star", accessibilityDescription: "orgstar")
158            button.title = ""
159        }
160    }
161
162    @objc private func choose(_ sender: NSMenuItem) {
163        if let id = sender.representedObject as? String {
164            NSApp.activate()
165            run(id)
166        }
167    }
168
169    @objc private func open(_ sender: NSMenuItem) {
170        if case .entry(let path, let offset)? = sender.representedObject as? AppLink {
171            NSApp.activate()
172            jump(path, offset)
173        }
174    }
175
176    @objc private func activate() {
177        NSApp.activate()
178    }
179}
180
181/// Clocked time per day and heading (`ClockReport.timeReport`) for chosen files and dates.
182struct ClockReportView: View {
183    let workspace: WorkspaceModel
184    /// Open buffers are read as they are, unsaved edits included, as the agenda reads them.
185    let session: DocumentSession
186    @State private var start = Calendar.current.date(byAdding: .day, value: -6, to: Date()) ?? Date()
187    @State private var end = Date()
188    @State private var limit = false
189    @State private var selected: Set<String> = []
190    @State private var report = ""
191
192    private var candidates: [FileEntry] { workspace.files.filter { $0.kind == .org } }
193
194    var body: some View {
195        HSplitView {
196            List(candidates, selection: $selected) { file in
197                Text(file.relativePath).tag(file.path)
198            }
199            .frame(minWidth: 180, idealWidth: 220, maxWidth: 320)
200            VStack(alignment: .leading, spacing: 8) {
201                HStack {
202                    Toggle("From", isOn: $limit)
203                    DatePicker("", selection: $start, displayedComponents: .date).labelsHidden().disabled(!limit)
204                    Text("to")
205                    DatePicker("", selection: $end, displayedComponents: .date).labelsHidden().disabled(!limit)
206                    Spacer()
207                    Button("Copy") {
208                        NSPasteboard.general.clearContents()
209                        NSPasteboard.general.setString(report, forType: .string)
210                    }
211                    Button("Save…", action: saveReport)
212                }
213                ScrollView([.horizontal, .vertical]) {
214                    Text(report.isEmpty ? "Choose files with clocked time." : report)
215                        .font(.body.monospaced())
216                        .textSelection(.enabled)
217                        .fixedSize()
218                        .padding(4)
219                }
220                .defaultScrollAnchor(.topLeading)
221                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
222            }
223            .padding(12)
224        }
225        .navigationTitle("Clock Report")
226        .onAppear {
227            if selected.isEmpty {
228                selected = Set(candidates.filter { text(of: $0.path)?.contains("CLOCK: [") ?? false }.map(\.path))
229            }
230            compute()
231        }
232        .onChange(of: selected) { compute() }
233        .onChange(of: session.editVersion) { compute() }
234        .onChange(of: session.dirtyPaths) { compute() }
235        .onChange(of: start) { compute() }
236        .onChange(of: end) { compute() }
237        .onChange(of: limit) { compute() }
238    }
239
240    private func day(_ date: Date) -> String {
241        let c = Calendar.current.dateComponents([.year, .month, .day], from: date)
242        return String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
243    }
244
245    /// The file's text: its open buffer, else the file on disk.
246    private func text(of path: String) -> String? {
247        session.openTexts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8))
248    }
249
250    private func compute() {
251        var entries: [ClockReport.Entry] = []
252        for path in selected.sorted() {
253            guard let text = text(of: path) else { continue }
254            entries += ClockReport.entries(text, settings: workspace.settings.org)
255        }
256        report = selected.isEmpty ? "" : ClockReport.timeReport(entries, start: limit ? day(start) : nil, end: limit ? day(end) : nil)
257    }
258
259    private func saveReport() {
260        let panel = NSSavePanel()
261        panel.nameFieldStringValue = "time-report.org"
262        guard panel.runModal() == .OK, let url = panel.url else { return }
263        do {
264            try report.write(to: url, atomically: true, encoding: .utf8)
265        } catch {
266            NSAlert(error: error).runModal()
267        }
268    }
269}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form