Sources/Orgstar/CaptureView.swift
418 lines · 19596 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 /// An org-roam capture: its templates in place of capture.toml's, filed through it.
37 @State private var roam: RoamCapture?
38 /// The `captureRequest` serial of an x-callback-url capture, whose caller hears how it ends.
39 @State private var callbackSerial: Int?
40 /// The capture's hooks are running.
41 @State private var finishing = false
42 @FocusState private var focused: Bool
43 @Environment(\.dismissWindow) private var dismissWindow
44 @Environment(\.openWindow) private var openWindow
45
46 var body: some View {
47 VStack(alignment: .leading, spacing: 12) {
48 if let template, editing {
49 Text("\(template.name) → \(target(template))").font(.headline)
50 TextEditor(text: $text, selection: $selection)
51 .font(.body.monospaced())
52 .focused($focused)
53 .frame(minHeight: 140)
54 HStack {
55 Spacer()
56 Button("Cancel", role: .cancel) { close() }
57 .keyboardShortcut(.cancelAction)
58 if template.kind == .entry, roam == nil {
59 Button("Refile…") { finish(refile: true) }
60 }
61 Button("Capture") { finish() }
62 .keyboardShortcut(.return, modifiers: .command)
63 }
64 } else if let template, !questions.isEmpty {
65 Text(template.name).font(.headline)
66 Form {
67 ForEach(questions.indices, id: \.self) { index in
68 let question = questions[index]
69 TextField(question.prompt, text: $answers[index], prompt: Text(placeholder(question)))
70 if !question.choices.isEmpty {
71 Text(question.choices.prefix(12).joined(separator: " ")).font(.caption).foregroundStyle(.secondary)
72 }
73 }
74 }
75 HStack {
76 Spacer()
77 Button("Cancel", role: .cancel) { close() }
78 .keyboardShortcut(.cancelAction)
79 Button("Continue") { expand() }
80 .keyboardShortcut(.defaultAction)
81 }
82 } else {
83 // The window's title says Capture; this line is for the keys typed and the day.
84 if !keys.isEmpty || day != nil {
85 HStack(spacing: 12) {
86 if !keys.isEmpty { Text(verbatim: "[\(keys)]").monospaced() }
87 if day != nil { Text("Scheduled \(captureDate(Date()).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated)))") }
88 }
89 .font(.headline)
90 }
91 ForEach(CaptureTemplates.menu(templates, groups: groups, typed: keys)) { item in
92 Button {
93 switch item {
94 case .group(let group): keys = group.key
95 case .template(let template): choose(template)
96 }
97 } label: {
98 HStack {
99 Text("[\(item.key)]").monospaced().foregroundStyle(.secondary)
100 switch item {
101 case .group(let group):
102 Text(group.name + "…")
103 case .template(let template):
104 Text(template.name)
105 Spacer()
106 Text(target(template)).foregroundStyle(.secondary).font(.caption)
107 }
108 }
109 }
110 .buttonStyle(.plain)
111 }
112 }
113 if let problem { Text(problem).font(.caption).foregroundStyle(.red) }
114 }
115 .padding(16)
116 .frame(width: 520)
117 .onKeyPress(phases: .down) { press in
118 guard template == nil else { return .ignored }
119 if press.key == .delete, !keys.isEmpty {
120 keys.removeLast()
121 return .handled
122 }
123 // Keys narrow the list until they name a template, as `org-capture` selects one.
124 let typed = keys + press.characters
125 if let match = templates.first(where: { $0.key == typed }) {
126 choose(match)
127 } else if !press.characters.isEmpty, templates.contains(where: { $0.key.hasPrefix(typed) }) {
128 keys = typed
129 } else {
130 return .ignored
131 }
132 return .handled
133 }
134 .onAppear {
135 reset()
136 takeRequest()
137 }
138 .onChange(of: commands.captureRequest?.serial) {
139 guard commands.captureRequest != nil else { return }
140 reset()
141 takeRequest()
142 }
143 .onDisappear { endCallback(filed: nil) }
144 }
145
146 /// What an empty answer means.
147 private func placeholder(_ question: Capture.Question) -> String {
148 switch question.kind {
149 case .text, .property, .clipboard: question.defaultValue
150 case .tags: "tag:tag"
151 case .date(let withTime, _): withTime ? "now; or +2d, fri 14:00" : "today; or +2d, fri"
152 }
153 }
154
155 /// Where the template files; for org-roam, the file's name, marked when it's new.
156 private func target(_ template: CaptureTemplate) -> String {
157 guard let roam else { return Self.target(template) }
158 let name = Self.target(template)
159 return roam.isNew(template) ? String(localized: "\(name) (new)", comment: "Capture window: an org-roam template's file that capturing makes") : name
160 }
161
162 static func target(_ template: CaptureTemplate) -> String {
163 if template.options.denote { return "a new Denote note" }
164 let file = (template.target.file as NSString).lastPathComponent
165 switch template.target {
166 case .file, .heading: return file
167 case .headline(_, let headline): return "\(file) / \(headline)"
168 case .outline(_, let path): return ([file] + path).joined(separator: " / ")
169 case .datetree(_, let path, _): return ([file] + path + ["date tree"]).joined(separator: " / ")
170 case .regexp(_, let regexp): return "\(file) / \(regexp)"
171 case .id(let id): return "ID \(id)"
172 case .clock: return "clocked entry"
173 }
174 }
175
176 private func reset() {
177 let loaded = CaptureTemplates.load()
178 templates = loaded.templates
179 groups = loaded.groups
180 problem = loaded.problems.first
181 template = nil
182 treeDate = nil
183 editing = false
184 keys = ""
185 day = nil
186 roam = nil
187 let clocked = clock.running
188 let clockFile = clocked.map { Links.abbreviate($0.path, home: OrgPaths.home) }
189 context = CaptureContext(
190 initial: commands.editor?.selectedText ?? "",
191 annotation: session.captureAnnotation(),
192 clipboard: NSPasteboard.general.string(forType: .string) ?? "",
193 file: session.path ?? "",
194 userName: NSFullUserName(),
195 clockHeading: clocked?.heading ?? "",
196 clockLink: clocked.map { "[[file:\(clockFile!)::*\($0.heading)][\($0.heading)]]" } ?? "",
197 allTags: (try? workspace.index.tags()) ?? [],
198 tagsColumn: UserDefaults.standard.object(forKey: "tagsColumn") as? Int ?? -77
199 )
200 context.readsTemplateFiles()
201 }
202
203 /// An org-protocol capture: its link properties fill `%a`, `%i` and `%:…`, and its
204 /// template, when it names one, is chosen.
205 private func takeRequest() {
206 guard let request = commands.captureRequest else { return }
207 commands.captureRequest = nil
208 // Another capture takes the window from an x-callback-url one, which ends cancelled.
209 endCallback(filed: nil)
210 if commands.captureCallback?.serial == request.serial { callbackSerial = request.serial }
211 if let roam = commands.roamCapture {
212 commands.roamCapture = nil
213 self.roam = roam
214 templates = roam.templates
215 groups = []
216 problem = nil
217 context.now = roam.now
218 if templates.count == 1 { choose(templates[0]) }
219 return
220 }
221 day = request.day
222 context.initial = request.properties["initial"] ?? ""
223 context.annotation = request.properties["annotation"] ?? ""
224 context.linkProperties = request.properties
225 if let key = request.template {
226 if let match = templates.first(where: { $0.key == key }) { choose(match) } else { problem = "No capture template \"\(key)\"" }
227 }
228 }
229
230 private func choose(_ chosen: CaptureTemplate) {
231 template = chosen
232 keys = ""
233 // `%^g` offers the target file's tags.
234 let path = DocumentSession.resolve(chosen.target.file, root: workspace.rootPaths.first)
235 if !chosen.target.file.isEmpty, let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) {
236 var tags: [String] = []
237 for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
238 context.fileTags = tags
239 }
240 denote = chosen.options.denote ? DenoteCapture(roots: workspace.rootPaths, paths: workspace.files.map(\.path)) : nil
241 denoteFile = nil
242 questions = (denote?.questions ?? []) + (asksTreeDate(chosen) ? [Self.treeQuestion] : []) + Capture.questions(chosen.template, context: context)
243 answers = questions.map { _ in "" }
244 if questions.isEmpty { expand() }
245 }
246
247 /// `:time-prompt` asks first, unless the agenda day is the date.
248 private func asksTreeDate(_ template: CaptureTemplate) -> Bool { template.asksTreeDate && day == nil }
249
250 static let treeQuestion = Capture.Question(prompt: "Date for tree entry", defaultValue: "", choices: [], kind: .date(withTime: false, inactive: false))
251
252 private func expand() {
253 guard let template else { return }
254 var answers = answers
255 if let denote {
256 denoteAnswers = Array(answers.prefix(denote.questions.count))
257 answers.removeFirst(min(denote.questions.count, answers.count))
258 }
259 if asksTreeDate(template) {
260 treeDate = Capture.treeDate(answers.removeFirst(), now: Date())
261 }
262 context.now = captureDate(Date())
263 switch Capture.fill(template.template, context: context, answers: answers) {
264 case .failure(.message(let message)):
265 problem = message
266 self.template = nil
267 case .success(var filled):
268 if let day { filled = Capture.scheduling(filled.text, cursor: filled.cursor, on: day) }
269 text = filled.text
270 if template.options.immediateFinish {
271 finish()
272 return
273 }
274 let index = String.Index(utf16Offset: filled.cursor, in: text)
275 selection = TextSelection(insertionPoint: index)
276 editing = true
277 focused = true
278 }
279 }
280
281 /// `now` on the agenda day captured for, as `org-overriding-default-time` sets `%t`, `%U`
282 /// and the date tree's day.
283 private func captureDate(_ now: Date) -> Date {
284 if let treeDate { return treeDate }
285 if let roam { return roam.now }
286 guard let day else { return now }
287 let d = Days.date(day)
288 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
289 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
290 }
291
292 /// Files the capture once the `capture-before-finalize` hooks have run on it; a hook that
293 /// fails cancels it, with the window left open.
294 private func finish(refile: Bool = false) {
295 guard let template, !finishing else { return }
296 guard session.hasHooks(.captureBeforeFinalize) else { return file(refile: refile) }
297 finishing = true
298 Task {
299 let hooked = await session.runCaptureHooks(text, template: template.key, interactive: true)
300 finishing = false
301 switch hooked {
302 case .failure(let error):
303 problem = error.message
304 if template.options.immediateFinish { editing = true }
305 case .success(let changed):
306 text = changed
307 file(refile: refile)
308 }
309 }
310 }
311
312 private func file(refile: Bool) {
313 guard let template else { return }
314 let opened = context.now
315 let now = Date()
316 let placed: Result<(path: String, offset: Int), CaptureError>
317 if let roam {
318 placed = roam.file(text, with: template)
319 } else if let denote {
320 do {
321 let file = try denoteFile ?? denote.create(denoteAnswers, now: now)
322 if denoteFile == nil { Task { await workspace.refresh() } }
323 denoteFile = file
324 placed = session.capture(text, template: template, root: workspace.rootPaths.first, file: file, now: captureDate(now))
325 } catch {
326 placed = .failure(CaptureError(message: "Can't make the note: \(error)"))
327 }
328 } else {
329 placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
330 #if APPSTORE
331 let path = resolved.file ?? DocumentSession.resolve(resolved.template.target.file, root: workspace.rootPaths.first)
332 guard commands.reach([path]) else {
333 return .failure(CaptureError(message: String(localized: "orgstar can't reach \(OrgPaths.abbreviatingWithTilde(path)).", comment: "Alert for a folder outside the sidebar's folders")))
334 }
335 #endif
336 return session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: captureDate(now))
337 }
338 }
339 switch placed {
340 case .failure(let error):
341 problem = error.message
342 if template.options.immediateFinish { editing = true }
343 return
344 case .success(let entry):
345 commands.show("Captured to \(Self.target(template))")
346 endCallback(filed: (template, entry.path))
347 let options = template.options
348 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
349 Task { [commands, clock, session, workspace] in
350 let outcome = await clock.captured(entry, options: options, session: session, paths: paths, ask: commands.askClock, opened: opened, now: now)
351 for message in outcome.messages { commands.show(message) }
352 if refile {
353 Self.refile(entry, session: session, workspace: workspace, commands: commands)
354 } else if let jump = outcome.jump {
355 commands.jump(path: jump.path, offset: jump.offset)
356 } else if options.jumpToCaptured {
357 commands.jump(path: entry.path, offset: entry.offset)
358 }
359 }
360 }
361 if refile { openWindow(id: "main") }
362 close()
363 }
364
365 /// `org-capture-refile`: the filed entry, moved where the answer says.
366 private static func refile(_ entry: (path: String, offset: Int), session: DocumentSession, workspace: WorkspaceModel, commands: AppCommands) {
367 let document = session.openDocuments.first { $0.path == entry.path }?.document
368 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
369 let targets = workspace.refileTargets(openPath: entry.path, document: document)
370 commands.ask(Prompt(key: "refile", message: String(localized: "Refile to:"), choices: targets.map(\.label))) { answer in
371 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
372 if let message = session.refile(to: target, from: entry) { commands.show(message) }
373 }
374 }
375
376 private func close() {
377 endCallback(filed: nil)
378 reset()
379 dismissWindow(id: "capture")
380 }
381
382 /// Tells an x-callback-url capture's caller it was filed, or cancelled when `filed` is nil.
383 private func endCallback(filed: (template: CaptureTemplate, path: String)?) {
384 guard let serial = callbackSerial else { return }
385 callbackSerial = nil
386 commands.captureEnded(serial: serial, filed: filed)
387 }
388}
389
390/// A system-wide shortcut, registered with Carbon so it needs no accessibility permission.
391@MainActor
392final class GlobalHotKey {
393 private var reference: EventHotKeyRef?
394 private var handler: EventHandlerRef?
395 private let action: () -> Void
396
397 /// ⌃⌥Space.
398 init(action: @escaping () -> Void) {
399 self.action = action
400 var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
401 let me = Unmanaged.passUnretained(self).toOpaque()
402 InstallEventHandler(GetApplicationEventTarget(), { _, _, data in
403 guard let data else { return noErr }
404 let hotKey = Unmanaged<GlobalHotKey>.fromOpaque(data).takeUnretainedValue()
405 MainActor.assumeIsolated { hotKey.action() }
406 return noErr
407 }, 1, &spec, me, &handler)
408 let id = EventHotKeyID(signature: OSType(0x4F52_4753), id: 1)
409 RegisterEventHotKey(UInt32(kVK_Space), UInt32(controlKey | optionKey), id, GetApplicationEventTarget(), 0, &reference)
410 }
411
412 func unregister() {
413 if let reference { UnregisterEventHotKey(reference) }
414 if let handler { RemoveEventHandler(handler) }
415 reference = nil
416 handler = nil
417 }
418}