Sources/Orgstar/CaptureView.swift

62fdf490e1b4bd89900f188ea9cb58718e52d75b
orgstar/Sources/Orgstar/CaptureView.swift history · blame · raw

218 lines · 8905 bytes

  1import AppKit
  2import Carbon.HIToolbox
  3import OrgApp
  4import OrgCore
  5import SwiftUI
  6
  7/// The capture window: pick a template by its key, answer its prompts, edit the entry, and
  8/// ⌘Return files it where the template says, as `org-capture` does.
  9struct CaptureView: View {
 10    let workspace: WorkspaceModel
 11    let session: DocumentSession
 12    let commands: AppCommands
 13    let clock: ClockModel
 14    @State private var templates = CaptureTemplates.defaults
 15    @State private var problem: String?
 16    @State private var template: CaptureTemplate?
 17    @State private var questions: [Capture.Question] = []
 18    @State private var answers: [String] = []
 19    @State private var text = ""
 20    @State private var selection: TextSelection?
 21    @State private var context = CaptureContext()
 22    @State private var editing = false
 23    @FocusState private var focused: Bool
 24    @Environment(\.dismissWindow) private var dismissWindow
 25
 26    var body: some View {
 27        VStack(alignment: .leading, spacing: 12) {
 28            if let template, editing {
 29                Text("\(template.name) → \(target(template))").font(.headline)
 30                TextEditor(text: $text, selection: $selection)
 31                    .font(.body.monospaced())
 32                    .focused($focused)
 33                    .frame(minHeight: 140)
 34                HStack {
 35                    Spacer()
 36                    Button("Cancel", role: .cancel) { close() }
 37                        .keyboardShortcut(.cancelAction)
 38                    Button("File It") { finish() }
 39                        .keyboardShortcut(.return, modifiers: .command)
 40                }
 41            } else if let template, !questions.isEmpty {
 42                Text(template.name).font(.headline)
 43                Form {
 44                    ForEach(questions.indices, id: \.self) { index in
 45                        TextField(questions[index].prompt, text: $answers[index], prompt: Text(questions[index].defaultValue))
 46                    }
 47                }
 48                HStack {
 49                    Spacer()
 50                    Button("Cancel", role: .cancel) { close() }
 51                        .keyboardShortcut(.cancelAction)
 52                    Button("Continue") { expand() }
 53                        .keyboardShortcut(.defaultAction)
 54                }
 55            } else {
 56                Text("Capture").font(.headline)
 57                ForEach(templates) { template in
 58                    Button {
 59                        choose(template)
 60                    } label: {
 61                        HStack {
 62                            Text("[\(template.key)]").monospaced().foregroundStyle(.secondary)
 63                            Text(template.name)
 64                            Spacer()
 65                            Text(target(template)).foregroundStyle(.secondary).font(.caption)
 66                        }
 67                    }
 68                    .buttonStyle(.plain)
 69                }
 70                if let problem { Text(problem).font(.caption).foregroundStyle(.red) }
 71            }
 72        }
 73        .padding(16)
 74        .frame(width: 520)
 75        .onKeyPress(phases: .down) { press in
 76            guard template == nil, let match = templates.first(where: { $0.key == press.characters }) else { return .ignored }
 77            choose(match)
 78            return .handled
 79        }
 80        .onAppear(perform: reset)
 81    }
 82
 83    private func target(_ template: CaptureTemplate) -> String {
 84        let file = (template.target.file as NSString).lastPathComponent
 85        switch template.target {
 86        case .file, .heading: return file
 87        case .headline(_, let headline): return "\(file) / \(headline)"
 88        case .outline(_, let path): return ([file] + path).joined(separator: " / ")
 89        case .datetree(_, let path, _): return ([file] + path + ["date tree"]).joined(separator: " / ")
 90        case .id(let id): return "ID \(id)"
 91        case .clock: return "clocked entry"
 92        }
 93    }
 94
 95    private func reset() {
 96        let loaded = CaptureTemplates.load()
 97        templates = loaded.templates
 98        problem = loaded.problems.first
 99        template = nil
100        editing = false
101        context = CaptureContext(
102            initial: commands.editor?.selectedText ?? "",
103            annotation: session.captureAnnotation(),
104            clipboard: NSPasteboard.general.string(forType: .string) ?? "",
105            file: session.path ?? "",
106            userName: NSFullUserName()
107        )
108    }
109
110    private func choose(_ chosen: CaptureTemplate) {
111        template = chosen
112        questions = Capture.questions(chosen.template)
113        answers = questions.map { _ in "" }
114        if questions.isEmpty { expand() }
115    }
116
117    private func expand() {
118        guard let template else { return }
119        context.now = Date()
120        switch Capture.fill(template.template, context: context, answers: answers) {
121        case .failure(.message(let message)):
122            problem = message
123            self.template = nil
124        case .success(let filled):
125            text = filled.text
126            if template.options.immediateFinish {
127                finish()
128                return
129            }
130            let index = String.Index(utf16Offset: filled.cursor, in: text)
131            selection = TextSelection(insertionPoint: index)
132            editing = true
133            focused = true
134        }
135    }
136
137    /// `id` and `clock` targets as a file and a heading.
138    private func resolved(_ template: CaptureTemplate) -> Result<(template: CaptureTemplate, file: String?), CaptureError> {
139        switch template.target {
140        case .id(let id):
141            guard let location = try? workspace.index.headings(withID: id).first else {
142                return .failure(CaptureError(message: "Cannot find target ID \"\(id)\""))
143            }
144            return .success((template, location.path))
145        case .clock:
146            guard let entry = clock.entry(session) else { return .failure(CaptureError(message: "No running clock")) }
147            return .success((template.retargeted(.heading(file: entry.path, offset: entry.offset)), entry.path))
148        default:
149            return .success((template, nil))
150        }
151    }
152
153    private func finish() {
154        guard let template else { return }
155        let opened = context.now
156        let now = Date()
157        let placed = resolved(template).flatMap { resolved in
158            session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: now)
159        }
160        switch placed {
161        case .failure(let error):
162            problem = error.message
163            if template.options.immediateFinish { editing = true }
164            return
165        case .success(let entry):
166            commands.show("Captured to \(target(template))")
167            let options = template.options
168            if options.clockIn {
169                // Clocked from when capture began; the clock it interrupted resumes after.
170                let previous = clock.entry(session)
171                commands.show(clock.clockIn(session, path: entry.path, at: entry.offset, now: opened))
172                if !options.clockKeep {
173                    commands.show(clock.clockOut(session, now: now))
174                    if options.clockResume, let previous {
175                        commands.show(clock.clockIn(session, path: previous.path, at: previous.offset, now: now))
176                    }
177                }
178            }
179            if options.jumpToCaptured { commands.jump(path: entry.path, offset: entry.offset) }
180        }
181        close()
182    }
183
184    private func close() {
185        reset()
186        dismissWindow(id: "capture")
187    }
188}
189
190/// A system-wide shortcut, registered with Carbon so it needs no accessibility permission.
191@MainActor
192final class GlobalHotKey {
193    private var reference: EventHotKeyRef?
194    private var handler: EventHandlerRef?
195    private let action: () -> Void
196
197    /// ⌃⌥Space.
198    init(action: @escaping () -> Void) {
199        self.action = action
200        var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
201        let me = Unmanaged.passUnretained(self).toOpaque()
202        InstallEventHandler(GetApplicationEventTarget(), { _, _, data in
203            guard let data else { return noErr }
204            let hotKey = Unmanaged<GlobalHotKey>.fromOpaque(data).takeUnretainedValue()
205            MainActor.assumeIsolated { hotKey.action() }
206            return noErr
207        }, 1, &spec, me, &handler)
208        let id = EventHotKeyID(signature: OSType(0x4F52_4753), id: 1)
209        RegisterEventHotKey(UInt32(kVK_Space), UInt32(controlKey | optionKey), id, GetApplicationEventTarget(), 0, &reference)
210    }
211
212    func unregister() {
213        if let reference { UnregisterEventHotKey(reference) }
214        if let handler { RemoveEventHandler(handler) }
215        reference = nil
216        handler = nil
217    }
218}