Sources/Orgstar/ContentView.swift

6dc096637db6e263db38fad845d46bc852cd3962
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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