code_context_menus.rs

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