Sources/Orgstar/CaptureView.swift

d32d29c0620e94a09a204185d1a2004a8d58c518
orgstar/Sources/Orgstar/CaptureView.swift history · blame · raw

239 lines · 10155 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) → \(Self.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                        let question = questions[index]
 46                        TextField(question.prompt, text: $answers[index], prompt: Text(placeholder(question)))
 47                        if !question.choices.isEmpty {
 48                            Text(question.choices.prefix(12).joined(separator: "  ")).font(.caption).foregroundStyle(.secondary)
 49                        }
 50                    }
 51                }
 52                HStack {
 53                    Spacer()
 54                    Button("Cancel", role: .cancel) { close() }
 55                        .keyboardShortcut(.cancelAction)
 56                    Button("Continue") { expand() }
 57                        .keyboardShortcut(.defaultAction)
 58                }
 59            } else {
 60                Text("Capture").font(.headline)
 61                ForEach(templates) { template in
 62                    Button {
 63                        choose(template)
 64                    } label: {
 65                        HStack {
 66                            Text("[\(template.key)]").monospaced().foregroundStyle(.secondary)
 67                            Text(template.name)
 68                            Spacer()
 69                            Text(Self.target(template)).foregroundStyle(.secondary).font(.caption)
 70                        }
 71                    }
 72                    .buttonStyle(.plain)
 73                }
 74                if let problem { Text(problem).font(.caption).foregroundStyle(.red) }
 75            }
 76        }
 77        .padding(16)
 78        .frame(width: 520)
 79        .onKeyPress(phases: .down) { press in
 80            guard template == nil, let match = templates.first(where: { $0.key == press.characters }) else { return .ignored }
 81            choose(match)
 82            return .handled
 83        }
 84        .onAppear {
 85            reset()
 86            takeRequest()
 87        }
 88        .onChange(of: commands.captureRequest?.serial) {
 89            guard commands.captureRequest != nil else { return }
 90            reset()
 91            takeRequest()
 92        }
 93    }
 94
 95    /// What an empty answer means.
 96    private func placeholder(_ question: Capture.Question) -> String {
 97        switch question.kind {
 98        case .text, .property, .clipboard: question.defaultValue
 99        case .tags: "tag:tag"
100        case .date(let withTime, _): withTime ? "now; or +2d, fri 14:00" : "today; or +2d, fri"
101        }
102    }
103
104    static func target(_ template: CaptureTemplate) -> String {
105        let file = (template.target.file as NSString).lastPathComponent
106        switch template.target {
107        case .file, .heading: return file
108        case .headline(_, let headline): return "\(file) / \(headline)"
109        case .outline(_, let path): return ([file] + path).joined(separator: " / ")
110        case .datetree(_, let path, _): return ([file] + path + ["date tree"]).joined(separator: " / ")
111        case .id(let id): return "ID \(id)"
112        case .clock: return "clocked entry"
113        }
114    }
115
116    private func reset() {
117        let loaded = CaptureTemplates.load()
118        templates = loaded.templates
119        problem = loaded.problems.first
120        template = nil
121        editing = false
122        let clocked = clock.running
123        let clockFile = clocked.map { Links.abbreviate($0.path, home: NSHomeDirectory()) }
124        context = CaptureContext(
125            initial: commands.editor?.selectedText ?? "",
126            annotation: session.captureAnnotation(),
127            clipboard: NSPasteboard.general.string(forType: .string) ?? "",
128            file: session.path ?? "",
129            userName: NSFullUserName(),
130            clockHeading: clocked?.heading ?? "",
131            clockLink: clocked.map { "[[file:\(clockFile!)::*\($0.heading)][\($0.heading)]]" } ?? "",
132            allTags: (try? workspace.index.tags()) ?? [],
133            tagsColumn: UserDefaults.standard.object(forKey: "tagsColumn") as? Int ?? -77
134        )
135    }
136
137    /// An org-protocol capture: its link properties fill `%a`, `%i` and `%:…`, and its
138    /// template, when it names one, is chosen.
139    private func takeRequest() {
140        guard let request = commands.captureRequest else { return }
141        commands.captureRequest = nil
142        context.initial = request.properties["initial"] ?? ""
143        context.annotation = request.properties["annotation"] ?? ""
144        context.linkProperties = request.properties
145        if let key = request.template {
146            if let match = templates.first(where: { $0.key == key }) { choose(match) } else { problem = "No capture template \"\(key)\"" }
147        }
148    }
149
150    private func choose(_ chosen: CaptureTemplate) {
151        template = chosen
152        // `%^g` offers the target file's tags.
153        let path = DocumentSession.resolve(chosen.target.file, root: workspace.rootPaths.first)
154        if !chosen.target.file.isEmpty, let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) {
155            var tags: [String] = []
156            for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
157            context.fileTags = tags
158        }
159        questions = Capture.questions(chosen.template, context: context)
160        answers = questions.map { _ in "" }
161        if questions.isEmpty { expand() }
162    }
163
164    private func expand() {
165        guard let template else { return }
166        context.now = Date()
167        switch Capture.fill(template.template, context: context, answers: answers) {
168        case .failure(.message(let message)):
169            problem = message
170            self.template = nil
171        case .success(let filled):
172            text = filled.text
173            if template.options.immediateFinish {
174                finish()
175                return
176            }
177            let index = String.Index(utf16Offset: filled.cursor, in: text)
178            selection = TextSelection(insertionPoint: index)
179            editing = true
180            focused = true
181        }
182    }
183
184    private func finish() {
185        guard let template else { return }
186        let opened = context.now
187        let now = Date()
188        let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
189            session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: now)
190        }
191        switch placed {
192        case .failure(let error):
193            problem = error.message
194            if template.options.immediateFinish { editing = true }
195            return
196        case .success(let entry):
197            commands.show("Captured to \(Self.target(template))")
198            let options = template.options
199            for message in clock.captured(entry, options: options, session: session, opened: opened, now: now) { commands.show(message) }
200            if options.jumpToCaptured { commands.jump(path: entry.path, offset: entry.offset) }
201        }
202        close()
203    }
204
205    private func close() {
206        reset()
207        dismissWindow(id: "capture")
208    }
209}
210
211/// A system-wide shortcut, registered with Carbon so it needs no accessibility permission.
212@MainActor
213final class GlobalHotKey {
214    private var reference: EventHotKeyRef?
215    private var handler: EventHandlerRef?
216    private let action: () -> Void
217
218    /// ⌃⌥Space.
219    init(action: @escaping () -> Void) {
220        self.action = action
221        var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
222        let me = Unmanaged.passUnretained(self).toOpaque()
223        InstallEventHandler(GetApplicationEventTarget(), { _, _, data in
224            guard let data else { return noErr }
225            let hotKey = Unmanaged<GlobalHotKey>.fromOpaque(data).takeUnretainedValue()
226            MainActor.assumeIsolated { hotKey.action() }
227            return noErr
228        }, 1, &spec, me, &handler)
229        let id = EventHotKeyID(signature: OSType(0x4F52_4753), id: 1)
230        RegisterEventHotKey(UInt32(kVK_Space), UInt32(controlKey | optionKey), id, GetApplicationEventTarget(), 0, &reference)
231    }
232
233    func unregister() {
234        if let reference { UnregisterEventHotKey(reference) }
235        if let handler { RemoveEventHandler(handler) }
236        reference = nil
237        handler = nil
238    }
239}