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