Sources/Orgstar/CaptureView.swift

3f183dc5a69542840ae20a73ec755d1148b354dd
orgstar/Sources/Orgstar/CaptureView.swift history · blame · raw

267 lines · 11545 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    /// `id` and `clock` targets as a file and a heading.
185    static func resolved(
186        _ template: CaptureTemplate, workspace: WorkspaceModel, session: DocumentSession, clock: ClockModel
187    ) -> Result<(template: CaptureTemplate, file: String?), CaptureError> {
188        switch template.target {
189        case .id(let id):
190            guard let location = try? workspace.index.headings(withID: id).first else {
191                return .failure(CaptureError(message: "Cannot find target ID \"\(id)\""))
192            }
193            return .success((template, location.path))
194        case .clock:
195            guard let entry = clock.entry(session) else { return .failure(CaptureError(message: "No running clock")) }
196            return .success((template.retargeted(.heading(file: entry.path, offset: entry.offset)), entry.path))
197        default:
198            return .success((template, nil))
199        }
200    }
201
202    private func finish() {
203        guard let template else { return }
204        let opened = context.now
205        let now = Date()
206        let placed = Self.resolved(template, workspace: workspace, session: session, clock: clock).flatMap { resolved in
207            session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: now)
208        }
209        switch placed {
210        case .failure(let error):
211            problem = error.message
212            if template.options.immediateFinish { editing = true }
213            return
214        case .success(let entry):
215            commands.show("Captured to \(Self.target(template))")
216            let options = template.options
217            if options.clockIn {
218                // Clocked from when capture began; the clock it interrupted resumes after.
219                let previous = clock.entry(session)
220                commands.show(clock.clockIn(session, path: entry.path, at: entry.offset, now: opened))
221                if !options.clockKeep {
222                    commands.show(clock.clockOut(session, now: now))
223                    if options.clockResume, let previous {
224                        commands.show(clock.clockIn(session, path: previous.path, at: previous.offset, now: now))
225                    }
226                }
227            }
228            if options.jumpToCaptured { commands.jump(path: entry.path, offset: entry.offset) }
229        }
230        close()
231    }
232
233    private func close() {
234        reset()
235        dismissWindow(id: "capture")
236    }
237}
238
239/// A system-wide shortcut, registered with Carbon so it needs no accessibility permission.
240@MainActor
241final class GlobalHotKey {
242    private var reference: EventHotKeyRef?
243    private var handler: EventHandlerRef?
244    private let action: () -> Void
245
246    /// ⌃⌥Space.
247    init(action: @escaping () -> Void) {
248        self.action = action
249        var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
250        let me = Unmanaged.passUnretained(self).toOpaque()
251        InstallEventHandler(GetApplicationEventTarget(), { _, _, data in
252            guard let data else { return noErr }
253            let hotKey = Unmanaged<GlobalHotKey>.fromOpaque(data).takeUnretainedValue()
254            MainActor.assumeIsolated { hotKey.action() }
255            return noErr
256        }, 1, &spec, me, &handler)
257        let id = EventHotKeyID(signature: OSType(0x4F52_4753), id: 1)
258        RegisterEventHotKey(UInt32(kVK_Space), UInt32(controlKey | optionKey), id, GetApplicationEventTarget(), 0, &reference)
259    }
260
261    func unregister() {
262        if let reference { UnregisterEventHotKey(reference) }
263        if let handler { RemoveEventHandler(handler) }
264        reference = nil
265        handler = nil
266    }
267}