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