Sources/Orgstar/CaptureView.swift

73fcba4bfb8709ee26c1b1ecee1b70ce400e5b7e
orgstar/Sources/Orgstar/CaptureView.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form