From 27eca131c388fe0687e517d9819011b69ada868f Mon Sep 17 00:00:00 2001 From: Balthazar Rouberol Date: Sun, 15 Aug 2021 20:35:20 +0200 Subject: [PATCH] Avoid breaking from the document bound when handling a mouse click Fixes #26 --- src/editor.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/editor.rs b/src/editor.rs index 732908f..ace27c1 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -156,7 +156,16 @@ impl Editor { ), MouseEvent::Release(_, _) => { if !self.mouse_event_buffer.is_empty() { - self.cursor_position = self.mouse_event_buffer.pop().unwrap(); + // Make sure that we're moving to an x/y location in which we already + // have text, to avoid breaking out of the document bounds. + let cursor_position = self.mouse_event_buffer.pop().unwrap(); + if cursor_position.y.saturating_add(1) <= self.document.num_rows() { + if let Some(target_row) = self.document.get_row(cursor_position.y) { + if cursor_position.x <= target_row.len() { + self.cursor_position = cursor_position; + } + } + } } } _ => (),