code_context_menus.rs

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