Sources/Orgstar/CaptureView.swift
346 lines · 16089 bytes
1import AppKit
2import Carbon.HIToolbox
3import OrgApp
4import OrgCore
5import OrgDocument
6import SwiftUI
7
8/// The capture window: pick a template by its key, answer its prompts, edit the entry, and
9/// ⌘Return files it where the template says, as `org-capture` does. Refile… files it and then
10/// asks where to move it (`org-capture-refile`).
11struct CaptureView: View {
12 let workspace: WorkspaceModel
13 let session: DocumentSession
14 let commands: AppCommands
15 let clock: ClockModel
16 @State private var templates = CaptureTemplates.defaults
17 @State private var groups: [CaptureGroup] = []
18 /// The day `:time-prompt` asked for.
19 @State private var treeDate: Date?
20 /// A `denote = true` template's note: its questions, their answers, and once made, its file.
21 @State private var denote: DenoteCapture?
22 @State private var denoteAnswers: [String] = []
23 @State private var denoteFile: String?
24 @State private var problem: String?
25 @State private var template: CaptureTemplate?
26 @State private var questions: [Capture.Question] = []
27 @State private var answers: [String] = []
28 @State private var text = ""
29 @State private var selection: TextSelection?
30 @State private var context = CaptureContext()
31 @State private var editing = false
32 /// The template keys typed so far, for multi-key templates such as "wb".
33 @State private var keys = ""
34 /// The agenda day the entry is captured for, as `Days` numbers it.
35 @State private var day: Int?
36 @FocusState private var focused: Bool
37 @Environment(\.dismissWindow) private var dismissWindow
38 @Environment(\.openWindow) private var openWindow
39
40 var body: some View {
41 VStack(alignment: .leading, spacing: 12) {
42 if let template, editing {
43 Text("\(template.name) → \(Self.target(template))").font(.headline)
44 TextEditor(text: $text, selection: $selection)
45 .font(.body.monospaced())
46 .focused($focused)
47 .frame(minHeight: 140)
48 HStack {
49 Spacer()
50 Button("Cancel", role: .cancel) { close() }
51 .keyboardShortcut(.cancelAction)
52 if template.kind == .entry {
53 Button("Refile…") { finish(refile: true) }
54 }
55 Button("File It") { finish() }
56 .keyboardShortcut(.return, modifiers: .command)
57 }
58 } else if let template, !questions.isEmpty {
59 Text(template.name).font(.headline)
60 Form {
61 ForEach(questions.indices, id: \.self) { index in
62 let question = questions[index]
63 TextField(question.prompt, text: $answers[index], prompt: Text(placeholder(question)))
64 if !question.choices.isEmpty {
65 Text(question.choices.prefix(12).joined(separator: " ")).font(.caption).foregroundStyle(.secondary)
66 }
67 }
68 }
69 HStack {
70 Spacer()
71 Button("Cancel", role: .cancel) { close() }
72 .keyboardShortcut(.cancelAction)
73 Button("Continue") { expand() }
74 .keyboardShortcut(.defaultAction)
75 }
76 } else {
77 Text((keys.isEmpty ? "Capture" : "Capture: \(keys)") + (day == nil ? "" : ", scheduled " + captureDate(Date()).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))))
78 .font(.headline)
79 ForEach(CaptureTemplates.menu(templates, groups: groups, typed: keys)) { item in
80 Button {
81 switch item {
82 case .group(let group): keys = group.key
83 case .template(let template): choose(template)
84 }
85 } label: {
86 HStack {
87 Text("[\(item.key)]").monospaced().foregroundStyle(.secondary)
88 switch item {
89 case .group(let group):
90 Text(group.name + "…")
91 case .template(let template):
92 Text(template.name)
93 Spacer()
94 Text(Self.target(template)).foregroundStyle(.secondary).font(.caption)
95 }
96 }
97 }
98 .buttonStyle(.plain)
99 }
100 }
101 if let problem { Text(problem).font(.caption).foregroundStyle(.red) }
102 }
103 .padding(16)
104 .frame(width: 520)
105 .onKeyPress(phases: .down) { press in
106 guard template == nil else { return .ignored }
107 if press.key == .delete, !keys.isEmpty {
108 keys.removeLast()
109 return .handled
110 }
111 // Keys narrow the list until they name a template, as `org-capture` selects one.
112 let typed = keys + press.characters
113 if let match = templates.first(where: { $0.key == typed }) {
114 choose(match)
115 } else if !press.characters.isEmpty, templates.contains(where: { $0.key.hasPrefix(typed) }) {
116 keys = typed
117 } else {
118 return .ignored
119 }
120 return .handled
121 }
122 .onAppear {
123 reset()
124 takeRequest()
125 }
126 .onChange(of: commands.captureRequest?.serial) {
127 guard commands.captureRequest != nil else { return }
128 reset()
129 takeRequest()
130 }
131 }
132
133 /// What an empty answer means.
134 private func placeholder(_ question: Capture.Question) -> String {
135 switch question.kind {
136 case .text, .property, .clipboard: question.defaultValue
137 case .tags: "tag:tag"
138 case .date(let withTime, _): withTime ? "now; or +2d, fri 14:00" : "today; or +2d, fri"
139 }
140 }
141
142 static func target(_ template: CaptureTemplate) -> String {
143 if template.options.denote { return "a new Denote note" }
144 let file = (template.target.file as NSString).lastPathComponent
145 switch template.target {
146 case .file, .heading: return file
147 case .headline(_, let headline): return "\(file) / \(headline)"
148 case .outline(_, let path): return ([file] + path).joined(separator: " / ")
149 case .datetree(_, let path, _): return ([file] + path + ["date tree"]).joined(separator: " / ")
150 case .regexp(_, let regexp): return "\(file) / \(regexp)"
151 case .id(let id): return "ID \(id)"
152 case .clock: return "clocked entry"
153 }
154 }
155
156 private func reset() {
157 let loaded = CaptureTemplates.load()
158 templates = loaded.templates
159 groups = loaded.groups
160 problem = loaded.problems.first
161 template = nil
162 treeDate = nil
163 editing = false
164 keys = ""
165 day = nil
166 let clocked = clock.running
167 let clockFile = clocked.map { Links.abbreviate($0.path, home: NSHomeDirectory()) }
168 context = CaptureContext(
169 initial: commands.editor?.selectedText ?? "",
170 annotation: session.captureAnnotation(),
171 clipboard: NSPasteboard.general.string(forType: .string) ?? "",
172 file: session.path ?? "",
173 userName: NSFullUserName(),
174 clockHeading: clocked?.heading ?? "",
175 clockLink: clocked.map { "[[file:\(clockFile!)::*\($0.heading)][\($0.heading)]]" } ?? "",
176 allTags: (try? workspace.index.tags()) ?? [],
177 tagsColumn: UserDefaults.standard.object(forKey: "tagsColumn") as? Int ?? -77
178 )
179 context.readsTemplateFiles()
180 }
181
182 /// An org-protocol capture: its link properties fill `%a`, `%i` and `%:…`, and its
183 /// template, when it names one, is chosen.
184 private func takeRequest() {
185 guard let request = commands.captureRequest else { return }
186 commands.captureRequest = nil
187 day = request.day
188 context.initial = request.properties["initial"] ?? ""
189 context.annotation = request.properties["annotation"] ?? ""
190 context.linkProperties = request.properties
191 if let key = request.template {
192 if let match = templates.first(where: { $0.key == key }) { choose(match) } else { problem = "No capture template \"\(key)\"" }
193 }
194 }
195
196 private func choose(_ chosen: CaptureTemplate) {
197 template = chosen
198 keys = ""
199 // `%^g` offers the target file's tags.
200 let path = DocumentSession.resolve(chosen.target.file, root: workspace.rootPaths.first)
201 if !chosen.target.file.isEmpty, let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) {
202 var tags: [String] = []
203 for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
204 context.fileTags = tags
205 }
206 denote = chosen.options.denote ? DenoteCapture(roots: workspace.rootPaths, paths: workspace.files.map(\.path)) : nil
207 denoteFile = nil
208 questions = (denote?.questions ?? []) + (asksTreeDate(chosen) ? [Self.treeQuestion] : []) + Capture.questions(chosen.template, context: context)
209 answers = questions.map { _ in "" }
210 if questions.isEmpty { expand() }
211 }
212
213 /// `:time-prompt` asks first, unless the agenda day is the date.
214 private func asksTreeDate(_ template: CaptureTemplate) -> Bool { template.asksTreeDate && day == nil }
215
216 static let treeQuestion = Capture.Question(prompt: "Date for tree entry", defaultValue: "", choices: [], kind: .date(withTime: false, inactive: false))
217
218 private func expand() {
219 guard let template else { return }
220 var answers = answers
221 if let denote {
222 denoteAnswers = Array(answers.prefix(denote.questions.count))
223 answers.removeFirst(min(denote.questions.count, answers.count))
224 }
225 if asksTreeDate(template) {
226 treeDate = Capture.treeDate(answers.removeFirst(), now: Date())
227 }
228 context.now = captureDate(Date())
229 switch Capture.fill(template.template, context: context, answers: answers) {
230 case .failure(.message(let message)):
231 problem = message
232 self.template = nil
233 case .success(var filled):
234 if let day { filled = Capture.scheduling(filled.text, cursor: filled.cursor, on: day) }
235 text = filled.text
236 if template.options.immediateFinish {
237 finish()
238 return
239 }
240 let index = String.Index(utf16Offset: filled.cursor, in: text)
241 selection = TextSelection(insertionPoint: index)
242 editing = true
243 focused = true
244 }
245 }
246
247 /// `now` on the agenda day captured for, as `org-overriding-default-time` sets `%t`, `%U`
248 /// and the date tree's day.
249 private func captureDate(_ now: Date) -> Date {
250 if let treeDate { return treeDate }
251 guard let day else { return now }
252 let d = Days.date(day)
253 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
254 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day, hour: time.hour, minute: time.minute, second: time.second)) ?? now
255 }
256
257 private func finish(refile: Bool = false) {
258 guard let template else { return }
259 let opened = context.now
260 let now = Date()
261 let placed: Result<(path: String, offset: Int), CaptureError>
262 if let denote {
263 do {
264 let file = try denoteFile ?? denote.create(denoteAnswers, now: now)
265 if denoteFile == nil { Task { await workspace.refresh() } }
266 denoteFile = file
267 placed = session.capture(text, template: template, root: workspace.rootPaths.first, file: file, now: captureDate(now))
268 } catch {
269 placed = .failure(CaptureError(message: "Can't make the note: \(error)"))
270 }
271 } else {
272 placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
273 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: captureDate(now))
274 }
275 }
276 switch placed {
277 case .failure(let error):
278 problem = error.message
279 if template.options.immediateFinish { editing = true }
280 return
281 case .success(let entry):
282 commands.show("Captured to \(Self.target(template))")
283 let options = template.options
284 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
285 Task { [commands, clock, session, workspace] in
286 let outcome = await clock.captured(entry, options: options, session: session, paths: paths, ask: commands.askClock, opened: opened, now: now)
287 for message in outcome.messages { commands.show(message) }
288 if refile {
289 Self.refile(entry, session: session, workspace: workspace, commands: commands)
290 } else if let jump = outcome.jump {
291 commands.jump(path: jump.path, offset: jump.offset)
292 } else if options.jumpToCaptured {
293 commands.jump(path: entry.path, offset: entry.offset)
294 }
295 }
296 }
297 if refile { openWindow(id: "main") }
298 close()
299 }
300
301 /// `org-capture-refile`: the filed entry, moved where the answer says.
302 private static func refile(_ entry: (path: String, offset: Int), session: DocumentSession, workspace: WorkspaceModel, commands: AppCommands) {
303 let document = session.openDocuments.first { $0.path == entry.path }?.document
304 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
305 let targets = workspace.refileTargets(openPath: entry.path, document: document)
306 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
307 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
308 if let message = session.refile(to: target, from: entry) { commands.show(message) }
309 }
310 }
311
312 private func close() {
313 reset()
314 dismissWindow(id: "capture")
315 }
316}
317
318/// A system-wide shortcut, registered with Carbon so it needs no accessibility permission.
319@MainActor
320final class GlobalHotKey {
321 private var reference: EventHotKeyRef?
322 private var handler: EventHandlerRef?
323 private let action: () -> Void
324
325 /// ⌃⌥Space.
326 init(action: @escaping () -> Void) {
327 self.action = action
328 var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
329 let me = Unmanaged.passUnretained(self).toOpaque()
330 InstallEventHandler(GetApplicationEventTarget(), { _, _, data in
331 guard let data else { return noErr }
332 let hotKey = Unmanaged<GlobalHotKey>.fromOpaque(data).takeUnretainedValue()
333 MainActor.assumeIsolated { hotKey.action() }
334 return noErr
335 }, 1, &spec, me, &handler)
336 let id = EventHotKeyID(signature: OSType(0x4F52_4753), id: 1)
337 RegisterEventHotKey(UInt32(kVK_Space), UInt32(controlKey | optionKey), id, GetApplicationEventTarget(), 0, &reference)
338 }
339
340 func unregister() {
341 if let reference { UnregisterEventHotKey(reference) }
342 if let handler { RemoveEventHandler(handler) }
343 reference = nil
344 handler = nil
345 }
346}