Sources/Orgstar/ContentView.swift

1ee4104d217911b4b02b04a288f8cd7128ead4dd
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

472 lines · 20665 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import OrgEditorAppKit
  5import OrgIndex
  6import SwiftUI
  7
  8struct ContentView: View {
  9    let workspace: WorkspaceModel
 10    let session: DocumentSession
 11    @Bindable var commands: AppCommands
 12    let scheduler: ReminderScheduler?
 13    let clock: ClockModel
 14    @AppStorage("reminders") private var remindersEnabled = true
 15    @AppStorage("reminderLead") private var reminderLead = 12
 16    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 17    @State private var reminderAgenda: AgendaModel?
 18    @State private var trust = TrustStore()
 19    @State private var hotKey: GlobalHotKey?
 20    @State private var statusItem: ClockStatusItem?
 21    @AppStorage("globalCapture") private var globalCapture = true
 22    @State private var hour = 0
 23    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 24    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 25    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 26    @State private var keymap = KeymapPreset.emacs.keymap
 27    @AppStorage("tagsColumn") private var tagsColumn = -77
 28    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
 29    @AppStorage("splitLine") private var splitLine = false
 30    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 31    @AppStorage("fillColumn") private var fillColumn = 80
 32    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 33    @AppStorage("prettyEntities") private var prettyEntities = true
 34
 35    private var options: EditingOptions {
 36        Preferences.options(
 37            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
 38            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities
 39        )
 40    }
 41    @State private var selectedFile: String?
 42    @State private var query = ""
 43    @FocusState private var searchFocused: Bool
 44    @Environment(\.openWindow) private var openWindow
 45    @Environment(\.openSettings) private var openSettings
 46
 47    private var main: some View {
 48        NavigationSplitView {
 49            Sidebar(workspace: workspace, selection: $selectedFile)
 50                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
 51        } content: {
 52            Group {
 53                if query.isEmpty {
 54                    OutlineColumn(session: session)
 55                } else {
 56                    SearchResults(results: workspace.search(query, overlay: workspace.overlay(path: session.path, document: session.document))) { location in
 57                        guard location.path == session.path || UnsavedChanges.resolve(session) else { return }
 58                        selectedFile = location.path
 59                        session.show(location)
 60                    }
 61                }
 62            }
 63            .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 360)
 64        } detail: {
 65            if session.path != nil {
 66                EditorView(session: session, commands: commands, keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, onAppCommand: perform, onExternal: runExternal)
 67                    .safeAreaInset(edge: .bottom, spacing: 0) { EchoArea(commands: commands) }
 68            } else {
 69                ContentUnavailableView(
 70                    workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
 71                    systemImage: "doc.text",
 72                    description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 73                )
 74            }
 75        }
 76        .navigationTitle(session.path.map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
 77        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
 78        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
 79        .searchFocused($searchFocused)
 80        .toolbar {
 81            if workspace.isIndexing { ProgressView().controlSize(.small) }
 82            if let running = clock.running {
 83                Menu {
 84                    Button("Clock Out") { perform("app.clock.out") }
 85                    Button("Cancel Clock") { perform("app.clock.cancel") }
 86                    Button("Go to Clocked Entry") { perform("app.clock.goto") }
 87                } label: {
 88                    TimelineView(.periodic(from: .now, by: 30)) { context in
 89                        Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
 90                    }
 91                }
 92                .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
 93            }
 94            if session.conflict != nil {
 95                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
 96                    .help("The file changed on disk, and the changes conflict with yours")
 97            }
 98        }
 99        .onChange(of: selectedFile) { old, path in
100            guard let path, path != session.path else { return }
101            if UnsavedChanges.resolve(session) {
102                session.open(path)
103            } else {
104                selectedFile = old
105            }
106        }
107        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
108        .onChange(of: options, initial: true) { _, options in session.options = options }
109        .onChange(of: preset, initial: true) { loadKeymap() }
110        .sheet(isPresented: $commands.showingPalette) {
111            PaletteView(keymap: keymap) { id in
112                commands.showingPalette = false
113                // After the sheet closes, so app commands can present their own.
114                DispatchQueue.main.async { perform(id) }
115            }
116        }
117        .onChange(of: session.conflict) { _, conflict in
118            if conflict != nil { commands.showingConflict = true }
119        }
120        .alert("Conflicting changes", isPresented: $commands.showingConflict) {
121            Button("Keep Mine") { session.keepMine() }
122            Button("Use Disk Version") { session.useDiskVersion() }
123            Button("Decide Later", role: .cancel) {}
124        } message: {
125            Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
126        }
127        .onChange(of: workspace.changedFile?.version) {
128            if let path = workspace.changedFile?.path { session.fileChanged(path) }
129        }
130    }
131
132    var body: some View {
133        main
134        .onChange(of: clock.running, initial: true) { _, running in
135            if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
136            statusItem?.update(running)
137        }
138        .onChange(of: globalCapture, initial: true) { _, enabled in
139            hotKey?.unregister()
140            hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
141        }
142        .onChange(of: commands.runRequest?.serial) {
143            if let id = commands.runRequest?.id { perform(id) }
144        }
145        .onChange(of: commands.jumpRequest?.id) {
146            guard let request = commands.jumpRequest else { return }
147            if request.path != session.path {
148                guard UnsavedChanges.resolve(session) else { return }
149                session.open(request.path)
150                selectedFile = request.path
151            }
152            session.reveal(request.offset)
153        }
154        .onChange(of: commands.focusSearch) { _, focus in
155            if focus {
156                searchFocused = true
157                commands.focusSearch = false
158            }
159        }
160        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
161            guard case .success(let url) = result else { return }
162            Task {
163                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
164            }
165        }
166        .sheet(isPresented: $commands.showingQuickOpen) {
167            QuickOpenView(workspace: workspace) { entry in
168                selectedFile = entry.path
169                commands.showingQuickOpen = false
170            }
171        }
172        .alert("Orgstar", isPresented: errorShown) {
173            Button("OK") {
174                workspace.lastError = nil
175                session.lastError = nil
176            }
177        } message: {
178            Text(workspace.lastError ?? session.lastError ?? "")
179        }
180        .task(id: ReminderKey(
181            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
182            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
183        )) {
184            await updateReminders()
185        }
186        .task {
187            while !Task.isCancelled {
188                try? await Task.sleep(for: .seconds(3600))
189                hour += 1
190            }
191        }
192        .task {
193            DevelopmentHooks.scheduleSnapshot()
194            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
195            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
196            if let id = DevelopmentHooks.windowToOpen {
197                if id == "settings" { openSettings() } else { openWindow(id: id) }
198            }
199            await workspace.refresh()
200            workspace.startWatching()
201        }
202    }
203
204    /// Writes the export beside the file, as Emacs's export dispatcher does.
205    private func export(_ format: String) {
206        guard let path = session.path, let text = session.document?.text else {
207            commands.show("No file is open")
208            return
209        }
210        let url = URL(fileURLWithPath: path)
211        let base = url.deletingPathExtension()
212        let defaults = Preferences.orgSettings
213        switch format {
214        case "html", "html-open", "markdown":
215            let target = base.appendingPathExtension(format == "markdown" ? "md" : "html")
216            let content = format == "markdown"
217                ? MarkdownExport.document(text, settings: defaults)
218                : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults)
219            do {
220                try content.write(to: target, atomically: true, encoding: .utf8)
221                commands.show("Exported to \(target.lastPathComponent)")
222                if format == "html-open" { NSWorkspace.shared.open(target) }
223            } catch {
224                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
225            }
226        default:
227            let functions = ["pdf": "org-latex-export-to-pdf", "odt": "org-odt-export-to-odt", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
228            guard let function = functions[format] else { return }
229            commands.show("Exporting with Emacs…")
230            Task {
231                do {
232                    let written = try await EmacsRunner.export(text: text, path: path, function: function)
233                    commands.show("Exported to \((written as NSString).lastPathComponent)")
234                } catch {
235                    commands.show("\(error)")
236                }
237            }
238        }
239    }
240
241    /// Work a command hands to the platform: tables recalculated in Emacs.
242    private func runExternal(_ request: ExternalRequest) {
243        switch request {
244        case .emacsTable(let table, let point, let form, let reason, let lisp):
245            let run = {
246                commands.show("Recalculating in Emacs (\(reason))…")
247                Task { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
248            }
249            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
250            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
251            if trust.isTrusted(path: path, content: content) { return run() }
252            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
253                switch answer {
254                case "always":
255                    trust.trust(path: path, content: content)
256                    run()
257                case "yes": run()
258                default: commands.show("Not recalculated")
259                }
260            }
261        case .babel(let job):
262            let run = {
263                commands.show("Running \(job.language) block…")
264                Task { commands.show(await session.runBabel(job)) }
265            }
266            guard let path = session.path else { return }
267            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
268            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
269            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
270                switch answer {
271                case "always":
272                    trust.trust(path: path, content: job.blockText)
273                    run()
274                case "yes": run()
275                default: commands.show("Not run")
276                }
277            }
278        }
279    }
280
281    private struct ReminderKey: Hashable {
282        var enabled: Bool
283        var lead: Int
284        var subfolders: Bool
285        var files: Int
286        var changed: Int?
287        var edits: Int
288        var hour: Int
289    }
290
291    /// Sets the notifications for the next week's timed entries, once edits pause.
292    private func updateReminders() async {
293        guard let scheduler else { return }
294        guard remindersEnabled else {
295            await scheduler.clear()
296            return
297        }
298        try? await Task.sleep(for: .seconds(2))
299        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
300        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
301        reminderAgenda = agenda
302        agenda.includeSubfolders = agendaSubfolders
303        let open = session.path.flatMap { path in session.document.map { (path, $0.text) } }
304        let reminders = await agenda.reminders(open: open, lead: reminderLead)
305        guard !Task.isCancelled else { return }
306        await scheduler.reconcile(reminders)
307    }
308
309    private func loadKeymap() {
310        let loaded = KeymapLoader.load(preset)
311        keymap = loaded.keymap
312        if let first = loaded.problems.first {
313            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
314            commands.show("keymap.toml: \(first)\(more)")
315        }
316    }
317
318    /// Runs a command from a key, the palette or the Org menu.
319    private func perform(_ id: String) {
320        switch id {
321        case "app.save":
322            if !session.save(), session.conflict != nil { commands.showingConflict = true }
323        case "app.quick-open": commands.showingQuickOpen = true
324        case "app.palette": commands.showingPalette = true
325        case "app.search": commands.focusSearch = true
326        case "app.reload-keymap":
327            loadKeymap()
328            commands.show("Keymap reloaded")
329        case "app.refile":
330            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
331            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
332                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
333                if let message = session.refile(to: target) { commands.show(message) }
334            }
335        case "app.archive":
336            if let message = session.archive() { commands.show(message) }
337        case "app.agenda":
338            openWindow(id: "agenda")
339        case "app.clock.in":
340            commands.show(clock.clockIn(session))
341        case "app.clock.out":
342            commands.show(clock.clockOut(session))
343        case "app.clock.cancel":
344            commands.show(clock.clockOut(session, cancel: true))
345        case "app.clock.goto":
346            if let location = clock.location(session) { commands.jump(path: location.path, offset: location.offset) } else { commands.show("No active clock") }
347        case "app.clock.report":
348            openWindow(id: "clock-report")
349        case "app.board":
350            openWindow(id: "board")
351        case "app.capture":
352            NSApp.activate()
353            openWindow(id: "capture")
354        case let id where id.hasPrefix("app.export."):
355            export(String(id.dropFirst("app.export.".count)))
356        default:
357            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
358        }
359    }
360
361    private var errorShown: Binding<Bool> {
362        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
363    }
364}
365
366struct Sidebar: View {
367    let workspace: WorkspaceModel
368    @Binding var selection: String?
369
370    var body: some View {
371        List(selection: $selection) {
372            ForEach(workspace.rootPaths, id: \.self) { root in
373                Section((root as NSString).lastPathComponent) {
374                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
375                        Label(node.name, systemImage: icon(node))
376                            .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
377                            .tag(node.file?.path)
378                    }
379                }
380                .contextMenu {
381                    Button("Remove Folder") { try? workspace.removeRoot(path: root) }
382                }
383            }
384        }
385        .listStyle(.sidebar)
386    }
387
388    private func icon(_ node: FileTreeNode) -> String {
389        guard let file = node.file else { return "folder" }
390        switch file.kind {
391        case .org: return "doc.text"
392        case .archive: return "archivebox"
393        case .conflict: return "exclamationmark.triangle"
394        }
395    }
396}
397
398struct OutlineColumn: View {
399    let session: DocumentSession
400
401    var body: some View {
402        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
403            Button {
404                session.reveal(entry.start)
405            } label: {
406                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
407                    .lineLimit(1)
408                    .padding(.leading, CGFloat(entry.level - 1) * 12)
409            }
410            .buttonStyle(.plain)
411        }
412        .overlay {
413            if session.path != nil, session.outline.isEmpty {
414                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
415            }
416        }
417    }
418}
419
420struct SearchResults: View {
421    let results: [HeadingLocation]
422    let open: (HeadingLocation) -> Void
423
424    var body: some View {
425        List(results, id: \.self) { location in
426            Button {
427                open(location)
428            } label: {
429                VStack(alignment: .leading, spacing: 2) {
430                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
431                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
432                }
433            }
434            .buttonStyle(.plain)
435        }
436        .overlay {
437            if results.isEmpty { ContentUnavailableView.search }
438        }
439    }
440}
441
442struct QuickOpenView: View {
443    let workspace: WorkspaceModel
444    let open: (FileEntry) -> Void
445    @State private var query = ""
446    @Environment(\.dismiss) private var dismiss
447
448    var body: some View {
449        let matches = workspace.quickOpen(query)
450        VStack(spacing: 0) {
451            TextField("Open file", text: $query)
452                .textFieldStyle(.plain)
453                .font(.title3)
454                .padding(12)
455                .onSubmit { if let first = matches.first { open(first) } }
456            Divider()
457            List(matches) { entry in
458                Button {
459                    open(entry)
460                } label: {
461                    VStack(alignment: .leading, spacing: 2) {
462                        Text(entry.name)
463                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
464                    }
465                }
466                .buttonStyle(.plain)
467            }
468        }
469        .frame(width: 520, height: 360)
470        .onExitCommand { dismiss() }
471    }
472}