Sources/Orgstar/ContentView.swift

2e50d150645045338c8026719a350801b4edfc44
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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