Sources/Orgstar/PaneView.swift

68713d7d2d6d1639dde4cea824091b453ecbd1d5
orgstar/Sources/Orgstar/PaneView.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form