1use iced::widget::operation::scroll_to;
4use iced::widget::scrollable;
5use iced::{Point, Task};
6#[cfg(not(target_arch = "wasm32"))]
7use std::time::Instant;
8
9#[cfg(target_arch = "wasm32")]
10use web_time::Instant;
11
12use super::cursor_set;
13use crate::buffer::TextBuffer;
14use crate::canvas_editor::features::vim::VimMotion;
15use crate::canvas_editor::render::wrapping::{VisualLine, WrappingCalculator};
16use crate::canvas_editor::{
17 ArrowDirection, CodeEditor, Message, measure_char_width, measure_text_width,
18};
19fn column_on_visual_row(
39 pos: (usize, usize),
40 current_vl: &VisualLine,
41 target_vl: &VisualLine,
42 buffer: &TextBuffer,
43) -> usize {
44 let (line, col) = pos;
45 if target_vl.logical_line == line {
46 let offset_in_current = col.saturating_sub(current_vl.start_col);
47 let target_col = target_vl.start_col + offset_in_current;
48 if target_col >= target_vl.end_col {
49 target_vl.end_col.saturating_sub(1).max(target_vl.start_col)
50 } else {
51 target_col
52 }
53 } else {
54 let target_line_len = buffer.line_len(target_vl.logical_line);
55 (target_vl.start_col + col.min(target_vl.len())).min(target_line_len)
56 }
57}
58
59fn compute_next_position(
63 pos: (usize, usize),
64 direction: ArrowDirection,
65 buffer: &TextBuffer,
66 visual_lines: &[VisualLine],
67) -> Option<(usize, usize)> {
68 let (line, col) = pos;
69 match direction {
70 ArrowDirection::Up | ArrowDirection::Down => {
71 let current_visual =
72 WrappingCalculator::logical_to_visual(visual_lines, line, col)?;
73
74 let target_visual = match direction {
75 ArrowDirection::Up => current_visual.checked_sub(1)?,
76 ArrowDirection::Down => {
77 let next = current_visual + 1;
78 if next < visual_lines.len() {
79 next
80 } else {
81 return None;
82 }
83 }
84 _ => return None,
85 };
86
87 let target_vl = &visual_lines[target_visual];
88 let current_vl = &visual_lines[current_visual];
89
90 Some((
91 target_vl.logical_line,
92 column_on_visual_row(pos, current_vl, target_vl, buffer),
93 ))
94 }
95 ArrowDirection::Left => {
96 if col > 0 {
97 Some((line, col - 1))
98 } else if line > 0 {
99 Some((line - 1, buffer.line_len(line - 1)))
100 } else {
101 None
102 }
103 }
104 ArrowDirection::Right => {
105 let line_len = buffer.line_len(line);
106 if col < line_len {
107 Some((line, col + 1))
108 } else if line + 1 < buffer.line_count() {
109 Some((line + 1, 0))
110 } else {
111 None
112 }
113 }
114 }
115}
116
117impl CodeEditor {
118 pub(crate) fn vim_normal_position(
122 &self,
123 position: (usize, usize),
124 ) -> (usize, usize) {
125 let line = position.0.min(self.buffer.line_count().saturating_sub(1));
126 let line_len = self.buffer.line_len(line);
127 let max_col = line_len.saturating_sub(1);
128 (line, position.1.min(max_col))
129 }
130
131 fn vim_position_after(&self, position: (usize, usize)) -> (usize, usize) {
132 let line_len = self.buffer.line_len(position.0);
133 if line_len == 0 {
134 if position.0 + 1 < self.buffer.line_count() {
135 (position.0 + 1, 0)
136 } else {
137 position
138 }
139 } else {
140 (position.0, (position.1 + 1).min(line_len))
141 }
142 }
143
144 pub(crate) fn apply_vim_visual_selection(
147 &mut self,
148 anchor: (usize, usize),
149 active: (usize, usize),
150 linewise: bool,
151 ) {
152 let anchor = self.vim_normal_position(anchor);
153 let active = self.vim_normal_position(active);
154 let cursor = if linewise {
155 let start_line = anchor.0.min(active.0);
156 let end_line = anchor.0.max(active.0);
157 let end = if end_line + 1 < self.buffer.line_count() {
158 (end_line + 1, 0)
159 } else {
160 (end_line, self.buffer.line_len(end_line))
161 };
162 cursor_set::Cursor { position: end, anchor: Some((start_line, 0)) }
163 } else if active >= anchor {
164 cursor_set::Cursor {
165 position: self.vim_position_after(active),
166 anchor: Some(anchor),
167 }
168 } else {
169 cursor_set::Cursor {
170 position: active,
171 anchor: Some(self.vim_position_after(anchor)),
172 }
173 };
174 self.cursors.set_single(cursor.position);
175 self.cursors.primary_mut().anchor = cursor.anchor;
176 self.overlay_cache.clear();
177 }
178
179 pub(crate) fn vim_motion_target(
182 &self,
183 start: (usize, usize),
184 motion: VimMotion,
185 count: usize,
186 explicit_count: bool,
187 ) -> (usize, usize) {
188 let mut position = self.vim_normal_position(start);
189 let count = count.max(1);
190
191 match motion {
192 VimMotion::Left => {
193 position.1 = position.1.saturating_sub(count);
194 }
195 VimMotion::Right => {
196 let max_col =
197 self.buffer.line_len(position.0).saturating_sub(1);
198 position.1 = position.1.saturating_add(count).min(max_col);
199 }
200 VimMotion::Up | VimMotion::Down => {
201 let direction = if motion == VimMotion::Up {
202 ArrowDirection::Up
203 } else {
204 ArrowDirection::Down
205 };
206 let visual_lines =
207 self.visual_lines_cached(self.viewport_width);
208 for _ in 0..count {
209 let Some(next) = compute_next_position(
210 position,
211 direction,
212 &self.buffer,
213 &visual_lines,
214 ) else {
215 break;
216 };
217 position = self.vim_normal_position(next);
218 }
219 }
220 VimMotion::WordForward
221 | VimMotion::WordBackward
222 | VimMotion::WordEnd => {
223 let chars = self.vim_char_index();
224 for _ in 0..count {
225 position = Self::vim_word_motion(&chars, position, motion);
226 }
227 }
228 VimMotion::LineStart => position.1 = 0,
229 VimMotion::FirstNonBlank => {
230 position.1 = self
231 .buffer
232 .line(position.0)
233 .chars()
234 .position(|ch| !ch.is_whitespace())
235 .unwrap_or(0);
236 }
237 VimMotion::LineEnd => {
238 position.1 = self.buffer.line_len(position.0).saturating_sub(1);
239 }
240 VimMotion::DocumentStart => {
241 let line = count
242 .saturating_sub(1)
243 .min(self.buffer.line_count().saturating_sub(1));
244 position = (line, 0);
245 }
246 VimMotion::DocumentEnd => {
247 let line = if explicit_count {
248 count
249 .saturating_sub(1)
250 .min(self.buffer.line_count().saturating_sub(1))
251 } else {
252 self.buffer.line_count().saturating_sub(1)
253 };
254 position = (line, 0);
255 }
256 }
257
258 self.vim_normal_position(position)
259 }
260
261 fn vim_char_index(&self) -> Vec<((usize, usize), char)> {
267 let mut chars = Vec::new();
268 for line in 0..self.buffer.line_count() {
269 chars.extend(
270 self.buffer
271 .line(line)
272 .chars()
273 .enumerate()
274 .map(|(col, ch)| ((line, col), ch)),
275 );
276 if line + 1 < self.buffer.line_count() {
277 chars.push(((line, self.buffer.line_len(line)), '\n'));
278 }
279 }
280 chars
281 }
282
283 fn vim_word_motion(
286 chars: &[((usize, usize), char)],
287 start: (usize, usize),
288 motion: VimMotion,
289 ) -> (usize, usize) {
290 #[derive(Clone, Copy, PartialEq, Eq)]
291 enum Class {
292 Space,
293 Word,
294 Punctuation,
295 }
296
297 fn class(ch: char) -> Class {
298 if ch.is_whitespace() {
299 Class::Space
300 } else if ch.is_alphanumeric() || ch == '_' {
301 Class::Word
302 } else {
303 Class::Punctuation
304 }
305 }
306
307 if chars.is_empty() {
308 return (0, 0);
309 }
310
311 let insertion =
312 chars.partition_point(|(position, _)| *position < start);
313 let exact = insertion < chars.len() && chars[insertion].0 == start;
314
315 match motion {
316 VimMotion::WordForward => {
317 let mut index = insertion;
318 if exact {
319 let current_class = class(chars[index].1);
320 if current_class == Class::Space {
321 while index < chars.len()
322 && class(chars[index].1) == Class::Space
323 {
324 index += 1;
325 }
326 } else {
327 while index < chars.len()
328 && class(chars[index].1) == current_class
329 {
330 index += 1;
331 }
332 while index < chars.len()
333 && class(chars[index].1) == Class::Space
334 {
335 index += 1;
336 }
337 }
338 }
339 chars[index.min(chars.len() - 1)].0
340 }
341 VimMotion::WordBackward => {
342 let mut index = insertion.saturating_sub(1);
343 while index > 0 && class(chars[index].1) == Class::Space {
344 index -= 1;
345 }
346 let target_class = class(chars[index].1);
347 while index > 0 && class(chars[index - 1].1) == target_class {
348 index -= 1;
349 }
350 chars[index].0
351 }
352 VimMotion::WordEnd => {
353 let mut index = insertion.min(chars.len() - 1);
354 if exact {
355 let current_class = class(chars[index].1);
356 if current_class != Class::Space
357 && index + 1 < chars.len()
358 && class(chars[index + 1].1) == current_class
359 {
360 while index + 1 < chars.len()
361 && class(chars[index + 1].1) == current_class
362 {
363 index += 1;
364 }
365 return chars[index].0;
366 }
367 index = (index + 1).min(chars.len() - 1);
368 }
369 while index + 1 < chars.len()
370 && class(chars[index].1) == Class::Space
371 {
372 index += 1;
373 }
374 let target_class = class(chars[index].1);
375 while index + 1 < chars.len()
376 && class(chars[index + 1].1) == target_class
377 {
378 index += 1;
379 }
380 chars[index].0
381 }
382 _ => start,
383 }
384 }
385
386 pub fn set_cursor(&mut self, line: usize, col: usize) -> Task<Message> {
418 let line = line.min(self.buffer.line_count().saturating_sub(1));
419 let line_len = self.buffer.line(line).chars().count();
420 let col = col.min(line_len);
421
422 self.cursors.set_single((line, col));
423 self.is_dragging = false;
426
427 self.last_blink = Instant::now();
429
430 self.overlay_cache.clear();
431 self.scroll_to_cursor()
432 }
433
434 pub(crate) fn move_cursor(&mut self, direction: ArrowDirection) {
439 let visual_lines = self.visual_lines_cached(self.viewport_width);
443
444 for cursor in self.cursors.as_mut_slice() {
445 if let Some(new_pos) = compute_next_position(
446 cursor.position,
447 direction,
448 &self.buffer,
449 &visual_lines,
450 ) {
451 cursor.position = new_pos;
452 }
453 }
454
455 self.cursors.sort_and_merge();
457
458 self.overlay_cache.clear();
461 }
462
463 pub(crate) fn calculate_cursor_from_point(
470 &self,
471 point: Point,
472 ) -> Option<(usize, usize)> {
473 if point.x < self.gutter_width() {
475 return None; }
477
478 let visual_line_idx = (point.y / self.line_height) as usize;
480
481 let visual_lines = self.visual_lines_cached(self.viewport_width);
484
485 if visual_line_idx >= visual_lines.len() {
486 let last_line = self.buffer.line_count().saturating_sub(1);
488 let last_col = self.buffer.line_len(last_line);
489 return Some((last_line, last_col));
490 }
491
492 let visual_line = &visual_lines[visual_line_idx];
493
494 let x_in_text =
496 point.x - self.gutter_width() - 5.0 + self.horizontal_scroll_offset;
497
498 let line_content = self.buffer.line(visual_line.logical_line);
500
501 let mut current_width = 0.0;
502 let mut col_offset = 0;
503
504 for c in line_content
506 .chars()
507 .skip(visual_line.start_col)
508 .take(visual_line.end_col - visual_line.start_col)
509 {
510 let char_width =
511 measure_char_width(c, self.full_char_width, self.char_width);
512
513 if current_width + char_width / 2.0 > x_in_text {
514 break;
515 }
516 current_width += char_width;
517 col_offset += 1;
518 }
519
520 let col = visual_line.start_col + col_offset;
521 Some((visual_line.logical_line, col))
522 }
523
524 pub(crate) fn handle_mouse_click(&mut self, point: Point) {
528 let before = self.cursors.primary_position();
529 if let Some(pos) = self.calculate_cursor_from_point(point) {
530 self.cursors.primary_mut().position = pos;
531 if self.cursors.primary_position() != before {
532 self.overlay_cache.clear();
534 }
535 }
536 }
537
538 pub(crate) fn classify_click(&self, position: Point) -> u8 {
545 let now = Instant::now();
546 let count = match self.last_click.get() {
547 Some((time, pos, count))
548 if now.duration_since(time)
549 < std::time::Duration::from_millis(400)
550 && pos.distance(position) < 6.0 =>
551 {
552 if count >= 3 {
553 1
554 } else {
555 count + 1
556 }
557 }
558 _ => 1,
559 };
560 self.last_click.set(Some((now, position, count)));
561 count
562 }
563
564 pub(crate) fn scroll_to_line(
586 &self,
587 line: usize,
588 rows_above: usize,
589 ) -> Task<Message> {
590 let visual_lines = self.visual_lines_cached(self.viewport_width);
591
592 let Some(visual_index) =
593 WrappingCalculator::logical_to_visual(&visual_lines, line, 0)
594 else {
595 return Task::none();
596 };
597
598 let first_visible = visual_index.saturating_sub(rows_above);
602
603 scroll_to(
604 self.scrollable_id.clone(),
605 scrollable::AbsoluteOffset {
606 x: 0.0,
607 y: first_visible as f32 * self.line_height,
608 },
609 )
610 }
611
612 pub(crate) fn scroll_to_cursor(&self) -> Task<Message> {
614 let visual_lines = self.visual_lines_cached(self.viewport_width);
617
618 let pos = self.cursors.primary_position();
619 let cursor_visual =
620 WrappingCalculator::logical_to_visual(&visual_lines, pos.0, pos.1);
621
622 let cursor_y = if let Some(visual_idx) = cursor_visual {
623 visual_idx as f32 * self.line_height
624 } else {
625 pos.0 as f32 * self.line_height
627 };
628
629 let viewport_top = self.viewport_scroll;
630 let viewport_bottom = self.viewport_scroll + self.viewport_height;
631
632 let top_margin = self.line_height * 2.0;
634 let bottom_margin = self.line_height * 2.0;
635
636 let new_v_scroll = if cursor_y < viewport_top + top_margin {
638 Some((cursor_y - top_margin).max(0.0))
640 } else if cursor_y + self.line_height > viewport_bottom - bottom_margin
641 {
642 Some(
644 cursor_y + self.line_height + bottom_margin
645 - self.viewport_height,
646 )
647 } else {
648 None
649 };
650
651 let vertical_task = if let Some(new_scroll) = new_v_scroll {
652 scroll_to(
653 self.scrollable_id.clone(),
654 scrollable::AbsoluteOffset { x: 0.0, y: new_scroll },
655 )
656 } else {
657 Task::none()
658 };
659
660 let h_task = if !self.wrap_enabled {
662 let cursor_content_x = if let Some(visual_idx) = cursor_visual {
664 let vl = &visual_lines[visual_idx];
665 let line_content = self.buffer.line(vl.logical_line);
666 let prefix: String = line_content
667 .chars()
668 .skip(vl.start_col)
669 .take(pos.1.saturating_sub(vl.start_col))
670 .collect();
671 self.gutter_width()
672 + 5.0
673 + measure_text_width(
674 &prefix,
675 self.full_char_width,
676 self.char_width,
677 )
678 } else {
679 self.gutter_width() + 5.0
680 };
681
682 let left_boundary = self.gutter_width() + self.char_width;
683 let right_boundary = self.viewport_width - self.char_width * 2.0;
684 let cursor_viewport_x =
685 cursor_content_x - self.horizontal_scroll_offset;
686
687 let new_h_offset = if cursor_viewport_x < left_boundary {
688 (cursor_content_x - left_boundary).max(0.0)
689 } else if cursor_viewport_x > right_boundary {
690 cursor_content_x - right_boundary
691 } else {
692 self.horizontal_scroll_offset };
694
695 if (new_h_offset - self.horizontal_scroll_offset).abs() > 0.5 {
696 scroll_to(
697 self.horizontal_scrollable_id.clone(),
698 scrollable::AbsoluteOffset { x: new_h_offset, y: 0.0 },
699 )
700 } else {
701 Task::none()
702 }
703 } else {
704 Task::none()
705 };
706
707 Task::batch([vertical_task, h_task])
708 }
709
710 fn rows_per_page(&self) -> usize {
729 ((self.viewport_height / self.line_height) as usize).max(1)
730 }
731
732 fn move_cursors_by_visual_row(&mut self, map_row: impl Fn(usize) -> usize) {
749 let visual_lines = self.visual_lines_cached(self.viewport_width);
750 let Some(last_row) = visual_lines.len().checked_sub(1) else {
751 return; };
753
754 for cursor in self.cursors.as_mut_slice() {
755 let Some(current_row) = WrappingCalculator::logical_to_visual(
756 &visual_lines,
757 cursor.position.0,
758 cursor.position.1,
759 ) else {
760 continue;
761 };
762
763 let target_row = map_row(current_row).min(last_row);
764 cursor.position = (
765 visual_lines[target_row].logical_line,
766 column_on_visual_row(
767 cursor.position,
768 &visual_lines[current_row],
769 &visual_lines[target_row],
770 &self.buffer,
771 ),
772 );
773 }
774
775 self.cursors.sort_and_merge();
776 self.overlay_cache.clear();
777 }
778
779 pub(crate) fn page_up(&mut self) {
781 let rows = self.rows_per_page();
782 self.move_cursors_by_visual_row(|row| row.saturating_sub(rows));
783 }
784
785 pub(crate) fn page_down(&mut self) {
787 let rows = self.rows_per_page();
788 self.move_cursors_by_visual_row(|row| row.saturating_add(rows));
789 }
790
791 pub(crate) fn handle_mouse_drag(&mut self, point: Point) {
795 if let Some(pos) = self.calculate_cursor_from_point(point) {
796 self.cursors.primary_mut().position = pos;
797 }
798 }
799}
800
801impl CodeEditor {
802 pub(crate) fn point_from_position(
804 &self,
805 line: usize,
806 col: usize,
807 ) -> Option<iced::Point> {
808 let visual_lines = self.visual_lines_cached(self.viewport_width);
809 let visual_index =
810 WrappingCalculator::logical_to_visual(&visual_lines, line, col)?;
811 let visual_line = &visual_lines[visual_index];
812 let line_content = self.buffer.line(visual_line.logical_line);
813 let prefix_len = col.saturating_sub(visual_line.start_col);
814 let prefix_text: String = line_content
815 .chars()
816 .skip(visual_line.start_col)
817 .take(prefix_len)
818 .collect();
819 let x = self.gutter_width()
820 + 5.0
821 + measure_text_width(
822 &prefix_text,
823 self.full_char_width,
824 self.char_width,
825 );
826 let y = visual_index as f32 * self.line_height;
827 Some(iced::Point::new(x, y))
828 }
829
830 pub(crate) fn word_start_in_line(line: &str, col: usize) -> usize {
834 let chars: Vec<char> = line.chars().collect();
835 if chars.is_empty() {
836 return 0;
837 }
838 let mut idx = col.min(chars.len());
839 if idx == chars.len() {
840 idx = idx.saturating_sub(1);
841 }
842 if !Self::is_word_char(chars[idx]) {
843 if idx > 0 && Self::is_word_char(chars[idx - 1]) {
844 idx -= 1;
845 } else {
846 return col.min(chars.len());
847 }
848 }
849 while idx > 0 && Self::is_word_char(chars[idx - 1]) {
850 idx -= 1;
851 }
852 idx
853 }
854
855 pub(crate) fn word_end_in_line(line: &str, col: usize) -> usize {
857 let chars: Vec<char> = line.chars().collect();
858 if chars.is_empty() {
859 return 0;
860 }
861 let mut idx = col.min(chars.len());
862 if idx == chars.len() {
863 idx = idx.saturating_sub(1);
864 }
865
866 if !Self::is_word_char(chars[idx]) {
868 if idx > 0 && Self::is_word_char(chars[idx - 1]) {
869 return idx;
874 } else {
875 return col.min(chars.len());
877 }
878 }
879
880 while idx < chars.len() && Self::is_word_char(chars[idx]) {
882 idx += 1;
883 }
884 idx
885 }
886
887 pub(crate) fn is_word_char(ch: char) -> bool {
889 ch == '_' || ch.is_alphanumeric()
890 }
891
892 pub fn cursor_screen_position(&self) -> Option<iced::Point> {
913 let pos = self.cursors.primary_position();
914 self.point_from_position(pos.0, pos.1)
915 }
916
917 pub fn cursor_position(&self) -> (usize, usize) {
936 self.cursors.primary_position()
937 }
938}
939
940#[cfg(test)]
941mod tests {
942 use super::*;
943 #[test]
944 fn test_word_start_in_line() {
945 let line = "foo_bar baz";
946 assert_eq!(CodeEditor::word_start_in_line(line, 0), 0);
947 assert_eq!(CodeEditor::word_start_in_line(line, 2), 0);
948 assert_eq!(CodeEditor::word_start_in_line(line, 4), 0);
949 assert_eq!(CodeEditor::word_start_in_line(line, 7), 0);
950 assert_eq!(CodeEditor::word_start_in_line(line, 9), 8);
951 }
952
953 #[test]
954 fn vim_word_motion_crosses_line_boundary_via_prebuilt_index() {
955 let editor = CodeEditor::new("one two\nthree four", "txt");
956 let chars = editor.vim_char_index();
957
958 assert_eq!(
959 CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordForward),
960 (1, 0)
961 );
962 assert_eq!(
963 CodeEditor::vim_word_motion(
964 &chars,
965 (1, 0),
966 VimMotion::WordBackward
967 ),
968 (0, 4)
969 );
970 assert_eq!(
971 CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordEnd),
972 (0, 6)
973 );
974 }
975
976 #[test]
977 fn test_cursor_movement() {
978 let mut editor = CodeEditor::new("line1\nline2", "py");
979 editor.move_cursor(ArrowDirection::Down);
980 assert_eq!(editor.cursors.primary_position().0, 1);
981 editor.move_cursor(ArrowDirection::Right);
982 assert_eq!(editor.cursors.primary_position().1, 1);
983 }
984
985 #[test]
986 fn test_page_down() {
987 let content = (0..100)
989 .map(|i| format!("line {i}"))
990 .collect::<Vec<_>>()
991 .join("\n");
992 let mut editor = CodeEditor::new(&content, "py");
993
994 editor.page_down();
995 assert!(editor.cursors.primary_position().0 >= 25);
997 assert!(editor.cursors.primary_position().0 <= 35);
998 }
999
1000 #[test]
1001 fn test_page_up() {
1002 let content = (0..100)
1004 .map(|i| format!("line {i}"))
1005 .collect::<Vec<_>>()
1006 .join("\n");
1007 let mut editor = CodeEditor::new(&content, "py");
1008
1009 editor.cursors.primary_mut().position = (50, 0);
1011 editor.page_up();
1012
1013 assert!(editor.cursors.primary_position().0 >= 15);
1015 assert!(editor.cursors.primary_position().0 <= 25);
1016 }
1017
1018 #[test]
1019 fn test_page_down_at_end() {
1020 let content =
1021 (0..10).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
1022 let mut editor = CodeEditor::new(&content, "py");
1023
1024 editor.page_down();
1025 assert_eq!(editor.cursors.primary_position().0, 9);
1027 }
1028
1029 fn wrapped_editor() -> CodeEditor {
1034 let long = "x".repeat(400);
1035 let content =
1036 (0..10).map(|_| long.clone()).collect::<Vec<_>>().join("\n");
1037 let mut editor = CodeEditor::new(&content, "py");
1038 editor.viewport_height = editor.line_height * 3.0;
1039 editor.viewport_width = 300.0;
1040 editor
1041 }
1042
1043 #[test]
1044 fn test_page_down_moves_one_viewport_of_visual_rows() {
1045 let mut editor = wrapped_editor();
1050 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1051 let rows_in_first_line =
1052 visual_lines.iter().filter(|row| row.logical_line == 0).count();
1053 assert!(
1054 rows_in_first_line > 3,
1055 "the fixture only tests anything if its lines really wrap"
1056 );
1057
1058 editor.cursors.primary_mut().position = (0, 0);
1060 editor.page_down();
1061
1062 let target = &visual_lines[3];
1063 assert_eq!(
1064 editor.cursors.primary_position(),
1065 (target.logical_line, target.start_col)
1066 );
1067 assert_eq!(editor.cursors.primary_position().0, 0);
1069 }
1070
1071 #[test]
1072 fn test_page_up_moves_one_viewport_of_visual_rows() {
1073 let mut editor = wrapped_editor();
1074 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1075
1076 let start = &visual_lines[20];
1077 editor.cursors.primary_mut().position =
1078 (start.logical_line, start.start_col);
1079 editor.page_up();
1080
1081 let target = &visual_lines[17];
1082 assert_eq!(
1083 editor.cursors.primary_position(),
1084 (target.logical_line, target.start_col)
1085 );
1086 }
1087
1088 #[test]
1089 fn test_paging_stops_at_the_last_visual_row() {
1090 let mut editor = wrapped_editor();
1091 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1092 let last = visual_lines.len() - 1;
1093
1094 let start = &visual_lines[last];
1095 editor.cursors.primary_mut().position =
1096 (start.logical_line, start.start_col);
1097 editor.page_down();
1098
1099 assert_eq!(editor.cursors.primary_position().0, start.logical_line);
1100 }
1101
1102 #[test]
1103 fn test_rows_per_page_counts_whole_rows_only() {
1104 let mut editor = CodeEditor::new("line0\nline1", "py");
1105
1106 editor.viewport_height = editor.line_height * 3.0;
1107 assert_eq!(editor.rows_per_page(), 3);
1108
1109 editor.viewport_height = editor.line_height * 3.5;
1111 assert_eq!(editor.rows_per_page(), 3);
1112
1113 editor.viewport_height = 0.0;
1116 assert_eq!(editor.rows_per_page(), 1);
1117 }
1118
1119 #[test]
1120 fn test_page_down_still_moves_with_a_zero_height_viewport() {
1121 let mut editor = CodeEditor::new("line0\nline1\nline2", "py");
1122 editor.viewport_height = 0.0;
1123 editor.cursors.primary_mut().position = (0, 0);
1124
1125 editor.page_down();
1126
1127 assert_eq!(editor.cursors.primary_position(), (1, 0));
1128 }
1129
1130 #[test]
1131 fn test_column_on_visual_row_keeps_the_offset_inside_a_wrapped_line() {
1132 let buffer = TextBuffer::new("hello world");
1133 let current = VisualLine::new(0, 0, 0, 5);
1134 let target = VisualLine::new(0, 1, 5, 11);
1135
1136 assert_eq!(column_on_visual_row((0, 2), ¤t, &target, &buffer), 7);
1139 }
1140
1141 #[test]
1142 fn test_column_on_visual_row_clamps_when_the_target_line_is_shorter() {
1143 let buffer = TextBuffer::new("longer line\nab");
1144 let current = VisualLine::new(0, 0, 0, 11);
1145 let target = VisualLine::new(1, 0, 0, 2);
1146
1147 assert_eq!(column_on_visual_row((0, 9), ¤t, &target, &buffer), 2);
1148 }
1149
1150 #[test]
1151 fn test_page_up_at_start() {
1152 let content = (0..100)
1153 .map(|i| format!("line {i}"))
1154 .collect::<Vec<_>>()
1155 .join("\n");
1156 let mut editor = CodeEditor::new(&content, "py");
1157
1158 editor.cursors.primary_mut().position = (0, 0);
1160 editor.page_up();
1161 assert_eq!(editor.cursors.primary_position().0, 0);
1162 }
1163
1164 #[test]
1165 fn test_cursor_click_cjk() {
1166 use iced::Point;
1167 let mut editor = CodeEditor::new("你好", "txt");
1168 editor.set_line_numbers_enabled(false);
1169 editor.set_folding_enabled(false);
1172
1173 let full_char_width = editor.full_char_width();
1174 let half_width = full_char_width / 2.0;
1175 let padding = 5.0;
1176
1177 editor
1183 .handle_mouse_click(Point::new((half_width - 2.0) + padding, 10.0));
1184
1185 assert_eq!(editor.cursors.primary_position(), (0, 0));
1186
1187 editor
1190 .handle_mouse_click(Point::new((half_width + 2.0) + padding, 10.0));
1191 assert_eq!(editor.cursors.primary_position(), (0, 1));
1192
1193 editor.handle_mouse_click(Point::new(
1197 (full_char_width + half_width - 2.0) + padding,
1198 10.0,
1199 ));
1200 assert_eq!(editor.cursors.primary_position(), (0, 1));
1201
1202 editor.handle_mouse_click(Point::new(
1206 (full_char_width + half_width + 2.0) + padding,
1207 10.0,
1208 ));
1209 assert_eq!(editor.cursors.primary_position(), (0, 2));
1210 }
1211
1212 #[test]
1213 fn test_multi_cursor_move_left() {
1214 let mut editor = CodeEditor::new("abc\ndef", "rs");
1215 editor.cursors.primary_mut().position = (0, 2);
1216 editor.cursors.add_cursor((1, 2));
1217
1218 editor.move_cursor(ArrowDirection::Left);
1219
1220 let positions: Vec<(usize, usize)> =
1222 editor.cursors.iter().map(|c| c.position).collect();
1223 assert!(positions.contains(&(0, 1)));
1224 assert!(positions.contains(&(1, 1)));
1225 }
1226
1227 #[test]
1228 fn test_multi_cursor_move_right() {
1229 let mut editor = CodeEditor::new("abc\ndef", "rs");
1230 editor.cursors.primary_mut().position = (0, 1);
1231 editor.cursors.add_cursor((1, 1));
1232
1233 editor.move_cursor(ArrowDirection::Right);
1234
1235 let positions: Vec<(usize, usize)> =
1236 editor.cursors.iter().map(|c| c.position).collect();
1237 assert!(positions.contains(&(0, 2)));
1238 assert!(positions.contains(&(1, 2)));
1239 }
1240
1241 #[test]
1242 fn test_multi_cursor_move_deduplicates() {
1243 let mut editor = CodeEditor::new("abc", "rs");
1244 editor.cursors.primary_mut().position = (0, 0);
1246 editor.cursors.add_cursor((0, 1));
1247 assert_eq!(editor.cursors.len(), 2);
1248
1249 editor.move_cursor(ArrowDirection::Right);
1250
1251 assert_eq!(editor.cursors.len(), 2);
1253 }
1254}