1use crate::CodeEditor;
7use iced::widget::{
8 Id, Space, button, column, container, markdown, mouse_area, row,
9 scrollable, stack, text,
10};
11use iced::{Background, Border, Color, Element, Length, Point, Shadow, Theme};
12
13const MAX_COMPLETION_ITEMS: usize = 8;
15const COMPLETION_ITEM_HEIGHT: f32 = 20.0;
17const COMPLETION_HEADER_HEIGHT: f32 = 24.0;
19const COMPLETION_PADDING: f32 = 4.0;
21const COMPLETION_MENU_WIDTH: f32 = 250.0;
23const SCROLLABLE_BORDER_RADIUS: f32 = 4.0;
25
26pub struct LspOverlayState {
41 pub hover_text: Option<String>,
43 pub hover_items: Vec<iced::widget::markdown::Item>,
45 pub hover_visible: bool,
47 pub hover_position: Option<Point>,
49 pub hover_interactive: bool,
51 pub all_completions: Vec<String>,
53 pub completion_filter: String,
55 pub completion_items: Vec<String>,
57 pub completion_visible: bool,
59 pub completion_selected: usize,
61 pub completion_suppressed: bool,
63 pub completion_position: Option<Point>,
65}
66
67impl LspOverlayState {
68 pub fn new() -> Self {
80 Self {
81 hover_text: None,
82 hover_items: Vec::new(),
83 hover_visible: false,
84 hover_position: None,
85 hover_interactive: false,
86 all_completions: Vec::new(),
87 completion_filter: String::new(),
88 completion_items: Vec::new(),
89 completion_visible: false,
90 completion_selected: 0,
91 completion_suppressed: false,
92 completion_position: None,
93 }
94 }
95
96 pub fn set_hover_position(&mut self, point: Point) {
111 self.hover_position = Some(point);
112 }
113
114 pub fn show_hover(&mut self, text: String) {
129 self.hover_items = iced::widget::markdown::parse(&text).collect();
130 self.hover_text = Some(text);
131 self.hover_visible = true;
132 }
133
134 pub fn clear_hover(&mut self) {
150 self.hover_text = None;
151 self.hover_items.clear();
152 self.hover_visible = false;
153 self.hover_position = None;
154 self.hover_interactive = false;
155 }
156
157 pub fn set_completions(&mut self, items: Vec<String>, position: Point) {
175 self.all_completions = items;
176 self.completion_selected = 0;
177 self.completion_position = Some(position);
178 self.filter_completions();
179 }
180
181 pub fn clear_completions(&mut self) {
196 self.all_completions.clear();
197 self.completion_items.clear();
198 self.completion_filter.clear();
199 self.completion_visible = false;
200 self.completion_suppressed = false;
201 }
202
203 pub fn filter_completions(&mut self) {
223 let filter = self.completion_filter.to_lowercase();
224 if filter.is_empty() {
225 self.completion_items = self.all_completions.clone();
226 } else {
227 self.completion_items = self
228 .all_completions
229 .iter()
230 .filter(|item| item.to_lowercase().contains(&filter))
231 .cloned()
232 .collect();
233 }
234 self.completion_visible = !self.completion_items.is_empty();
235 if self.completion_selected >= self.completion_items.len() {
236 self.completion_selected =
237 self.completion_items.len().saturating_sub(1);
238 }
239 }
240
241 pub fn navigate(&mut self, delta: i32) {
260 if self.completion_items.is_empty() {
261 return;
262 }
263 let len = self.completion_items.len();
264 let current = self.completion_selected as i32;
265 self.completion_selected =
266 ((current + delta).rem_euclid(len as i32)) as usize;
267 }
268
269 pub fn selected_item(&self) -> Option<&str> {
282 self.completion_items.get(self.completion_selected).map(String::as_str)
283 }
284
285 pub fn scroll_offset_for_selected(&self) -> f32 {
305 self.completion_selected as f32 * COMPLETION_ITEM_HEIGHT
306 }
307}
308
309impl Default for LspOverlayState {
310 fn default() -> Self {
311 Self::new()
312 }
313}
314
315#[derive(Debug, Clone)]
354pub enum LspOverlayMessage {
355 HoverEntered,
357 HoverExited,
359 CompletionSelected(usize),
361 CompletionClosed,
363 CompletionNavigateUp,
365 CompletionNavigateDown,
367 CompletionConfirm,
369}
370
371fn measure_hover_width(editor: &CodeEditor, text: &str) -> f32 {
387 text.lines().map(|line| editor.measure_text_width(line)).fold(0.0, f32::max)
388}
389
390pub fn view_lsp_overlay<'a, M: Clone + 'a>(
433 state: &'a LspOverlayState,
434 editor: &'a CodeEditor,
435 theme: &'a Theme,
436 font_size: f32,
437 line_height: f32,
438 f: impl Fn(LspOverlayMessage) -> M + 'a,
439) -> Element<'a, M> {
440 if editor.is_dialog_open() {
445 return empty_overlay();
446 }
447
448 let msg_hover_entered = f(LspOverlayMessage::HoverEntered);
450 let msg_hover_exited = f(LspOverlayMessage::HoverExited);
451 let msg_completion_closed = f(LspOverlayMessage::CompletionClosed);
452 let msg_completion_selected: Vec<M> = (0..state.completion_items.len())
453 .map(|i| f(LspOverlayMessage::CompletionSelected(i)))
454 .collect();
455
456 let mut has_overlay = false;
457
458 let hover_layer: Element<'a, M> = build_hover_layer(
460 state,
461 editor,
462 theme,
463 (font_size, line_height),
464 msg_hover_entered,
465 msg_hover_exited,
466 &mut has_overlay,
467 );
468
469 let completion_layer: Element<'a, M> = build_completion_layer(
471 state,
472 editor,
473 line_height,
474 msg_completion_closed,
475 msg_completion_selected,
476 &mut has_overlay,
477 );
478
479 if !has_overlay {
480 return container(
481 Space::new().width(Length::Shrink).height(Length::Shrink),
482 )
483 .into();
484 }
485
486 let base = container(Space::new().width(Length::Fill).height(Length::Fill))
487 .width(Length::Fill)
488 .height(Length::Fill);
489
490 stack![base, completion_layer, hover_layer].into()
492}
493
494fn build_hover_layer<'a, M: Clone + 'a>(
496 state: &'a LspOverlayState,
497 editor: &'a CodeEditor,
498 theme: &'a Theme,
499 text_metrics: (f32, f32),
500 msg_entered: M,
501 msg_exited: M,
502 has_overlay: &mut bool,
503) -> Element<'a, M> {
504 let (font_size, line_height) = text_metrics;
505 if !state.hover_visible {
506 return empty_overlay();
507 }
508
509 let Some(hover) =
510 state.hover_text.as_ref().filter(|t| !t.trim().is_empty())
511 else {
512 return empty_overlay();
513 };
514
515 let line_count = hover.lines().count().max(1);
516 let visible_lines = line_count.min(10);
517 let hover_padding = 8.0;
518 let scroll_height = line_height * visible_lines as f32
519 + (line_height * 0.75).max(10.0)
520 + hover_padding * 2.0;
521
522 let viewport_width = editor.viewport_width();
523 let max_line_width = measure_hover_width(editor, hover);
524 let max_width = (viewport_width - 24.0).max(0.0);
525 let content_max_width = if max_width > hover_padding * 2.0 {
526 max_width - hover_padding * 2.0
527 } else {
528 max_width
529 };
530 let content_width = if content_max_width > 0.0 {
531 max_line_width.min(content_max_width)
532 } else {
533 max_line_width
534 };
535 let hover_width = content_width + hover_padding * 2.0;
536
537 let palette = theme.palette();
538 let markdown_settings = markdown::Settings::with_text_size(
539 font_size,
540 markdown::Style::from_palette(palette),
541 );
542
543 let entered_for_map = msg_entered.clone();
544 let entered_for_enter = msg_entered.clone();
545 let entered_for_move = msg_entered;
546
547 let hover_content = scrollable(
548 container(
549 markdown::view(&state.hover_items, markdown_settings)
550 .map(move |_| entered_for_map.clone()),
551 )
552 .width(Length::Fixed(hover_width))
553 .padding(hover_padding),
554 )
555 .height(Length::Fixed(scroll_height))
556 .width(Length::Fixed(hover_width))
557 .style(|theme: &Theme, _status| {
558 let palette = theme.extended_palette();
559 scrollable::Style {
560 container: container::Style {
561 background: Some(Background::Color(Color::TRANSPARENT)),
562 ..container::Style::default()
563 },
564 vertical_rail: lsp_scrollable_rail(palette),
565 horizontal_rail: lsp_scrollable_rail(palette),
566 gap: None,
567 auto_scroll: scrollable::AutoScroll {
568 background: Color::TRANSPARENT.into(),
569 border: Border::default(),
570 shadow: Shadow::default(),
571 icon: Color::TRANSPARENT,
572 },
573 }
574 });
575
576 let hover_box = container(column![hover_content])
577 .width(Length::Shrink)
578 .style(|theme: &Theme| {
579 let palette = theme.extended_palette();
580 container::Style {
581 background: Some(iced::Background::Color(
582 palette.background.weak.color,
583 )),
584 border: iced::Border {
585 color: palette.primary.weak.color,
586 width: 1.0,
587 radius: 6.0.into(),
588 },
589 ..Default::default()
590 }
591 });
592
593 let hover_box: Element<'_, M> = mouse_area(hover_box)
594 .on_enter(entered_for_enter)
595 .on_move(move |_| entered_for_move.clone())
596 .on_exit(msg_exited)
597 .into();
598
599 let hover_pos = state.hover_position.unwrap_or(Point::new(4.0, 4.0));
600 let viewport_scroll = editor.viewport_scroll();
601 let hover_pos =
602 Point::new(hover_pos.x, (hover_pos.y - viewport_scroll).max(0.0));
603 let viewport_height = editor.viewport_height();
604 let gap = 1.0;
605 let show_above = hover_pos.y >= scroll_height + gap;
606
607 let gap_x = (editor.char_width() * 0.5).max(2.0);
608 let right_x = hover_pos.x + gap_x;
609 let left_x = hover_pos.x - hover_width - gap_x;
610 let max_x = (viewport_width - hover_width - 4.0).max(0.0);
611
612 let offset_x = if right_x <= max_x {
613 right_x
614 } else if left_x >= 0.0 {
615 left_x
616 } else {
617 right_x.clamp(0.0, max_x)
618 };
619
620 let offset_y = if show_above {
621 (hover_pos.y - scroll_height - gap).max(0.0)
622 } else {
623 (hover_pos.y + line_height + gap).max(0.0).min(viewport_height)
624 };
625
626 *has_overlay = true;
627
628 container(
629 column![
630 Space::new().height(Length::Fixed(offset_y)),
631 row![Space::new().width(Length::Fixed(offset_x)), hover_box]
632 ]
633 .spacing(0)
634 .width(Length::Fill)
635 .height(Length::Fill),
636 )
637 .width(Length::Fill)
638 .height(Length::Fill)
639 .into()
640}
641
642fn build_completion_layer<'a, M: Clone + 'a>(
644 state: &'a LspOverlayState,
645 editor: &'a CodeEditor,
646 line_height: f32,
647 msg_closed: M,
648 msg_selected: Vec<M>,
649 has_overlay: &mut bool,
650) -> Element<'a, M> {
651 if !state.completion_visible
652 || state.completion_items.is_empty()
653 || state.completion_suppressed
654 {
655 return empty_overlay();
656 }
657
658 let visible_count = state.completion_items.len().min(MAX_COMPLETION_ITEMS);
659 let menu_height = COMPLETION_HEADER_HEIGHT
660 + (visible_count as f32 * COMPLETION_ITEM_HEIGHT)
661 + (COMPLETION_PADDING * 2.0);
662
663 let cursor_pos = state.completion_position.unwrap_or(Point::new(4.0, 4.0));
664 let viewport_width = editor.viewport_width();
665 let viewport_height = editor.viewport_height();
666 let viewport_scroll = editor.viewport_scroll();
667
668 let menu_width = COMPLETION_MENU_WIDTH.min(viewport_width - 8.0);
669 let adjusted_y = (cursor_pos.y - viewport_scroll).max(0.0);
670 let space_below = viewport_height - adjusted_y - line_height;
671 let show_above =
672 space_below < menu_height + 4.0 && adjusted_y >= menu_height + 4.0;
673
674 let offset_x = cursor_pos.x.min(viewport_width - menu_width - 4.0).max(4.0);
675 let offset_y = if show_above {
676 (adjusted_y - menu_height - 4.0).max(0.0)
677 } else {
678 adjusted_y + line_height + 4.0
679 };
680
681 let completion_elements: Vec<Element<'_, M>> = state
682 .completion_items
683 .iter()
684 .enumerate()
685 .zip(msg_selected)
686 .map(|((index, item), msg)| {
687 let is_selected = index == state.completion_selected;
688 button(
689 text(item.clone())
690 .size(12)
691 .line_height(iced::widget::text::LineHeight::Relative(1.5)),
692 )
693 .padding([2, 8])
694 .width(Length::Fill)
695 .on_press(msg)
696 .style(move |theme: &Theme, _status| {
697 let palette = theme.extended_palette();
698 if is_selected {
699 button::Style {
700 background: Some(iced::Background::Color(
701 palette.primary.weak.color,
702 )),
703 text_color: Color::WHITE,
704 ..Default::default()
705 }
706 } else {
707 button::Style {
708 background: Some(iced::Background::Color(
709 palette.background.weak.color,
710 )),
711 text_color: Color::WHITE,
712 ..Default::default()
713 }
714 }
715 })
716 .into()
717 })
718 .collect();
719
720 let completion_box = scrollable(column(completion_elements).spacing(0))
721 .height(Length::Fixed(menu_height))
722 .width(Length::Fixed(menu_width))
723 .id(Id::new("completion_scrollable"))
724 .style(|theme: &Theme, _status| {
725 let palette = theme.extended_palette();
726 scrollable::Style {
727 container: container::Style {
728 background: Some(iced::Background::Color(
729 palette.background.weak.color,
730 )),
731 border: iced::Border {
732 color: palette.primary.weak.color,
733 width: 1.0,
734 radius: SCROLLABLE_BORDER_RADIUS.into(),
735 },
736 ..Default::default()
737 },
738 vertical_rail: lsp_scrollable_rail(palette),
739 horizontal_rail: lsp_scrollable_rail(palette),
740 gap: None,
741 auto_scroll: scrollable::AutoScroll {
742 background: Color::TRANSPARENT.into(),
743 border: Border::default(),
744 shadow: Shadow::default(),
745 icon: Color::TRANSPARENT,
746 },
747 }
748 });
749
750 *has_overlay = true;
751
752 let click_outside =
753 button(Space::new().width(Length::Fill).height(Length::Fill))
754 .width(Length::Fill)
755 .height(Length::Fill)
756 .on_press(msg_closed)
757 .style(|_theme: &Theme, _status| button::Style {
758 background: Some(Background::Color(Color::TRANSPARENT)),
759 ..Default::default()
760 });
761
762 let completion_content = container(
763 column![
764 Space::new().height(Length::Fixed(offset_y)),
765 row![Space::new().width(Length::Fixed(offset_x)), completion_box]
766 ]
767 .spacing(0)
768 .width(Length::Fill)
769 .height(Length::Fill),
770 )
771 .width(Length::Fill)
772 .height(Length::Fill);
773
774 stack![click_outside, completion_content].into()
775}
776
777fn lsp_scrollable_rail(
782 palette: &iced::theme::palette::Extended,
783) -> scrollable::Rail {
784 crate::canvas_editor::render::view::scrollable_rail(
785 palette.background.weak.color,
786 palette.primary.weak.color,
787 SCROLLABLE_BORDER_RADIUS,
788 )
789}
790
791fn empty_overlay<'a, M: 'a>() -> Element<'a, M> {
793 container(Space::new().width(Length::Shrink).height(Length::Shrink)).into()
794}
795
796#[cfg(test)]
797mod tests {
798 use super::*;
799 use iced::Point;
800
801 fn assert_same_width(measured: f32, expected: f32) {
804 assert_eq!(
805 crate::canvas_editor::compare_floats(measured, expected),
806 std::cmp::Ordering::Equal,
807 "expected {expected}, measured {measured}"
808 );
809 }
810
811 #[test]
812 fn test_hover_width_is_the_widest_line_not_the_first_or_the_last() {
813 let editor = CodeEditor::new("", "rs");
818 let text = "fn a()\nfn a_much_longer_signature()\nfn b()";
819
820 assert_same_width(
821 measure_hover_width(&editor, text),
822 editor.measure_text_width("fn a_much_longer_signature()"),
823 );
824 }
825
826 #[test]
827 fn test_hover_width_of_a_single_line_is_that_line() {
828 let editor = CodeEditor::new("", "rs");
829
830 assert_same_width(
831 measure_hover_width(&editor, "fn main()"),
832 editor.measure_text_width("fn main()"),
833 );
834 }
835
836 #[test]
837 fn test_hover_width_of_empty_text_is_zero() {
838 let editor = CodeEditor::new("", "rs");
841
842 assert_same_width(measure_hover_width(&editor, ""), 0.0);
843 }
844
845 #[test]
846 fn test_lsp_overlay_state_new() {
847 let state = LspOverlayState::new();
848 assert!(!state.hover_visible);
849 assert!(!state.completion_visible);
850 assert!(state.hover_text.is_none());
851 assert!(state.completion_items.is_empty());
852 }
853
854 #[test]
855 fn test_show_hover() {
856 let mut state = LspOverlayState::new();
857 state.show_hover("hello".to_string());
858 assert!(state.hover_visible);
859 assert_eq!(state.hover_text, Some("hello".to_string()));
860 }
861
862 #[test]
863 fn test_clear_hover() {
864 let mut state = LspOverlayState::new();
865 state.show_hover("hello".to_string());
866 state.hover_interactive = true;
867 state.hover_position = Some(Point::ORIGIN);
868 state.clear_hover();
869 assert!(!state.hover_visible);
870 assert!(state.hover_text.is_none());
871 assert!(!state.hover_interactive);
872 assert!(state.hover_position.is_none());
873 }
874
875 #[test]
876 fn test_set_hover_position() {
877 let mut state = LspOverlayState::new();
878 state.set_hover_position(Point::new(10.0, 20.0));
879 assert_eq!(state.hover_position, Some(Point::new(10.0, 20.0)));
880 }
881
882 #[test]
883 fn test_set_completions() {
884 let mut state = LspOverlayState::new();
885 state.set_completions(
886 vec!["foo".to_string(), "bar".to_string()],
887 Point::ORIGIN,
888 );
889 assert_eq!(state.completion_items.len(), 2);
890 assert!(state.completion_visible);
891 assert_eq!(state.completion_selected, 0);
892 }
893
894 #[test]
895 fn test_clear_completions() {
896 let mut state = LspOverlayState::new();
897 state.set_completions(vec!["foo".to_string()], Point::ORIGIN);
898 state.clear_completions();
899 assert!(!state.completion_visible);
900 assert!(state.all_completions.is_empty());
901 assert!(state.completion_items.is_empty());
902 }
903
904 #[test]
905 fn test_filter_completions() {
906 let mut state = LspOverlayState::new();
907 state.set_completions(
908 vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
909 Point::ORIGIN,
910 );
911 state.completion_filter = "ba".to_string();
912 state.filter_completions();
913 assert_eq!(state.completion_items.len(), 2);
914 assert!(state.completion_items.contains(&"bar".to_string()));
915 assert!(state.completion_items.contains(&"baz".to_string()));
916 }
917
918 #[test]
919 fn test_navigate() {
920 let mut state = LspOverlayState::new();
921 state.set_completions(
922 vec!["a".to_string(), "b".to_string(), "c".to_string()],
923 Point::ORIGIN,
924 );
925 state.navigate(1);
926 assert_eq!(state.completion_selected, 1);
927 state.navigate(-1);
928 assert_eq!(state.completion_selected, 0);
929 state.navigate(-1);
931 assert_eq!(state.completion_selected, 2);
932 state.navigate(1);
934 assert_eq!(state.completion_selected, 0);
935 }
936
937 #[test]
938 #[allow(clippy::float_cmp)]
943 fn test_scroll_offset_for_selected() {
944 let mut state = LspOverlayState::new();
945 assert_eq!(state.scroll_offset_for_selected(), 0.0);
946 state.set_completions(
947 vec!["a".to_string(), "b".to_string(), "c".to_string()],
948 Point::ORIGIN,
949 );
950 assert_eq!(state.scroll_offset_for_selected(), 0.0);
951 state.navigate(1);
952 assert_eq!(state.scroll_offset_for_selected(), COMPLETION_ITEM_HEIGHT);
953 state.navigate(1);
954 assert_eq!(
955 state.scroll_offset_for_selected(),
956 2.0 * COMPLETION_ITEM_HEIGHT
957 );
958 }
959
960 #[test]
961 fn test_selected_item() {
962 let mut state = LspOverlayState::new();
963 assert_eq!(state.selected_item(), None);
964 state.set_completions(
965 vec!["first".to_string(), "second".to_string()],
966 Point::ORIGIN,
967 );
968 assert_eq!(state.selected_item(), Some("first"));
969 state.navigate(1);
970 assert_eq!(state.selected_item(), Some("second"));
971 }
972}