Skip to content

Commit

Permalink
Subtle bug around line fragment computations
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmassicotte committed Dec 20, 2024
1 parent ace5e37 commit 63cc672
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions Sources/Glyph/NSTextLayoutFragment+Additions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,10 @@ extension NSTextLineFragment {
for index in (start..<length).reversed() {
let point = locationForCharacter(at: index)

if span.upperBound > point.x {
if span.upperBound >= point.x {
end = min(index + 1, length)
break
}

if span.upperBound == point.x {
end = index
break
}
}

guard let end else { return nil }
Expand Down Expand Up @@ -85,16 +80,24 @@ extension NSTextLayoutFragment {
precondition(location >= 0)
precondition(location != NSNotFound)

var locationOffset = location

for textLineFragment in textLineFragments {
// we have to shift to compute overlap, and then shift back to compute the span
let bounds = textLineFragment.typographicBounds.offsetBy(dx: origin.x, dy: origin.y)

let overlap = bounds.intersection(rect)
let overlap = bounds.intersection(rect).offsetBy(dx: -origin.x, dy: -origin.y)
let span: Range<CGFloat> = overlap.minX..<overlap.maxX

// the locationOffset has to be computed even if we do not overlap
let offset = locationOffset
defer {
locationOffset += textLineFragment.characterRange.length
}

guard let localRange = textLineFragment.rangeOfCharacters(intersecting: span) else { continue }

let range = NSRange(
location: localRange.location + location,
location: localRange.location + offset,
length: localRange.length
)

Expand Down

0 comments on commit 63cc672

Please sign in to comment.