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| div().size_4().bg(color).rounded_xs().into_any_element())
 547                            .or_else(|| {
 548                                completion.icon_path.as_ref().map(|path| {
 549                                    Icon::from_path(path)
 550                                        .size(IconSize::XSmall)
 551                                        .color(Color::Muted)
 552                                        .into_any_element()
 553                                })
 554                            });
 555
 556                        div().min_w(px(280.)).max_w(px(540.)).child(
 557                            ListItem::new(mat.candidate_id)
 558                                .inset(true)
 559                                .toggle_state(item_ix == selected_item)
 560                                .on_click(cx.listener(move |editor, _event, window, cx| {
 561                                    cx.stop_propagation();
 562                                    if let Some(task) = editor.confirm_completion(
 563                                        &ConfirmCompletion {
 564                                            item_ix: Some(item_ix),
 565                                        },
 566                                        window,
 567                                        cx,
 568                                    ) {
 569                                        task.detach_and_log_err(cx)
 570                                    }
 571                                }))
 572                                .start_slot::<AnyElement>(start_slot)
 573                                .child(h_flex().overflow_hidden().child(completion_label))
 574                                .end_slot::<Label>(documentation_label),
 575                        )
 576                    })
 577                    .collect()
 578            },
 579        )
 580        .occlude()
 581        .max_h(max_height_in_lines as f32 * window.line_height())
 582        .track_scroll(self.scroll_handle.clone())
 583        .y_flipped(y_flipped)
 584        .with_width_from_item(widest_completion_ix)
 585        .with_sizing_behavior(ListSizingBehavior::Infer);
 586
 587        Popover::new().child(list).into_any_element()
 588    }
 589
 590    fn render_aside(
 591        &mut self,
 592        editor: &Editor,
 593        max_size: Size<Pixels>,
 594        window: &mut Window,
 595        cx: &mut Context<Editor>,
 596    ) -> Option<AnyElement> {
 597        if !self.show_completion_documentation {
 598            return None;
 599        }
 600
 601        let mat = &self.entries.borrow()[self.selected_item];
 602        let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
 603            .documentation
 604            .as_ref()?
 605        {
 606            CompletionDocumentation::MultiLinePlainText(text) => div().child(text.clone()),
 607            CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.is_empty() => {
 608                let markdown = self.markdown_element.get_or_insert_with(|| {
 609                    cx.new(|cx| {
 610                        let languages = editor
 611                            .workspace
 612                            .as_ref()
 613                            .and_then(|(workspace, _)| workspace.upgrade())
 614                            .map(|workspace| workspace.read(cx).app_state().languages.clone());
 615                        let language = editor
 616                            .language_at(self.initial_position, cx)
 617                            .map(|l| l.name().to_proto());
 618                        Markdown::new(
 619                            SharedString::default(),
 620                            hover_markdown_style(window, cx),
 621                            languages,
 622                            language,
 623                            cx,
 624                        )
 625                        .copy_code_block_buttons(false)
 626                        .open_url(open_markdown_url)
 627                    })
 628                });
 629                markdown.update(cx, |markdown, cx| {
 630                    markdown.reset(parsed.clone(), cx);
 631                });
 632                div().child(markdown.clone())
 633            }
 634            CompletionDocumentation::MultiLineMarkdown(_) => return None,
 635            CompletionDocumentation::SingleLine(_) => return None,
 636            CompletionDocumentation::Undocumented => return None,
 637        };
 638
 639        Some(
 640            Popover::new()
 641                .child(
 642                    multiline_docs
 643                        .id("multiline_docs")
 644                        .px(MENU_ASIDE_X_PADDING / 2.)
 645                        .max_w(max_size.width)
 646                        .max_h(max_size.height)
 647                        .overflow_y_scroll()
 648                        .occlude(),
 649                )
 650                .into_any_element(),
 651        )
 652    }
 653
 654    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 655        let mut matches = if let Some(query) = query {
 656            fuzzy::match_strings(
 657                &self.match_candidates,
 658                query,
 659                query.chars().any(|c| c.is_uppercase()),
 660                100,
 661                &Default::default(),
 662                executor,
 663            )
 664            .await
 665        } else {
 666            self.match_candidates
 667                .iter()
 668                .enumerate()
 669                .map(|(candidate_id, candidate)| StringMatch {
 670                    candidate_id,
 671                    score: Default::default(),
 672                    positions: Default::default(),
 673                    string: candidate.string.clone(),
 674                })
 675                .collect()
 676        };
 677
 678        let mut additional_matches = Vec::new();
 679        // Deprioritize all candidates where the query's start does not match the start of any word in the candidate
 680        if let Some(query) = query {
 681            if let Some(query_start) = query.chars().next() {
 682                let (primary, secondary) = matches.into_iter().partition(|string_match| {
 683                    split_words(&string_match.string).any(|word| {
 684                        // Check that the first codepoint of the word as lowercase matches the first
 685                        // codepoint of the query as lowercase
 686                        word.chars()
 687                            .flat_map(|codepoint| codepoint.to_lowercase())
 688                            .zip(query_start.to_lowercase())
 689                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 690                    })
 691                });
 692                matches = primary;
 693                additional_matches = secondary;
 694            }
 695        }
 696
 697        let completions = self.completions.borrow_mut();
 698        if self.sort_completions {
 699            matches.sort_unstable_by_key(|mat| {
 700                // We do want to strike a balance here between what the language server tells us
 701                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 702                // `Creat` and there is a local variable called `CreateComponent`).
 703                // So what we do is: we bucket all matches into two buckets
 704                // - Strong matches
 705                // - Weak matches
 706                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 707                // and the Weak matches are the rest.
 708                //
 709                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 710                // matches, we prefer language-server sort_text first.
 711                //
 712                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 713                // Rest of the matches(weak) can be sorted as language-server expects.
 714
 715                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 716                enum MatchScore<'a> {
 717                    Strong {
 718                        score: Reverse<OrderedFloat<f64>>,
 719                        sort_text: Option<&'a str>,
 720                        sort_key: (usize, &'a str),
 721                    },
 722                    Weak {
 723                        sort_text: Option<&'a str>,
 724                        score: Reverse<OrderedFloat<f64>>,
 725                        sort_key: (usize, &'a str),
 726                    },
 727                }
 728
 729                let completion = &completions[mat.candidate_id];
 730                let sort_key = completion.sort_key();
 731                let sort_text =
 732                    if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
 733                        lsp_completion.sort_text.as_deref()
 734                    } else {
 735                        None
 736                    };
 737                let score = Reverse(OrderedFloat(mat.score));
 738
 739                if mat.score >= 0.2 {
 740                    MatchScore::Strong {
 741                        score,
 742                        sort_text,
 743                        sort_key,
 744                    }
 745                } else {
 746                    MatchScore::Weak {
 747                        sort_text,
 748                        score,
 749                        sort_key,
 750                    }
 751                }
 752            });
 753        }
 754        drop(completions);
 755
 756        matches.extend(additional_matches);
 757
 758        *self.entries.borrow_mut() = matches;
 759        self.selected_item = 0;
 760        // This keeps the display consistent when y_flipped.
 761        self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
 762    }
 763}
 764
 765#[derive(Clone)]
 766pub struct AvailableCodeAction {
 767    pub excerpt_id: ExcerptId,
 768    pub action: CodeAction,
 769    pub provider: Rc<dyn CodeActionProvider>,
 770}
 771
 772#[derive(Clone)]
 773pub struct CodeActionContents {
 774    pub tasks: Option<Rc<ResolvedTasks>>,
 775    pub actions: Option<Rc<[AvailableCodeAction]>>,
 776}
 777
 778impl CodeActionContents {
 779    fn len(&self) -> usize {
 780        match (&self.tasks, &self.actions) {
 781            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 782            (Some(tasks), None) => tasks.templates.len(),
 783            (None, Some(actions)) => actions.len(),
 784            (None, None) => 0,
 785        }
 786    }
 787
 788    fn is_empty(&self) -> bool {
 789        match (&self.tasks, &self.actions) {
 790            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 791            (Some(tasks), None) => tasks.templates.is_empty(),
 792            (None, Some(actions)) => actions.is_empty(),
 793            (None, None) => true,
 794        }
 795    }
 796
 797    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 798        self.tasks
 799            .iter()
 800            .flat_map(|tasks| {
 801                tasks
 802                    .templates
 803                    .iter()
 804                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 805            })
 806            .chain(self.actions.iter().flat_map(|actions| {
 807                actions.iter().map(|available| CodeActionsItem::CodeAction {
 808                    excerpt_id: available.excerpt_id,
 809                    action: available.action.clone(),
 810                    provider: available.provider.clone(),
 811                })
 812            }))
 813    }
 814
 815    pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
 816        match (&self.tasks, &self.actions) {
 817            (Some(tasks), Some(actions)) => {
 818                if index < tasks.templates.len() {
 819                    tasks
 820                        .templates
 821                        .get(index)
 822                        .cloned()
 823                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 824                } else {
 825                    actions.get(index - tasks.templates.len()).map(|available| {
 826                        CodeActionsItem::CodeAction {
 827                            excerpt_id: available.excerpt_id,
 828                            action: available.action.clone(),
 829                            provider: available.provider.clone(),
 830                        }
 831                    })
 832                }
 833            }
 834            (Some(tasks), None) => tasks
 835                .templates
 836                .get(index)
 837                .cloned()
 838                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 839            (None, Some(actions)) => {
 840                actions
 841                    .get(index)
 842                    .map(|available| CodeActionsItem::CodeAction {
 843                        excerpt_id: available.excerpt_id,
 844                        action: available.action.clone(),
 845                        provider: available.provider.clone(),
 846                    })
 847            }
 848            (None, None) => None,
 849        }
 850    }
 851}
 852
 853#[allow(clippy::large_enum_variant)]
 854#[derive(Clone)]
 855pub enum CodeActionsItem {
 856    Task(TaskSourceKind, ResolvedTask),
 857    CodeAction {
 858        excerpt_id: ExcerptId,
 859        action: CodeAction,
 860        provider: Rc<dyn CodeActionProvider>,
 861    },
 862}
 863
 864impl CodeActionsItem {
 865    fn as_task(&self) -> Option<&ResolvedTask> {
 866        let Self::Task(_, task) = self else {
 867            return None;
 868        };
 869        Some(task)
 870    }
 871
 872    fn as_code_action(&self) -> Option<&CodeAction> {
 873        let Self::CodeAction { action, .. } = self else {
 874            return None;
 875        };
 876        Some(action)
 877    }
 878
 879    pub fn label(&self) -> String {
 880        match self {
 881            Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
 882            Self::Task(_, task) => task.resolved_label.clone(),
 883        }
 884    }
 885}
 886
 887pub struct CodeActionsMenu {
 888    pub actions: CodeActionContents,
 889    pub buffer: Entity<Buffer>,
 890    pub selected_item: usize,
 891    pub scroll_handle: UniformListScrollHandle,
 892    pub deployed_from_indicator: Option<DisplayRow>,
 893}
 894
 895impl CodeActionsMenu {
 896    fn select_first(&mut self, cx: &mut Context<Editor>) {
 897        self.selected_item = if self.scroll_handle.y_flipped() {
 898            self.actions.len() - 1
 899        } else {
 900            0
 901        };
 902        self.scroll_handle
 903            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 904        cx.notify()
 905    }
 906
 907    fn select_last(&mut self, cx: &mut Context<Editor>) {
 908        self.selected_item = if self.scroll_handle.y_flipped() {
 909            0
 910        } else {
 911            self.actions.len() - 1
 912        };
 913        self.scroll_handle
 914            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 915        cx.notify()
 916    }
 917
 918    fn select_prev(&mut self, cx: &mut Context<Editor>) {
 919        self.selected_item = if self.scroll_handle.y_flipped() {
 920            self.next_match_index()
 921        } else {
 922            self.prev_match_index()
 923        };
 924        self.scroll_handle
 925            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 926        cx.notify();
 927    }
 928
 929    fn select_next(&mut self, cx: &mut Context<Editor>) {
 930        self.selected_item = if self.scroll_handle.y_flipped() {
 931            self.prev_match_index()
 932        } else {
 933            self.next_match_index()
 934        };
 935        self.scroll_handle
 936            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 937        cx.notify();
 938    }
 939
 940    fn prev_match_index(&self) -> usize {
 941        if self.selected_item > 0 {
 942            self.selected_item - 1
 943        } else {
 944            self.actions.len() - 1
 945        }
 946    }
 947
 948    fn next_match_index(&self) -> usize {
 949        if self.selected_item + 1 < self.actions.len() {
 950            self.selected_item + 1
 951        } else {
 952            0
 953        }
 954    }
 955
 956    fn visible(&self) -> bool {
 957        !self.actions.is_empty()
 958    }
 959
 960    fn origin(&self) -> ContextMenuOrigin {
 961        if let Some(row) = self.deployed_from_indicator {
 962            ContextMenuOrigin::GutterIndicator(row)
 963        } else {
 964            ContextMenuOrigin::Cursor
 965        }
 966    }
 967
 968    fn render(
 969        &self,
 970        _style: &EditorStyle,
 971        max_height_in_lines: u32,
 972        y_flipped: bool,
 973        window: &mut Window,
 974        cx: &mut Context<Editor>,
 975    ) -> AnyElement {
 976        let actions = self.actions.clone();
 977        let selected_item = self.selected_item;
 978        let list = uniform_list(
 979            cx.entity().clone(),
 980            "code_actions_menu",
 981            self.actions.len(),
 982            move |_this, range, _, cx| {
 983                actions
 984                    .iter()
 985                    .skip(range.start)
 986                    .take(range.end - range.start)
 987                    .enumerate()
 988                    .map(|(ix, action)| {
 989                        let item_ix = range.start + ix;
 990                        let selected = item_ix == selected_item;
 991                        let colors = cx.theme().colors();
 992                        div().min_w(px(220.)).max_w(px(540.)).child(
 993                            ListItem::new(item_ix)
 994                                .inset(true)
 995                                .toggle_state(selected)
 996                                .when_some(action.as_code_action(), |this, action| {
 997                                    this.on_click(cx.listener(move |editor, _, window, cx| {
 998                                        cx.stop_propagation();
 999                                        if let Some(task) = editor.confirm_code_action(
1000                                            &ConfirmCodeAction {
1001                                                item_ix: Some(item_ix),
1002                                            },
1003                                            window,
1004                                            cx,
1005                                        ) {
1006                                            task.detach_and_log_err(cx)
1007                                        }
1008                                    }))
1009                                    .child(
1010                                        h_flex()
1011                                            .overflow_hidden()
1012                                            .child(
1013                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1014                                                action.lsp_action.title().replace("\n", ""),
1015                                            )
1016                                            .when(selected, |this| {
1017                                                this.text_color(colors.text_accent)
1018                                            }),
1019                                    )
1020                                })
1021                                .when_some(action.as_task(), |this, task| {
1022                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1023                                        cx.stop_propagation();
1024                                        if let Some(task) = editor.confirm_code_action(
1025                                            &ConfirmCodeAction {
1026                                                item_ix: Some(item_ix),
1027                                            },
1028                                            window,
1029                                            cx,
1030                                        ) {
1031                                            task.detach_and_log_err(cx)
1032                                        }
1033                                    }))
1034                                    .child(
1035                                        h_flex()
1036                                            .overflow_hidden()
1037                                            .child(task.resolved_label.replace("\n", ""))
1038                                            .when(selected, |this| {
1039                                                this.text_color(colors.text_accent)
1040                                            }),
1041                                    )
1042                                }),
1043                        )
1044                    })
1045                    .collect()
1046            },
1047        )
1048        .occlude()
1049        .max_h(max_height_in_lines as f32 * window.line_height())
1050        .track_scroll(self.scroll_handle.clone())
1051        .y_flipped(y_flipped)
1052        .with_width_from_item(
1053            self.actions
1054                .iter()
1055                .enumerate()
1056                .max_by_key(|(_, action)| match action {
1057                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1058                    CodeActionsItem::CodeAction { action, .. } => {
1059                        action.lsp_action.title().chars().count()
1060                    }
1061                })
1062                .map(|(ix, _)| ix),
1063        )
1064        .with_sizing_behavior(ListSizingBehavior::Infer);
1065
1066        Popover::new().child(list).into_any_element()
1067    }
1068}