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