From d0107d2ce4783df41617bfa22084fa59046b6ff8 Mon Sep 17 00:00:00 2001 From: Matt Campbell Date: Wed, 16 Oct 2024 06:58:17 -0500 Subject: [PATCH] Make access_position_from_offset return an Option so it doesn't have to panic in release builds --- masonry/src/text/selection.rs | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/masonry/src/text/selection.rs b/masonry/src/text/selection.rs index 0c9c95912..94dd5ff51 100644 --- a/masonry/src/text/selection.rs +++ b/masonry/src/text/selection.rs @@ -267,7 +267,11 @@ impl TextWithSelection { self.layout.draw(scene, point); } - fn access_position_from_offset(&self, offset: usize, affinity: Affinity) -> TextPosition { + fn access_position_from_offset( + &self, + offset: usize, + affinity: Affinity, + ) -> Option { let text = self.text().as_ref(); debug_assert!(offset <= text.len(), "offset out of range"); @@ -300,21 +304,26 @@ impl TextWithSelection { let mut length_sum = 0_usize; for (character_index, length) in character_lengths.iter().copied().enumerate() { if run_offset == length_sum { - return TextPosition { + return Some(TextPosition { node: id, character_index, - }; + }); } length_sum += length as usize; } - return TextPosition { + return Some(TextPosition { node: id, character_index: character_lengths.len(), - }; + }); } } - panic!("offset not within the range of any run"); + debug_panic!( + "offset {} not within the range of any run; text length: {}", + offset, + text.len() + ); + None } pub fn accessibility(&mut self, update: &mut TreeUpdate, parent_node: &mut NodeBuilder) { @@ -324,10 +333,15 @@ impl TextWithSelection { } else { Affinity::Downstream }; - let anchor = self.access_position_from_offset(self.selection.anchor, anchor_affinity); - let focus = - self.access_position_from_offset(self.selection.active, self.selection.active_affinity); - parent_node.set_text_selection(TextSelection { anchor, focus }); + if let Some(anchor) = + self.access_position_from_offset(self.selection.anchor, anchor_affinity) + { + if let Some(focus) = self + .access_position_from_offset(self.selection.active, self.selection.active_affinity) + { + parent_node.set_text_selection(TextSelection { anchor, focus }); + } + } parent_node.add_action(accesskit::Action::SetTextSelection); }