Sources/Orgstar/PaneView.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/Orgstar/PaneView.swift history · blame · raw

139 lines · 6628 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import OrgEditorAppKit
  5import OrgPresentation
  6import OrgHighlight
  7import SwiftUI
  8
  9/// What every editor view is set up with, from the settings.
 10struct EditorSettings: Equatable {
 11    var keymap = KeymapPreset.emacs.keymap
 12    var modal = false
 13    var optionAsMeta = OptionAsMeta.left
 14    var options = EditingOptions.org
 15    var showMarkup = false
 16    var showLineNumbers = true
 17    var theme = ThemeSpec.default
 18}
 19
 20/// One pane's editor: the text view of the buffer the pane shows, from the store, which keeps
 21/// one editor per open file and one text view per pane showing it. A new editor becomes its
 22/// buffer's live state; the pane's reveal requests go to its text view.
 23struct PaneView: NSViewRepresentable {
 24    /// One highlighter for every editor: it caches compiled grammars and results.
 25    static let highlighter = TreeSitterHighlighter()
 26
 27    let pane: EditorPane
 28    let session: DocumentSession
 29    let commands: AppCommands
 30    let settings: EditorSettings
 31    let onAppCommand: (String) -> Void
 32
 33    final class Coordinator {
 34        var path: String?
 35        var textView: NSTextView?
 36        var revealID = 0
 37    }
 38
 39    func makeCoordinator() -> Coordinator { Coordinator() }
 40
 41    func makeNSView(context: Context) -> NSView { NSView() }
 42
 43    func updateNSView(_ container: NSView, context: Context) {
 44        let coordinator = context.coordinator
 45        let store = commands.store
 46        if coordinator.path != pane.path {
 47            coordinator.path = pane.path
 48            container.subviews.forEach { $0.removeFromSuperview() }
 49            coordinator.textView = nil
 50            if let path = pane.path, let shown = store.view(for: pane, path: path, make: { makeEditor(path, container) }) {
 51                shown.scroll.frame = container.bounds
 52                container.addSubview(shown.scroll)
 53                coordinator.textView = shown.textView
 54                if session.focused === pane {
 55                    container.window?.makeFirstResponder(shown.textView)
 56                    commands.editor = shown.editor
 57                }
 58            } else if session.focused === pane {
 59                commands.editor = nil
 60            }
 61        }
 62        if let path = pane.path, let editor = store.editor(for: path) {
 63            if editor.keymap != settings.keymap { editor.keymap = settings.keymap }
 64            editor.modal = settings.modal
 65            editor.optionAsMeta = settings.optionAsMeta
 66            // `buffer-file-name`, for clock tables.
 67            var options = settings.options
 68            options.filePath = path
 69            if editor.options != options { editor.options = options }
 70            editor.showMarkup = settings.showMarkup
 71            editor.showLineNumbers = settings.showLineNumbers
 72            editor.themeSpec = settings.theme
 73        }
 74        container.window?.isDocumentEdited = !session.dirtyPaths.isEmpty
 75        if let request = pane.revealRequest, request.id != coordinator.revealID, let textView = coordinator.textView, let path = pane.path, let editor = store.editor(for: path) {
 76            coordinator.revealID = request.id
 77            // The editor reveals in its active view: this pane's, once it has focus.
 78            textView.window?.makeFirstResponder(textView)
 79            editor.reveal(request.offset)
 80        }
 81    }
 82
 83    /// An editor for `path`, which becomes the buffer's live state.
 84    private func makeEditor(_ path: String, _ container: NSView) -> OrgEditor? {
 85        guard let entry = session.openDocuments.first(where: { $0.path == path }) else { return nil }
 86        let document = entry.document
 87        let mode: OrgEditor.Mode = DocumentSession.isOrgPath(path) ? .org : .plain(language: FileTypes.language(path))
 88        let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable, highlighter: Self.highlighter, mode: mode, options: settings.options)
 89        let store = commands.store
 90        editor.onChange = { [weak session] in session?.bufferChanged(path) }
 91        editor.baseDirectory = URL(fileURLWithPath: path).deletingLastPathComponent()
 92        editor.onMessage = { [weak commands] in commands?.show($0) }
 93        editor.onKeysPending = { [weak commands] keys, next in
 94            commands?.pendingKeys = keys
 95            commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) }
 96        }
 97        editor.onModeChange = { [weak commands] in commands?.editorState = $0 }
 98        editor.onSelectionChange = { [weak commands] in commands?.selection = $0 }
 99        editor.onFocus = { [weak session, weak commands, weak editor] textView in
100            guard let session, let commands, let editor else { return }
101            commands.editor = editor
102            if let pane = store.pane(of: textView) {
103                session.focused = pane
104                store.window(of: pane.id)?.focused = pane.id
105            }
106        }
107        editor.onAppCommand = onAppCommand
108        editor.onOpenFile = { [weak session, weak commands] typed in
109            let expanded = (typed as NSString).expandingTildeInPath
110            let base = URL(fileURLWithPath: path).deletingLastPathComponent()
111            let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path
112            guard FileManager.default.fileExists(atPath: target) else {
113                commands?.show("No file \(typed)")
114                return
115            }
116            session?.open(target)
117        }
118        editor.onJumpToEditor = { [weak session] other, offset in
119            guard let session, let path = store.editors.first(where: { $0.value === other })?.key else { return }
120            session.open(path)
121            session.reveal(offset)
122        }
123        editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) }
124        editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } }
125        editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) }
126        editor.onEffect = { [weak commands, weak session] effect in
127            switch effect {
128            case .storedLinkUsed(let link): commands?.storedLinks.removeAll { $0.link == link }
129            case .copy(let text):
130                NSPasteboard.general.clearContents()
131                NSPasteboard.general.setString(text, forType: .string)
132            case .refreshSetup: session?.refreshSetup()
133            case .message, .sparseTree, .fold: break
134            }
135        }
136        session.attach(editor, for: path)
137        return editor
138    }
139}