Use Option to encode empty text case in hit test methods

This commit is contained in:
Héctor Ramón Jiménez 2021-09-15 14:49:13 +07:00
parent 93fec8d273
commit 643500bbdf
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
10 changed files with 59 additions and 52 deletions

View file

@ -284,7 +284,7 @@ impl backend::Text for Backend {
bounds: Size,
point: iced_native::Point,
nearest_only: bool,
) -> text::Hit {
) -> Option<text::Hit> {
self.text_pipeline.hit_test(
contents,
size,

View file

@ -129,7 +129,7 @@ impl Pipeline {
bounds: iced_native::Size,
point: iced_native::Point,
nearest_only: bool,
) -> Hit {
) -> Option<Hit> {
use wgpu_glyph::GlyphCruncher;
let wgpu_glyph::FontId(font_id) = self.find_font(font);
@ -190,23 +190,25 @@ impl Pipeline {
if !nearest_only {
for (idx, bounds) in bounds.clone() {
if bounds.contains(point) {
return Hit::CharOffset(char_index(idx));
return Some(Hit::CharOffset(char_index(idx)));
}
}
}
let (idx, nearest) = bounds.fold(
(0usize, iced_native::Point::ORIGIN),
|acc: (usize, iced_native::Point), (idx, bounds)| {
if bounds.center().distance(point) < acc.1.distance(point) {
(idx, bounds.center())
(None, iced_native::Point::ORIGIN),
|best, (idx, bounds)| {
let center = bounds.center();
if center.distance(point) < best.1.distance(point) {
(Some(idx), center)
} else {
acc
best
}
},
);
Hit::NearestCharOffset(char_index(idx), (point - nearest).into())
idx.map(|idx| Hit::NearestCharOffset(char_index(idx), point - nearest))
}
pub fn trim_measurement_cache(&mut self) {