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