|
| 1 | +// |
| 2 | +// InlineSuggestionManager.swift |
| 3 | +// CodeEditTextView |
| 4 | +// |
| 5 | +// Created by anxkhn on 6/29/26. |
| 6 | +// |
| 7 | + |
| 8 | +import AppKit |
| 9 | + |
| 10 | +/// Manages a single inline "ghost text" suggestion within a ``TextView``. |
| 11 | +/// |
| 12 | +/// The suggestion is rendered by an ``InlineSuggestionView`` inserted as a sibling overlay below the text view's |
| 13 | +/// content. The manager never mutates ``TextView/textStorage`` and never shifts real text layout. It only typesets the |
| 14 | +/// suggestion text and positions the overlay at the caret using ``TextLayoutManager/rectForOffset(_:)``. |
| 15 | +public final class InlineSuggestionManager { |
| 16 | + weak var textView: TextView? |
| 17 | + |
| 18 | + /// The color used to draw the ghost text. Defaults to ``NSColor/placeholderTextColor``. |
| 19 | + public var suggestionColor: NSColor = .placeholderTextColor |
| 20 | + |
| 21 | + /// The suggestion currently being displayed, if any. |
| 22 | + public private(set) var current: InlineSuggestion? |
| 23 | + |
| 24 | + /// The overlay view drawing the current suggestion, if any. |
| 25 | + private var suggestionView: InlineSuggestionView? |
| 26 | + |
| 27 | + init(textView: TextView) { |
| 28 | + self.textView = textView |
| 29 | + } |
| 30 | + |
| 31 | + // MARK: - Set, Clear |
| 32 | + |
| 33 | + /// Sets the suggestion text anchored at the given document offset. |
| 34 | + /// |
| 35 | + /// Passing `nil` or an empty string clears any existing suggestion. |
| 36 | + /// - Parameters: |
| 37 | + /// - text: The suggestion text. May contain line breaks for a multi-line suggestion. |
| 38 | + /// - offset: The document offset to anchor the suggestion to. |
| 39 | + public func setSuggestion(_ text: String?, at offset: Int) { |
| 40 | + guard let text, !text.isEmpty else { |
| 41 | + clearSuggestion() |
| 42 | + return |
| 43 | + } |
| 44 | + setSuggestion(InlineSuggestion(offset: offset, text: text)) |
| 45 | + } |
| 46 | + |
| 47 | + /// Sets the suggestion to display. |
| 48 | + /// |
| 49 | + /// Passing `nil` clears any existing suggestion. |
| 50 | + /// - Parameter suggestion: The suggestion to display, or `nil` to clear. |
| 51 | + public func setSuggestion(_ suggestion: InlineSuggestion?) { |
| 52 | + guard let suggestion else { |
| 53 | + clearSuggestion() |
| 54 | + return |
| 55 | + } |
| 56 | + current = suggestion |
| 57 | + render(suggestion, rebuildLines: true) |
| 58 | + } |
| 59 | + |
| 60 | + /// Clears any displayed suggestion and removes the overlay view. |
| 61 | + public func clearSuggestion() { |
| 62 | + current = nil |
| 63 | + suggestionView?.removeFromSuperview() |
| 64 | + suggestionView = nil |
| 65 | + } |
| 66 | + |
| 67 | + // MARK: - Layout |
| 68 | + |
| 69 | + /// Recomputes the suggestion's geometry and repositions the overlay. |
| 70 | + /// |
| 71 | + /// This is a cheap no-op when no suggestion is being displayed. If the anchored offset no longer fits within the |
| 72 | + /// document (for instance after an edit shrinks the text), the suggestion is cleared safely. |
| 73 | + public func updateLayout() { |
| 74 | + guard let current else { return } |
| 75 | + guard let textView, current.offset <= textView.textStorage.length else { |
| 76 | + clearSuggestion() |
| 77 | + return |
| 78 | + } |
| 79 | + render(current, rebuildLines: false) |
| 80 | + } |
| 81 | + |
| 82 | + // MARK: - Rendering |
| 83 | + |
| 84 | + /// Renders the given suggestion, inserting or updating the overlay view. |
| 85 | + /// - Parameters: |
| 86 | + /// - suggestion: The suggestion to render. |
| 87 | + /// - rebuildLines: Whether the typeset lines should be rebuilt. Pass `false` to only reposition. |
| 88 | + private func render(_ suggestion: InlineSuggestion, rebuildLines: Bool) { |
| 89 | + guard let textView else { return } |
| 90 | + |
| 91 | + let ctLines = rebuildLines || suggestionView == nil |
| 92 | + ? makeCTLines(for: suggestion.text) |
| 93 | + : suggestionView?.ctLines ?? makeCTLines(for: suggestion.text) |
| 94 | + |
| 95 | + guard let layout = makeLayout(for: suggestion, lineCount: ctLines.count) else { |
| 96 | + clearSuggestion() |
| 97 | + return |
| 98 | + } |
| 99 | + |
| 100 | + if let suggestionView { |
| 101 | + suggestionView.frame = layout.frame |
| 102 | + if rebuildLines { |
| 103 | + suggestionView.update(ctLines: ctLines, geometry: layout.geometry) |
| 104 | + } else { |
| 105 | + suggestionView.update(geometry: layout.geometry) |
| 106 | + } |
| 107 | + } else { |
| 108 | + let view = InlineSuggestionView(ctLines: ctLines, geometry: layout.geometry) |
| 109 | + view.frame = layout.frame |
| 110 | + textView.addSubview(view, positioned: .below, relativeTo: nil) |
| 111 | + suggestionView = view |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + /// The drawing attributes for the ghost text, read from the text view's typing attributes. |
| 116 | + private func suggestionAttributes() -> [NSAttributedString.Key: Any] { |
| 117 | + guard let textView else { return [:] } |
| 118 | + return [ |
| 119 | + .font: textView.font, |
| 120 | + .foregroundColor: suggestionColor, |
| 121 | + .kern: textView.kern |
| 122 | + ] |
| 123 | + } |
| 124 | + |
| 125 | + /// Typesets the suggestion text into one `CTLine` per line break. |
| 126 | + private func makeCTLines(for text: String) -> [CTLine] { |
| 127 | + let attributes = suggestionAttributes() |
| 128 | + return splitIntoLines(text).map { line in |
| 129 | + CTLineCreateWithAttributedString(NSAttributedString(string: line, attributes: attributes)) |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + /// Splits the text into lines on any ``LineEnding`` sequence, preserving empty trailing lines. |
| 134 | + private func splitIntoLines(_ text: String) -> [String] { |
| 135 | + let endings = LineEnding.allCases.sorted { $0.length > $1.length } |
| 136 | + var lines: [String] = [] |
| 137 | + var currentLine = "" |
| 138 | + var index = text.startIndex |
| 139 | + while index < text.endIndex { |
| 140 | + let remaining = text[index...] |
| 141 | + if let ending = endings.first(where: { remaining.hasPrefix($0.rawValue) }) { |
| 142 | + lines.append(currentLine) |
| 143 | + currentLine = "" |
| 144 | + index = text.index(index, offsetBy: ending.length) |
| 145 | + } else { |
| 146 | + currentLine.append(text[index]) |
| 147 | + index = text.index(after: index) |
| 148 | + } |
| 149 | + } |
| 150 | + lines.append(currentLine) |
| 151 | + return lines |
| 152 | + } |
| 153 | + |
| 154 | + /// The computed frame and geometry for a suggestion. |
| 155 | + private struct Layout { |
| 156 | + let frame: CGRect |
| 157 | + let geometry: InlineSuggestionView.Geometry |
| 158 | + } |
| 159 | + |
| 160 | + /// Computes the overlay frame and drawing geometry for a suggestion. |
| 161 | + private func makeLayout(for suggestion: InlineSuggestion, lineCount: Int) -> Layout? { |
| 162 | + guard let textView, |
| 163 | + let layoutManager = textView.layoutManager, |
| 164 | + let caretRect = layoutManager.rectForOffset(suggestion.offset) else { |
| 165 | + return nil |
| 166 | + } |
| 167 | + |
| 168 | + let lineHeight = layoutManager.estimateLineHeight() |
| 169 | + let (descent, heightDifference) = lineMetrics(multiplier: layoutManager.lineHeightMultiplier) |
| 170 | + |
| 171 | + let geometry = InlineSuggestionView.Geometry( |
| 172 | + firstLineXPosition: caretRect.minX, |
| 173 | + continuationXPosition: layoutManager.edgeInsets.left, |
| 174 | + lineHeight: lineHeight, |
| 175 | + descent: descent, |
| 176 | + heightDifference: heightDifference |
| 177 | + ) |
| 178 | + |
| 179 | + let frame = CGRect( |
| 180 | + x: 0, |
| 181 | + y: caretRect.minY, |
| 182 | + width: textView.frame.width, |
| 183 | + height: lineHeight * CGFloat(lineCount) |
| 184 | + ) |
| 185 | + |
| 186 | + return Layout(frame: frame, geometry: geometry) |
| 187 | + } |
| 188 | + |
| 189 | + /// Computes the descent and scaled height difference for the current suggestion attributes. |
| 190 | + private func lineMetrics(multiplier: CGFloat) -> (descent: CGFloat, heightDifference: CGFloat) { |
| 191 | + let referenceLine = CTLineCreateWithAttributedString( |
| 192 | + NSAttributedString(string: "0", attributes: suggestionAttributes()) |
| 193 | + ) |
| 194 | + var ascent: CGFloat = 0 |
| 195 | + var descent: CGFloat = 0 |
| 196 | + var leading: CGFloat = 0 |
| 197 | + CTLineGetTypographicBounds(referenceLine, &ascent, &descent, &leading) |
| 198 | + let unscaledHeight = ascent + descent + leading |
| 199 | + let heightDifference = (unscaledHeight * multiplier) - unscaledHeight |
| 200 | + return (descent, heightDifference) |
| 201 | + } |
| 202 | +} |
0 commit comments