1use fuzzy::{StringMatch, StringMatchCandidate};
2use gpui::{
3 div, px, uniform_list, AnyElement, BackgroundExecutor, Div, Entity, FontWeight,
4 ListSizingBehavior, ScrollStrategy, SharedString, Size, StrikethroughStyle, StyledText,
5 UniformListScrollHandle, WeakEntity,
6};
7use language::Buffer;
8use language::{CodeLabel, CompletionDocumentation};
9use lsp::LanguageServerId;
10use multi_buffer::{Anchor, ExcerptId};
11use ordered_float::OrderedFloat;
12use project::{CodeAction, Completion, TaskSourceKind};
13
14use std::{
15 cell::RefCell,
16 cmp::{min, Reverse},
17 iter,
18 ops::Range,
19 rc::Rc,
20};
21use task::ResolvedTask;
22use ui::{prelude::*, Color, IntoElement, ListItem, Pixels, Popover, Styled};
23use util::ResultExt;
24use workspace::Workspace;
25
26use crate::{
27 actions::{ConfirmCodeAction, ConfirmCompletion},
28 render_parsed_markdown, split_words, styled_runs_for_code_label, CodeActionProvider,
29 CompletionId, CompletionProvider, DisplayRow, Editor, EditorStyle, ResolvedTasks,
30};
31
32pub const MENU_GAP: Pixels = px(4.);
33pub const MENU_ASIDE_X_PADDING: Pixels = px(16.);
34pub const MENU_ASIDE_MIN_WIDTH: Pixels = px(260.);
35pub const MENU_ASIDE_MAX_WIDTH: Pixels = px(500.);
36
37pub enum CodeContextMenu {
38 Completions(CompletionsMenu),
39 CodeActions(CodeActionsMenu),
40}
41
42impl CodeContextMenu {
43 pub fn select_first(
44 &mut self,
45 provider: Option<&dyn CompletionProvider>,
46 cx: &mut Context<Editor>,
47 ) -> bool {
48 if self.visible() {
49 match self {
50 CodeContextMenu::Completions(menu) => menu.select_first(provider, cx),
51 CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
52 }
53 true
54 } else {
55 false
56 }
57 }
58
59 pub fn select_prev(
60 &mut self,
61 provider: Option<&dyn CompletionProvider>,
62 cx: &mut Context<Editor>,
63 ) -> bool {
64 if self.visible() {
65 match self {
66 CodeContextMenu::Completions(menu) => menu.select_prev(provider, cx),
67 CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
68 }
69 true
70 } else {
71 false
72 }
73 }
74
75 pub fn select_next(
76 &mut self,
77 provider: Option<&dyn CompletionProvider>,
78 cx: &mut Context<Editor>,
79 ) -> bool {
80 if self.visible() {
81 match self {
82 CodeContextMenu::Completions(menu) => menu.select_next(provider, cx),
83 CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
84 }
85 true
86 } else {
87 false
88 }
89 }
90
91 pub fn select_last(
92 &mut self,
93 provider: Option<&dyn CompletionProvider>,
94 cx: &mut Context<Editor>,
95 ) -> bool {
96 if self.visible() {
97 match self {
98 CodeContextMenu::Completions(menu) => menu.select_last(provider, cx),
99 CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
100 }
101 true
102 } else {
103 false
104 }
105 }
106
107 pub fn visible(&self) -> bool {
108 match self {
109 CodeContextMenu::Completions(menu) => menu.visible(),
110 CodeContextMenu::CodeActions(menu) => menu.visible(),
111 }
112 }
113
114 pub fn origin(&self) -> ContextMenuOrigin {
115 match self {
116 CodeContextMenu::Completions(menu) => menu.origin(),
117 CodeContextMenu::CodeActions(menu) => menu.origin(),
118 }
119 }
120
121 pub fn render(
122 &self,
123 style: &EditorStyle,
124 max_height_in_lines: u32,
125 y_flipped: bool,
126 window: &mut Window,
127 cx: &mut Context<Editor>,
128 ) -> AnyElement {
129 match self {
130 CodeContextMenu::Completions(menu) => {
131 menu.render(style, max_height_in_lines, y_flipped, window, cx)
132 }
133 CodeContextMenu::CodeActions(menu) => {
134 menu.render(style, max_height_in_lines, y_flipped, window, cx)
135 }
136 }
137 }
138
139 pub fn render_aside(
140 &self,
141 style: &EditorStyle,
142 max_size: Size<Pixels>,
143 workspace: Option<WeakEntity<Workspace>>,
144 cx: &mut Context<Editor>,
145 ) -> Option<AnyElement> {
146 match self {
147 CodeContextMenu::Completions(menu) => menu.render_aside(style, max_size, workspace, cx),
148 CodeContextMenu::CodeActions(_) => None,
149 }
150 }
151}
152
153pub enum ContextMenuOrigin {
154 Cursor,
155 GutterIndicator(DisplayRow),
156}
157
158#[derive(Clone, Debug)]
159pub struct CompletionsMenu {
160 pub id: CompletionId,
161 sort_completions: bool,
162 pub initial_position: Anchor,
163 pub buffer: Entity<Buffer>,
164 pub completions: Rc<RefCell<Box<[Completion]>>>,
165 match_candidates: Rc<[StringMatchCandidate]>,
166 pub entries: Rc<RefCell<Vec<StringMatch>>>,
167 pub selected_item: usize,
168 scroll_handle: UniformListScrollHandle,
169 resolve_completions: bool,
170 show_completion_documentation: bool,
171 last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
172}
173
174impl CompletionsMenu {
175 pub fn new(
176 id: CompletionId,
177 sort_completions: bool,
178 show_completion_documentation: bool,
179 initial_position: Anchor,
180 buffer: Entity<Buffer>,
181 completions: Box<[Completion]>,
182 ) -> Self {
183 let match_candidates = completions
184 .iter()
185 .enumerate()
186 .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
187 .collect();
188
189 Self {
190 id,
191 sort_completions,
192 initial_position,
193 buffer,
194 show_completion_documentation,
195 completions: RefCell::new(completions).into(),
196 match_candidates,
197 entries: RefCell::new(Vec::new()).into(),
198 selected_item: 0,
199 scroll_handle: UniformListScrollHandle::new(),
200 resolve_completions: true,
201 last_rendered_range: RefCell::new(None).into(),
202 }
203 }
204
205 pub fn new_snippet_choices(
206 id: CompletionId,
207 sort_completions: bool,
208 choices: &Vec<String>,
209 selection: Range<Anchor>,
210 buffer: Entity<Buffer>,
211 ) -> Self {
212 let completions = choices
213 .iter()
214 .map(|choice| Completion {
215 old_range: selection.start.text_anchor..selection.end.text_anchor,
216 new_text: choice.to_string(),
217 label: CodeLabel {
218 text: choice.to_string(),
219 runs: Default::default(),
220 filter_range: Default::default(),
221 },
222 server_id: LanguageServerId(usize::MAX),
223 documentation: None,
224 lsp_completion: Default::default(),
225 confirm: None,
226 resolved: true,
227 })
228 .collect();
229
230 let match_candidates = choices
231 .iter()
232 .enumerate()
233 .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
234 .collect();
235 let entries = choices
236 .iter()
237 .enumerate()
238 .map(|(id, completion)| StringMatch {
239 candidate_id: id,
240 score: 1.,
241 positions: vec![],
242 string: completion.clone(),
243 })
244 .collect::<Vec<_>>();
245 Self {
246 id,
247 sort_completions,
248 initial_position: selection.start,
249 buffer,
250 completions: RefCell::new(completions).into(),
251 match_candidates,
252 entries: RefCell::new(entries).into(),
253 selected_item: 0,
254 scroll_handle: UniformListScrollHandle::new(),
255 resolve_completions: false,
256 show_completion_documentation: false,
257 last_rendered_range: RefCell::new(None).into(),
258 }
259 }
260
261 fn select_first(
262 &mut self,
263 provider: Option<&dyn CompletionProvider>,
264 cx: &mut Context<Editor>,
265 ) {
266 let index = if self.scroll_handle.y_flipped() {
267 self.entries.borrow().len() - 1
268 } else {
269 0
270 };
271 self.update_selection_index(index, provider, cx);
272 }
273
274 fn select_last(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
275 let index = if self.scroll_handle.y_flipped() {
276 0
277 } else {
278 self.entries.borrow().len() - 1
279 };
280 self.update_selection_index(index, provider, cx);
281 }
282
283 fn select_prev(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
284 let index = if self.scroll_handle.y_flipped() {
285 self.next_match_index()
286 } else {
287 self.prev_match_index()
288 };
289 self.update_selection_index(index, provider, cx);
290 }
291
292 fn select_next(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
293 let index = if self.scroll_handle.y_flipped() {
294 self.prev_match_index()
295 } else {
296 self.next_match_index()
297 };
298 self.update_selection_index(index, provider, cx);
299 }
300
301 fn update_selection_index(
302 &mut self,
303 match_index: usize,
304 provider: Option<&dyn CompletionProvider>,
305 cx: &mut Context<Editor>,
306 ) {
307 if self.selected_item != match_index {
308 self.selected_item = match_index;
309 self.scroll_handle
310 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
311 self.resolve_visible_completions(provider, cx);
312 cx.notify();
313 }
314 }
315
316 fn prev_match_index(&self) -> usize {
317 if self.selected_item > 0 {
318 self.selected_item - 1
319 } else {
320 self.entries.borrow().len() - 1
321 }
322 }
323
324 fn next_match_index(&self) -> usize {
325 if self.selected_item + 1 < self.entries.borrow().len() {
326 self.selected_item + 1
327 } else {
328 0
329 }
330 }
331
332 pub fn resolve_visible_completions(
333 &mut self,
334 provider: Option<&dyn CompletionProvider>,
335 cx: &mut Context<Editor>,
336 ) {
337 if !self.resolve_completions {
338 return;
339 }
340 let Some(provider) = provider else {
341 return;
342 };
343
344 // Attempt to resolve completions for every item that will be displayed. This matters
345 // because single line documentation may be displayed inline with the completion.
346 //
347 // When navigating to the very beginning or end of completions, `last_rendered_range` may
348 // have no overlap with the completions that will be displayed, so instead use a range based
349 // on the last rendered count.
350 const APPROXIMATE_VISIBLE_COUNT: usize = 12;
351 let last_rendered_range = self.last_rendered_range.borrow().clone();
352 let visible_count = last_rendered_range
353 .clone()
354 .map_or(APPROXIMATE_VISIBLE_COUNT, |range| range.count());
355 let entries = self.entries.borrow();
356 let entry_range = if self.selected_item == 0 {
357 0..min(visible_count, entries.len())
358 } else if self.selected_item == entries.len() - 1 {
359 entries.len().saturating_sub(visible_count)..entries.len()
360 } else {
361 last_rendered_range.map_or(0..0, |range| {
362 min(range.start, entries.len())..min(range.end, entries.len())
363 })
364 };
365
366 // Expand the range to resolve more completions than are predicted to be visible, to reduce
367 // jank on navigation.
368 const EXTRA_TO_RESOLVE: usize = 4;
369 let entry_indices = util::iterate_expanded_and_wrapped_usize_range(
370 entry_range.clone(),
371 EXTRA_TO_RESOLVE,
372 EXTRA_TO_RESOLVE,
373 entries.len(),
374 );
375
376 // Avoid work by sometimes filtering out completions that already have documentation.
377 // This filtering doesn't happen if the completions are currently being updated.
378 let completions = self.completions.borrow();
379 let candidate_ids = entry_indices
380 .map(|i| entries[i].candidate_id)
381 .filter(|i| completions[*i].documentation.is_none());
382
383 // Current selection is always resolved even if it already has documentation, to handle
384 // out-of-spec language servers that return more results later.
385 let selected_candidate_id = entries[self.selected_item].candidate_id;
386 let candidate_ids = iter::once(selected_candidate_id)
387 .chain(candidate_ids.filter(|id| *id != selected_candidate_id))
388 .collect::<Vec<usize>>();
389 drop(entries);
390
391 if candidate_ids.is_empty() {
392 return;
393 }
394
395 let resolve_task = provider.resolve_completions(
396 self.buffer.clone(),
397 candidate_ids,
398 self.completions.clone(),
399 cx,
400 );
401
402 cx.spawn(move |editor, mut cx| async move {
403 if let Some(true) = resolve_task.await.log_err() {
404 editor.update(&mut cx, |_, cx| cx.notify()).ok();
405 }
406 })
407 .detach();
408 }
409
410 pub fn visible(&self) -> bool {
411 !self.entries.borrow().is_empty()
412 }
413
414 fn origin(&self) -> ContextMenuOrigin {
415 ContextMenuOrigin::Cursor
416 }
417
418 fn render(
419 &self,
420 style: &EditorStyle,
421 max_height_in_lines: u32,
422 y_flipped: bool,
423 window: &mut Window,
424 cx: &mut Context<Editor>,
425 ) -> AnyElement {
426 let completions = self.completions.borrow_mut();
427 let show_completion_documentation = self.show_completion_documentation;
428 let widest_completion_ix = self
429 .entries
430 .borrow()
431 .iter()
432 .enumerate()
433 .max_by_key(|(_, mat)| {
434 let completion = &completions[mat.candidate_id];
435 let documentation = &completion.documentation;
436
437 let mut len = completion.label.text.chars().count();
438 if let Some(CompletionDocumentation::SingleLine(text)) = documentation {
439 if show_completion_documentation {
440 len += text.chars().count();
441 }
442 }
443
444 len
445 })
446 .map(|(ix, _)| ix);
447 drop(completions);
448
449 let selected_item = self.selected_item;
450 let completions = self.completions.clone();
451 let entries = self.entries.clone();
452 let last_rendered_range = self.last_rendered_range.clone();
453 let style = style.clone();
454 let list = uniform_list(
455 cx.entity().clone(),
456 "completions",
457 self.entries.borrow().len(),
458 move |_editor, range, _window, cx| {
459 last_rendered_range.borrow_mut().replace(range.clone());
460 let start_ix = range.start;
461 let completions_guard = completions.borrow_mut();
462
463 entries.borrow()[range]
464 .iter()
465 .enumerate()
466 .map(|(ix, mat)| {
467 let item_ix = start_ix + ix;
468 let completion = &completions_guard[mat.candidate_id];
469 let documentation = if show_completion_documentation {
470 &completion.documentation
471 } else {
472 &None
473 };
474
475 let filter_start = completion.label.filter_range.start;
476 let highlights = gpui::combine_highlights(
477 mat.ranges().map(|range| {
478 (
479 filter_start + range.start..filter_start + range.end,
480 FontWeight::BOLD.into(),
481 )
482 }),
483 styled_runs_for_code_label(&completion.label, &style.syntax).map(
484 |(range, mut highlight)| {
485 // Ignore font weight for syntax highlighting, as we'll use it
486 // for fuzzy matches.
487 highlight.font_weight = None;
488 if completion.lsp_completion.deprecated.unwrap_or(false) {
489 highlight.strikethrough = Some(StrikethroughStyle {
490 thickness: 1.0.into(),
491 ..Default::default()
492 });
493 highlight.color = Some(cx.theme().colors().text_muted);
494 }
495
496 (range, highlight)
497 },
498 ),
499 );
500
501 let completion_label = StyledText::new(completion.label.text.clone())
502 .with_highlights(&style.text, highlights);
503 let documentation_label = if let Some(
504 CompletionDocumentation::SingleLine(text),
505 ) = documentation
506 {
507 if text.trim().is_empty() {
508 None
509 } else {
510 Some(
511 Label::new(text.clone())
512 .ml_4()
513 .size(LabelSize::Small)
514 .color(Color::Muted),
515 )
516 }
517 } else {
518 None
519 };
520 let color_swatch = completion
521 .color()
522 .map(|color| div().size_4().bg(color).rounded_sm());
523
524 div().min_w(px(280.)).max_w(px(540.)).child(
525 ListItem::new(mat.candidate_id)
526 .inset(true)
527 .toggle_state(item_ix == selected_item)
528 .on_click(cx.listener(move |editor, _event, window, cx| {
529 cx.stop_propagation();
530 if let Some(task) = editor.confirm_completion(
531 &ConfirmCompletion {
532 item_ix: Some(item_ix),
533 },
534 window,
535 cx,
536 ) {
537 task.detach_and_log_err(cx)
538 }
539 }))
540 .start_slot::<Div>(color_swatch)
541 .child(h_flex().overflow_hidden().child(completion_label))
542 .end_slot::<Label>(documentation_label),
543 )
544 })
545 .collect()
546 },
547 )
548 .occlude()
549 .max_h(max_height_in_lines as f32 * window.line_height())
550 .track_scroll(self.scroll_handle.clone())
551 .y_flipped(y_flipped)
552 .with_width_from_item(widest_completion_ix)
553 .with_sizing_behavior(ListSizingBehavior::Infer);
554
555 Popover::new().child(list).into_any_element()
556 }
557
558 fn render_aside(
559 &self,
560 style: &EditorStyle,
561 max_size: Size<Pixels>,
562 workspace: Option<WeakEntity<Workspace>>,
563 cx: &mut Context<Editor>,
564 ) -> Option<AnyElement> {
565 if !self.show_completion_documentation {
566 return None;
567 }
568
569 let mat = &self.entries.borrow()[self.selected_item];
570 let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
571 .documentation
572 .as_ref()?
573 {
574 CompletionDocumentation::MultiLinePlainText(text) => {
575 div().child(SharedString::from(text.clone()))
576 }
577 CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.text.is_empty() => div()
578 .child(render_parsed_markdown(
579 "completions_markdown",
580 parsed,
581 &style,
582 workspace,
583 cx,
584 )),
585 CompletionDocumentation::MultiLineMarkdown(_) => return None,
586 CompletionDocumentation::SingleLine(_) => return None,
587 CompletionDocumentation::Undocumented => return None,
588 };
589
590 Some(
591 Popover::new()
592 .child(
593 multiline_docs
594 .id("multiline_docs")
595 .px(MENU_ASIDE_X_PADDING / 2.)
596 .max_w(max_size.width)
597 .max_h(max_size.height)
598 .overflow_y_scroll()
599 .occlude(),
600 )
601 .into_any_element(),
602 )
603 }
604
605 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
606 let mut matches = if let Some(query) = query {
607 fuzzy::match_strings(
608 &self.match_candidates,
609 query,
610 query.chars().any(|c| c.is_uppercase()),
611 100,
612 &Default::default(),
613 executor,
614 )
615 .await
616 } else {
617 self.match_candidates
618 .iter()
619 .enumerate()
620 .map(|(candidate_id, candidate)| StringMatch {
621 candidate_id,
622 score: Default::default(),
623 positions: Default::default(),
624 string: candidate.string.clone(),
625 })
626 .collect()
627 };
628
629 // Remove all candidates where the query's start does not match the start of any word in the candidate
630 if let Some(query) = query {
631 if let Some(query_start) = query.chars().next() {
632 matches.retain(|string_match| {
633 split_words(&string_match.string).any(|word| {
634 // Check that the first codepoint of the word as lowercase matches the first
635 // codepoint of the query as lowercase
636 word.chars()
637 .flat_map(|codepoint| codepoint.to_lowercase())
638 .zip(query_start.to_lowercase())
639 .all(|(word_cp, query_cp)| word_cp == query_cp)
640 })
641 });
642 }
643 }
644
645 let completions = self.completions.borrow_mut();
646 if self.sort_completions {
647 matches.sort_unstable_by_key(|mat| {
648 // We do want to strike a balance here between what the language server tells us
649 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
650 // `Creat` and there is a local variable called `CreateComponent`).
651 // So what we do is: we bucket all matches into two buckets
652 // - Strong matches
653 // - Weak matches
654 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
655 // and the Weak matches are the rest.
656 //
657 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
658 // matches, we prefer language-server sort_text first.
659 //
660 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
661 // Rest of the matches(weak) can be sorted as language-server expects.
662
663 #[derive(PartialEq, Eq, PartialOrd, Ord)]
664 enum MatchScore<'a> {
665 Strong {
666 score: Reverse<OrderedFloat<f64>>,
667 sort_text: Option<&'a str>,
668 sort_key: (usize, &'a str),
669 },
670 Weak {
671 sort_text: Option<&'a str>,
672 score: Reverse<OrderedFloat<f64>>,
673 sort_key: (usize, &'a str),
674 },
675 }
676
677 let completion = &completions[mat.candidate_id];
678 let sort_key = completion.sort_key();
679 let sort_text = completion.lsp_completion.sort_text.as_deref();
680 let score = Reverse(OrderedFloat(mat.score));
681
682 if mat.score >= 0.2 {
683 MatchScore::Strong {
684 score,
685 sort_text,
686 sort_key,
687 }
688 } else {
689 MatchScore::Weak {
690 sort_text,
691 score,
692 sort_key,
693 }
694 }
695 });
696 }
697 drop(completions);
698
699 *self.entries.borrow_mut() = matches;
700 self.selected_item = 0;
701 // This keeps the display consistent when y_flipped.
702 self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
703 }
704}
705
706#[derive(Clone)]
707pub struct AvailableCodeAction {
708 pub excerpt_id: ExcerptId,
709 pub action: CodeAction,
710 pub provider: Rc<dyn CodeActionProvider>,
711}
712
713#[derive(Clone)]
714pub struct CodeActionContents {
715 pub tasks: Option<Rc<ResolvedTasks>>,
716 pub actions: Option<Rc<[AvailableCodeAction]>>,
717}
718
719impl CodeActionContents {
720 fn len(&self) -> usize {
721 match (&self.tasks, &self.actions) {
722 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
723 (Some(tasks), None) => tasks.templates.len(),
724 (None, Some(actions)) => actions.len(),
725 (None, None) => 0,
726 }
727 }
728
729 fn is_empty(&self) -> bool {
730 match (&self.tasks, &self.actions) {
731 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
732 (Some(tasks), None) => tasks.templates.is_empty(),
733 (None, Some(actions)) => actions.is_empty(),
734 (None, None) => true,
735 }
736 }
737
738 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
739 self.tasks
740 .iter()
741 .flat_map(|tasks| {
742 tasks
743 .templates
744 .iter()
745 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
746 })
747 .chain(self.actions.iter().flat_map(|actions| {
748 actions.iter().map(|available| CodeActionsItem::CodeAction {
749 excerpt_id: available.excerpt_id,
750 action: available.action.clone(),
751 provider: available.provider.clone(),
752 })
753 }))
754 }
755
756 pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
757 match (&self.tasks, &self.actions) {
758 (Some(tasks), Some(actions)) => {
759 if index < tasks.templates.len() {
760 tasks
761 .templates
762 .get(index)
763 .cloned()
764 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
765 } else {
766 actions.get(index - tasks.templates.len()).map(|available| {
767 CodeActionsItem::CodeAction {
768 excerpt_id: available.excerpt_id,
769 action: available.action.clone(),
770 provider: available.provider.clone(),
771 }
772 })
773 }
774 }
775 (Some(tasks), None) => tasks
776 .templates
777 .get(index)
778 .cloned()
779 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
780 (None, Some(actions)) => {
781 actions
782 .get(index)
783 .map(|available| CodeActionsItem::CodeAction {
784 excerpt_id: available.excerpt_id,
785 action: available.action.clone(),
786 provider: available.provider.clone(),
787 })
788 }
789 (None, None) => None,
790 }
791 }
792}
793
794#[allow(clippy::large_enum_variant)]
795#[derive(Clone)]
796pub enum CodeActionsItem {
797 Task(TaskSourceKind, ResolvedTask),
798 CodeAction {
799 excerpt_id: ExcerptId,
800 action: CodeAction,
801 provider: Rc<dyn CodeActionProvider>,
802 },
803}
804
805impl CodeActionsItem {
806 fn as_task(&self) -> Option<&ResolvedTask> {
807 let Self::Task(_, task) = self else {
808 return None;
809 };
810 Some(task)
811 }
812
813 fn as_code_action(&self) -> Option<&CodeAction> {
814 let Self::CodeAction { action, .. } = self else {
815 return None;
816 };
817 Some(action)
818 }
819
820 pub fn label(&self) -> String {
821 match self {
822 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
823 Self::Task(_, task) => task.resolved_label.clone(),
824 }
825 }
826}
827
828pub struct CodeActionsMenu {
829 pub actions: CodeActionContents,
830 pub buffer: Entity<Buffer>,
831 pub selected_item: usize,
832 pub scroll_handle: UniformListScrollHandle,
833 pub deployed_from_indicator: Option<DisplayRow>,
834}
835
836impl CodeActionsMenu {
837 fn select_first(&mut self, cx: &mut Context<Editor>) {
838 self.selected_item = if self.scroll_handle.y_flipped() {
839 self.actions.len() - 1
840 } else {
841 0
842 };
843 self.scroll_handle
844 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
845 cx.notify()
846 }
847
848 fn select_last(&mut self, cx: &mut Context<Editor>) {
849 self.selected_item = if self.scroll_handle.y_flipped() {
850 0
851 } else {
852 self.actions.len() - 1
853 };
854 self.scroll_handle
855 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
856 cx.notify()
857 }
858
859 fn select_prev(&mut self, cx: &mut Context<Editor>) {
860 self.selected_item = if self.scroll_handle.y_flipped() {
861 self.next_match_index()
862 } else {
863 self.prev_match_index()
864 };
865 self.scroll_handle
866 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
867 cx.notify();
868 }
869
870 fn select_next(&mut self, cx: &mut Context<Editor>) {
871 self.selected_item = if self.scroll_handle.y_flipped() {
872 self.prev_match_index()
873 } else {
874 self.next_match_index()
875 };
876 self.scroll_handle
877 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
878 cx.notify();
879 }
880
881 fn prev_match_index(&self) -> usize {
882 if self.selected_item > 0 {
883 self.selected_item - 1
884 } else {
885 self.actions.len() - 1
886 }
887 }
888
889 fn next_match_index(&self) -> usize {
890 if self.selected_item + 1 < self.actions.len() {
891 self.selected_item + 1
892 } else {
893 0
894 }
895 }
896
897 fn visible(&self) -> bool {
898 !self.actions.is_empty()
899 }
900
901 fn origin(&self) -> ContextMenuOrigin {
902 if let Some(row) = self.deployed_from_indicator {
903 ContextMenuOrigin::GutterIndicator(row)
904 } else {
905 ContextMenuOrigin::Cursor
906 }
907 }
908
909 fn render(
910 &self,
911 _style: &EditorStyle,
912 max_height_in_lines: u32,
913 y_flipped: bool,
914 window: &mut Window,
915 cx: &mut Context<Editor>,
916 ) -> AnyElement {
917 let actions = self.actions.clone();
918 let selected_item = self.selected_item;
919 let list = uniform_list(
920 cx.entity().clone(),
921 "code_actions_menu",
922 self.actions.len(),
923 move |_this, range, _, cx| {
924 actions
925 .iter()
926 .skip(range.start)
927 .take(range.end - range.start)
928 .enumerate()
929 .map(|(ix, action)| {
930 let item_ix = range.start + ix;
931 let selected = item_ix == selected_item;
932 let colors = cx.theme().colors();
933 div().min_w(px(220.)).max_w(px(540.)).child(
934 ListItem::new(item_ix)
935 .inset(true)
936 .toggle_state(selected)
937 .when_some(action.as_code_action(), |this, action| {
938 this.on_click(cx.listener(move |editor, _, window, cx| {
939 cx.stop_propagation();
940 if let Some(task) = editor.confirm_code_action(
941 &ConfirmCodeAction {
942 item_ix: Some(item_ix),
943 },
944 window,
945 cx,
946 ) {
947 task.detach_and_log_err(cx)
948 }
949 }))
950 .child(
951 h_flex()
952 .overflow_hidden()
953 .child(
954 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
955 action.lsp_action.title.replace("\n", ""),
956 )
957 .when(selected, |this| {
958 this.text_color(colors.text_accent)
959 }),
960 )
961 })
962 .when_some(action.as_task(), |this, task| {
963 this.on_click(cx.listener(move |editor, _, window, cx| {
964 cx.stop_propagation();
965 if let Some(task) = editor.confirm_code_action(
966 &ConfirmCodeAction {
967 item_ix: Some(item_ix),
968 },
969 window,
970 cx,
971 ) {
972 task.detach_and_log_err(cx)
973 }
974 }))
975 .child(
976 h_flex()
977 .overflow_hidden()
978 .child(task.resolved_label.replace("\n", ""))
979 .when(selected, |this| {
980 this.text_color(colors.text_accent)
981 }),
982 )
983 }),
984 )
985 })
986 .collect()
987 },
988 )
989 .occlude()
990 .max_h(max_height_in_lines as f32 * window.line_height())
991 .track_scroll(self.scroll_handle.clone())
992 .y_flipped(y_flipped)
993 .with_width_from_item(
994 self.actions
995 .iter()
996 .enumerate()
997 .max_by_key(|(_, action)| match action {
998 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
999 CodeActionsItem::CodeAction { action, .. } => {
1000 action.lsp_action.title.chars().count()
1001 }
1002 })
1003 .map(|(ix, _)| ix),
1004 )
1005 .with_sizing_behavior(ListSizingBehavior::Infer);
1006
1007 Popover::new().child(list).into_any_element()
1008 }
1009}