Sources/Orgstar/CaptureView.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/Orgstar/CaptureView.swift history · blame · raw

352 lines · 16549 bytes

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