Sources/Orgstar/ContentView.swift

e28aeb4beaa6ea07f2762b6a522439ee0371b2e0
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

563 lines · 24924 bytes

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