1use iced::Size;
4use iced::alignment;
5use iced::mouse;
6use iced::widget::canvas::Canvas;
7use iced::widget::{
8 Column, MouseArea, Row, Scrollable, Space, container, scrollable, text,
9};
10use iced::{Background, Border, Color, Element, Length, Rectangle, Shadow};
11use iced_aw::ContextMenu;
12
13use super::text::{expand_tabs, expand_tabs_visible};
14use super::wrapping::{self, WrappingCalculator};
15use crate::canvas_editor::features::command_palette::dialog as command_palette_dialog;
16use crate::canvas_editor::features::context_menu;
17use crate::canvas_editor::features::goto_line::dialog as goto_line_dialog;
18use crate::canvas_editor::features::search::dialog as search_dialog;
19use crate::canvas_editor::features::sticky_scroll;
20use crate::canvas_editor::input::ime_requester::ImeRequester;
21use crate::canvas_editor::{CodeEditor, Message, TAB_WIDTH};
22use std::rc::Rc;
23
24const CODE_TEXT_LEFT_PADDING: f32 = 5.0;
27
28const STICKY_SEPARATOR_WIDTH: f32 = 1.0;
30
31const SCROLLBAR_WIDTH: f32 = 8.0;
34const SCROLLER_WIDTH: f32 = 6.0;
36const SCROLLBAR_MARGIN: f32 = 2.0;
38
39fn canvas_scrollbar() -> scrollable::Scrollbar {
41 scrollable::Scrollbar::new()
42 .width(SCROLLBAR_WIDTH)
43 .scroller_width(SCROLLER_WIDTH)
44 .margin(SCROLLBAR_MARGIN)
45}
46
47fn scroller_alpha(status: scrollable::Status) -> (f32, f32) {
51 let pick = |on_bar: bool| if on_bar { 1.0 / 0.6 } else { 1.0 };
52 match status {
53 scrollable::Status::Active { .. } => (0.6, 0.6),
54 scrollable::Status::Hovered {
55 is_vertical_scrollbar_hovered: v,
56 is_horizontal_scrollbar_hovered: h,
57 ..
58 } => (pick(v), pick(h)),
59 scrollable::Status::Dragged {
60 is_vertical_scrollbar_dragged: v,
61 is_horizontal_scrollbar_dragged: h,
62 ..
63 } => (pick(v), pick(h)),
64 }
65}
66
67fn canvas_scrollbar_style(
71 scrollbar_bg: Color,
72 scroller_color: Color,
73 status: scrollable::Status,
74) -> scrollable::Style {
75 let (v, h) = scroller_alpha(status);
76 let scale =
77 |a: f32| Color { a: (scroller_color.a * a).min(1.0), ..scroller_color };
78 let pill = SCROLLBAR_WIDTH * 10.0;
81 scrollable::Style {
82 container: container::Style {
83 background: Some(Background::Color(Color::TRANSPARENT)),
84 ..container::Style::default()
85 },
86 vertical_rail: scrollable_rail(scrollbar_bg, scale(v), pill),
87 horizontal_rail: scrollable_rail(scrollbar_bg, scale(h), pill),
88 gap: None,
89 auto_scroll: scrollable::AutoScroll {
90 background: Color::TRANSPARENT.into(),
91 border: Border::default(),
92 shadow: Shadow::default(),
93 icon: Color::TRANSPARENT,
94 },
95 }
96}
97
98impl CodeEditor {
99 fn calculate_canvas_height(&self) -> (Rc<Vec<wrapping::VisualLine>>, f32) {
105 let visual_lines = self.visual_lines_cached(self.viewport_width);
108 let total_visual_lines = visual_lines.len();
109 let content_height = total_visual_lines as f32 * self.line_height;
110
111 let canvas_height = content_height.max(self.viewport_height);
115
116 (visual_lines, canvas_height)
117 }
118
119 fn create_scrollable_style(
123 &self,
124 ) -> impl Fn(&iced::Theme, scrollable::Status) -> scrollable::Style {
125 let scrollbar_bg = self.style.scrollbar_background;
126 let scroller_color = self.style.scroller_color;
127
128 move |_theme, status| {
129 canvas_scrollbar_style(scrollbar_bg, scroller_color, status)
130 }
131 }
132
133 fn create_canvas_with_scrollable(
143 &self,
144 canvas_height: f32,
145 ) -> Scrollable<'_, Message> {
146 let canvas = Canvas::new(self)
147 .width(Length::Fill)
148 .height(Length::Fixed(canvas_height));
149
150 Scrollable::new(canvas)
151 .id(self.scrollable_id.clone())
152 .width(Length::Fill)
153 .height(Length::Fill)
154 .direction(scrollable::Direction::Vertical(canvas_scrollbar()))
155 .on_scroll(Message::Scrolled)
156 .style(self.create_scrollable_style())
157 }
158
159 pub(crate) fn should_show_horizontal_scrollbar(
176 &self,
177 max_content_width: f32,
178 ) -> bool {
179 !self.wrap_enabled && max_content_width > self.last_canvas_width.get()
180 }
181
182 fn create_horizontal_scrollbar(
192 &self,
193 max_content_width: f32,
194 ) -> Option<Element<'_, Message>> {
195 if !self.should_show_horizontal_scrollbar(max_content_width) {
196 return None;
197 }
198
199 let scrollbar_bg = self.style.scrollbar_background;
200 let scroller_color = self.style.scroller_color;
201
202 let h_scrollable = Scrollable::new(
203 Space::new().width(Length::Fixed(max_content_width)).height(0.0),
204 )
205 .id(self.horizontal_scrollable_id.clone())
206 .width(Length::Fill)
207 .height(Length::Fixed(12.0))
208 .direction(scrollable::Direction::Horizontal(canvas_scrollbar()))
209 .on_scroll(Message::HorizontalScrolled)
210 .style(move |_theme, status| {
211 canvas_scrollbar_style(scrollbar_bg, scroller_color, status)
212 });
213
214 Some(h_scrollable.into())
215 }
216
217 fn create_gutter_container(
223 &self,
224 ) -> Option<container::Container<'_, Message>> {
225 if self.line_numbers_enabled {
226 let gutter_background = self.style.gutter_background;
227 Some(
228 container(
229 Space::new().width(Length::Fill).height(Length::Fill),
230 )
231 .width(Length::Fixed(self.gutter_columns().line_numbers.end))
234 .height(Length::Fill)
235 .style(move |_| container::Style {
236 background: Some(Background::Color(gutter_background)),
237 ..container::Style::default()
238 }),
239 )
240 } else {
241 None
242 }
243 }
244
245 fn create_code_background_container(
251 &self,
252 ) -> container::Container<'_, Message> {
253 let background_color = self.style.background;
254 container(Space::new().width(Length::Fill).height(Length::Fill))
255 .width(Length::Fill)
256 .height(Length::Fill)
257 .style(move |_| container::Style {
258 background: Some(Background::Color(background_color)),
259 ..container::Style::default()
260 })
261 }
262
263 fn create_vim_status_bar(&self) -> Element<'_, Message> {
265 let (left_text, right_text) = self.vim_state.status_line_text();
266 let background = self.style.gutter_background;
267 let text_color = self.style.text_color;
268
269 container(
270 Row::new()
271 .push(
272 text(left_text).size(self.font_size).style(move |_| {
273 text::Style { color: Some(text_color) }
274 }),
275 )
276 .push(Space::new().width(Length::Fill))
277 .push(
278 text(right_text).size(self.font_size).style(move |_| {
279 text::Style { color: Some(text_color) }
280 }),
281 ),
282 )
283 .padding([2, 8])
284 .width(Length::Fill)
285 .height(Length::Fixed(self.line_height.max(20.0)))
286 .style(move |_| container::Style {
287 background: Some(Background::Color(background)),
288 ..container::Style::default()
289 })
290 .into()
291 }
292
293 fn create_background_layer(&self) -> Row<'_, Message> {
299 let gutter_container = self.create_gutter_container();
300 let code_background_container = self.create_code_background_container();
301
302 if let Some(gutter) = gutter_container {
303 Row::new().push(gutter).push(code_background_container)
304 } else {
305 Row::new().push(code_background_container)
306 }
307 }
308
309 fn calculate_ime_cursor_rect(
319 &self,
320 visual_lines: &[wrapping::VisualLine],
321 ) -> Rectangle {
322 let ime_enabled = self.is_focused() && self.has_canvas_focus;
323
324 if !ime_enabled {
325 return Rectangle::new(
326 iced::Point::new(0.0, 0.0),
327 Size::new(0.0, 0.0),
328 );
329 }
330
331 if let Some(cursor_visual) = WrappingCalculator::logical_to_visual(
332 visual_lines,
333 self.cursors.primary_position().0,
334 self.cursors.primary_position().1,
335 ) {
336 let vl = &visual_lines[cursor_visual];
337 let line_content = self.buffer.line(vl.logical_line);
338 let prefix_len =
339 self.cursors.primary_position().1.saturating_sub(vl.start_col);
340 let prefix_text: String = line_content
341 .chars()
342 .skip(vl.start_col)
343 .take(prefix_len)
344 .collect();
345 let cursor_x = self.gutter_width()
346 + 5.0
347 + crate::canvas_editor::measure_text_width(
348 &prefix_text,
349 self.full_char_width,
350 self.char_width,
351 )
352 - self.horizontal_scroll_offset;
353
354 let cursor_y = (cursor_visual as f32 * self.line_height)
358 - self.viewport_scroll;
359
360 Rectangle::new(
361 iced::Point::new(cursor_x, cursor_y + 2.0),
362 Size::new(2.0, self.line_height - 4.0),
363 )
364 } else {
365 Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(0.0, 0.0))
366 }
367 }
368
369 fn create_sticky_header_row(
383 &self,
384 line: usize,
385 syntax_set: &syntect::parsing::SyntaxSet,
386 syntax: &syntect::parsing::SyntaxReference,
387 theme: &syntect::highlighting::Theme,
388 ) -> Element<'_, Message> {
389 let font = self.font;
390 let font_size = self.font_size;
391 let line_number_color = self.style.line_number_color;
392
393 let mut row = Row::new();
394
395 let fold_margin_width = self.fold_margin_width();
398 let fold_margin =
399 || Space::new().width(Length::Fixed(fold_margin_width));
400 let markers_first = self.fold_marker_position
401 == crate::FoldMarkerPosition::BeforeLineNumbers;
402 if markers_first {
403 row = row.push(fold_margin());
404 }
405
406 if self.line_numbers_enabled {
407 row = row.push(
408 container(
409 text(format!("{}", line + 1))
410 .size(font_size)
411 .font(font)
412 .style(move |_| text::Style {
413 color: Some(line_number_color),
414 }),
415 )
416 .width(Length::Fixed(self.line_number_gutter_width()))
417 .align_x(alignment::Horizontal::Center),
418 );
419 }
420
421 if !markers_first {
422 row = row.push(fold_margin());
423 }
424 row =
425 row.push(Space::new().width(Length::Fixed(CODE_TEXT_LEFT_PADDING)));
426
427 let spans =
428 self.highlighted_line_cached(line, syntax, theme, syntax_set);
429 let mut code = Row::new();
430 for (color, content) in spans.iter() {
431 let color = *color;
432 let content = if self.show_whitespace {
435 expand_tabs_visible(content, TAB_WIDTH)
436 } else {
437 expand_tabs(content, TAB_WIDTH).into_owned()
438 };
439 let span_font =
441 if content.is_ascii() { font } else { iced::Font::DEFAULT };
442 code = code.push(
443 text(content)
444 .size(font_size)
445 .font(span_font)
446 .wrapping(text::Wrapping::None)
447 .style(move |_| text::Style { color: Some(color) }),
448 );
449 }
450 row = row.push(code);
451
452 MouseArea::new(
453 container(row)
454 .width(Length::Fill)
455 .height(Length::Fixed(self.line_height))
456 .clip(true),
457 )
458 .interaction(mouse::Interaction::Pointer)
459 .on_press(Message::StickyScrollJump(line))
460 .into()
461 }
462
463 fn create_sticky_scroll_layer(
476 &self,
477 visual_lines: &[wrapping::VisualLine],
478 ) -> Option<Element<'_, Message>> {
479 if !self.sticky_scroll_enabled || self.line_height <= 0.0 {
480 return None;
481 }
482
483 let first_visible =
487 (self.viewport_scroll / self.line_height).floor() as usize;
488 let top_line = visual_lines.get(first_visible)?.logical_line;
489
490 let regions = self.block_regions();
494 let headers = sticky_scroll::sticky_headers(
495 ®ions,
496 top_line,
497 sticky_scroll::DEFAULT_MAX_STICKY_LINES,
498 );
499 if headers.is_empty() {
500 return None;
501 }
502
503 let (syntax_set, syntax, theme) = self.resolve_syntax();
504 let (Some(syntax), Some(theme)) = (syntax, theme) else {
505 return None;
506 };
507
508 let mut column = Column::new();
509 for line in headers {
510 column = column.push(
511 self.create_sticky_header_row(line, syntax_set, syntax, theme),
512 );
513 }
514
515 let background = self.style.gutter_background;
516 let border_color = self.style.gutter_border;
517
518 let column = column.push(
521 container(Space::new().width(Length::Fill).height(Length::Fill))
522 .width(Length::Fill)
523 .height(Length::Fixed(STICKY_SEPARATOR_WIDTH))
524 .style(move |_| container::Style {
525 background: Some(Background::Color(border_color)),
526 ..container::Style::default()
527 }),
528 );
529
530 Some(
531 container(column)
532 .width(Length::Fill)
533 .height(Length::Shrink)
534 .style(move |_| container::Style {
535 background: Some(Background::Color(background)),
536 ..container::Style::default()
537 })
538 .into(),
539 )
540 }
541
542 fn create_ime_layer(&self, cursor_rect: Rectangle) -> Element<'_, Message> {
552 let ime_enabled = self.is_focused() && self.has_canvas_focus;
553
554 let ime_layer = ImeRequester::new(ime_enabled, cursor_rect, None);
557 iced::Element::new(ime_layer)
558 }
559
560 fn with_context_menu<'a>(
574 &self,
575 underlay: impl Into<Element<'a, Message>>,
576 ) -> Element<'a, Message> {
577 let action_context = self.action_context();
578 let custom_context_menu_entries =
579 self.custom_context_menu_entries().to_vec();
580 let default_context_menu_enabled = self.default_context_menu_enabled();
581 let translations = self.translations;
582 ContextMenu::new(underlay, move || {
583 context_menu::view(
584 &custom_context_menu_entries,
585 default_context_menu_enabled,
586 action_context,
587 translations,
588 )
589 })
590 .into()
591 }
592
593 pub fn view(&self) -> Element<'_, Message> {
622 let (visual_lines, canvas_height) = self.calculate_canvas_height();
624
625 let scrollable = self.with_context_menu(
628 self.create_canvas_with_scrollable(canvas_height),
629 );
630
631 let background_row = self.create_background_layer();
633
634 let mut editor_stack =
636 iced::widget::Stack::new().push(background_row).push(scrollable);
637
638 editor_stack = editor_stack.push(
643 self.create_sticky_scroll_layer(visual_lines.as_ref())
644 .unwrap_or_else(|| Space::new().into()),
645 );
646
647 let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
651 let ime_layer = self.create_ime_layer(cursor_rect);
652 editor_stack = editor_stack.push(ime_layer);
653
654 if self.goto_line_state.is_open {
656 let goto_line_dialog = goto_line_dialog::view(
657 &self.goto_line_state,
658 self.buffer.line_count(),
659 );
660 let positioned_dialog = container(
661 Row::new()
662 .push(Space::new().width(Length::Fill))
663 .push(goto_line_dialog)
664 .push(Space::new().width(Length::Fill)),
665 )
666 .padding(20)
667 .width(Length::Fill)
668 .height(Length::Shrink);
669
670 editor_stack = editor_stack.push(positioned_dialog);
671 }
672
673 if self.command_palette_state.is_open {
676 let entries = self.command_palette_entries();
677 let palette = command_palette_dialog::view(
678 &self.command_palette_state,
679 &entries,
680 &self.translations,
681 );
682 let positioned_palette = container(
683 Row::new()
684 .push(Space::new().width(Length::Fill))
685 .push(palette)
686 .push(Space::new().width(Length::Fill)),
687 )
688 .padding(20)
689 .width(Length::Fill)
690 .height(Length::Shrink);
691
692 editor_stack = editor_stack.push(positioned_palette);
693 }
694
695 let editor_container = container(editor_stack)
697 .width(Length::Fill)
698 .height(Length::Fill)
699 .clip(true);
700
701 let editor_body: Element<'_, Message> = if self.wrap_enabled {
703 editor_container.into()
704 } else {
705 let max_content_width = self.max_content_width();
710 if let Some(h_scrollbar) =
711 self.create_horizontal_scrollbar(max_content_width)
712 {
713 Column::new().push(editor_container).push(h_scrollbar).into()
714 } else {
715 editor_container.into()
716 }
717 };
718
719 let editor_body = if self.search_state.is_open {
720 Column::new()
721 .push(search_dialog::view(
722 &self.search_state,
723 &self.translations,
724 !self.vim_enabled,
725 !self.goto_line_state.is_open
726 && !self.command_palette_state.is_open,
727 ))
728 .push(editor_body)
729 .width(Length::Fill)
730 .height(Length::Fill)
731 .into()
732 } else {
733 editor_body
734 };
735
736 if self.vim_enabled {
737 Column::new()
738 .push(editor_body)
739 .push(self.create_vim_status_bar())
740 .width(Length::Fill)
741 .height(Length::Fill)
742 .into()
743 } else {
744 editor_body
745 }
746 }
747}
748
749pub(crate) fn scrollable_rail(
762 background: Color,
763 scroller: Color,
764 radius: f32,
765) -> iced::widget::scrollable::Rail {
766 iced::widget::scrollable::Rail {
767 background: Some(background.into()),
768 border: iced::Border {
769 radius: radius.into(),
770 width: 0.0,
771 color: Color::TRANSPARENT,
772 },
773 scroller: iced::widget::scrollable::Scroller {
774 background: scroller.into(),
775 border: iced::Border {
776 radius: radius.into(),
777 width: 0.0,
778 color: Color::TRANSPARENT,
779 },
780 },
781 }
782}
783
784#[cfg(test)]
785mod tests {
786 use super::*;
787
788 #[test]
789 fn ime_uses_canvas_preedit_without_a_duplicate_runtime_overlay()
790 -> Result<(), &'static str> {
791 use iced::advanced::input_method::InputMethod;
792 use iced::advanced::{Layout, Shell, layout, renderer::Headless};
793
794 let renderer = iced::futures::executor::block_on(iced::Renderer::new(
795 iced::Font::DEFAULT,
796 iced::Pixels(13.0),
797 Some("tiny-skia"),
798 ))
799 .ok_or("headless software renderer unavailable")?;
800 let mut editor = CodeEditor::new("", "txt");
801 editor.focus_for_test();
802 let _ = editor.handle_ime_preedit_msg("中文", &Some(0..3));
803 let cursor =
804 Rectangle::new(iced::Point::new(40.0, 20.0), Size::new(2.0, 18.0));
805 let mut layer = editor.create_ime_layer(cursor);
806 let mut tree = iced::advanced::widget::Tree::new(&layer);
807 let node = layer.as_widget_mut().layout(
808 &mut tree,
809 &renderer,
810 &layout::Limits::new(Size::ZERO, Size::new(500.0, 300.0)),
811 );
812 let mut messages = Vec::new();
813 let mut shell = Shell::new(&mut messages);
814 layer.as_widget_mut().update(
815 &mut tree,
816 &iced::Event::Window(iced::window::Event::RedrawRequested(
817 iced::time::Instant::now(),
818 )),
819 Layout::new(&node),
820 mouse::Cursor::Unavailable,
821 &renderer,
822 &mut iced::advanced::clipboard::Null,
823 &mut shell,
824 &Rectangle::with_size(Size::new(500.0, 300.0)),
825 );
826 assert!(matches!(shell.input_method(), InputMethod::Enabled {
827 cursor: requested, preedit: None, ..
828 } if *requested == cursor));
829 Ok(())
830 }
831
832 type InputState = iced::widget::text_input::State<
833 <iced::Renderer as iced::advanced::text::Renderer>::Paragraph,
834 >;
835
836 fn input_states(
837 tree: &mut iced::advanced::widget::Tree,
838 ) -> Vec<&mut InputState> {
839 if tree.tag == iced::advanced::widget::tree::Tag::of::<InputState>() {
840 vec![tree.state.downcast_mut::<InputState>()]
841 } else {
842 tree.children.iter_mut().flat_map(input_states).collect()
843 }
844 }
845
846 #[test]
847 fn search_input_focus_survives_sticky_header_transitions()
848 -> Result<(), &'static str> {
849 assert_dialog_focus_survives_sticky_header_transitions(false, 0)
850 }
851
852 #[test]
853 fn replace_input_focus_survives_sticky_header_transitions()
854 -> Result<(), &'static str> {
855 assert_dialog_focus_survives_sticky_header_transitions(true, 1)
856 }
857
858 fn assert_dialog_focus_survives_sticky_header_transitions(
859 replace: bool,
860 focused_input: usize,
861 ) -> Result<(), &'static str> {
862 use iced::advanced::{Layout, Shell, layout, renderer::Headless};
863 use iced::keyboard::{self, Key, key::Named};
864
865 let renderer = iced::futures::executor::block_on(iced::Renderer::new(
866 iced::Font::DEFAULT,
867 iced::Pixels(13.0),
868 Some("tiny-skia"),
869 ))
870 .ok_or("headless software renderer unavailable")?;
871 let mut editor = CodeEditor::new(
872 "fn main() {\n let needle = 1;\n let value = needle;\n}",
873 "rs",
874 );
875 let _ = editor.handle_open_search(replace);
876 editor.search_state.set_query("needle".into(), &editor.buffer);
877 editor.search_state.set_replace_with("replacement".into());
878 let mut tree = iced::advanced::widget::Tree::new(editor.view());
879 let mut inputs = input_states(&mut tree);
880 inputs[focused_input].focus();
881 inputs[focused_input].select_range(1, 3);
882 let selection = inputs[focused_input].cursor();
883
884 for (scroll, key, text) in [
887 (editor.line_height(), Key::Named(Named::Backspace), None),
888 (0.0, Key::Named(Named::Enter), None),
889 (
890 editor.line_height(),
891 Key::Character("x".into()),
892 Some("x".into()),
893 ),
894 ] {
895 editor.viewport_scroll = scroll;
896 let visual_lines =
897 editor.visual_lines_cached(editor.viewport_width);
898 assert_eq!(
899 editor.create_sticky_scroll_layer(&visual_lines).is_some(),
900 scroll > 0.0,
901 );
902 let mut view = editor.view();
903 tree.diff(&view);
904 let inputs = input_states(&mut tree);
905 assert!(
906 inputs[focused_input].is_focused(),
907 "dialog lost focus after scroll"
908 );
909 assert_eq!(inputs[focused_input].cursor(), selection);
910
911 let node = view.as_widget_mut().layout(
912 &mut tree,
913 &renderer,
914 &layout::Limits::new(Size::ZERO, Size::new(800.0, 400.0)),
915 );
916 let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
917 key: key.clone(),
918 modified_key: key.clone(),
919 physical_key: keyboard::key::Physical::Unidentified(
920 keyboard::key::NativeCode::Unidentified,
921 ),
922 location: keyboard::Location::Standard,
923 modifiers: keyboard::Modifiers::empty(),
924 text,
925 repeat: false,
926 });
927 let mut messages = Vec::new();
928 let mut shell = Shell::new(&mut messages);
929 view.as_widget_mut().update(
930 &mut tree,
931 &event,
932 Layout::new(&node),
933 mouse::Cursor::Unavailable,
934 &renderer,
935 &mut iced::advanced::clipboard::Null,
936 &mut shell,
937 &node.bounds(),
938 );
939 assert!(shell.is_event_captured());
940 assert_eq!(messages.len(), 1);
941 assert!(
942 matches!(
943 (&messages[0], replace, key),
944 (Message::FindNext, false, Key::Named(Named::Enter))
945 | (
946 Message::ReplaceNext,
947 true,
948 Key::Named(Named::Enter)
949 )
950 | (Message::SearchQueryChanged(_), false, _)
951 | (Message::ReplaceQueryChanged(_), true, _)
952 ),
953 "key escaped the dialog: {messages:?}"
954 );
955 input_states(&mut tree)[focused_input].select_range(1, 3);
956 }
957 Ok(())
958 }
959
960 #[test]
961 fn test_should_show_horizontal_scrollbar_after_reset_with_known_canvas_width()
962 {
963 let mut editor = CodeEditor::new("short\n", "rs");
968 editor.wrap_enabled = false;
969 editor.last_canvas_width.set(200.0);
970
971 let _ = editor
972 .reset("a very very very long single line that clearly exceeds two hundred pixels of rendered width");
973
974 let max_content_width = editor.max_content_width();
975 assert!(
976 editor.should_show_horizontal_scrollbar(max_content_width),
977 "wide content narrower canvas should require a horizontal scrollbar after reset()"
978 );
979 }
980
981 #[test]
982 fn test_should_show_horizontal_scrollbar_false_when_content_fits() {
983 let mut editor = CodeEditor::new("short", "rs");
984 editor.wrap_enabled = false;
985 editor.last_canvas_width.set(800.0);
986
987 let max_content_width = editor.max_content_width();
988 assert!(
989 !editor.should_show_horizontal_scrollbar(max_content_width),
990 "content narrower than the canvas should not need a horizontal scrollbar"
991 );
992 }
993
994 #[test]
995 fn test_should_show_horizontal_scrollbar_false_when_wrap_enabled() {
996 let mut editor = CodeEditor::new(
997 "a very very very long single line that clearly exceeds two hundred pixels of rendered width",
998 "rs",
999 );
1000 editor.wrap_enabled = true;
1001 editor.last_canvas_width.set(50.0);
1002
1003 let max_content_width = editor.max_content_width();
1004 assert!(
1005 !editor.should_show_horizontal_scrollbar(max_content_width),
1006 "wrapped content never needs a horizontal scrollbar regardless of width"
1007 );
1008 }
1009
1010 #[test]
1011 fn test_scrollable_rail_sets_background_scroller_and_radius() {
1012 let bg = Color::from_rgb(0.1, 0.2, 0.3);
1013 let scroller = Color::from_rgb(0.4, 0.5, 0.6);
1014 let rail = scrollable_rail(bg, scroller, 4.0);
1015
1016 assert_eq!(rail.background, Some(iced::Background::Color(bg)));
1017 assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
1018 assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
1019 assert!(rail.border.width.abs() < f32::EPSILON);
1020 assert_eq!(
1021 rail.scroller.border.radius,
1022 iced::border::Radius::from(4.0)
1023 );
1024 }
1025
1026 #[test]
1027 fn test_sticky_layer_absent_when_disabled() {
1028 let mut editor =
1029 CodeEditor::new("fn main() {\n let x = 1;\n}", "rs");
1030 editor.set_sticky_scroll_enabled(false);
1031 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1032
1033 assert!(
1034 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
1035 );
1036 }
1037
1038 #[test]
1039 fn test_sticky_layer_absent_without_enclosing_block() {
1040 let editor = CodeEditor::new("a\nb\nc", "rs");
1042 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1043
1044 assert!(
1045 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
1046 );
1047 }
1048
1049 #[test]
1050 fn test_sticky_layer_absent_at_top_of_file() {
1051 let editor = CodeEditor::new(
1053 "fn main() {\n let x = 1;\n let y = 2;\n}",
1054 "rs",
1055 );
1056 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1057
1058 assert!(
1059 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
1060 );
1061 }
1062
1063 #[test]
1064 fn test_sticky_layer_survives_code_folding_being_disabled() {
1065 let mut editor = CodeEditor::new(
1070 "fn main() {\n let x = 1;\n let y = 2;\n}",
1071 "rs",
1072 );
1073 editor.set_folding_enabled(false);
1074 editor.viewport_scroll = editor.line_height();
1075 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1076
1077 assert!(
1078 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
1079 );
1080 }
1081
1082 #[test]
1083 fn test_sticky_layer_maps_a_wrapped_segment_back_to_its_logical_line() {
1084 let mut editor = CodeEditor::new(
1094 "fn main() {\n if a {\n let x = 1; let y = 2; let z = 3; let w = 4;\n }\n}",
1095 "rs",
1096 )
1097 .with_wrap_column(Some(20));
1098
1099 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1100 let continuation = visual_lines
1101 .iter()
1102 .position(|line| line.logical_line == 2 && line.segment_index == 1)
1103 .unwrap_or_default();
1104 assert!(
1105 continuation > 2,
1106 "the fixture must wrap far enough for the two indices to diverge"
1107 );
1108
1109 editor.viewport_scroll = continuation as f32 * editor.line_height();
1110 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1111
1112 assert!(
1113 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some(),
1114 "a continuation segment is still inside both enclosing blocks"
1115 );
1116 assert_eq!(editor.sticky_headroom(2), 2);
1119 }
1120
1121 #[test]
1122 fn test_sticky_layer_present_when_scrolled_into_block() {
1123 let mut editor = CodeEditor::new(
1124 "fn main() {\n let x = 1;\n let y = 2;\n}",
1125 "rs",
1126 );
1127 editor.viewport_scroll = editor.line_height();
1130 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1131
1132 assert!(
1133 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
1134 );
1135 }
1136
1137 #[test]
1138 fn test_canvas_scrollbar_style_uses_transparent_container() {
1139 let bg = Color::from_rgb(0.1, 0.2, 0.3);
1140 let scroller = Color::from_rgb(0.4, 0.5, 0.6);
1141 let active = scrollable::Status::Active {
1142 is_horizontal_scrollbar_disabled: false,
1143 is_vertical_scrollbar_disabled: false,
1144 };
1145 let style = canvas_scrollbar_style(bg, scroller, active);
1146
1147 assert_eq!(
1148 style.container.background,
1149 Some(Background::Color(Color::TRANSPARENT))
1150 );
1151 let expected_rail = scrollable_rail(bg, scroller, 4.0);
1152 assert_eq!(style.vertical_rail.background, expected_rail.background);
1153 assert_eq!(style.horizontal_rail.background, expected_rail.background);
1154 }
1155
1156 #[test]
1157 fn test_canvas_scroller_is_faint_away_and_solid_on_the_bar() {
1158 let bg = Color::TRANSPARENT;
1159 let scroller = Color::from_rgba(0.4, 0.5, 0.6, 0.6);
1160 let alpha = |status| match canvas_scrollbar_style(bg, scroller, status)
1161 .vertical_rail
1162 .scroller
1163 .background
1164 {
1165 Background::Color(c) => c.a,
1166 _ => f32::NAN,
1168 };
1169 let away = alpha(scrollable::Status::Active {
1170 is_horizontal_scrollbar_disabled: false,
1171 is_vertical_scrollbar_disabled: false,
1172 });
1173 let over = alpha(scrollable::Status::Hovered {
1174 is_horizontal_scrollbar_hovered: false,
1175 is_vertical_scrollbar_hovered: false,
1176 is_horizontal_scrollbar_disabled: false,
1177 is_vertical_scrollbar_disabled: false,
1178 });
1179 let on_bar = alpha(scrollable::Status::Dragged {
1180 is_horizontal_scrollbar_dragged: false,
1181 is_vertical_scrollbar_dragged: true,
1182 is_horizontal_scrollbar_disabled: false,
1183 is_vertical_scrollbar_disabled: false,
1184 });
1185 assert!(away < over && over < on_bar, "{away} {over} {on_bar}");
1186 assert!((on_bar - 1.0).abs() < 1e-6);
1187 }
1188}
1189
1190#[cfg(test)]
1191#[path = "../option_sticky_tests.rs"]
1192mod option_sticky_tests;
1193
1194#[cfg(test)]
1195#[path = "search_focus_tests.rs"]
1196mod search_focus_tests;