Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ReviewDiffCodeLayout.swift

148 lines5.6 KB

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