Sources/Orgstar/PaneView.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/Orgstar/PaneView.swift history · blame · raw

136 lines · 6472 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            editor.options = settings.options
 67            editor.showMarkup = settings.showMarkup
 68            editor.showLineNumbers = settings.showLineNumbers
 69            editor.themeSpec = settings.theme
 70        }
 71        container.window?.isDocumentEdited = !session.dirtyPaths.isEmpty
 72        if let request = pane.revealRequest, request.id != coordinator.revealID, let textView = coordinator.textView, let path = pane.path, let editor = store.editor(for: path) {
 73            coordinator.revealID = request.id
 74            // The editor reveals in its active view: this pane's, once it has focus.
 75            textView.window?.makeFirstResponder(textView)
 76            editor.reveal(request.offset)
 77        }
 78    }
 79
 80    /// An editor for `path`, which becomes the buffer's live state.
 81    private func makeEditor(_ path: String, _ container: NSView) -> OrgEditor? {
 82        guard let entry = session.openDocuments.first(where: { $0.path == path }) else { return nil }
 83        let document = entry.document
 84        let mode: OrgEditor.Mode = DocumentSession.isOrgPath(path) ? .org : .plain(language: FileTypes.language(path))
 85        let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable, highlighter: Self.highlighter, mode: mode, options: settings.options)
 86        let store = commands.store
 87        editor.onChange = { [weak session] in session?.bufferChanged(path) }
 88        editor.baseDirectory = URL(fileURLWithPath: path).deletingLastPathComponent()
 89        editor.onMessage = { [weak commands] in commands?.show($0) }
 90        editor.onKeysPending = { [weak commands] keys, next in
 91            commands?.pendingKeys = keys
 92            commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) }
 93        }
 94        editor.onModeChange = { [weak commands] in commands?.editorState = $0 }
 95        editor.onSelectionChange = { [weak commands] in commands?.selection = $0 }
 96        editor.onFocus = { [weak session, weak commands, weak editor] textView in
 97            guard let session, let commands, let editor else { return }
 98            commands.editor = editor
 99            if let pane = store.pane(of: textView) {
100                session.focused = pane
101                store.window(of: pane.id)?.focused = pane.id
102            }
103        }
104        editor.onAppCommand = onAppCommand
105        editor.onOpenFile = { [weak session, weak commands] typed in
106            let expanded = (typed as NSString).expandingTildeInPath
107            let base = URL(fileURLWithPath: path).deletingLastPathComponent()
108            let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path
109            guard FileManager.default.fileExists(atPath: target) else {
110                commands?.show("No file \(typed)")
111                return
112            }
113            session?.open(target)
114        }
115        editor.onJumpToEditor = { [weak session] other, offset in
116            guard let session, let path = store.editors.first(where: { $0.value === other })?.key else { return }
117            session.open(path)
118            session.reveal(offset)
119        }
120        editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) }
121        editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } }
122        editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) }
123        editor.onEffect = { [weak commands, weak session] effect in
124            switch effect {
125            case .storedLinkUsed(let link): commands?.storedLinks.removeAll { $0.link == link }
126            case .copy(let text):
127                NSPasteboard.general.clearContents()
128                NSPasteboard.general.setString(text, forType: .string)
129            case .refreshSetup: session?.refreshSetup()
130            case .message, .sparseTree, .fold: break
131            }
132        }
133        session.attach(editor, for: path)
134        return editor
135    }
136}