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