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 let msg_hover_entered = f(LspOverlayMessage::HoverEntered);
442 let msg_hover_exited = f(LspOverlayMessage::HoverExited);
443 let msg_completion_closed = f(LspOverlayMessage::CompletionClosed);
444 let msg_completion_selected: Vec<M> = (0..state.completion_items.len())
445 .map(|i| f(LspOverlayMessage::CompletionSelected(i)))
446 .collect();
447
448 let mut has_overlay = false;
449
450 let hover_layer: Element<'a, M> = build_hover_layer(
452 state,
453 editor,
454 theme,
455 (font_size, line_height),
456 msg_hover_entered,
457 msg_hover_exited,
458 &mut has_overlay,
459 );
460
461 let completion_layer: Element<'a, M> = build_completion_layer(
463 state,
464 editor,
465 line_height,
466 msg_completion_closed,
467 msg_completion_selected,
468 &mut has_overlay,
469 );
470
471 if !has_overlay {
472 return container(
473 Space::new().width(Length::Shrink).height(Length::Shrink),
474 )
475 .into();
476 }
477
478 let base = container(Space::new().width(Length::Fill).height(Length::Fill))
479 .width(Length::Fill)
480 .height(Length::Fill);
481
482 stack![base, completion_layer, hover_layer].into()
484}
485
486fn build_hover_layer<'a, M: Clone + 'a>(
488 state: &'a LspOverlayState,
489 editor: &'a CodeEditor,
490 theme: &'a Theme,
491 text_metrics: (f32, f32),
492 msg_entered: M,
493 msg_exited: M,
494 has_overlay: &mut bool,
495) -> Element<'a, M> {
496 let (font_size, line_height) = text_metrics;
497 if !state.hover_visible {
498 return empty_overlay();
499 }
500
501 let Some(hover) =
502 state.hover_text.as_ref().filter(|t| !t.trim().is_empty())
503 else {
504 return empty_overlay();
505 };
506
507 let line_count = hover.lines().count().max(1);
508 let visible_lines = line_count.min(10);
509 let hover_padding = 8.0;
510 let scroll_height = line_height * visible_lines as f32
511 + (line_height * 0.75).max(10.0)
512 + hover_padding * 2.0;
513
514 let viewport_width = editor.viewport_width();
515 let max_line_width = measure_hover_width(editor, hover);
516 let max_width = (viewport_width - 24.0).max(0.0);
517 let content_max_width = if max_width > hover_padding * 2.0 {
518 max_width - hover_padding * 2.0
519 } else {
520 max_width
521 };
522 let content_width = if content_max_width > 0.0 {
523 max_line_width.min(content_max_width)
524 } else {
525 max_line_width
526 };
527 let hover_width = content_width + hover_padding * 2.0;
528
529 let palette = theme.palette();
530 let markdown_settings = markdown::Settings::with_text_size(
531 font_size,
532 markdown::Style::from_palette(palette),
533 );
534
535 let entered_for_map = msg_entered.clone();
536 let entered_for_enter = msg_entered.clone();
537 let entered_for_move = msg_entered;
538
539 let hover_content = scrollable(
540 container(
541 markdown::view(&state.hover_items, markdown_settings)
542 .map(move |_| entered_for_map.clone()),
543 )
544 .width(Length::Fixed(hover_width))
545 .padding(hover_padding),
546 )
547 .height(Length::Fixed(scroll_height))
548 .width(Length::Fixed(hover_width))
549 .style(|theme: &Theme, _status| {
550 let palette = theme.extended_palette();
551 scrollable::Style {
552 container: container::Style {
553 background: Some(Background::Color(Color::TRANSPARENT)),
554 ..container::Style::default()
555 },
556 vertical_rail: lsp_scrollable_rail(palette),
557 horizontal_rail: lsp_scrollable_rail(palette),
558 gap: None,
559 auto_scroll: scrollable::AutoScroll {
560 background: Color::TRANSPARENT.into(),
561 border: Border::default(),
562 shadow: Shadow::default(),
563 icon: Color::TRANSPARENT,
564 },
565 }
566 });
567
568 let hover_box = container(column![hover_content])
569 .width(Length::Shrink)
570 .style(|theme: &Theme| {
571 let palette = theme.extended_palette();
572 container::Style {
573 background: Some(iced::Background::Color(
574 palette.background.weak.color,
575 )),
576 border: iced::Border {
577 color: palette.primary.weak.color,
578 width: 1.0,
579 radius: 6.0.into(),
580 },
581 ..Default::default()
582 }
583 });
584
585 let hover_box: Element<'_, M> = mouse_area(hover_box)
586 .on_enter(entered_for_enter)
587 .on_move(move |_| entered_for_move.clone())
588 .on_exit(msg_exited)
589 .into();
590
591 let hover_pos = state.hover_position.unwrap_or(Point::new(4.0, 4.0));
592 let viewport_scroll = editor.viewport_scroll();
593 let hover_pos =
594 Point::new(hover_pos.x, (hover_pos.y - viewport_scroll).max(0.0));
595 let viewport_height = editor.viewport_height();
596 let gap = 1.0;
597 let show_above = hover_pos.y >= scroll_height + gap;
598
599 let gap_x = (editor.char_width() * 0.5).max(2.0);
600 let right_x = hover_pos.x + gap_x;
601 let left_x = hover_pos.x - hover_width - gap_x;
602 let max_x = (viewport_width - hover_width - 4.0).max(0.0);
603
604 let offset_x = if right_x <= max_x {
605 right_x
606 } else if left_x >= 0.0 {
607 left_x
608 } else {
609 right_x.clamp(0.0, max_x)
610 };
611
612 let offset_y = if show_above {
613 (hover_pos.y - scroll_height - gap).max(0.0)
614 } else {
615 (hover_pos.y + line_height + gap).max(0.0).min(viewport_height)
616 };
617
618 *has_overlay = true;
619
620 container(
621 column![
622 Space::new().height(Length::Fixed(offset_y)),
623 row![Space::new().width(Length::Fixed(offset_x)), hover_box]
624 ]
625 .spacing(0)
626 .width(Length::Fill)
627 .height(Length::Fill),
628 )
629 .width(Length::Fill)
630 .height(Length::Fill)
631 .into()
632}
633
634fn build_completion_layer<'a, M: Clone + 'a>(
636 state: &'a LspOverlayState,
637 editor: &'a CodeEditor,
638 line_height: f32,
639 msg_closed: M,
640 msg_selected: Vec<M>,
641 has_overlay: &mut bool,
642) -> Element<'a, M> {
643 if !state.completion_visible
644 || state.completion_items.is_empty()
645 || state.completion_suppressed
646 {
647 return empty_overlay();
648 }
649
650 let visible_count = state.completion_items.len().min(MAX_COMPLETION_ITEMS);
651 let menu_height = COMPLETION_HEADER_HEIGHT
652 + (visible_count as f32 * COMPLETION_ITEM_HEIGHT)
653 + (COMPLETION_PADDING * 2.0);
654
655 let cursor_pos = state.completion_position.unwrap_or(Point::new(4.0, 4.0));
656 let viewport_width = editor.viewport_width();
657 let viewport_height = editor.viewport_height();
658 let viewport_scroll = editor.viewport_scroll();
659
660 let menu_width = COMPLETION_MENU_WIDTH.min(viewport_width - 8.0);
661 let adjusted_y = (cursor_pos.y - viewport_scroll).max(0.0);
662 let space_below = viewport_height - adjusted_y - line_height;
663 let show_above =
664 space_below < menu_height + 4.0 && adjusted_y >= menu_height + 4.0;
665
666 let offset_x = cursor_pos.x.min(viewport_width - menu_width - 4.0).max(4.0);
667 let offset_y = if show_above {
668 (adjusted_y - menu_height - 4.0).max(0.0)
669 } else {
670 adjusted_y + line_height + 4.0
671 };
672
673 let completion_elements: Vec<Element<'_, M>> = state
674 .completion_items
675 .iter()
676 .enumerate()
677 .zip(msg_selected)
678 .map(|((index, item), msg)| {
679 let is_selected = index == state.completion_selected;
680 button(
681 text(item.clone())
682 .size(12)
683 .line_height(iced::widget::text::LineHeight::Relative(1.5)),
684 )
685 .padding([2, 8])
686 .width(Length::Fill)
687 .on_press(msg)
688 .style(move |theme: &Theme, _status| {
689 let palette = theme.extended_palette();
690 if is_selected {
691 button::Style {
692 background: Some(iced::Background::Color(
693 palette.primary.weak.color,
694 )),
695 text_color: Color::WHITE,
696 ..Default::default()
697 }
698 } else {
699 button::Style {
700 background: Some(iced::Background::Color(
701 palette.background.weak.color,
702 )),
703 text_color: Color::WHITE,
704 ..Default::default()
705 }
706 }
707 })
708 .into()
709 })
710 .collect();
711
712 let completion_box = scrollable(column(completion_elements).spacing(0))
713 .height(Length::Fixed(menu_height))
714 .width(Length::Fixed(menu_width))
715 .id(Id::new("completion_scrollable"))
716 .style(|theme: &Theme, _status| {
717 let palette = theme.extended_palette();
718 scrollable::Style {
719 container: container::Style {
720 background: Some(iced::Background::Color(
721 palette.background.weak.color,
722 )),
723 border: iced::Border {
724 color: palette.primary.weak.color,
725 width: 1.0,
726 radius: SCROLLABLE_BORDER_RADIUS.into(),
727 },
728 ..Default::default()
729 },
730 vertical_rail: lsp_scrollable_rail(palette),
731 horizontal_rail: lsp_scrollable_rail(palette),
732 gap: None,
733 auto_scroll: scrollable::AutoScroll {
734 background: Color::TRANSPARENT.into(),
735 border: Border::default(),
736 shadow: Shadow::default(),
737 icon: Color::TRANSPARENT,
738 },
739 }
740 });
741
742 *has_overlay = true;
743
744 let click_outside =
745 button(Space::new().width(Length::Fill).height(Length::Fill))
746 .width(Length::Fill)
747 .height(Length::Fill)
748 .on_press(msg_closed)
749 .style(|_theme: &Theme, _status| button::Style {
750 background: Some(Background::Color(Color::TRANSPARENT)),
751 ..Default::default()
752 });
753
754 let completion_content = container(
755 column![
756 Space::new().height(Length::Fixed(offset_y)),
757 row![Space::new().width(Length::Fixed(offset_x)), completion_box]
758 ]
759 .spacing(0)
760 .width(Length::Fill)
761 .height(Length::Fill),
762 )
763 .width(Length::Fill)
764 .height(Length::Fill);
765
766 stack![click_outside, completion_content].into()
767}
768
769fn lsp_scrollable_rail(
774 palette: &iced::theme::palette::Extended,
775) -> scrollable::Rail {
776 crate::canvas_editor::render::view::scrollable_rail(
777 palette.background.weak.color,
778 palette.primary.weak.color,
779 SCROLLABLE_BORDER_RADIUS,
780 )
781}
782
783fn empty_overlay<'a, M: 'a>() -> Element<'a, M> {
785 container(Space::new().width(Length::Shrink).height(Length::Shrink)).into()
786}
787
788#[cfg(test)]
789mod tests {
790 use super::*;
791 use iced::Point;
792
793 fn assert_same_width(measured: f32, expected: f32) {
796 assert_eq!(
797 crate::canvas_editor::compare_floats(measured, expected),
798 std::cmp::Ordering::Equal,
799 "expected {expected}, measured {measured}"
800 );
801 }
802
803 #[test]
804 fn test_hover_width_is_the_widest_line_not_the_first_or_the_last() {
805 let editor = CodeEditor::new("", "rs");
810 let text = "fn a()\nfn a_much_longer_signature()\nfn b()";
811
812 assert_same_width(
813 measure_hover_width(&editor, text),
814 editor.measure_text_width("fn a_much_longer_signature()"),
815 );
816 }
817
818 #[test]
819 fn test_hover_width_of_a_single_line_is_that_line() {
820 let editor = CodeEditor::new("", "rs");
821
822 assert_same_width(
823 measure_hover_width(&editor, "fn main()"),
824 editor.measure_text_width("fn main()"),
825 );
826 }
827
828 #[test]
829 fn test_hover_width_of_empty_text_is_zero() {
830 let editor = CodeEditor::new("", "rs");
833
834 assert_same_width(measure_hover_width(&editor, ""), 0.0);
835 }
836
837 #[test]
838 fn test_lsp_overlay_state_new() {
839 let state = LspOverlayState::new();
840 assert!(!state.hover_visible);
841 assert!(!state.completion_visible);
842 assert!(state.hover_text.is_none());
843 assert!(state.completion_items.is_empty());
844 }
845
846 #[test]
847 fn test_show_hover() {
848 let mut state = LspOverlayState::new();
849 state.show_hover("hello".to_string());
850 assert!(state.hover_visible);
851 assert_eq!(state.hover_text, Some("hello".to_string()));
852 }
853
854 #[test]
855 fn test_clear_hover() {
856 let mut state = LspOverlayState::new();
857 state.show_hover("hello".to_string());
858 state.hover_interactive = true;
859 state.hover_position = Some(Point::ORIGIN);
860 state.clear_hover();
861 assert!(!state.hover_visible);
862 assert!(state.hover_text.is_none());
863 assert!(!state.hover_interactive);
864 assert!(state.hover_position.is_none());
865 }
866
867 #[test]
868 fn test_set_hover_position() {
869 let mut state = LspOverlayState::new();
870 state.set_hover_position(Point::new(10.0, 20.0));
871 assert_eq!(state.hover_position, Some(Point::new(10.0, 20.0)));
872 }
873
874 #[test]
875 fn test_set_completions() {
876 let mut state = LspOverlayState::new();
877 state.set_completions(
878 vec!["foo".to_string(), "bar".to_string()],
879 Point::ORIGIN,
880 );
881 assert_eq!(state.completion_items.len(), 2);
882 assert!(state.completion_visible);
883 assert_eq!(state.completion_selected, 0);
884 }
885
886 #[test]
887 fn test_clear_completions() {
888 let mut state = LspOverlayState::new();
889 state.set_completions(vec!["foo".to_string()], Point::ORIGIN);
890 state.clear_completions();
891 assert!(!state.completion_visible);
892 assert!(state.all_completions.is_empty());
893 assert!(state.completion_items.is_empty());
894 }
895
896 #[test]
897 fn test_filter_completions() {
898 let mut state = LspOverlayState::new();
899 state.set_completions(
900 vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
901 Point::ORIGIN,
902 );
903 state.completion_filter = "ba".to_string();
904 state.filter_completions();
905 assert_eq!(state.completion_items.len(), 2);
906 assert!(state.completion_items.contains(&"bar".to_string()));
907 assert!(state.completion_items.contains(&"baz".to_string()));
908 }
909
910 #[test]
911 fn test_navigate() {
912 let mut state = LspOverlayState::new();
913 state.set_completions(
914 vec!["a".to_string(), "b".to_string(), "c".to_string()],
915 Point::ORIGIN,
916 );
917 state.navigate(1);
918 assert_eq!(state.completion_selected, 1);
919 state.navigate(-1);
920 assert_eq!(state.completion_selected, 0);
921 state.navigate(-1);
923 assert_eq!(state.completion_selected, 2);
924 state.navigate(1);
926 assert_eq!(state.completion_selected, 0);
927 }
928
929 #[test]
930 #[allow(clippy::float_cmp)]
935 fn test_scroll_offset_for_selected() {
936 let mut state = LspOverlayState::new();
937 assert_eq!(state.scroll_offset_for_selected(), 0.0);
938 state.set_completions(
939 vec!["a".to_string(), "b".to_string(), "c".to_string()],
940 Point::ORIGIN,
941 );
942 assert_eq!(state.scroll_offset_for_selected(), 0.0);
943 state.navigate(1);
944 assert_eq!(state.scroll_offset_for_selected(), COMPLETION_ITEM_HEIGHT);
945 state.navigate(1);
946 assert_eq!(
947 state.scroll_offset_for_selected(),
948 2.0 * COMPLETION_ITEM_HEIGHT
949 );
950 }
951
952 #[test]
953 fn test_selected_item() {
954 let mut state = LspOverlayState::new();
955 assert_eq!(state.selected_item(), None);
956 state.set_completions(
957 vec!["first".to_string(), "second".to_string()],
958 Point::ORIGIN,
959 );
960 assert_eq!(state.selected_item(), Some("first"));
961 state.navigate(1);
962 assert_eq!(state.selected_item(), Some("second"));
963 }
964}