Skip to content
This repository has been archived by the owner on Jul 15, 2024. It is now read-only.

Commit

Permalink
Fix boundaries in the edit_text example
Browse files Browse the repository at this point in the history
  • Loading branch information
DJMcNab committed Aug 5, 2023
1 parent 1aea28f commit d4f8ca6
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions examples/edit_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,22 @@ struct DocumentState {
font_context: FontContext,
}

impl DocumentState {
fn update_selection(&mut self) {
let next_char_boundary = |mut idx| {
if idx > self.text.len() {
panic!("Tried to set selection outside of the string")
}
while !self.text.is_char_boundary(idx) {
idx += 1;
}
idx
};
self.selection.active = next_char_boundary(self.selection.active);
self.selection.anchor = next_char_boundary(self.selection.anchor);
}
}

impl Default for DocumentState {
fn default() -> Self {
let mut this = Self {
Expand Down Expand Up @@ -236,11 +252,11 @@ impl WindowState {
let rect = Rect::from_points(
Point::new(
composition_start.min(composition_end - 1.0),
TEXT_Y + FONT_SIZE as f64 + 2.0,
TEXT_Y + FONT_SIZE as f64 + 7.0,
),
Point::new(
composition_start.max(composition_end + 1.0),
TEXT_Y + FONT_SIZE as f64,
TEXT_Y + FONT_SIZE as f64 + 5.0,
),
);
sb.fill(
Expand Down Expand Up @@ -299,7 +315,6 @@ impl WinHandler for WindowState {
fn release_input_lock(&mut self, _token: TextFieldToken) {
// no action required; this example is simple enough that this
// state is not actually shared.
eprintln!("{:?}", &self.document.borrow().text)
}

fn key_down(&mut self, event: KeyEvent) -> bool {
Expand Down Expand Up @@ -412,7 +427,9 @@ impl InputHandler for AppInputHandler {
self.state.borrow().composition.clone()
}
fn set_selection(&mut self, range: Selection) {
self.state.borrow_mut().selection = range;
let mut state = self.state.borrow_mut();
state.selection = range;
state.update_selection();
self.window_handle.request_anim_frame();
}
fn set_composition_range(&mut self, range: Option<Range<usize>>) {
Expand All @@ -433,6 +450,7 @@ impl InputHandler for AppInputHandler {
doc.selection.anchor = range.start + text.len();
doc.selection.active = range.start + text.len();
}
doc.update_selection();
doc.refresh_layout();
doc.composition = None;
self.window_handle.request_anim_frame();
Expand Down

0 comments on commit d4f8ca6

Please sign in to comment.