// ScratchLineNumberGutter.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT // Line-number gutter for `ScratchEditor`'s text view, implemented as a plain // floating overlay `NSView` rather than an `NSRulerView`. Enabling // `NSScrollView.rulersVisible` in this SwiftUI `NSViewRepresentable` mis-tiles // the document view (text goes invisible and stops taking input), and drawing // inside a layer-backed `NSTextView` never reaches `draw(_:)`. A floating // subview draws normally and leaves the text view untouched. It reads the text // view's layout manager and the clip view's scroll offset to place one // right-aligned number per source line in the visible region. #if os(macOS) import AppKit final class ScratchLineNumberGutter: NSView { private weak var textView: NSTextView? private weak var scrollView: NSScrollView? init(scrollView: NSScrollView, textView: NSTextView) { self.scrollView = scrollView self.textView = textView let height: CGFloat = scrollView.contentView.bounds.height super.init(frame: NSRect(x: 0, y: 0, width: ScratchTextView.lineNumberGutterWidth, height: height)) self.autoresizingMask = [.height] let clip: NSClipView = scrollView.contentView clip.postsBoundsChangedNotifications = true let center: NotificationCenter = NotificationCenter.default center.addObserver(self, selector: #selector(refresh), name: NSView.boundsDidChangeNotification, object: clip) center.addObserver(self, selector: #selector(refresh), name: NSText.didChangeNotification, object: textView) center.addObserver(self, selector: #selector(refresh), name: NSView.frameDidChangeNotification, object: textView) } required init?(coder: NSCoder) { fatalError("ScratchLineNumberGutter does not support NSCoder init") } deinit { NotificationCenter.default.removeObserver(self) } override var isFlipped: Bool { true } /// Redraw the whole gutter after an edit / scroll / relayout. A programmatic /// text replace (format / load / reset) can happen without an /// `NSText.didChangeNotification`, so the host also nudges this directly. @objc func refresh() { needsDisplay = true } override func draw(_ dirtyRect: NSRect) { gutterFillColor.setFill() bounds.fill() gutterDividerColor.setStroke() let divider: NSBezierPath = NSBezierPath() let dividerX: CGFloat = bounds.maxX - dividerHalfPixel divider.move(to: NSPoint(x: dividerX, y: bounds.minY)) divider.line(to: NSPoint(x: dividerX, y: bounds.maxY)) divider.lineWidth = 1 divider.stroke() guard let textView: NSTextView = textView, let layoutManager: NSLayoutManager = textView.layoutManager, let container: NSTextContainer = textView.textContainer, let clip: NSClipView = scrollView?.contentView else { return } let visibleRect: NSRect = clip.documentVisibleRect let inset: CGFloat = textView.textContainerInset.height let ns: NSString = textView.string as NSString let total: Int = ns.length let attrs: [NSAttributedString.Key: Any] = [ .font: gutterFont, .foregroundColor: gutterTextColor, ] // Glyphs visible in the clip, then the source-line walk over that range. let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: container) let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil) // Snap to the START of the first visible source line before counting: when // word-wrap puts a wrapped continuation fragment at the top of the visible // area, `charRange.location` lands mid-line, and `lineNumber(at:)` would // over-count by one (throwing off every number below it). let firstLineStart: Int = ns.lineRange(for: NSRange(location: min(charRange.location, total), length: 0)).location var lineIndex: Int = lineNumber(at: firstLineStart, in: ns) var cursor: Int = firstLineStart let visibleEnd: Int = NSMaxRange(charRange) while cursor < visibleEnd && cursor < total { let lineRange: NSRange = ns.lineRange(for: NSRange(location: cursor, length: 0)) // Position from the line *fragment* rect (the row's box), not the glyph // bounding rect. `boundingRect` is inconsistent across a trailing // newline and blank lines — it's what left the last number cramped // against the trailing empty line. The fragment rect is one clean, // uniform-height box per row. let firstGlyph: Int = layoutManager.glyphIndexForCharacter(at: lineRange.location) let fragment: NSRect = layoutManager.lineFragmentRect( forGlyphAt: firstGlyph, effectiveRange: nil, withoutAdditionalLayout: true ) drawNumber(lineIndex, docY: fragment.minY + inset, lineHeight: fragment.height, visibleMinY: visibleRect.minY, attrs: attrs) let advance: Int = NSMaxRange(lineRange) if advance <= cursor { break } cursor = advance lineIndex += 1 } // Trailing empty line (empty doc, or one ending in a newline): drawn from // the layout manager's extra fragment, which `boundingRect` on a // zero-length range does not cover. let endsWithNewline: Bool = total > 0 && CharacterSet.newlines.contains( Unicode.Scalar(ns.character(at: total - 1)) ?? Unicode.Scalar(0) ) if total == 0 || endsWithNewline { let extra: NSRect = layoutManager.extraLineFragmentRect if extra.height > 0 { drawNumber(lineIndex, docY: extra.minY + inset, lineHeight: extra.height, visibleMinY: visibleRect.minY, attrs: attrs) } } } private func drawNumber(_ n: Int, docY: CGFloat, lineHeight: CGFloat, visibleMinY: CGFloat, attrs: [NSAttributedString.Key: Any]) { // Document Y → gutter-local Y (the gutter floats over the visible area). let y: CGFloat = docY - visibleMinY let label: NSString = "\(n)" as NSString let size: CGSize = label.size(withAttributes: attrs) let point: NSPoint = NSPoint( x: bounds.maxX - size.width - rightInset, y: y + (lineHeight - size.height) * verticalCenterFraction ) label.draw(at: point, withAttributes: attrs) } /// 1-based source line number of the character at `loc`. Counts CR/LF/CRLF. private func lineNumber(at loc: Int, in text: NSString) -> Int { if loc <= 0 { return 1 } var line: Int = 1 text.enumerateSubstrings(in: NSRange(location: 0, length: loc), options: [.byLines, .substringNotRequired]) { _, _, _, _ in line += 1 } return line } private let rightInset: CGFloat = 6 private let dividerHalfPixel: CGFloat = 0.5 private let gutterFontSize: CGFloat = 11 private let verticalCenterFraction: CGFloat = 0.5 private let gutterFillColor: NSColor = .controlBackgroundColor private let gutterDividerColor: NSColor = .separatorColor private let gutterTextColor: NSColor = .tertiaryLabelColor private var gutterFont: NSFont { NSFont.monospacedSystemFont(ofSize: gutterFontSize, weight: .regular) } } #endif