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, GUTTER_WIDTH, 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
31fn canvas_scrollbar_style(
34 scrollbar_bg: Color,
35 scroller_color: Color,
36) -> scrollable::Style {
37 scrollable::Style {
38 container: container::Style {
39 background: Some(Background::Color(Color::TRANSPARENT)),
40 ..container::Style::default()
41 },
42 vertical_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
43 horizontal_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
44 gap: None,
45 auto_scroll: scrollable::AutoScroll {
46 background: Color::TRANSPARENT.into(),
47 border: Border::default(),
48 shadow: Shadow::default(),
49 icon: Color::TRANSPARENT,
50 },
51 }
52}
53
54impl CodeEditor {
55 fn calculate_canvas_height(&self) -> (Rc<Vec<wrapping::VisualLine>>, f32) {
61 let visual_lines = self.visual_lines_cached(self.viewport_width);
64 let total_visual_lines = visual_lines.len();
65 let content_height = total_visual_lines as f32 * self.line_height;
66
67 let canvas_height = content_height.max(self.viewport_height);
71
72 (visual_lines, canvas_height)
73 }
74
75 fn create_scrollable_style(
79 &self,
80 ) -> impl Fn(&iced::Theme, scrollable::Status) -> scrollable::Style {
81 let scrollbar_bg = self.style.scrollbar_background;
82 let scroller_color = self.style.scroller_color;
83
84 move |_theme, _status| {
85 canvas_scrollbar_style(scrollbar_bg, scroller_color)
86 }
87 }
88
89 fn create_canvas_with_scrollable(
99 &self,
100 canvas_height: f32,
101 ) -> Scrollable<'_, Message> {
102 let canvas = Canvas::new(self)
103 .width(Length::Fill)
104 .height(Length::Fixed(canvas_height));
105
106 Scrollable::new(canvas)
107 .id(self.scrollable_id.clone())
108 .width(Length::Fill)
109 .height(Length::Fill)
110 .on_scroll(Message::Scrolled)
111 .style(self.create_scrollable_style())
112 }
113
114 pub(crate) fn should_show_horizontal_scrollbar(
131 &self,
132 max_content_width: f32,
133 ) -> bool {
134 !self.wrap_enabled && max_content_width > self.last_canvas_width.get()
135 }
136
137 fn create_horizontal_scrollbar(
147 &self,
148 max_content_width: f32,
149 ) -> Option<Element<'_, Message>> {
150 if !self.should_show_horizontal_scrollbar(max_content_width) {
151 return None;
152 }
153
154 let scrollbar_bg = self.style.scrollbar_background;
155 let scroller_color = self.style.scroller_color;
156
157 let h_scrollable = Scrollable::new(
158 Space::new().width(Length::Fixed(max_content_width)).height(0.0),
159 )
160 .id(self.horizontal_scrollable_id.clone())
161 .width(Length::Fill)
162 .height(Length::Fixed(12.0))
163 .direction(scrollable::Direction::Horizontal(
164 scrollable::Scrollbar::new(),
165 ))
166 .on_scroll(Message::HorizontalScrolled)
167 .style(move |_theme, _status| {
168 canvas_scrollbar_style(scrollbar_bg, scroller_color)
169 });
170
171 Some(h_scrollable.into())
172 }
173
174 fn create_gutter_container(
180 &self,
181 ) -> Option<container::Container<'_, Message>> {
182 if self.line_numbers_enabled {
183 let gutter_background = self.style.gutter_background;
184 Some(
185 container(
186 Space::new().width(Length::Fill).height(Length::Fill),
187 )
188 .width(Length::Fixed(GUTTER_WIDTH))
189 .height(Length::Fill)
190 .style(move |_| container::Style {
191 background: Some(Background::Color(gutter_background)),
192 ..container::Style::default()
193 }),
194 )
195 } else {
196 None
197 }
198 }
199
200 fn create_code_background_container(
206 &self,
207 ) -> container::Container<'_, Message> {
208 let background_color = self.style.background;
209 container(Space::new().width(Length::Fill).height(Length::Fill))
210 .width(Length::Fill)
211 .height(Length::Fill)
212 .style(move |_| container::Style {
213 background: Some(Background::Color(background_color)),
214 ..container::Style::default()
215 })
216 }
217
218 fn create_vim_status_bar(&self) -> Element<'_, Message> {
220 let (left_text, right_text) = self.vim_state.status_line_text();
221 let background = self.style.gutter_background;
222 let text_color = self.style.text_color;
223
224 container(
225 Row::new()
226 .push(
227 text(left_text).size(self.font_size).style(move |_| {
228 text::Style { color: Some(text_color) }
229 }),
230 )
231 .push(Space::new().width(Length::Fill))
232 .push(
233 text(right_text).size(self.font_size).style(move |_| {
234 text::Style { color: Some(text_color) }
235 }),
236 ),
237 )
238 .padding([2, 8])
239 .width(Length::Fill)
240 .height(Length::Fixed(self.line_height.max(20.0)))
241 .style(move |_| container::Style {
242 background: Some(Background::Color(background)),
243 ..container::Style::default()
244 })
245 .into()
246 }
247
248 fn create_background_layer(&self) -> Row<'_, Message> {
254 let gutter_container = self.create_gutter_container();
255 let code_background_container = self.create_code_background_container();
256
257 if let Some(gutter) = gutter_container {
258 Row::new().push(gutter).push(code_background_container)
259 } else {
260 Row::new().push(code_background_container)
261 }
262 }
263
264 fn calculate_ime_cursor_rect(
274 &self,
275 visual_lines: &[wrapping::VisualLine],
276 ) -> Rectangle {
277 let ime_enabled = self.is_focused() && self.has_canvas_focus;
278
279 if !ime_enabled {
280 return Rectangle::new(
281 iced::Point::new(0.0, 0.0),
282 Size::new(0.0, 0.0),
283 );
284 }
285
286 if let Some(cursor_visual) = WrappingCalculator::logical_to_visual(
287 visual_lines,
288 self.cursors.primary_position().0,
289 self.cursors.primary_position().1,
290 ) {
291 let vl = &visual_lines[cursor_visual];
292 let line_content = self.buffer.line(vl.logical_line);
293 let prefix_len =
294 self.cursors.primary_position().1.saturating_sub(vl.start_col);
295 let prefix_text: String = line_content
296 .chars()
297 .skip(vl.start_col)
298 .take(prefix_len)
299 .collect();
300 let cursor_x = self.gutter_width()
301 + 5.0
302 + crate::canvas_editor::measure_text_width(
303 &prefix_text,
304 self.full_char_width,
305 self.char_width,
306 )
307 - self.horizontal_scroll_offset;
308
309 let cursor_y = (cursor_visual as f32 * self.line_height)
313 - self.viewport_scroll;
314
315 Rectangle::new(
316 iced::Point::new(cursor_x, cursor_y + 2.0),
317 Size::new(2.0, self.line_height - 4.0),
318 )
319 } else {
320 Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(0.0, 0.0))
321 }
322 }
323
324 fn create_sticky_header_row(
338 &self,
339 line: usize,
340 syntax_set: &syntect::parsing::SyntaxSet,
341 syntax: &syntect::parsing::SyntaxReference,
342 theme: &syntect::highlighting::Theme,
343 ) -> Element<'_, Message> {
344 let font = self.font;
345 let font_size = self.font_size;
346 let line_number_color = self.style.line_number_color;
347
348 let mut row = Row::new();
349
350 if self.line_numbers_enabled {
351 row = row.push(
352 container(
353 text(format!("{}", line + 1))
354 .size(font_size)
355 .font(font)
356 .style(move |_| text::Style {
357 color: Some(line_number_color),
358 }),
359 )
360 .width(Length::Fixed(self.line_number_gutter_width()))
361 .align_x(alignment::Horizontal::Center),
362 );
363 }
364
365 row = row
368 .push(Space::new().width(Length::Fixed(self.fold_margin_width())));
369 row =
370 row.push(Space::new().width(Length::Fixed(CODE_TEXT_LEFT_PADDING)));
371
372 let spans =
373 self.highlighted_line_cached(line, syntax, theme, syntax_set);
374 let mut code = Row::new();
375 for (color, content) in spans.iter() {
376 let color = *color;
377 let content = if self.show_whitespace {
380 expand_tabs_visible(content, TAB_WIDTH)
381 } else {
382 expand_tabs(content, TAB_WIDTH).into_owned()
383 };
384 let span_font =
386 if content.is_ascii() { font } else { iced::Font::DEFAULT };
387 code = code.push(
388 text(content)
389 .size(font_size)
390 .font(span_font)
391 .wrapping(text::Wrapping::None)
392 .style(move |_| text::Style { color: Some(color) }),
393 );
394 }
395 row = row.push(code);
396
397 MouseArea::new(
398 container(row)
399 .width(Length::Fill)
400 .height(Length::Fixed(self.line_height))
401 .clip(true),
402 )
403 .interaction(mouse::Interaction::Pointer)
404 .on_press(Message::StickyScrollJump(line))
405 .into()
406 }
407
408 fn create_sticky_scroll_layer(
421 &self,
422 visual_lines: &[wrapping::VisualLine],
423 ) -> Option<Element<'_, Message>> {
424 if !self.sticky_scroll_enabled || self.line_height <= 0.0 {
425 return None;
426 }
427
428 let first_visible =
432 (self.viewport_scroll / self.line_height).floor() as usize;
433 let top_line = visual_lines.get(first_visible)?.logical_line;
434
435 let regions = self.block_regions();
439 let headers = sticky_scroll::sticky_headers(
440 ®ions,
441 top_line,
442 sticky_scroll::DEFAULT_MAX_STICKY_LINES,
443 );
444 if headers.is_empty() {
445 return None;
446 }
447
448 let (syntax_set, syntax, theme) = self.resolve_syntax();
449 let (Some(syntax), Some(theme)) = (syntax, theme) else {
450 return None;
451 };
452
453 let mut column = Column::new();
454 for line in headers {
455 column = column.push(
456 self.create_sticky_header_row(line, syntax_set, syntax, theme),
457 );
458 }
459
460 let background = self.style.gutter_background;
461 let border_color = self.style.gutter_border;
462
463 let column = column.push(
466 container(Space::new().width(Length::Fill).height(Length::Fill))
467 .width(Length::Fill)
468 .height(Length::Fixed(STICKY_SEPARATOR_WIDTH))
469 .style(move |_| container::Style {
470 background: Some(Background::Color(border_color)),
471 ..container::Style::default()
472 }),
473 );
474
475 Some(
476 container(column)
477 .width(Length::Fill)
478 .height(Length::Shrink)
479 .style(move |_| container::Style {
480 background: Some(Background::Color(background)),
481 ..container::Style::default()
482 })
483 .into(),
484 )
485 }
486
487 fn create_ime_layer(&self, cursor_rect: Rectangle) -> Element<'_, Message> {
497 let ime_enabled = self.is_focused() && self.has_canvas_focus;
498
499 let ime_layer = ImeRequester::new(ime_enabled, cursor_rect, None);
502 iced::Element::new(ime_layer)
503 }
504
505 pub fn view(&self) -> Element<'_, Message> {
534 let (visual_lines, canvas_height) = self.calculate_canvas_height();
536
537 let scrollable = self.create_canvas_with_scrollable(canvas_height);
539
540 let background_row = self.create_background_layer();
542
543 let mut editor_stack =
545 iced::widget::Stack::new().push(background_row).push(scrollable);
546
547 editor_stack = editor_stack.push(
552 self.create_sticky_scroll_layer(visual_lines.as_ref())
553 .unwrap_or_else(|| Space::new().into()),
554 );
555
556 let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
560 let ime_layer = self.create_ime_layer(cursor_rect);
561 editor_stack = editor_stack.push(ime_layer);
562
563 if self.goto_line_state.is_open {
565 let goto_line_dialog = goto_line_dialog::view(
566 &self.goto_line_state,
567 self.buffer.line_count(),
568 );
569 let positioned_dialog = container(
570 Row::new()
571 .push(Space::new().width(Length::Fill))
572 .push(goto_line_dialog)
573 .push(Space::new().width(Length::Fill)),
574 )
575 .padding(20)
576 .width(Length::Fill)
577 .height(Length::Shrink);
578
579 editor_stack = editor_stack.push(positioned_dialog);
580 }
581
582 if self.command_palette_state.is_open {
585 let entries = self.command_palette_entries();
586 let palette = command_palette_dialog::view(
587 &self.command_palette_state,
588 &entries,
589 &self.translations,
590 );
591 let positioned_palette = container(
592 Row::new()
593 .push(Space::new().width(Length::Fill))
594 .push(palette)
595 .push(Space::new().width(Length::Fill)),
596 )
597 .padding(20)
598 .width(Length::Fill)
599 .height(Length::Shrink);
600
601 editor_stack = editor_stack.push(positioned_palette);
602 }
603
604 let editor_container = container(editor_stack)
606 .width(Length::Fill)
607 .height(Length::Fill)
608 .clip(true);
609
610 let action_context = self.action_context();
614 let custom_context_menu_entries =
615 self.custom_context_menu_entries().to_vec();
616 let default_context_menu_enabled = self.default_context_menu_enabled();
617 let translations = self.translations;
618 let editor_container = ContextMenu::new(editor_container, move || {
619 context_menu::view(
620 &custom_context_menu_entries,
621 default_context_menu_enabled,
622 action_context,
623 translations,
624 )
625 });
626
627 let editor_body: Element<'_, Message> = if self.wrap_enabled {
629 editor_container.into()
630 } else {
631 let max_content_width = self.max_content_width();
636 if let Some(h_scrollbar) =
637 self.create_horizontal_scrollbar(max_content_width)
638 {
639 Column::new().push(editor_container).push(h_scrollbar).into()
640 } else {
641 editor_container.into()
642 }
643 };
644
645 let editor_body = if self.search_state.is_open {
646 Column::new()
647 .push(search_dialog::view(
648 &self.search_state,
649 &self.translations,
650 !self.vim_enabled,
651 !self.goto_line_state.is_open
652 && !self.command_palette_state.is_open,
653 ))
654 .push(editor_body)
655 .width(Length::Fill)
656 .height(Length::Fill)
657 .into()
658 } else {
659 editor_body
660 };
661
662 if self.vim_enabled {
663 Column::new()
664 .push(editor_body)
665 .push(self.create_vim_status_bar())
666 .width(Length::Fill)
667 .height(Length::Fill)
668 .into()
669 } else {
670 editor_body
671 }
672 }
673}
674
675pub(crate) fn scrollable_rail(
688 background: Color,
689 scroller: Color,
690 radius: f32,
691) -> iced::widget::scrollable::Rail {
692 iced::widget::scrollable::Rail {
693 background: Some(background.into()),
694 border: iced::Border {
695 radius: radius.into(),
696 width: 0.0,
697 color: Color::TRANSPARENT,
698 },
699 scroller: iced::widget::scrollable::Scroller {
700 background: scroller.into(),
701 border: iced::Border {
702 radius: radius.into(),
703 width: 0.0,
704 color: Color::TRANSPARENT,
705 },
706 },
707 }
708}
709
710#[cfg(test)]
711mod tests {
712 use super::*;
713
714 #[test]
715 fn ime_uses_canvas_preedit_without_a_duplicate_runtime_overlay()
716 -> Result<(), &'static str> {
717 use iced::advanced::input_method::InputMethod;
718 use iced::advanced::{Layout, Shell, layout, renderer::Headless};
719
720 let renderer = iced::futures::executor::block_on(iced::Renderer::new(
721 iced::Font::DEFAULT,
722 iced::Pixels(13.0),
723 Some("tiny-skia"),
724 ))
725 .ok_or("headless software renderer unavailable")?;
726 let mut editor = CodeEditor::new("", "txt");
727 editor.focus_for_test();
728 let _ = editor.handle_ime_preedit_msg("中文", &Some(0..3));
729 let cursor =
730 Rectangle::new(iced::Point::new(40.0, 20.0), Size::new(2.0, 18.0));
731 let mut layer = editor.create_ime_layer(cursor);
732 let mut tree = iced::advanced::widget::Tree::new(&layer);
733 let node = layer.as_widget_mut().layout(
734 &mut tree,
735 &renderer,
736 &layout::Limits::new(Size::ZERO, Size::new(500.0, 300.0)),
737 );
738 let mut messages = Vec::new();
739 let mut shell = Shell::new(&mut messages);
740 layer.as_widget_mut().update(
741 &mut tree,
742 &iced::Event::Window(iced::window::Event::RedrawRequested(
743 iced::time::Instant::now(),
744 )),
745 Layout::new(&node),
746 mouse::Cursor::Unavailable,
747 &renderer,
748 &mut iced::advanced::clipboard::Null,
749 &mut shell,
750 &Rectangle::with_size(Size::new(500.0, 300.0)),
751 );
752 assert!(matches!(shell.input_method(), InputMethod::Enabled {
753 cursor: requested, preedit: None, ..
754 } if *requested == cursor));
755 Ok(())
756 }
757
758 type InputState = iced::widget::text_input::State<
759 <iced::Renderer as iced::advanced::text::Renderer>::Paragraph,
760 >;
761
762 fn input_states(
763 tree: &mut iced::advanced::widget::Tree,
764 ) -> Vec<&mut InputState> {
765 if tree.tag == iced::advanced::widget::tree::Tag::of::<InputState>() {
766 vec![tree.state.downcast_mut::<InputState>()]
767 } else {
768 tree.children.iter_mut().flat_map(input_states).collect()
769 }
770 }
771
772 #[test]
773 fn search_input_focus_survives_sticky_header_transitions()
774 -> Result<(), &'static str> {
775 assert_dialog_focus_survives_sticky_header_transitions(false, 0)
776 }
777
778 #[test]
779 fn replace_input_focus_survives_sticky_header_transitions()
780 -> Result<(), &'static str> {
781 assert_dialog_focus_survives_sticky_header_transitions(true, 1)
782 }
783
784 fn assert_dialog_focus_survives_sticky_header_transitions(
785 replace: bool,
786 focused_input: usize,
787 ) -> Result<(), &'static str> {
788 use iced::advanced::{Layout, Shell, layout, renderer::Headless};
789 use iced::keyboard::{self, Key, key::Named};
790
791 let renderer = iced::futures::executor::block_on(iced::Renderer::new(
792 iced::Font::DEFAULT,
793 iced::Pixels(13.0),
794 Some("tiny-skia"),
795 ))
796 .ok_or("headless software renderer unavailable")?;
797 let mut editor = CodeEditor::new(
798 "fn main() {\n let needle = 1;\n let value = needle;\n}",
799 "rs",
800 );
801 let _ = editor.handle_open_search(replace);
802 editor.search_state.set_query("needle".into(), &editor.buffer);
803 editor.search_state.set_replace_with("replacement".into());
804 let mut tree = iced::advanced::widget::Tree::new(editor.view());
805 let mut inputs = input_states(&mut tree);
806 inputs[focused_input].focus();
807 inputs[focused_input].select_range(1, 3);
808 let selection = inputs[focused_input].cursor();
809
810 for (scroll, key, text) in [
813 (editor.line_height(), Key::Named(Named::Backspace), None),
814 (0.0, Key::Named(Named::Enter), None),
815 (
816 editor.line_height(),
817 Key::Character("x".into()),
818 Some("x".into()),
819 ),
820 ] {
821 editor.viewport_scroll = scroll;
822 let visual_lines =
823 editor.visual_lines_cached(editor.viewport_width);
824 assert_eq!(
825 editor.create_sticky_scroll_layer(&visual_lines).is_some(),
826 scroll > 0.0,
827 );
828 let mut view = editor.view();
829 tree.diff(&view);
830 let inputs = input_states(&mut tree);
831 assert!(
832 inputs[focused_input].is_focused(),
833 "dialog lost focus after scroll"
834 );
835 assert_eq!(inputs[focused_input].cursor(), selection);
836
837 let node = view.as_widget_mut().layout(
838 &mut tree,
839 &renderer,
840 &layout::Limits::new(Size::ZERO, Size::new(800.0, 400.0)),
841 );
842 let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
843 key: key.clone(),
844 modified_key: key.clone(),
845 physical_key: keyboard::key::Physical::Unidentified(
846 keyboard::key::NativeCode::Unidentified,
847 ),
848 location: keyboard::Location::Standard,
849 modifiers: keyboard::Modifiers::empty(),
850 text,
851 repeat: false,
852 });
853 let mut messages = Vec::new();
854 let mut shell = Shell::new(&mut messages);
855 view.as_widget_mut().update(
856 &mut tree,
857 &event,
858 Layout::new(&node),
859 mouse::Cursor::Unavailable,
860 &renderer,
861 &mut iced::advanced::clipboard::Null,
862 &mut shell,
863 &node.bounds(),
864 );
865 assert!(shell.is_event_captured());
866 assert_eq!(messages.len(), 1);
867 assert!(
868 matches!(
869 (&messages[0], replace, key),
870 (Message::FindNext, false, Key::Named(Named::Enter))
871 | (
872 Message::ReplaceNext,
873 true,
874 Key::Named(Named::Enter)
875 )
876 | (Message::SearchQueryChanged(_), false, _)
877 | (Message::ReplaceQueryChanged(_), true, _)
878 ),
879 "key escaped the dialog: {messages:?}"
880 );
881 input_states(&mut tree)[focused_input].select_range(1, 3);
882 }
883 Ok(())
884 }
885
886 #[test]
887 fn test_should_show_horizontal_scrollbar_after_reset_with_known_canvas_width()
888 {
889 let mut editor = CodeEditor::new("short\n", "rs");
894 editor.wrap_enabled = false;
895 editor.last_canvas_width.set(200.0);
896
897 let _ = editor
898 .reset("a very very very long single line that clearly exceeds two hundred pixels of rendered width");
899
900 let max_content_width = editor.max_content_width();
901 assert!(
902 editor.should_show_horizontal_scrollbar(max_content_width),
903 "wide content narrower canvas should require a horizontal scrollbar after reset()"
904 );
905 }
906
907 #[test]
908 fn test_should_show_horizontal_scrollbar_false_when_content_fits() {
909 let mut editor = CodeEditor::new("short", "rs");
910 editor.wrap_enabled = false;
911 editor.last_canvas_width.set(800.0);
912
913 let max_content_width = editor.max_content_width();
914 assert!(
915 !editor.should_show_horizontal_scrollbar(max_content_width),
916 "content narrower than the canvas should not need a horizontal scrollbar"
917 );
918 }
919
920 #[test]
921 fn test_should_show_horizontal_scrollbar_false_when_wrap_enabled() {
922 let mut editor = CodeEditor::new(
923 "a very very very long single line that clearly exceeds two hundred pixels of rendered width",
924 "rs",
925 );
926 editor.wrap_enabled = true;
927 editor.last_canvas_width.set(50.0);
928
929 let max_content_width = editor.max_content_width();
930 assert!(
931 !editor.should_show_horizontal_scrollbar(max_content_width),
932 "wrapped content never needs a horizontal scrollbar regardless of width"
933 );
934 }
935
936 #[test]
937 fn test_scrollable_rail_sets_background_scroller_and_radius() {
938 let bg = Color::from_rgb(0.1, 0.2, 0.3);
939 let scroller = Color::from_rgb(0.4, 0.5, 0.6);
940 let rail = scrollable_rail(bg, scroller, 4.0);
941
942 assert_eq!(rail.background, Some(iced::Background::Color(bg)));
943 assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
944 assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
945 assert!(rail.border.width.abs() < f32::EPSILON);
946 assert_eq!(
947 rail.scroller.border.radius,
948 iced::border::Radius::from(4.0)
949 );
950 }
951
952 #[test]
953 fn test_sticky_layer_absent_when_disabled() {
954 let mut editor =
955 CodeEditor::new("fn main() {\n let x = 1;\n}", "rs");
956 editor.set_sticky_scroll_enabled(false);
957 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
958
959 assert!(
960 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
961 );
962 }
963
964 #[test]
965 fn test_sticky_layer_absent_without_enclosing_block() {
966 let editor = CodeEditor::new("a\nb\nc", "rs");
968 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
969
970 assert!(
971 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
972 );
973 }
974
975 #[test]
976 fn test_sticky_layer_absent_at_top_of_file() {
977 let editor = CodeEditor::new(
979 "fn main() {\n let x = 1;\n let y = 2;\n}",
980 "rs",
981 );
982 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
983
984 assert!(
985 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
986 );
987 }
988
989 #[test]
990 fn test_sticky_layer_survives_code_folding_being_disabled() {
991 let mut editor = CodeEditor::new(
996 "fn main() {\n let x = 1;\n let y = 2;\n}",
997 "rs",
998 );
999 editor.set_folding_enabled(false);
1000 editor.viewport_scroll = editor.line_height();
1001 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1002
1003 assert!(
1004 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
1005 );
1006 }
1007
1008 #[test]
1009 fn test_sticky_layer_maps_a_wrapped_segment_back_to_its_logical_line() {
1010 let mut editor = CodeEditor::new(
1020 "fn main() {\n if a {\n let x = 1; let y = 2; let z = 3; let w = 4;\n }\n}",
1021 "rs",
1022 )
1023 .with_wrap_column(Some(20));
1024
1025 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1026 let continuation = visual_lines
1027 .iter()
1028 .position(|line| line.logical_line == 2 && line.segment_index == 1)
1029 .unwrap_or_default();
1030 assert!(
1031 continuation > 2,
1032 "the fixture must wrap far enough for the two indices to diverge"
1033 );
1034
1035 editor.viewport_scroll = continuation as f32 * editor.line_height();
1036 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1037
1038 assert!(
1039 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some(),
1040 "a continuation segment is still inside both enclosing blocks"
1041 );
1042 assert_eq!(editor.sticky_headroom(2), 2);
1045 }
1046
1047 #[test]
1048 fn test_sticky_layer_present_when_scrolled_into_block() {
1049 let mut editor = CodeEditor::new(
1050 "fn main() {\n let x = 1;\n let y = 2;\n}",
1051 "rs",
1052 );
1053 editor.viewport_scroll = editor.line_height();
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_some()
1060 );
1061 }
1062
1063 #[test]
1064 fn test_canvas_scrollbar_style_uses_transparent_container() {
1065 let bg = Color::from_rgb(0.1, 0.2, 0.3);
1066 let scroller = Color::from_rgb(0.4, 0.5, 0.6);
1067 let style = canvas_scrollbar_style(bg, scroller);
1068
1069 assert_eq!(
1070 style.container.background,
1071 Some(Background::Color(Color::TRANSPARENT))
1072 );
1073 let expected_rail = scrollable_rail(bg, scroller, 4.0);
1074 assert_eq!(style.vertical_rail.background, expected_rail.background);
1075 assert_eq!(style.horizontal_rail.background, expected_rail.background);
1076 }
1077}
1078
1079#[cfg(test)]
1080#[path = "../option_sticky_tests.rs"]
1081mod option_sticky_tests;
1082
1083#[cfg(test)]
1084#[path = "search_focus_tests.rs"]
1085mod search_focus_tests;