Textley / app · textley.ai / Sources / Textley / LineNumberRuler.swift
| 1 | import AppKit |
| 2 | |
| 3 | @MainActor |
| 4 | final class LineNumberRuler: NSRulerView { |
| 5 | private weak var document: EditorDocument? |
| 6 | |
| 7 | init(scrollView: NSScrollView, document: EditorDocument) { |
| 8 | self.document = document |
| 9 | super.init(scrollView: scrollView, orientation: .verticalRuler) |
| 10 | clientView = document.editor |
| 11 | ruleThickness = 54 |
| 12 | clipsToBounds = true |
| 13 | NotificationCenter.default.addObserver(self, selector: #selector(didScroll), |
| 14 | name: NSView.boundsDidChangeNotification, object: scrollView.contentView) |
| 15 | } |
| 16 | |
| 17 | required init(coder: NSCoder) { fatalError("init(coder:) is unavailable") } |
| 18 | |
| 19 | @objc private func didScroll() { needsDisplay = true } |
| 20 | |
| 21 | override func drawHashMarksAndLabels(in rect: NSRect) { |
| 22 | NSColor.windowBackgroundColor.setFill() |
| 23 | bounds.intersection(rect).fill() |
| 24 | guard let document, let layout = document.editor.layoutManager, |
| 25 | let container = document.editor.textContainer, let scrollView else { return } |
| 26 | let textView = document.editor |
| 27 | let origin = textView.textContainerOrigin |
| 28 | let visible = scrollView.contentView.documentVisibleRect |
| 29 | let contentRect = visible.offsetBy(dx: -origin.x, dy: -origin.y) |
| 30 | let glyphs = layout.glyphRange(forBoundingRect: contentRect, in: container) |
| 31 | let attributes: [NSAttributedString.Key: Any] = [ |
| 32 | .font: NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular), |
| 33 | .foregroundColor: NSColor.secondaryLabelColor |
| 34 | ] |
| 35 | let source = textView.string as NSString |
| 36 | func draw(_ number: Int, at height: CGFloat) { |
| 37 | let text = String(number) as NSString |
| 38 | let size = text.size(withAttributes: attributes) |
| 39 | let point = convert(NSPoint(x: 0, y: height + origin.y), from: textView) |
| 40 | let y = isFlipped ? point.y + 1 : point.y - size.height - 1 |
| 41 | text.draw(at: NSPoint(x: ruleThickness - size.width - 8, y: y), withAttributes: attributes) |
| 42 | } |
| 43 | if source.length == 0 { |
| 44 | draw(1, at: 0) |
| 45 | } else { |
| 46 | layout.enumerateLineFragments(forGlyphRange: glyphs) { _, used, _, range, _ in |
| 47 | let character = layout.characterIndexForGlyph(at: range.location) |
| 48 | if character == 0 || source.character(at: character - 1) == 10 { |
| 49 | draw(document.lineNumber(at: character), at: used.minY) |
| 50 | } |
| 51 | } |
| 52 | if source.character(at: source.length - 1) == 10, |
| 53 | layout.extraLineFragmentTextContainer == container { |
| 54 | draw(document.lineNumber(at: source.length), at: layout.extraLineFragmentUsedRect.minY) |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | } |