146 lines
6.4 KiB
Swift
146 lines
6.4 KiB
Swift
// ScratchLineNumberRuler.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// LyrebirdUI/LiveCompile
|
|
//
|
|
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
|
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
|
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
|
// 1-based line label per visible line into the ruler's bounds.
|
|
|
|
#if os(macOS)
|
|
import AppKit
|
|
|
|
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
|
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
|
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
|
/// invalidates itself on every text edit and frame change.
|
|
final class ScratchLineNumberRuler: NSRulerView {
|
|
|
|
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
|
/// swaps the text view performs after attachment.
|
|
private weak var textView: NSTextView?
|
|
|
|
init(scrollView: NSScrollView, textView: NSTextView) {
|
|
self.textView = textView
|
|
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
|
self.clientView = textView
|
|
self.ruleThickness = gutterWidth
|
|
let center: NotificationCenter = NotificationCenter.default
|
|
center.addObserver(self,
|
|
selector: #selector(invalidateForChange(_:)),
|
|
name: NSText.didChangeNotification,
|
|
object: textView)
|
|
center.addObserver(self,
|
|
selector: #selector(invalidateForChange(_:)),
|
|
name: NSView.frameDidChangeNotification,
|
|
object: textView)
|
|
let clipView: NSClipView = scrollView.contentView
|
|
clipView.postsBoundsChangedNotifications = true
|
|
center.addObserver(self,
|
|
selector: #selector(invalidateForChange(_:)),
|
|
name: NSView.boundsDidChangeNotification,
|
|
object: clipView)
|
|
}
|
|
|
|
required init(coder: NSCoder) {
|
|
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
|
}
|
|
|
|
deinit {
|
|
NotificationCenter.default.removeObserver(self)
|
|
}
|
|
|
|
@objc private func invalidateForChange(_ note: Notification) {
|
|
needsDisplay = true
|
|
}
|
|
|
|
override func drawHashMarksAndLabels(in rect: NSRect) {
|
|
guard let textView: NSTextView,
|
|
let layoutManager: NSLayoutManager = textView.layoutManager,
|
|
let textContainer: NSTextContainer = textView.textContainer else {
|
|
return
|
|
}
|
|
|
|
gutterFillColor.setFill()
|
|
rect.fill()
|
|
gutterDividerColor.setStroke()
|
|
let dividerPath: NSBezierPath = NSBezierPath()
|
|
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
|
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
|
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
|
dividerPath.lineWidth = 1
|
|
dividerPath.stroke()
|
|
|
|
let nsText: NSString = textView.string as NSString
|
|
let totalLength: Int = nsText.length
|
|
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
|
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
|
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
|
let inset: CGFloat = textView.textContainerInset.height
|
|
let attrs: [NSAttributedString.Key: Any] = [
|
|
.font: rulerFont,
|
|
.foregroundColor: gutterTextColor,
|
|
]
|
|
|
|
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
|
var cursor: Int = charRange.location
|
|
let visibleEnd: Int = NSMaxRange(charRange)
|
|
while cursor < visibleEnd && cursor <= totalLength {
|
|
// `lineRange(for:)` advances cursor by the full line including its
|
|
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
|
// handled by Foundation.
|
|
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
|
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
|
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
|
actualCharacterRange: nil)
|
|
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
|
in: textContainer)
|
|
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
|
let label: NSString = "\(lineIndex)" as NSString
|
|
let size: CGSize = label.size(withAttributes: attrs)
|
|
let drawPoint: NSPoint = NSPoint(
|
|
x: bounds.maxX - size.width - rightInset,
|
|
y: yInView + ((usedRect.height - size.height) * 0.5)
|
|
)
|
|
label.draw(at: drawPoint, withAttributes: attrs)
|
|
|
|
let advance: Int = NSMaxRange(lineRange)
|
|
if advance <= cursor { break } // defensive — empty trailing line
|
|
cursor = advance
|
|
lineIndex += 1
|
|
}
|
|
}
|
|
|
|
// 1-based line number of the character at `loc`. Delegates to
|
|
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
|
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
|
// that precedes the first visible line.
|
|
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
|
if loc <= 0 { return 1 }
|
|
var line: Int = 1
|
|
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
|
text.enumerateSubstrings(in: prefixRange,
|
|
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
|
line += 1
|
|
}
|
|
return line
|
|
}
|
|
|
|
private let gutterWidth: CGFloat = 40
|
|
private let rightInset: CGFloat = 6
|
|
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
|
private let rulerFontSize: CGFloat = 11
|
|
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
|
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
|
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
|
private var rulerFont: NSFont {
|
|
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
|
}
|
|
}
|
|
|
|
#endif
|