|
| 1 | +import AppKit |
| 2 | + |
| 3 | +extension BlockInputTextView { |
| 4 | + /// TextKit can report zero-width bounds and omit native backgrounds when hidden delimiters wrap. |
| 5 | + /// Keep valid bounds for bidirectional runs; glyph positions recover the empty rectangles. |
| 6 | + func drawInlineCodeBackgrounds(in dirtyRect: NSRect) { |
| 7 | + guard let textStorage, let layoutManager, let textContainer else { |
| 8 | + return |
| 9 | + } |
| 10 | + layoutManager.ensureLayout(for: textContainer) |
| 11 | + let origin = textContainerOrigin |
| 12 | + let fullRange = NSRange(location: 0, length: textStorage.length) |
| 13 | + textStorage.enumerateAttribute(.blockInputInlineCodeBackground, in: fullRange) { value, range, _ in |
| 14 | + guard let color = value as? NSColor else { |
| 15 | + return |
| 16 | + } |
| 17 | + let glyphRange = layoutManager.glyphRange(forCharacterRange: range, actualCharacterRange: nil) |
| 18 | + color.setFill() |
| 19 | + var glyphIndex = glyphRange.location |
| 20 | + while glyphIndex < NSMaxRange(glyphRange) { |
| 21 | + var lineRange = NSRange() |
| 22 | + let lineRect = layoutManager.blockInputGlyphLineRect(forGlyphAt: glyphIndex, effectiveRange: &lineRange) |
| 23 | + let intersection = NSIntersectionRange(glyphRange, lineRange) |
| 24 | + var rect = layoutManager.boundingRect(forGlyphRange: intersection, in: textContainer) |
| 25 | + if rect.width <= 0 { |
| 26 | + let fragmentRect = layoutManager.lineFragmentRect(forGlyphAt: glyphIndex, effectiveRange: nil) |
| 27 | + let startX = fragmentRect.minX + layoutManager.location(forGlyphAt: intersection.location).x |
| 28 | + let endIndex = NSMaxRange(intersection) |
| 29 | + let endX = endIndex < NSMaxRange(lineRange) |
| 30 | + ? fragmentRect.minX + layoutManager.location(forGlyphAt: endIndex).x |
| 31 | + : lineRect.maxX |
| 32 | + rect.origin.x = min(startX, endX) |
| 33 | + rect.size.width = abs(endX - startX) |
| 34 | + } |
| 35 | + rect.origin.y = lineRect.minY |
| 36 | + rect.size.height = lineRect.height |
| 37 | + rect = rect.offsetBy(dx: origin.x, dy: origin.y) |
| 38 | + if rect.intersects(dirtyRect) { |
| 39 | + rect.fill() |
| 40 | + } |
| 41 | + glyphIndex = max(glyphIndex + 1, NSMaxRange(lineRange)) |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +extension NSAttributedString.Key { |
| 48 | + /// Keeps inline code fills out of TextKit's unreliable native background drawing around hidden delimiters. |
| 49 | + static let blockInputInlineCodeBackground = NSAttributedString.Key("BlockInputInlineCodeBackground") |
| 50 | +} |
0 commit comments