Open History to see the last commit
1import UIKit
2
3/// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights.
4/// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling.
5final class ReviewDiffCodeLayout: NSObject {
6 static let unboundedWidth = CGFloat.greatestFiniteMagnitude
7
8 // Measurement reuses one engine; only recently drawn rows retain a full TextKit layout.
9 private static var measurer: ReviewDiffTextLayout {
10 let key = "T3ReviewDiff.textMeasurer"
11 if let layout = Thread.current.threadDictionary[key] as? ReviewDiffTextLayout { return layout }
12 let layout = ReviewDiffTextLayout()
13 Thread.current.threadDictionary[key] = layout
14 return layout
15 }
16 private static let drawnLayouts: NSCache<ReviewDiffCodeLayout, ReviewDiffTextLayout> = {
17 let cache = NSCache<ReviewDiffCodeLayout, ReviewDiffTextLayout>()
18 cache.countLimit = 128
19 return cache
20 }()
21 let text: String
22 let starts: [Int]
23 let lineHeight: CGFloat
24 let firstLineHeight: CGFloat
25 let extraHeight: CGFloat
26 /// Widest visual line, which sizes horizontal scrolling when the row is not wrapped.
27 let usedWidth: CGFloat
28 private let font: UIFont
29 private let width: CGFloat
30 private let characterWidth: CGFloat
31 let usesNativeLayout: Bool
32
33 init(text: String, font: UIFont, width: CGFloat, characterWidth: CGFloat) {
34 self.text = text
35 self.font = font
36 self.width = width
37 self.characterWidth = characterWidth
38 lineHeight = ceil(font.lineHeight)
39 if text.utf8.allSatisfy({ $0 >= 32 && $0 <= 126 }) {
40 let length = max(1, text.utf8.count)
41 let columns = max(1, Int(min(width / characterWidth, CGFloat(length))))
42 starts = Array(stride(from: 0, to: length, by: columns))
43 firstLineHeight = font.lineHeight
44 extraHeight = CGFloat(starts.count - 1) * lineHeight
45 usedWidth = CGFloat(min(text.utf8.count, columns)) * characterWidth
46 usesNativeLayout = false
47 } else {
48 let layout = Self.measurer
49 layout.configure(text: text, font: font, width: width, characterWidth: characterWidth)
50 let manager = layout.manager
51 let container = layout.container
52 usesNativeLayout = true
53 starts = [0]
54 firstLineHeight = manager.numberOfGlyphs > 0
55 ? manager.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil).height : font.lineHeight
56 let used = manager.usedRect(for: container)
57 extraHeight = max(0, used.height - firstLineHeight)
58 usedWidth = ceil(used.width)
59 }
60 }
61
62 private func nativeLayout() -> ReviewDiffTextLayout {
63 if let cached = Self.drawnLayouts.object(forKey: self) { return cached }
64 let layout = ReviewDiffTextLayout()
65 layout.configure(text: text, font: font, width: width, characterWidth: characterWidth)
66 Self.drawnLayouts.setObject(layout, forKey: self)
67 return layout
68 }
69
70 /// Only colors change when syntax tokens arrive; the measured text and font stay intact.
71 func decorate(text: NSAttributedString, highlights: [NSRange], color: UIColor, version: Int) {
72 guard usesNativeLayout else { return }
73 let layout = nativeLayout()
74 guard layout.decorationVersion != version else { return }
75 let storage = layout.storage
76 let fullRange = NSRange(location: 0, length: storage.length)
77 storage.beginEditing()
78 storage.removeAttribute(.foregroundColor, range: fullRange)
79 storage.removeAttribute(.backgroundColor, range: fullRange)
80 text.enumerateAttribute(.foregroundColor, in: NSRange(location: 0, length: text.length)) { value, range, _ in
81 let intersection = NSIntersectionRange(range, fullRange)
82 if let value, intersection.length > 0 {
83 storage.addAttribute(.foregroundColor, value: value, range: intersection)
84 }
85 }
86 for range in highlights {
87 let intersection = NSIntersectionRange(range, fullRange)
88 if intersection.length > 0 {
89 storage.addAttribute(.backgroundColor, value: color, range: intersection)
90 }
91 }
92 storage.endEditing()
93 layout.decorationVersion = version
94 }
95
96 func draw(at origin: CGPoint, clip: CGRect) {
97 guard usesNativeLayout else { return }
98 let layout = nativeLayout()
99 let manager = layout.manager
100 let container = layout.container
101 let visible = clip.offsetBy(dx: -origin.x, dy: -origin.y)
102 let range = manager.glyphRange(forBoundingRect: visible, in: container)
103 manager.drawBackground(forGlyphRange: range, at: origin)
104 manager.drawGlyphs(forGlyphRange: range, at: origin)
105 }
106}
107
108private final class ReviewDiffTextLayout {
109 let storage = NSTextStorage()
110 let manager = NSLayoutManager()
111 let container = NSTextContainer(size: .zero)
112 var decorationVersion = -1
113
114 init() {
115 container.lineFragmentPadding = 0
116 container.lineBreakMode = .byCharWrapping
117 manager.addTextContainer(container)
118 storage.addLayoutManager(manager)
119 }
120
121 func configure(text: String, font: UIFont, width: CGFloat, characterWidth: CGFloat) {
122 let paragraph = NSMutableParagraphStyle()
123 paragraph.lineBreakMode = .byCharWrapping
124 paragraph.tabStops = []
125 paragraph.defaultTabInterval = characterWidth * 4
126 container.size = CGSize(width: max(1, width), height: .greatestFiniteMagnitude)
127 storage.setAttributedString(NSAttributedString(string: text, attributes: [
128 .font: font, .ligature: 0, .paragraphStyle: paragraph,
129 ]))
130 manager.ensureLayout(for: container)
131 }
132}