Skip to content

Commit 63cc672

Browse files
Subtle bug around line fragment computations
1 parent ace5e37 commit 63cc672

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

Sources/Glyph/NSTextLayoutFragment+Additions.swift

+12-9
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,10 @@ extension NSTextLineFragment {
3535
for index in (start..<length).reversed() {
3636
let point = locationForCharacter(at: index)
3737

38-
if span.upperBound > point.x {
38+
if span.upperBound >= point.x {
3939
end = min(index + 1, length)
4040
break
4141
}
42-
43-
if span.upperBound == point.x {
44-
end = index
45-
break
46-
}
4742
}
4843

4944
guard let end else { return nil }
@@ -85,16 +80,24 @@ extension NSTextLayoutFragment {
8580
precondition(location >= 0)
8681
precondition(location != NSNotFound)
8782

83+
var locationOffset = location
84+
8885
for textLineFragment in textLineFragments {
86+
// we have to shift to compute overlap, and then shift back to compute the span
8987
let bounds = textLineFragment.typographicBounds.offsetBy(dx: origin.x, dy: origin.y)
90-
91-
let overlap = bounds.intersection(rect)
88+
let overlap = bounds.intersection(rect).offsetBy(dx: -origin.x, dy: -origin.y)
9289
let span: Range<CGFloat> = overlap.minX..<overlap.maxX
9390

91+
// the locationOffset has to be computed even if we do not overlap
92+
let offset = locationOffset
93+
defer {
94+
locationOffset += textLineFragment.characterRange.length
95+
}
96+
9497
guard let localRange = textLineFragment.rangeOfCharacters(intersecting: span) else { continue }
9598

9699
let range = NSRange(
97-
location: localRange.location + location,
100+
location: localRange.location + offset,
98101
length: localRange.length
99102
)
100103

0 commit comments

Comments
 (0)