1use iced::Size;
4use iced::advanced::input_method;
5use iced::alignment;
6use iced::mouse;
7use iced::widget::canvas::Canvas;
8use iced::widget::{
9 Column, MouseArea, Row, Scrollable, Space, container, scrollable, text,
10};
11use iced::{Background, Border, Color, Element, Length, Rectangle, Shadow};
12use iced_aw::ContextMenu;
13
14use super::text::{expand_tabs, expand_tabs_visible};
15use super::wrapping::{self, WrappingCalculator};
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::{CodeEditor, GUTTER_WIDTH, Message, TAB_WIDTH};
23use std::rc::Rc;
24
25const CODE_TEXT_LEFT_PADDING: f32 = 5.0;
28
29const STICKY_SEPARATOR_WIDTH: f32 = 1.0;
31
32fn canvas_scrollbar_style(
35 scrollbar_bg: Color,
36 scroller_color: Color,
37) -> scrollable::Style {
38 scrollable::Style {
39 container: container::Style {
40 background: Some(Background::Color(Color::TRANSPARENT)),
41 ..container::Style::default()
42 },
43 vertical_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
44 horizontal_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
45 gap: None,
46 auto_scroll: scrollable::AutoScroll {
47 background: Color::TRANSPARENT.into(),
48 border: Border::default(),
49 shadow: Shadow::default(),
50 icon: Color::TRANSPARENT,
51 },
52 }
53}
54
55impl CodeEditor {
56 fn calculate_canvas_height(&self) -> (Rc<Vec<wrapping::VisualLine>>, f32) {
62 let visual_lines = self.visual_lines_cached(self.viewport_width);
65 let total_visual_lines = visual_lines.len();
66 let content_height = total_visual_lines as f32 * self.line_height;
67
68 let canvas_height = content_height.max(self.viewport_height);
72
73 (visual_lines, canvas_height)
74 }
75
76 fn create_scrollable_style(
80 &self,
81 ) -> impl Fn(&iced::Theme, scrollable::Status) -> scrollable::Style {
82 let scrollbar_bg = self.style.scrollbar_background;
83 let scroller_color = self.style.scroller_color;
84
85 move |_theme, _status| {
86 canvas_scrollbar_style(scrollbar_bg, scroller_color)
87 }
88 }
89
90 fn create_canvas_with_scrollable(
100 &self,
101 canvas_height: f32,
102 ) -> Scrollable<'_, Message> {
103 let canvas = Canvas::new(self)
104 .width(Length::Fill)
105 .height(Length::Fixed(canvas_height));
106
107 Scrollable::new(canvas)
108 .id(self.scrollable_id.clone())
109 .width(Length::Fill)
110 .height(Length::Fill)
111 .on_scroll(Message::Scrolled)
112 .style(self.create_scrollable_style())
113 }
114
115 fn create_horizontal_scrollbar(
125 &self,
126 max_content_width: f32,
127 ) -> Option<Element<'_, Message>> {
128 if self.wrap_enabled || max_content_width <= self.viewport_width {
129 return None;
130 }
131
132 let scrollbar_bg = self.style.scrollbar_background;
133 let scroller_color = self.style.scroller_color;
134
135 let h_scrollable = Scrollable::new(
136 Space::new().width(Length::Fixed(max_content_width)).height(0.0),
137 )
138 .id(self.horizontal_scrollable_id.clone())
139 .width(Length::Fill)
140 .height(Length::Fixed(12.0))
141 .direction(scrollable::Direction::Horizontal(
142 scrollable::Scrollbar::new(),
143 ))
144 .on_scroll(Message::HorizontalScrolled)
145 .style(move |_theme, _status| {
146 canvas_scrollbar_style(scrollbar_bg, scroller_color)
147 });
148
149 Some(h_scrollable.into())
150 }
151
152 fn create_gutter_container(
158 &self,
159 ) -> Option<container::Container<'_, Message>> {
160 if self.line_numbers_enabled {
161 let gutter_background = self.style.gutter_background;
162 Some(
163 container(
164 Space::new().width(Length::Fill).height(Length::Fill),
165 )
166 .width(Length::Fixed(GUTTER_WIDTH))
167 .height(Length::Fill)
168 .style(move |_| container::Style {
169 background: Some(Background::Color(gutter_background)),
170 ..container::Style::default()
171 }),
172 )
173 } else {
174 None
175 }
176 }
177
178 fn create_code_background_container(
184 &self,
185 ) -> container::Container<'_, Message> {
186 let background_color = self.style.background;
187 container(Space::new().width(Length::Fill).height(Length::Fill))
188 .width(Length::Fill)
189 .height(Length::Fill)
190 .style(move |_| container::Style {
191 background: Some(Background::Color(background_color)),
192 ..container::Style::default()
193 })
194 }
195
196 fn create_vim_status_bar(&self) -> Element<'_, Message> {
198 let (left_text, right_text) = self.vim_state.status_line_text();
199 let background = self.style.gutter_background;
200 let text_color = self.style.text_color;
201
202 container(
203 Row::new()
204 .push(
205 text(left_text).size(self.font_size).style(move |_| {
206 text::Style { color: Some(text_color) }
207 }),
208 )
209 .push(Space::new().width(Length::Fill))
210 .push(
211 text(right_text).size(self.font_size).style(move |_| {
212 text::Style { color: Some(text_color) }
213 }),
214 ),
215 )
216 .padding([2, 8])
217 .width(Length::Fill)
218 .height(Length::Fixed(self.line_height.max(20.0)))
219 .style(move |_| container::Style {
220 background: Some(Background::Color(background)),
221 ..container::Style::default()
222 })
223 .into()
224 }
225
226 fn create_background_layer(&self) -> Row<'_, Message> {
232 let gutter_container = self.create_gutter_container();
233 let code_background_container = self.create_code_background_container();
234
235 if let Some(gutter) = gutter_container {
236 Row::new().push(gutter).push(code_background_container)
237 } else {
238 Row::new().push(code_background_container)
239 }
240 }
241
242 fn calculate_ime_cursor_rect(
252 &self,
253 visual_lines: &[wrapping::VisualLine],
254 ) -> Rectangle {
255 let ime_enabled = self.is_focused() && self.has_canvas_focus;
256
257 if !ime_enabled {
258 return Rectangle::new(
259 iced::Point::new(0.0, 0.0),
260 Size::new(0.0, 0.0),
261 );
262 }
263
264 if let Some(cursor_visual) = WrappingCalculator::logical_to_visual(
265 visual_lines,
266 self.cursors.primary_position().0,
267 self.cursors.primary_position().1,
268 ) {
269 let vl = &visual_lines[cursor_visual];
270 let line_content = self.buffer.line(vl.logical_line);
271 let prefix_len =
272 self.cursors.primary_position().1.saturating_sub(vl.start_col);
273 let prefix_text: String = line_content
274 .chars()
275 .skip(vl.start_col)
276 .take(prefix_len)
277 .collect();
278 let cursor_x = self.gutter_width()
279 + 5.0
280 + crate::canvas_editor::measure_text_width(
281 &prefix_text,
282 self.full_char_width,
283 self.char_width,
284 )
285 - self.horizontal_scroll_offset;
286
287 let cursor_y = (cursor_visual as f32 * self.line_height)
291 - self.viewport_scroll;
292
293 Rectangle::new(
294 iced::Point::new(cursor_x, cursor_y + 2.0),
295 Size::new(2.0, self.line_height - 4.0),
296 )
297 } else {
298 Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(0.0, 0.0))
299 }
300 }
301
302 fn create_sticky_header_row(
316 &self,
317 line: usize,
318 syntax_set: &syntect::parsing::SyntaxSet,
319 syntax: &syntect::parsing::SyntaxReference,
320 theme: &syntect::highlighting::Theme,
321 ) -> Element<'_, Message> {
322 let font = self.font;
323 let font_size = self.font_size;
324 let line_number_color = self.style.line_number_color;
325
326 let mut row = Row::new();
327
328 if self.line_numbers_enabled {
329 row = row.push(
330 container(
331 text(format!("{}", line + 1))
332 .size(font_size)
333 .font(font)
334 .style(move |_| text::Style {
335 color: Some(line_number_color),
336 }),
337 )
338 .width(Length::Fixed(self.line_number_gutter_width()))
339 .align_x(alignment::Horizontal::Center),
340 );
341 }
342
343 row = row
346 .push(Space::new().width(Length::Fixed(self.fold_margin_width())));
347 row =
348 row.push(Space::new().width(Length::Fixed(CODE_TEXT_LEFT_PADDING)));
349
350 let spans =
351 self.highlighted_line_cached(line, syntax, theme, syntax_set);
352 let mut code = Row::new();
353 for (color, content) in spans.iter() {
354 let color = *color;
355 let content = if self.show_whitespace {
358 expand_tabs_visible(content, TAB_WIDTH)
359 } else {
360 expand_tabs(content, TAB_WIDTH).into_owned()
361 };
362 code = code.push(
363 text(content)
364 .size(font_size)
365 .font(font)
366 .wrapping(text::Wrapping::None)
367 .style(move |_| text::Style { color: Some(color) }),
368 );
369 }
370 row = row.push(code);
371
372 MouseArea::new(
373 container(row)
374 .width(Length::Fill)
375 .height(Length::Fixed(self.line_height))
376 .clip(true),
377 )
378 .interaction(mouse::Interaction::Pointer)
379 .on_press(Message::StickyScrollJump(line))
380 .into()
381 }
382
383 fn create_sticky_scroll_layer(
396 &self,
397 visual_lines: &[wrapping::VisualLine],
398 ) -> Option<Element<'_, Message>> {
399 if !self.sticky_scroll_enabled || self.line_height <= 0.0 {
400 return None;
401 }
402
403 let first_visible =
407 (self.viewport_scroll / self.line_height).floor() as usize;
408 let top_line = visual_lines.get(first_visible)?.logical_line;
409
410 let regions = self.block_regions();
414 let headers = sticky_scroll::sticky_headers(
415 ®ions,
416 top_line,
417 sticky_scroll::DEFAULT_MAX_STICKY_LINES,
418 );
419 if headers.is_empty() {
420 return None;
421 }
422
423 let (syntax_set, syntax, theme) = self.resolve_syntax();
424 let (Some(syntax), Some(theme)) = (syntax, theme) else {
425 return None;
426 };
427
428 let mut column = Column::new();
429 for line in headers {
430 column = column.push(
431 self.create_sticky_header_row(line, syntax_set, syntax, theme),
432 );
433 }
434
435 let background = self.style.gutter_background;
436 let border_color = self.style.gutter_border;
437
438 let column = column.push(
441 container(Space::new().width(Length::Fill).height(Length::Fill))
442 .width(Length::Fill)
443 .height(Length::Fixed(STICKY_SEPARATOR_WIDTH))
444 .style(move |_| container::Style {
445 background: Some(Background::Color(border_color)),
446 ..container::Style::default()
447 }),
448 );
449
450 Some(
451 container(column)
452 .width(Length::Fill)
453 .height(Length::Shrink)
454 .style(move |_| container::Style {
455 background: Some(Background::Color(background)),
456 ..container::Style::default()
457 })
458 .into(),
459 )
460 }
461
462 fn create_ime_layer(&self, cursor_rect: Rectangle) -> Element<'_, Message> {
472 let ime_enabled = self.is_focused() && self.has_canvas_focus;
473
474 let preedit =
475 self.ime_preedit.as_ref().map(|p| input_method::Preedit {
476 content: p.content.clone(),
477 selection: p.selection.clone(),
478 text_size: None,
479 });
480
481 let ime_layer = ImeRequester::new(ime_enabled, cursor_rect, preedit);
482 iced::Element::new(ime_layer)
483 }
484
485 pub fn view(&self) -> Element<'_, Message> {
514 let (visual_lines, canvas_height) = self.calculate_canvas_height();
516
517 let scrollable = self.create_canvas_with_scrollable(canvas_height);
519
520 let background_row = self.create_background_layer();
522
523 let mut editor_stack =
525 iced::widget::Stack::new().push(background_row).push(scrollable);
526
527 if let Some(sticky_layer) =
530 self.create_sticky_scroll_layer(visual_lines.as_ref())
531 {
532 editor_stack = editor_stack.push(sticky_layer);
533 }
534
535 let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
539 let ime_layer = self.create_ime_layer(cursor_rect);
540 editor_stack = editor_stack.push(ime_layer);
541
542 if self.search_state.is_open {
544 let search_dialog =
545 search_dialog::view(&self.search_state, &self.translations);
546
547 let positioned_dialog = container(
549 Row::new()
550 .push(Space::new().width(Length::Fill))
551 .push(search_dialog),
552 )
553 .padding(20)
554 .width(Length::Fill)
555 .height(Length::Shrink);
556
557 editor_stack = editor_stack.push(positioned_dialog);
558 }
559
560 if self.goto_line_state.is_open {
562 let goto_line_dialog = goto_line_dialog::view(
563 &self.goto_line_state,
564 self.buffer.line_count(),
565 );
566 let positioned_dialog = container(
567 Row::new()
568 .push(Space::new().width(Length::Fill))
569 .push(goto_line_dialog)
570 .push(Space::new().width(Length::Fill)),
571 )
572 .padding(20)
573 .width(Length::Fill)
574 .height(Length::Shrink);
575
576 editor_stack = editor_stack.push(positioned_dialog);
577 }
578
579 if self.command_palette_state.is_open {
582 let entries = self.command_palette_entries();
583 let palette = command_palette_dialog::view(
584 &self.command_palette_state,
585 &entries,
586 &self.translations,
587 );
588 let positioned_palette = container(
589 Row::new()
590 .push(Space::new().width(Length::Fill))
591 .push(palette)
592 .push(Space::new().width(Length::Fill)),
593 )
594 .padding(20)
595 .width(Length::Fill)
596 .height(Length::Shrink);
597
598 editor_stack = editor_stack.push(positioned_palette);
599 }
600
601 let editor_container = container(editor_stack)
603 .width(Length::Fill)
604 .height(Length::Fill)
605 .clip(true);
606
607 let action_context = self.action_context();
611 let custom_context_menu_entries =
612 self.custom_context_menu_entries().to_vec();
613 let default_context_menu_enabled = self.default_context_menu_enabled();
614 let translations = self.translations;
615 let editor_container = ContextMenu::new(editor_container, move || {
616 context_menu::view(
617 &custom_context_menu_entries,
618 default_context_menu_enabled,
619 action_context,
620 translations,
621 )
622 });
623
624 let editor_body: Element<'_, Message> = if self.wrap_enabled {
626 editor_container.into()
627 } else {
628 let max_content_width = self.max_content_width();
633 if let Some(h_scrollbar) =
634 self.create_horizontal_scrollbar(max_content_width)
635 {
636 Column::new().push(editor_container).push(h_scrollbar).into()
637 } else {
638 editor_container.into()
639 }
640 };
641
642 if self.vim_enabled {
643 Column::new()
644 .push(editor_body)
645 .push(self.create_vim_status_bar())
646 .width(Length::Fill)
647 .height(Length::Fill)
648 .into()
649 } else {
650 editor_body
651 }
652 }
653}
654
655pub(crate) fn scrollable_rail(
668 background: Color,
669 scroller: Color,
670 radius: f32,
671) -> iced::widget::scrollable::Rail {
672 iced::widget::scrollable::Rail {
673 background: Some(background.into()),
674 border: iced::Border {
675 radius: radius.into(),
676 width: 0.0,
677 color: Color::TRANSPARENT,
678 },
679 scroller: iced::widget::scrollable::Scroller {
680 background: scroller.into(),
681 border: iced::Border {
682 radius: radius.into(),
683 width: 0.0,
684 color: Color::TRANSPARENT,
685 },
686 },
687 }
688}
689
690#[cfg(test)]
691mod tests {
692 use super::*;
693
694 #[test]
695 fn test_scrollable_rail_sets_background_scroller_and_radius() {
696 let bg = Color::from_rgb(0.1, 0.2, 0.3);
697 let scroller = Color::from_rgb(0.4, 0.5, 0.6);
698 let rail = scrollable_rail(bg, scroller, 4.0);
699
700 assert_eq!(rail.background, Some(iced::Background::Color(bg)));
701 assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
702 assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
703 assert!(rail.border.width.abs() < f32::EPSILON);
704 assert_eq!(
705 rail.scroller.border.radius,
706 iced::border::Radius::from(4.0)
707 );
708 }
709
710 #[test]
711 fn test_sticky_layer_absent_when_disabled() {
712 let mut editor =
713 CodeEditor::new("fn main() {\n let x = 1;\n}", "rs");
714 editor.set_sticky_scroll_enabled(false);
715 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
716
717 assert!(
718 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
719 );
720 }
721
722 #[test]
723 fn test_sticky_layer_absent_without_enclosing_block() {
724 let editor = CodeEditor::new("a\nb\nc", "rs");
726 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
727
728 assert!(
729 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
730 );
731 }
732
733 #[test]
734 fn test_sticky_layer_absent_at_top_of_file() {
735 let editor = CodeEditor::new(
737 "fn main() {\n let x = 1;\n let y = 2;\n}",
738 "rs",
739 );
740 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
741
742 assert!(
743 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
744 );
745 }
746
747 #[test]
748 fn test_sticky_layer_survives_code_folding_being_disabled() {
749 let mut editor = CodeEditor::new(
754 "fn main() {\n let x = 1;\n let y = 2;\n}",
755 "rs",
756 );
757 editor.set_folding_enabled(false);
758 editor.viewport_scroll = editor.line_height();
759 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
760
761 assert!(
762 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
763 );
764 }
765
766 #[test]
767 fn test_sticky_layer_maps_a_wrapped_segment_back_to_its_logical_line() {
768 let mut editor = CodeEditor::new(
778 "fn main() {\n if a {\n let x = 1; let y = 2; let z = 3; let w = 4;\n }\n}",
779 "rs",
780 )
781 .with_wrap_column(Some(20));
782
783 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
784 let continuation = visual_lines
785 .iter()
786 .position(|line| line.logical_line == 2 && line.segment_index == 1)
787 .unwrap_or_default();
788 assert!(
789 continuation > 2,
790 "the fixture must wrap far enough for the two indices to diverge"
791 );
792
793 editor.viewport_scroll = continuation as f32 * editor.line_height();
794 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
795
796 assert!(
797 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some(),
798 "a continuation segment is still inside both enclosing blocks"
799 );
800 assert_eq!(editor.sticky_headroom(2), 2);
803 }
804
805 #[test]
806 fn test_sticky_layer_present_when_scrolled_into_block() {
807 let mut editor = CodeEditor::new(
808 "fn main() {\n let x = 1;\n let y = 2;\n}",
809 "rs",
810 );
811 editor.viewport_scroll = editor.line_height();
814 let visual_lines = editor.visual_lines_cached(editor.viewport_width);
815
816 assert!(
817 editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
818 );
819 }
820
821 #[test]
822 fn test_canvas_scrollbar_style_uses_transparent_container() {
823 let bg = Color::from_rgb(0.1, 0.2, 0.3);
824 let scroller = Color::from_rgb(0.4, 0.5, 0.6);
825 let style = canvas_scrollbar_style(bg, scroller);
826
827 assert_eq!(
828 style.container.background,
829 Some(Background::Color(Color::TRANSPARENT))
830 );
831 let expected_rail = scrollable_rail(bg, scroller, 4.0);
832 assert_eq!(style.vertical_rail.background, expected_rail.background);
833 assert_eq!(style.horizontal_rail.background, expected_rail.background);
834 }
835}