Sources/Orgstar/PaneView.swift
143 lines · 6907 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.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
95 editor.onMessage = { [weak commands] in commands?.show($0) }
96 editor.onKeysPending = { [weak commands] keys, next in
97 commands?.pendingKeys = keys
98 commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) }
99 }
100 editor.onModeChange = { [weak commands] in commands?.editorState = $0 }
101 editor.onSelectionChange = { [weak commands] in commands?.selection = $0 }
102 editor.onFocus = { [weak session, weak commands, weak editor] textView in
103 guard let session, let commands, let editor else { return }
104 commands.editor = editor
105 if let pane = store.pane(of: textView) {
106 session.focused = pane
107 store.window(of: pane.id)?.focused = pane.id
108 }
109 }
110 editor.onAppCommand = onAppCommand
111 editor.onOpenFile = { [weak session, weak commands] typed in
112 let expanded = (typed as NSString).expandingTildeInPath
113 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
114 let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path
115 guard FileManager.default.fileExists(atPath: target) else {
116 commands?.show("No file \(typed)")
117 return
118 }
119 session?.open(target)
120 }
121 editor.onJumpToEditor = { [weak session] other, offset in
122 guard let session, let path = store.editors.first(where: { $0.value === other })?.key else { return }
123 session.open(path)
124 session.reveal(offset)
125 }
126 editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) }
127 editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } }
128 editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) }
129 editor.onEffect = { [weak commands, weak session] effect in
130 switch effect {
131 case .storedLinkUsed(let link): commands?.storedLinks.removeAll { $0.link == link }
132 case .copy(let text):
133 NSPasteboard.general.clearContents()
134 NSPasteboard.general.setString(text, forType: .string)
135 case .refreshSetup: session?.refreshSetup()
136 case .timer(let timer): TimerModel.shared.set(timer)
137 case .message, .sparseTree, .fold: break
138 }
139 }
140 session.attach(editor, for: path)
141 return editor
142 }
143}