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;
  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        y_flipped: bool,
 130        window: &mut Window,
 131        cx: &mut Context<Editor>,
 132    ) -> AnyElement {
 133        match self {
 134            CodeContextMenu::Completions(menu) => {
 135                menu.render(style, max_height_in_lines, y_flipped, window, cx)
 136            }
 137            CodeContextMenu::CodeActions(menu) => {
 138                menu.render(style, max_height_in_lines, y_flipped, window, cx)
 139            }
 140        }
 141    }
 142
 143    pub fn render_aside(
 144        &mut self,
 145        editor: &Editor,
 146        max_size: Size<Pixels>,
 147        window: &mut Window,
 148        cx: &mut Context<Editor>,
 149    ) -> Option<AnyElement> {
 150        match self {
 151            CodeContextMenu::Completions(menu) => menu.render_aside(editor, max_size, window, cx),
 152            CodeContextMenu::CodeActions(_) => None,
 153        }
 154    }
 155
 156    pub fn focused(&self, window: &mut Window, cx: &mut Context<Editor>) -> bool {
 157        match self {
 158            CodeContextMenu::Completions(completions_menu) => completions_menu
 159                .markdown_element
 160                .as_ref()
 161                .is_some_and(|markdown| markdown.focus_handle(cx).contains_focused(window, cx)),
 162            CodeContextMenu::CodeActions(_) => false,
 163        }
 164    }
 165}
 166
 167pub enum ContextMenuOrigin {
 168    Cursor,
 169    GutterIndicator(DisplayRow),
 170}
 171
 172#[derive(Clone, Debug)]
 173pub struct CompletionsMenu {
 174    pub id: CompletionId,
 175    sort_completions: bool,
 176    pub initial_position: Anchor,
 177    pub buffer: Entity<Buffer>,
 178    pub completions: Rc<RefCell<Box<[Completion]>>>,
 179    match_candidates: Rc<[StringMatchCandidate]>,
 180    pub entries: Rc<RefCell<Vec<StringMatch>>>,
 181    pub selected_item: usize,
 182    scroll_handle: UniformListScrollHandle,
 183    resolve_completions: bool,
 184    show_completion_documentation: bool,
 185    pub(super) ignore_completion_provider: bool,
 186    last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
 187    markdown_element: Option<Entity<Markdown>>,
 188}
 189
 190impl CompletionsMenu {
 191    pub fn new(
 192        id: CompletionId,
 193        sort_completions: bool,
 194        show_completion_documentation: bool,
 195        ignore_completion_provider: bool,
 196        initial_position: Anchor,
 197        buffer: Entity<Buffer>,
 198        completions: Box<[Completion]>,
 199    ) -> Self {
 200        let match_candidates = completions
 201            .iter()
 202            .enumerate()
 203            .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
 204            .collect();
 205
 206        Self {
 207            id,
 208            sort_completions,
 209            initial_position,
 210            buffer,
 211            show_completion_documentation,
 212            ignore_completion_provider,
 213            completions: RefCell::new(completions).into(),
 214            match_candidates,
 215            entries: RefCell::new(Vec::new()).into(),
 216            selected_item: 0,
 217            scroll_handle: UniformListScrollHandle::new(),
 218            resolve_completions: true,
 219            last_rendered_range: RefCell::new(None).into(),
 220            markdown_element: None,
 221        }
 222    }
 223
 224    pub fn new_snippet_choices(
 225        id: CompletionId,
 226        sort_completions: bool,
 227        choices: &Vec<String>,
 228        selection: Range<Anchor>,
 229        buffer: Entity<Buffer>,
 230    ) -> Self {
 231        let completions = choices
 232            .iter()
 233            .map(|choice| Completion {
 234                old_range: selection.start.text_anchor..selection.end.text_anchor,
 235                new_text: choice.to_string(),
 236                label: CodeLabel {
 237                    text: choice.to_string(),
 238                    runs: Default::default(),
 239                    filter_range: Default::default(),
 240                },
 241                icon_path: None,
 242                documentation: None,
 243                confirm: 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        y_flipped: bool,
 443        window: &mut Window,
 444        cx: &mut Context<Editor>,
 445    ) -> AnyElement {
 446        let completions = self.completions.borrow_mut();
 447        let show_completion_documentation = self.show_completion_documentation;
 448        let widest_completion_ix = self
 449            .entries
 450            .borrow()
 451            .iter()
 452            .enumerate()
 453            .max_by_key(|(_, mat)| {
 454                let completion = &completions[mat.candidate_id];
 455                let documentation = &completion.documentation;
 456
 457                let mut len = completion.label.text.chars().count();
 458                if let Some(CompletionDocumentation::SingleLine(text)) = documentation {
 459                    if show_completion_documentation {
 460                        len += text.chars().count();
 461                    }
 462                }
 463
 464                len
 465            })
 466            .map(|(ix, _)| ix);
 467        drop(completions);
 468
 469        let selected_item = self.selected_item;
 470        let completions = self.completions.clone();
 471        let entries = self.entries.clone();
 472        let last_rendered_range = self.last_rendered_range.clone();
 473        let style = style.clone();
 474        let list = uniform_list(
 475            cx.entity().clone(),
 476            "completions",
 477            self.entries.borrow().len(),
 478            move |_editor, range, _window, cx| {
 479                last_rendered_range.borrow_mut().replace(range.clone());
 480                let start_ix = range.start;
 481                let completions_guard = completions.borrow_mut();
 482
 483                entries.borrow()[range]
 484                    .iter()
 485                    .enumerate()
 486                    .map(|(ix, mat)| {
 487                        let item_ix = start_ix + ix;
 488                        let completion = &completions_guard[mat.candidate_id];
 489                        let documentation = if show_completion_documentation {
 490                            &completion.documentation
 491                        } else {
 492                            &None
 493                        };
 494
 495                        let filter_start = completion.label.filter_range.start;
 496                        let highlights = gpui::combine_highlights(
 497                            mat.ranges().map(|range| {
 498                                (
 499                                    filter_start + range.start..filter_start + range.end,
 500                                    FontWeight::BOLD.into(),
 501                                )
 502                            }),
 503                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 504                                |(range, mut highlight)| {
 505                                    // Ignore font weight for syntax highlighting, as we'll use it
 506                                    // for fuzzy matches.
 507                                    highlight.font_weight = None;
 508                                    if completion
 509                                        .source
 510                                        .lsp_completion(false)
 511                                        .and_then(|lsp_completion| lsp_completion.deprecated)
 512                                        .unwrap_or(false)
 513                                    {
 514                                        highlight.strikethrough = Some(StrikethroughStyle {
 515                                            thickness: 1.0.into(),
 516                                            ..Default::default()
 517                                        });
 518                                        highlight.color = Some(cx.theme().colors().text_muted);
 519                                    }
 520
 521                                    (range, highlight)
 522                                },
 523                            ),
 524                        );
 525
 526                        let completion_label = StyledText::new(completion.label.text.clone())
 527                            .with_default_highlights(&style.text, highlights);
 528                        let documentation_label = if let Some(
 529                            CompletionDocumentation::SingleLine(text),
 530                        ) = documentation
 531                        {
 532                            if text.trim().is_empty() {
 533                                None
 534                            } else {
 535                                Some(
 536                                    Label::new(text.clone())
 537                                        .ml_4()
 538                                        .size(LabelSize::Small)
 539                                        .color(Color::Muted),
 540                                )
 541                            }
 542                        } else {
 543                            None
 544                        };
 545
 546                        let start_slot = completion
 547                            .color()
 548                            .map(|color| {
 549                                div()
 550                                    .flex_shrink_0()
 551                                    .size_3p5()
 552                                    .rounded_xs()
 553                                    .bg(color)
 554                                    .into_any_element()
 555                            })
 556                            .or_else(|| {
 557                                completion.icon_path.as_ref().map(|path| {
 558                                    Icon::from_path(path)
 559                                        .size(IconSize::XSmall)
 560                                        .color(Color::Muted)
 561                                        .into_any_element()
 562                                })
 563                            });
 564
 565                        div().min_w(px(280.)).max_w(px(540.)).child(
 566                            ListItem::new(mat.candidate_id)
 567                                .inset(true)
 568                                .toggle_state(item_ix == selected_item)
 569                                .on_click(cx.listener(move |editor, _event, window, cx| {
 570                                    cx.stop_propagation();
 571                                    if let Some(task) = editor.confirm_completion(
 572                                        &ConfirmCompletion {
 573                                            item_ix: Some(item_ix),
 574                                        },
 575                                        window,
 576                                        cx,
 577                                    ) {
 578                                        task.detach_and_log_err(cx)
 579                                    }
 580                                }))
 581                                .start_slot::<AnyElement>(start_slot)
 582                                .child(h_flex().overflow_hidden().child(completion_label))
 583                                .end_slot::<Label>(documentation_label),
 584                        )
 585                    })
 586                    .collect()
 587            },
 588        )
 589        .occlude()
 590        .max_h(max_height_in_lines as f32 * window.line_height())
 591        .track_scroll(self.scroll_handle.clone())
 592        .y_flipped(y_flipped)
 593        .with_width_from_item(widest_completion_ix)
 594        .with_sizing_behavior(ListSizingBehavior::Infer);
 595
 596        Popover::new().child(list).into_any_element()
 597    }
 598
 599    fn render_aside(
 600        &mut self,
 601        editor: &Editor,
 602        max_size: Size<Pixels>,
 603        window: &mut Window,
 604        cx: &mut Context<Editor>,
 605    ) -> Option<AnyElement> {
 606        if !self.show_completion_documentation {
 607            return None;
 608        }
 609
 610        let mat = &self.entries.borrow()[self.selected_item];
 611        let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
 612            .documentation
 613            .as_ref()?
 614        {
 615            CompletionDocumentation::MultiLinePlainText(text) => div().child(text.clone()),
 616            CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.is_empty() => {
 617                let markdown = self.markdown_element.get_or_insert_with(|| {
 618                    cx.new(|cx| {
 619                        let languages = editor
 620                            .workspace
 621                            .as_ref()
 622                            .and_then(|(workspace, _)| workspace.upgrade())
 623                            .map(|workspace| workspace.read(cx).app_state().languages.clone());
 624                        let language = editor
 625                            .language_at(self.initial_position, cx)
 626                            .map(|l| l.name().to_proto());
 627                        Markdown::new(
 628                            SharedString::default(),
 629                            hover_markdown_style(window, cx),
 630                            languages,
 631                            language,
 632                            cx,
 633                        )
 634                        .copy_code_block_buttons(false)
 635                        .open_url(open_markdown_url)
 636                    })
 637                });
 638                markdown.update(cx, |markdown, cx| {
 639                    markdown.reset(parsed.clone(), cx);
 640                });
 641                div().child(markdown.clone())
 642            }
 643            CompletionDocumentation::MultiLineMarkdown(_) => return None,
 644            CompletionDocumentation::SingleLine(_) => return None,
 645            CompletionDocumentation::Undocumented => return None,
 646        };
 647
 648        Some(
 649            Popover::new()
 650                .child(
 651                    multiline_docs
 652                        .id("multiline_docs")
 653                        .px(MENU_ASIDE_X_PADDING / 2.)
 654                        .max_w(max_size.width)
 655                        .max_h(max_size.height)
 656                        .overflow_y_scroll()
 657                        .occlude(),
 658                )
 659                .into_any_element(),
 660        )
 661    }
 662
 663    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 664        let mut matches = if let Some(query) = query {
 665            fuzzy::match_strings(
 666                &self.match_candidates,
 667                query,
 668                query.chars().any(|c| c.is_uppercase()),
 669                100,
 670                &Default::default(),
 671                executor,
 672            )
 673            .await
 674        } else {
 675            self.match_candidates
 676                .iter()
 677                .enumerate()
 678                .map(|(candidate_id, candidate)| StringMatch {
 679                    candidate_id,
 680                    score: Default::default(),
 681                    positions: Default::default(),
 682                    string: candidate.string.clone(),
 683                })
 684                .collect()
 685        };
 686
 687        let mut additional_matches = Vec::new();
 688        // Deprioritize all candidates where the query's start does not match the start of any word in the candidate
 689        if let Some(query) = query {
 690            if let Some(query_start) = query.chars().next() {
 691                let (primary, secondary) = matches.into_iter().partition(|string_match| {
 692                    split_words(&string_match.string).any(|word| {
 693                        // Check that the first codepoint of the word as lowercase matches the first
 694                        // codepoint of the query as lowercase
 695                        word.chars()
 696                            .flat_map(|codepoint| codepoint.to_lowercase())
 697                            .zip(query_start.to_lowercase())
 698                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 699                    })
 700                });
 701                matches = primary;
 702                additional_matches = secondary;
 703            }
 704        }
 705
 706        let completions = self.completions.borrow_mut();
 707        if self.sort_completions {
 708            matches.sort_unstable_by_key(|mat| {
 709                // We do want to strike a balance here between what the language server tells us
 710                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 711                // `Creat` and there is a local variable called `CreateComponent`).
 712                // So what we do is: we bucket all matches into two buckets
 713                // - Strong matches
 714                // - Weak matches
 715                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 716                // and the Weak matches are the rest.
 717                //
 718                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 719                // matches, we prefer language-server sort_text first.
 720                //
 721                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 722                // Rest of the matches(weak) can be sorted as language-server expects.
 723
 724                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 725                enum MatchScore<'a> {
 726                    Strong {
 727                        score: Reverse<OrderedFloat<f64>>,
 728                        sort_text: Option<&'a str>,
 729                        sort_key: (usize, &'a str),
 730                    },
 731                    Weak {
 732                        sort_text: Option<&'a str>,
 733                        score: Reverse<OrderedFloat<f64>>,
 734                        sort_key: (usize, &'a str),
 735                    },
 736                }
 737
 738                let completion = &completions[mat.candidate_id];
 739                let sort_key = completion.sort_key();
 740                let sort_text =
 741                    if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
 742                        lsp_completion.sort_text.as_deref()
 743                    } else {
 744                        None
 745                    };
 746                let score = Reverse(OrderedFloat(mat.score));
 747
 748                if mat.score >= 0.2 {
 749                    MatchScore::Strong {
 750                        score,
 751                        sort_text,
 752                        sort_key,
 753                    }
 754                } else {
 755                    MatchScore::Weak {
 756                        sort_text,
 757                        score,
 758                        sort_key,
 759                    }
 760                }
 761            });
 762        }
 763        drop(completions);
 764
 765        matches.extend(additional_matches);
 766
 767        *self.entries.borrow_mut() = matches;
 768        self.selected_item = 0;
 769        // This keeps the display consistent when y_flipped.
 770        self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
 771    }
 772}
 773
 774#[derive(Clone)]
 775pub struct AvailableCodeAction {
 776    pub excerpt_id: ExcerptId,
 777    pub action: CodeAction,
 778    pub provider: Rc<dyn CodeActionProvider>,
 779}
 780
 781#[derive(Clone)]
 782pub struct CodeActionContents {
 783    pub tasks: Option<Rc<ResolvedTasks>>,
 784    pub actions: Option<Rc<[AvailableCodeAction]>>,
 785}
 786
 787impl CodeActionContents {
 788    fn len(&self) -> usize {
 789        match (&self.tasks, &self.actions) {
 790            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 791            (Some(tasks), None) => tasks.templates.len(),
 792            (None, Some(actions)) => actions.len(),
 793            (None, None) => 0,
 794        }
 795    }
 796
 797    fn is_empty(&self) -> bool {
 798        match (&self.tasks, &self.actions) {
 799            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 800            (Some(tasks), None) => tasks.templates.is_empty(),
 801            (None, Some(actions)) => actions.is_empty(),
 802            (None, None) => true,
 803        }
 804    }
 805
 806    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 807        self.tasks
 808            .iter()
 809            .flat_map(|tasks| {
 810                tasks
 811                    .templates
 812                    .iter()
 813                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 814            })
 815            .chain(self.actions.iter().flat_map(|actions| {
 816                actions.iter().map(|available| CodeActionsItem::CodeAction {
 817                    excerpt_id: available.excerpt_id,
 818                    action: available.action.clone(),
 819                    provider: available.provider.clone(),
 820                })
 821            }))
 822    }
 823
 824    pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
 825        match (&self.tasks, &self.actions) {
 826            (Some(tasks), Some(actions)) => {
 827                if index < tasks.templates.len() {
 828                    tasks
 829                        .templates
 830                        .get(index)
 831                        .cloned()
 832                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 833                } else {
 834                    actions.get(index - tasks.templates.len()).map(|available| {
 835                        CodeActionsItem::CodeAction {
 836                            excerpt_id: available.excerpt_id,
 837                            action: available.action.clone(),
 838                            provider: available.provider.clone(),
 839                        }
 840                    })
 841                }
 842            }
 843            (Some(tasks), None) => tasks
 844                .templates
 845                .get(index)
 846                .cloned()
 847                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 848            (None, Some(actions)) => {
 849                actions
 850                    .get(index)
 851                    .map(|available| CodeActionsItem::CodeAction {
 852                        excerpt_id: available.excerpt_id,
 853                        action: available.action.clone(),
 854                        provider: available.provider.clone(),
 855                    })
 856            }
 857            (None, None) => None,
 858        }
 859    }
 860}
 861
 862#[allow(clippy::large_enum_variant)]
 863#[derive(Clone)]
 864pub enum CodeActionsItem {
 865    Task(TaskSourceKind, ResolvedTask),
 866    CodeAction {
 867        excerpt_id: ExcerptId,
 868        action: CodeAction,
 869        provider: Rc<dyn CodeActionProvider>,
 870    },
 871}
 872
 873impl CodeActionsItem {
 874    fn as_task(&self) -> Option<&ResolvedTask> {
 875        let Self::Task(_, task) = self else {
 876            return None;
 877        };
 878        Some(task)
 879    }
 880
 881    fn as_code_action(&self) -> Option<&CodeAction> {
 882        let Self::CodeAction { action, .. } = self else {
 883            return None;
 884        };
 885        Some(action)
 886    }
 887
 888    pub fn label(&self) -> String {
 889        match self {
 890            Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
 891            Self::Task(_, task) => task.resolved_label.clone(),
 892        }
 893    }
 894}
 895
 896pub struct CodeActionsMenu {
 897    pub actions: CodeActionContents,
 898    pub buffer: Entity<Buffer>,
 899    pub selected_item: usize,
 900    pub scroll_handle: UniformListScrollHandle,
 901    pub deployed_from_indicator: Option<DisplayRow>,
 902}
 903
 904impl CodeActionsMenu {
 905    fn select_first(&mut self, cx: &mut Context<Editor>) {
 906        self.selected_item = if self.scroll_handle.y_flipped() {
 907            self.actions.len() - 1
 908        } else {
 909            0
 910        };
 911        self.scroll_handle
 912            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 913        cx.notify()
 914    }
 915
 916    fn select_last(&mut self, cx: &mut Context<Editor>) {
 917        self.selected_item = if self.scroll_handle.y_flipped() {
 918            0
 919        } else {
 920            self.actions.len() - 1
 921        };
 922        self.scroll_handle
 923            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 924        cx.notify()
 925    }
 926
 927    fn select_prev(&mut self, cx: &mut Context<Editor>) {
 928        self.selected_item = if self.scroll_handle.y_flipped() {
 929            self.next_match_index()
 930        } else {
 931            self.prev_match_index()
 932        };
 933        self.scroll_handle
 934            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 935        cx.notify();
 936    }
 937
 938    fn select_next(&mut self, cx: &mut Context<Editor>) {
 939        self.selected_item = if self.scroll_handle.y_flipped() {
 940            self.prev_match_index()
 941        } else {
 942            self.next_match_index()
 943        };
 944        self.scroll_handle
 945            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 946        cx.notify();
 947    }
 948
 949    fn prev_match_index(&self) -> usize {
 950        if self.selected_item > 0 {
 951            self.selected_item - 1
 952        } else {
 953            self.actions.len() - 1
 954        }
 955    }
 956
 957    fn next_match_index(&self) -> usize {
 958        if self.selected_item + 1 < self.actions.len() {
 959            self.selected_item + 1
 960        } else {
 961            0
 962        }
 963    }
 964
 965    fn visible(&self) -> bool {
 966        !self.actions.is_empty()
 967    }
 968
 969    fn origin(&self) -> ContextMenuOrigin {
 970        if let Some(row) = self.deployed_from_indicator {
 971            ContextMenuOrigin::GutterIndicator(row)
 972        } else {
 973            ContextMenuOrigin::Cursor
 974        }
 975    }
 976
 977    fn render(
 978        &self,
 979        _style: &EditorStyle,
 980        max_height_in_lines: u32,
 981        y_flipped: bool,
 982        window: &mut Window,
 983        cx: &mut Context<Editor>,
 984    ) -> AnyElement {
 985        let actions = self.actions.clone();
 986        let selected_item = self.selected_item;
 987        let list = uniform_list(
 988            cx.entity().clone(),
 989            "code_actions_menu",
 990            self.actions.len(),
 991            move |_this, range, _, cx| {
 992                actions
 993                    .iter()
 994                    .skip(range.start)
 995                    .take(range.end - range.start)
 996                    .filter(|action| {
 997                        if action
 998                            .as_task()
 999                            .map(|task| matches!(task.task_type(), task::TaskType::Debug(_)))
1000                            .unwrap_or(false)
1001                        {
1002                            cx.has_flag::<Debugger>()
1003                        } else {
1004                            true
1005                        }
1006                    })
1007                    .enumerate()
1008                    .map(|(ix, action)| {
1009                        let item_ix = range.start + ix;
1010                        let selected = item_ix == selected_item;
1011                        let colors = cx.theme().colors();
1012                        div().min_w(px(220.)).max_w(px(540.)).child(
1013                            ListItem::new(item_ix)
1014                                .inset(true)
1015                                .toggle_state(selected)
1016                                .when_some(action.as_code_action(), |this, action| {
1017                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1018                                        cx.stop_propagation();
1019                                        if let Some(task) = editor.confirm_code_action(
1020                                            &ConfirmCodeAction {
1021                                                item_ix: Some(item_ix),
1022                                            },
1023                                            window,
1024                                            cx,
1025                                        ) {
1026                                            task.detach_and_log_err(cx)
1027                                        }
1028                                    }))
1029                                    .child(
1030                                        h_flex()
1031                                            .overflow_hidden()
1032                                            .child(
1033                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1034                                                action.lsp_action.title().replace("\n", ""),
1035                                            )
1036                                            .when(selected, |this| {
1037                                                this.text_color(colors.text_accent)
1038                                            }),
1039                                    )
1040                                })
1041                                .when_some(action.as_task(), |this, task| {
1042                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1043                                        cx.stop_propagation();
1044                                        if let Some(task) = editor.confirm_code_action(
1045                                            &ConfirmCodeAction {
1046                                                item_ix: Some(item_ix),
1047                                            },
1048                                            window,
1049                                            cx,
1050                                        ) {
1051                                            task.detach_and_log_err(cx)
1052                                        }
1053                                    }))
1054                                    .child(
1055                                        h_flex()
1056                                            .overflow_hidden()
1057                                            .child(task.resolved_label.replace("\n", ""))
1058                                            .when(selected, |this| {
1059                                                this.text_color(colors.text_accent)
1060                                            }),
1061                                    )
1062                                }),
1063                        )
1064                    })
1065                    .collect()
1066            },
1067        )
1068        .occlude()
1069        .max_h(max_height_in_lines as f32 * window.line_height())
1070        .track_scroll(self.scroll_handle.clone())
1071        .y_flipped(y_flipped)
1072        .with_width_from_item(
1073            self.actions
1074                .iter()
1075                .enumerate()
1076                .max_by_key(|(_, action)| match action {
1077                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1078                    CodeActionsItem::CodeAction { action, .. } => {
1079                        action.lsp_action.title().chars().count()
1080                    }
1081                })
1082                .map(|(ix, _)| ix),
1083        )
1084        .with_sizing_behavior(ListSizingBehavior::Infer);
1085
1086        Popover::new().child(list).into_any_element()
1087    }
1088}