Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix grapheme_position when ligatures are present #2196

Merged
merged 2 commits into from
Jan 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions graphics/src/text/paragraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,38 +187,43 @@ impl core::text::Paragraph for Paragraph {
}

fn grapheme_position(&self, line: usize, index: usize) -> Option<Point> {
use unicode_segmentation::UnicodeSegmentation;

let run = self.internal().buffer.layout_runs().nth(line)?;

// index represents a grapheme, not a glyph
// Let's find the first glyph for the given grapheme cluster
let mut last_start = None;
let mut last_grapheme_count = 0;
let mut graphemes_seen = 0;

let glyph = run
.glyphs
.iter()
.find(|glyph| {
if graphemes_seen == index {
return true;
}

if Some(glyph.start) != last_start {
last_grapheme_count = run.text[glyph.start..glyph.end]
.graphemes(false)
.count();
last_start = Some(glyph.start);
graphemes_seen += 1;
graphemes_seen += last_grapheme_count;
}

false
graphemes_seen >= index
})
.or_else(|| run.glyphs.last())?;

let advance_last = if index == run.glyphs.len() {
glyph.w
} else {
let advance = if index == 0 {
0.0
} else {
glyph.w
* (1.0
- graphemes_seen.saturating_sub(index) as f32
/ last_grapheme_count.max(1) as f32)
};

Some(Point::new(
glyph.x + glyph.x_offset * glyph.font_size + advance_last,
glyph.x + glyph.x_offset * glyph.font_size + advance,
glyph.y - glyph.y_offset * glyph.font_size,
))
}
Expand Down
Loading