Files
helder/Sources/HelderUI/Editor/CodeEditorController.swift
T

541 lines
24 KiB
Swift

import AppKit
import HelderCore
/// What the code pane shows; rebuilt by SwiftUI on every update, applied only where it changed.
struct CodeEditorConfiguration {
/// Identifies the document: the path plus the variant (`#original` for the HEAD text).
var documentID: String
var path: String
var text: String
/// Replace the view's text only when this moves; otherwise the user's typing is the truth.
var revision: Int
var language: Language?
var isEditable: Bool
var wrap: Bool
var tabSize: Int
/// Cheap identity of the marks; `makeMarks` runs only when it moves.
var marksKey: String
var makeMarks: () -> [Int: CodeLineMark]
var opensDiffOnClick: Bool
var knownSymbols: Set<String>
var symbolsVersion: Int
var flash: LineFlash?
/// The text view takes keyboard focus when this moves while the pane is shown.
var focusRequest: Int
/// ⌘A outside the text view: everything is selected when this moves while the pane is shown.
var selectAllRequest: Int
/// View → Zoom.
var fontScale: CGFloat
var isShown: Bool
}
struct CodeEditorActions {
var edited: (String) -> Void = { _ in }
var cursorMoved: (_ line: Int, _ column: Int) -> Void = { _, _ in }
var selectionChanged: (_ lines: ClosedRange<Int>?, _ code: String?) -> Void = { _, _ in }
var markedLineClicked: (Int) -> Void = { _ in }
/// Reference, selected code, and the anchor in top-left window coordinates.
var contextMenu: (AgentReference, String?, CGPoint) -> Void = { _, _, _ in }
var symbolClicked: (String) -> Void = { _ in }
/// ⌘→ with a selection; returns false when there was nothing to pass.
var passOnSelection: (CGPoint) -> Bool = { _ in false }
var command: (EditorKeyCommand) -> Void = { _ in }
}
@MainActor
final class CodeEditorController: NSObject, NSTextViewDelegate, NSLayoutManagerDelegate {
let scrollView = CodeScrollView()
let textView: CodeTextView
let gutter: CodeGutterView
var actions = CodeEditorActions()
private let layoutManager = NSLayoutManager()
private let container = NSTextContainer(size: NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
private var documents: [String: CodeDocument] = [:]
private var recent: [String] = []
private(set) var document: CodeDocument?
private(set) var configuration: CodeEditorConfiguration?
private(set) var marks: [Int: CodeLineMark] = [:]
private var wrap: Bool?
private var appliedFlash: UUID?
var flashLine: Int?
var flashStart: Date?
var flashTimer: Timer?
private(set) var symbolsUnderlined = false
private var appliedFocusRequest: Int?
private var appliedSelectAll: Int?
/// Read by the layout delegate, which AppKit calls off the main-actor annotation.
nonisolated(unsafe) private(set) var fontScale: CGFloat = 1
/// True inside `apply`: store updates then wait a turn, since SwiftUI is mid-update.
private var isApplying = false
var layout: NSLayoutManager { layoutManager }
var textContainer: NSTextContainer { container }
private static let documentCacheSize = 12
override init() {
let storage = NSTextStorage()
storage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(container)
layoutManager.allowsNonContiguousLayout = true
textView = CodeTextView(frame: .zero, textContainer: container)
gutter = CodeGutterView(scrollView: scrollView, orientation: .verticalRuler)
super.init()
layoutManager.delegate = self
configureTextView()
configureScrollView()
}
private func configureTextView() {
let tv = textView
tv.controller = self
tv.delegate = self
tv.isRichText = false
tv.importsGraphics = false
tv.allowsUndo = true
tv.usesFindBar = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.isContinuousSpellCheckingEnabled = false
tv.isGrammarCheckingEnabled = false
tv.isAutomaticLinkDetectionEnabled = false
tv.smartInsertDeleteEnabled = false
tv.drawsBackground = true
tv.backgroundColor = EditorColors.background
tv.insertionPointColor = EditorColors.amber
tv.selectedTextAttributes = [.backgroundColor: EditorColors.selection]
tv.font = EditorFonts.code
tv.textColor = EditorColors.syntax(.plain)
tv.typingAttributes = EditorFonts.baseAttributes(tabSize: 4)
tv.textContainerInset = NSSize(width: 0, height: EditorFonts.topInset)
tv.isVerticallyResizable = true
tv.minSize = .zero
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
container.lineFragmentPadding = 6
}
private func configureScrollView() {
scrollView.onTile = { [weak self] in self?.fitTextView() }
scrollView.documentView = textView
scrollView.drawsBackground = true
scrollView.backgroundColor = EditorColors.background
scrollView.hasVerticalScroller = true
scrollView.autohidesScrollers = true
scrollView.borderType = .noBorder
scrollView.automaticallyAdjustsContentInsets = false
scrollView.contentInsets = NSEdgeInsets(top: 0, left: 0, bottom: EditorFonts.bottomInset - EditorFonts.topInset, right: 0)
gutter.controller = self
gutter.ruleThickness = Metrics.codeGutter
// Since macOS 14 a view may draw outside its bounds; unclipped, the gutter paints over the columns around it.
gutter.clipsToBounds = true
gutter.clientView = textView
scrollView.verticalRulerView = gutter
scrollView.hasVerticalRuler = true
scrollView.rulersVisible = true
scrollView.contentView.postsBoundsChangedNotifications = true
NotificationCenter.default.addObserver(self, selector: #selector(scrolled), name: NSView.boundsDidChangeNotification,
object: scrollView.contentView)
}
@objc private func scrolled() {
gutter.needsDisplay = true
}
// MARK: Applying the configuration
func apply(_ next: CodeEditorConfiguration) {
isApplying = true
defer { isApplying = false }
let previous = configuration
configuration = next
applyWrap(next.wrap)
applyScale(next.fontScale)
textView.isEditable = next.isEditable
textView.isSelectable = true
var reloaded = false
if document?.id != next.documentID {
reloaded = switchDocument(to: next)
} else if let doc = document, doc.revision != next.revision {
replaceText(of: doc, with: next)
reloaded = true
}
guard let doc = document else { return }
doc.setTabSize(next.tabSize)
doc.setScale(fontScale)
if reloaded || doc.language != next.language || doc.symbolsVersion != next.symbolsVersion {
doc.language = next.language
doc.highlightAll(symbols: next.knownSymbols, version: next.symbolsVersion)
}
if previous?.marksKey != next.marksKey || previous?.documentID != next.documentID {
marks = next.makeMarks()
textView.needsDisplay = true
gutter.needsDisplay = true
}
applyFlash(next.flash, path: next.path)
applyFocusRequest(next)
applySelectAll(next)
}
private func applySelectAll(_ next: CodeEditorConfiguration) {
defer { appliedSelectAll = next.selectAllRequest }
guard let applied = appliedSelectAll, applied != next.selectAllRequest, next.isShown else { return }
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.focusTextView()
self.textView.selectAll(nil)
}
}
private func applyScale(_ scale: CGFloat) {
guard scale != fontScale else { return }
fontScale = scale
textView.font = EditorFonts.code(scale: scale)
textView.typingAttributes = EditorFonts.baseAttributes(tabSize: configuration?.tabSize ?? 4, scale: scale)
for doc in documents.values { doc.setScale(scale) }
layoutManager.invalidateLayout(forCharacterRange: NSRange(location: 0, length: layoutManager.textStorage?.length ?? 0),
actualCharacterRange: nil)
textView.needsDisplay = true
gutter.needsDisplay = true
}
/// Waits a turn so an overlay that just closed has left the window, and never takes
/// focus from a text field another overlay is typing in.
private func applyFocusRequest(_ next: CodeEditorConfiguration) {
defer { appliedFocusRequest = next.focusRequest }
guard let applied = appliedFocusRequest, applied != next.focusRequest, next.isShown else { return }
DispatchQueue.main.async { [weak self] in
guard let self, let window = self.textView.window else { return }
if let field = window.firstResponder as? NSTextView, field.isFieldEditor { return }
self.focusTextView()
}
}
/// Returns true when the document's text was (re)loaded and needs colouring.
private func switchDocument(to next: CodeEditorConfiguration) -> Bool {
if let current = document {
current.selection = textView.selectedRange()
current.scrollOrigin = scrollView.contentView.bounds.origin
}
let doc = documents[next.documentID] ?? CodeDocument(id: next.documentID)
documents[next.documentID] = doc
recent.removeAll { $0 == next.documentID }
recent.insert(next.documentID, at: 0)
for evicted in recent.dropFirst(Self.documentCacheSize) { documents[evicted] = nil }
recent = Array(recent.prefix(Self.documentCacheSize))
let isNew = doc.revision != next.revision
if isNew {
doc.language = next.language
doc.setScale(fontScale)
doc.load(next.text, revision: next.revision, tabSize: next.tabSize)
}
document = doc
layoutManager.replaceTextStorage(doc.storage)
textView.typingAttributes = EditorFonts.baseAttributes(tabSize: next.tabSize, scale: fontScale)
textView.setSelectedRange(clamped(doc.selection, in: doc))
appliedFlash = nil
flashLine = nil
let clip = scrollView.contentView
// The ruler gives the clip view a left inset, so its resting origin is not .zero.
let home = NSPoint(x: -clip.contentInsets.left, y: -clip.contentInsets.top)
clip.scroll(to: isNew ? home : doc.scrollOrigin)
scrollView.reflectScrolledClipView(clip)
textView.needsDisplay = true
gutter.needsDisplay = true
reportSelection()
return isNew
}
private func replaceText(of doc: CodeDocument, with next: CodeEditorConfiguration) {
let selection = textView.selectedRange()
let origin = scrollView.contentView.bounds.origin
doc.load(next.text, revision: next.revision, tabSize: next.tabSize)
textView.setSelectedRange(NSRange(location: min(selection.location, doc.length), length: 0))
scrollView.contentView.scroll(to: origin)
scrollView.reflectScrolledClipView(scrollView.contentView)
gutter.needsDisplay = true
}
private func clamped(_ range: NSRange, in doc: CodeDocument) -> NSRange {
let location = min(range.location, doc.length)
return NSRange(location: location, length: min(range.length, doc.length - location))
}
/// The text view always fills the visible width; unwrapped it may grow wider.
private func fitTextView() {
let size = scrollView.contentSize
let width = visibleWidth
if textView.frame.origin != .zero { textView.setFrameOrigin(.zero) }
textView.minSize = NSSize(width: width, height: size.height)
if wrap == true || textView.frame.width < width {
textView.frame.size.width = width
}
if textView.frame.height < size.height { textView.frame.size.height = size.height }
}
/// The content width right of the gutter.
private var visibleWidth: CGFloat {
max(1, scrollView.contentSize.width - scrollView.contentView.contentInsets.left)
}
private func applyWrap(_ on: Bool) {
guard wrap != on else { return }
wrap = on
scrollView.hasHorizontalScroller = !on
textView.isHorizontallyResizable = !on
container.widthTracksTextView = on
textView.autoresizingMask = on ? [.width] : []
container.containerSize = NSSize(width: on ? visibleWidth : CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
fitTextView()
layoutManager.invalidateLayout(forCharacterRange: NSRange(location: 0, length: layoutManager.textStorage?.length ?? 0),
actualCharacterRange: nil)
gutter.needsDisplay = true
}
private func applyFlash(_ flash: LineFlash?, path: String) {
guard let flash, flash.path == path else {
if flashLine != nil { endFlash() }
return
}
guard appliedFlash != flash.id, let doc = document, doc.revision > 0 || doc.length > 0 else { return }
appliedFlash = flash.id
startFlash(on: flash.line)
scroll(toLine: flash.line)
let offset = doc.lineIndex.start(ofLine: flash.line)
textView.setSelectedRange(NSRange(location: min(offset, doc.length), length: 0))
textView.needsDisplay = true
}
/// Centres a line in the pane, as near as the file permits.
func scroll(toLine line: Int) {
guard let doc = document else { return }
let rect = rowRect(forLine: line, in: doc)
let clip = scrollView.contentView
let maxY = max(0, textView.frame.height - clip.bounds.height)
let y = min(max(0, rect.midY - clip.bounds.height / 2), maxY)
clip.scroll(to: NSPoint(x: clip.bounds.origin.x, y: y))
scrollView.reflectScrolledClipView(clip)
}
private func rowRect(forLine line: Int, in doc: CodeDocument) -> NSRect {
let offset = doc.lineIndex.start(ofLine: line)
let origin = textView.textContainerOrigin
guard offset < doc.length else {
return layoutManager.extraLineFragmentRect.offsetBy(dx: origin.x, dy: origin.y)
}
let glyph = layoutManager.glyphIndexForCharacter(at: offset)
return layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).offsetBy(dx: origin.x, dy: origin.y)
}
// MARK: Rows
struct Row {
var line: Int
var isFirst: Bool
var isLast: Bool
/// In text view coordinates.
var rect: NSRect
}
/// Every visual row that intersects `rect` (text view coordinates), wrapped rows included.
func forEachRow(in rect: NSRect, _ body: (Row) -> Void) {
guard let doc = document else { return }
let origin = textView.textContainerOrigin
let index = doc.lineIndex
let bounds = rect.offsetBy(dx: -origin.x, dy: -origin.y)
let glyphs = layoutManager.glyphRange(forBoundingRect: bounds, in: container)
var glyph = glyphs.location
while glyph < NSMaxRange(glyphs) {
var fragment = NSRange()
let frame = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &fragment)
let chars = layoutManager.characterRange(forGlyphRange: fragment, actualGlyphRange: nil)
let line = index.line(containing: chars.location)
body(Row(line: line, isFirst: index.isLineStart(chars.location),
isLast: NSMaxRange(chars) >= index.end(ofLine: line),
rect: frame.offsetBy(dx: origin.x, dy: origin.y)))
glyph = max(NSMaxRange(fragment), glyph + 1)
}
if layoutManager.extraLineFragmentTextContainer != nil {
let extra = layoutManager.extraLineFragmentRect.offsetBy(dx: origin.x, dy: origin.y)
if extra.intersects(rect.insetBy(dx: 0, dy: -1)) {
body(Row(line: index.lineCount, isFirst: true, isLast: true, rect: extra))
}
}
}
// MARK: Layout: fixed rows, 20pt at actual size
nonisolated func layoutManager(_ layoutManager: NSLayoutManager,
shouldSetLineFragmentRect lineFragmentRect: UnsafeMutablePointer<NSRect>,
lineFragmentUsedRect: UnsafeMutablePointer<NSRect>,
baselineOffset: UnsafeMutablePointer<CGFloat>,
in textContainer: NSTextContainer, forGlyphRange glyphRange: NSRange) -> Bool {
let height = EditorFonts.lineHeight(scale: fontScale)
lineFragmentRect.pointee.size.height = height
lineFragmentUsedRect.pointee.size.height = height
baselineOffset.pointee = EditorFonts.baseline(scale: fontScale)
return true
}
// MARK: Text view delegate
nonisolated func undoManager(for view: NSTextView) -> UndoManager? {
MainActor.assumeIsolated { document?.undoManager }
}
nonisolated func textDidChange(_ notification: Notification) {
MainActor.assumeIsolated {
guard let doc = document else { return }
doc.highlightEdits()
actions.edited(textView.string)
gutter.needsDisplay = true
}
}
nonisolated func textViewDidChangeSelection(_ notification: Notification) {
MainActor.assumeIsolated {
reportSelection()
textView.needsDisplay = true
gutter.needsDisplay = true
}
}
private func reportSelection() {
if isApplying {
DispatchQueue.main.async { [weak self] in self?.reportSelection() }
return
}
guard let doc = document else { return }
let range = textView.selectedRange()
let caret = min(range.location + range.length, doc.length)
actions.cursorMoved(doc.lineIndex.line(containing: caret), doc.lineIndex.column(of: caret))
if range.length > 0 {
let code = (doc.storage.string as NSString).substring(with: clamped(range, in: doc))
actions.selectionChanged(EditorReference.lines(of: range, in: doc.lineIndex), code)
} else {
actions.selectionChanged(nil, nil)
}
}
// MARK: Gestures
private func characterIndex(atWindowPoint point: NSPoint) -> Int {
textView.characterIndexForInsertion(at: textView.convert(point, from: nil))
}
private func line(atWindowPoint point: NSPoint) -> Int? {
guard let doc = document else { return nil }
let local = textView.convert(point, from: nil)
let used = layoutManager.usedRect(for: container).offsetBy(dx: 0, dy: textView.textContainerOrigin.y)
guard local.y <= used.maxY else { return nil }
return doc.lineIndex.line(containing: characterIndex(atWindowPoint: point))
}
/// A plain click on a marked line in Actual opens the Diff there.
func plainClick(atWindowPoint point: NSPoint) {
guard configuration?.opensDiffOnClick == true,
let line = line(atWindowPoint: point), marks[line] != nil else { return }
let action = actions.markedLineClicked
DispatchQueue.main.async { action(line) }
}
/// ⌘-click: follows a class name the project declares.
func followSymbol(at event: NSEvent) -> Bool {
guard let name = symbol(atWindowPoint: event.locationInWindow) else { return false }
actions.symbolClicked(name)
return true
}
/// The known class name under the pointer; only a hit on the glyph itself counts, not the space after a line.
func symbol(atWindowPoint point: NSPoint) -> String? {
guard let configuration, !configuration.knownSymbols.isEmpty, let doc = document, doc.length > 0 else { return nil }
let origin = textView.textContainerOrigin
let local = textView.convert(point, from: nil)
let inContainer = NSPoint(x: local.x - origin.x, y: local.y - origin.y)
let glyph = layoutManager.glyphIndex(for: inContainer, in: container)
let box = layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: container)
guard box.contains(inContainer) else { return nil }
let name = PHPSymbols.word(in: doc.storage.string, at: layoutManager.characterIndexForGlyph(at: glyph))
return configuration.knownSymbols.contains(name) ? name : nil
}
func showContextMenu(for event: NSEvent) {
guard let configuration, let doc = document else { return }
focusTextView()
let selection = textView.selectedRange()
let clicked = line(atWindowPoint: event.locationInWindow) ?? doc.lineIndex.lineCount
let lines = selection.length > 0 ? EditorReference.lines(of: selection, in: doc.lineIndex) : nil
let code = selection.length > 0 ? (doc.storage.string as NSString).substring(with: clamped(selection, in: doc)) : nil
let reference = EditorReference.make(path: configuration.path, selectedLines: lines, clickedLine: clicked)
actions.contextMenu(reference, code, topLeft(event.locationInWindow))
}
func passOnSelection() -> Bool {
let range = textView.selectedRange()
guard range.length > 0, let window = textView.window else { return false }
let screen = textView.firstRect(forCharacterRange: range, actualRange: nil)
let rect = window.convertFromScreen(screen)
return actions.passOnSelection(topLeft(NSPoint(x: rect.minX, y: rect.minY)))
}
func run(_ command: EditorKeyCommand) {
actions.command(command)
}
func indent(outdent: Bool) -> Bool {
guard textView.isEditable, let configuration, let doc = document,
let edit = Indentation.edit(doc.storage.string, selection: textView.selectedRange(),
tabSize: configuration.tabSize, outdent: outdent) else { return textView.isEditable }
guard textView.shouldChangeText(in: edit.range, replacementString: edit.replacement) else { return true }
doc.storage.replaceCharacters(in: edit.range, with: NSAttributedString(string: edit.replacement, attributes: textView.typingAttributes))
textView.didChangeText()
textView.setSelectedRange(edit.selection)
textView.scrollRangeToVisible(edit.selection)
return true
}
func gutterClick(atWindowPoint point: NSPoint, extend: Bool) {
guard let doc = document else { return }
focusTextView()
let local = textView.convert(point, from: nil)
let line = doc.lineIndex.line(containing: textView.characterIndexForInsertion(at: NSPoint(x: 0, y: local.y)))
let start = doc.lineIndex.start(ofLine: line)
let end = doc.lineIndex.end(ofLine: line)
var range = NSRange(location: start, length: end - start)
if extend {
range = NSUnionRange(range, textView.selectedRange())
}
textView.setSelectedRange(range)
}
/// Underlines the class names while ⌘ is held, so the affordance shows exactly when a click would work.
func commandKeyChanged(_ down: Bool) {
guard down != symbolsUnderlined, document != nil else { return }
symbolsUnderlined = down
textView.needsDisplay = true
}
func focusTextView() {
if textView.window?.firstResponder !== textView { textView.window?.makeFirstResponder(textView) }
}
private func topLeft(_ point: NSPoint) -> CGPoint {
let height = textView.window?.contentView?.bounds.height ?? 0
return CGPoint(x: point.x, y: height - point.y)
}
}
/// Tells the controller when the visible size changes, so the text view can follow it.
final class CodeScrollView: NSScrollView {
var onTile: () -> Void = {}
override func tile() {
super.tile()
onTile()
}
}