Sources/Orgstar/CaptureView.swift
244 lines · 10512 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 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(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(perform: reset)
85 }
86
87 /// What an empty answer means.
88 private func placeholder(_ question: Capture.Question) -> String {
89 switch question.kind {
90 case .text, .property, .clipboard: question.defaultValue
91 case .tags: "tag:tag"
92 case .date(let withTime, _): withTime ? "now; or +2d, fri 14:00" : "today; or +2d, fri"
93 }
94 }
95
96 private func target(_ template: CaptureTemplate) -> String {
97 let file = (template.target.file as NSString).lastPathComponent
98 switch template.target {
99 case .file, .heading: return file
100 case .headline(_, let headline): return "\(file) / \(headline)"
101 case .outline(_, let path): return ([file] + path).joined(separator: " / ")
102 case .datetree(_, let path, _): return ([file] + path + ["date tree"]).joined(separator: " / ")
103 case .id(let id): return "ID \(id)"
104 case .clock: return "clocked entry"
105 }
106 }
107
108 private func reset() {
109 let loaded = CaptureTemplates.load()
110 templates = loaded.templates
111 problem = loaded.problems.first
112 template = nil
113 editing = false
114 let clocked = clock.running
115 let clockFile = clocked.map { Links.abbreviate($0.path, home: NSHomeDirectory()) }
116 context = CaptureContext(
117 initial: commands.editor?.selectedText ?? "",
118 annotation: session.captureAnnotation(),
119 clipboard: NSPasteboard.general.string(forType: .string) ?? "",
120 file: session.path ?? "",
121 userName: NSFullUserName(),
122 clockHeading: clocked?.heading ?? "",
123 clockLink: clocked.map { "[[file:\(clockFile!)::*\($0.heading)][\($0.heading)]]" } ?? "",
124 allTags: (try? workspace.index.tags()) ?? [],
125 tagsColumn: UserDefaults.standard.object(forKey: "tagsColumn") as? Int ?? -77
126 )
127 }
128
129 private func choose(_ chosen: CaptureTemplate) {
130 template = chosen
131 // `%^g` offers the target file's tags.
132 let path = DocumentSession.resolve(chosen.target.file, root: workspace.rootPaths.first)
133 if !chosen.target.file.isEmpty, let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) {
134 var tags: [String] = []
135 for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
136 context.fileTags = tags
137 }
138 questions = Capture.questions(chosen.template, context: context)
139 answers = questions.map { _ in "" }
140 if questions.isEmpty { expand() }
141 }
142
143 private func expand() {
144 guard let template else { return }
145 context.now = Date()
146 switch Capture.fill(template.template, context: context, answers: answers) {
147 case .failure(.message(let message)):
148 problem = message
149 self.template = nil
150 case .success(let filled):
151 text = filled.text
152 if template.options.immediateFinish {
153 finish()
154 return
155 }
156 let index = String.Index(utf16Offset: filled.cursor, in: text)
157 selection = TextSelection(insertionPoint: index)
158 editing = true
159 focused = true
160 }
161 }
162
163 /// `id` and `clock` targets as a file and a heading.
164 private func resolved(_ template: CaptureTemplate) -> Result<(template: CaptureTemplate, file: String?), CaptureError> {
165 switch template.target {
166 case .id(let id):
167 guard let location = try? workspace.index.headings(withID: id).first else {
168 return .failure(CaptureError(message: "Cannot find target ID \"\(id)\""))
169 }
170 return .success((template, location.path))
171 case .clock:
172 guard let entry = clock.entry(session) else { return .failure(CaptureError(message: "No running clock")) }
173 return .success((template.retargeted(.heading(file: entry.path, offset: entry.offset)), entry.path))
174 default:
175 return .success((template, nil))
176 }
177 }
178
179 private func finish() {
180 guard let template else { return }
181 let opened = context.now
182 let now = Date()
183 let placed = resolved(template).flatMap { resolved in
184 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: now)
185 }
186 switch placed {
187 case .failure(let error):
188 problem = error.message
189 if template.options.immediateFinish { editing = true }
190 return
191 case .success(let entry):
192 commands.show("Captured to \(target(template))")
193 let options = template.options
194 if options.clockIn {
195 // Clocked from when capture began; the clock it interrupted resumes after.
196 let previous = clock.entry(session)
197 commands.show(clock.clockIn(session, path: entry.path, at: entry.offset, now: opened))
198 if !options.clockKeep {
199 commands.show(clock.clockOut(session, now: now))
200 if options.clockResume, let previous {
201 commands.show(clock.clockIn(session, path: previous.path, at: previous.offset, now: now))
202 }
203 }
204 }
205 if options.jumpToCaptured { commands.jump(path: entry.path, offset: entry.offset) }
206 }
207 close()
208 }
209
210 private func close() {
211 reset()
212 dismissWindow(id: "capture")
213 }
214}
215
216/// A system-wide shortcut, registered with Carbon so it needs no accessibility permission.
217@MainActor
218final class GlobalHotKey {
219 private var reference: EventHotKeyRef?
220 private var handler: EventHandlerRef?
221 private let action: () -> Void
222
223 /// ⌃⌥Space.
224 init(action: @escaping () -> Void) {
225 self.action = action
226 var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
227 let me = Unmanaged.passUnretained(self).toOpaque()
228 InstallEventHandler(GetApplicationEventTarget(), { _, _, data in
229 guard let data else { return noErr }
230 let hotKey = Unmanaged<GlobalHotKey>.fromOpaque(data).takeUnretainedValue()
231 MainActor.assumeIsolated { hotKey.action() }
232 return noErr
233 }, 1, &spec, me, &handler)
234 let id = EventHotKeyID(signature: OSType(0x4F52_4753), id: 1)
235 RegisterEventHotKey(UInt32(kVK_Space), UInt32(controlKey | optionKey), id, GetApplicationEventTarget(), 0, &reference)
236 }
237
238 func unregister() {
239 if let reference { UnregisterEventHotKey(reference) }
240 if let handler { RemoveEventHandler(handler) }
241 reference = nil
242 handler = nil
243 }
244}