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        window: &mut Window,
 130        cx: &mut Context<Editor>,
 131    ) -> AnyElement {
 132        match self {
 133            CodeContextMenu::Completions(menu) => {
 134                menu.render(style, max_height_in_lines, window, cx)
 135            }
 136            CodeContextMenu::CodeActions(menu) => {
 137                menu.render(style, max_height_in_lines, window, cx)
 138            }
 139        }
 140    }
 141
 142    pub fn render_aside(
 143        &mut self,
 144        editor: &Editor,
 145        max_size: Size<Pixels>,
 146        window: &mut Window,
 147        cx: &mut Context<Editor>,
 148    ) -> Option<AnyElement> {
 149        match self {
 150            CodeContextMenu::Completions(menu) => menu.render_aside(editor, max_size, window, cx),
 151            CodeContextMenu::CodeActions(_) => None,
 152        }
 153    }
 154
 155    pub fn focused(&self, window: &mut Window, cx: &mut Context<Editor>) -> bool {
 156        match self {
 157            CodeContextMenu::Completions(completions_menu) => completions_menu
 158                .markdown_element
 159                .as_ref()
 160                .is_some_and(|markdown| markdown.focus_handle(cx).contains_focused(window, cx)),
 161            CodeContextMenu::CodeActions(_) => false,
 162        }
 163    }
 164}
 165
 166pub enum ContextMenuOrigin {
 167    Cursor,
 168    GutterIndicator(DisplayRow),
 169}
 170
 171#[derive(Clone, Debug)]
 172pub struct CompletionsMenu {
 173    pub id: CompletionId,
 174    sort_completions: bool,
 175    pub initial_position: Anchor,
 176    pub buffer: Entity<Buffer>,
 177    pub completions: Rc<RefCell<Box<[Completion]>>>,
 178    match_candidates: Rc<[StringMatchCandidate]>,
 179    pub entries: Rc<RefCell<Vec<StringMatch>>>,
 180    pub selected_item: usize,
 181    scroll_handle: UniformListScrollHandle,
 182    resolve_completions: bool,
 183    show_completion_documentation: bool,
 184    pub(super) ignore_completion_provider: bool,
 185    last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
 186    markdown_element: Option<Entity<Markdown>>,
 187}
 188
 189impl CompletionsMenu {
 190    pub fn new(
 191        id: CompletionId,
 192        sort_completions: bool,
 193        show_completion_documentation: bool,
 194        ignore_completion_provider: bool,
 195        initial_position: Anchor,
 196        buffer: Entity<Buffer>,
 197        completions: Box<[Completion]>,
 198    ) -> Self {
 199        let match_candidates = completions
 200            .iter()
 201            .enumerate()
 202            .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
 203            .collect();
 204
 205        Self {
 206            id,
 207            sort_completions,
 208            initial_position,
 209            buffer,
 210            show_completion_documentation,
 211            ignore_completion_provider,
 212            completions: RefCell::new(completions).into(),
 213            match_candidates,
 214            entries: RefCell::new(Vec::new()).into(),
 215            selected_item: 0,
 216            scroll_handle: UniformListScrollHandle::new(),
 217            resolve_completions: true,
 218            last_rendered_range: RefCell::new(None).into(),
 219            markdown_element: None,
 220        }
 221    }
 222
 223    pub fn new_snippet_choices(
 224        id: CompletionId,
 225        sort_completions: bool,
 226        choices: &Vec<String>,
 227        selection: Range<Anchor>,
 228        buffer: Entity<Buffer>,
 229    ) -> Self {
 230        let completions = choices
 231            .iter()
 232            .map(|choice| Completion {
 233                old_range: selection.start.text_anchor..selection.end.text_anchor,
 234                new_text: choice.to_string(),
 235                label: CodeLabel {
 236                    text: choice.to_string(),
 237                    runs: Default::default(),
 238                    filter_range: Default::default(),
 239                },
 240                icon_path: None,
 241                documentation: None,
 242                confirm: None,
 243                source: CompletionSource::Custom,
 244            })
 245            .collect();
 246
 247        let match_candidates = choices
 248            .iter()
 249            .enumerate()
 250            .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
 251            .collect();
 252        let entries = choices
 253            .iter()
 254            .enumerate()
 255            .map(|(id, completion)| StringMatch {
 256                candidate_id: id,
 257                score: 1.,
 258                positions: vec![],
 259                string: completion.clone(),
 260            })
 261            .collect::<Vec<_>>();
 262        Self {
 263            id,
 264            sort_completions,
 265            initial_position: selection.start,
 266            buffer,
 267            completions: RefCell::new(completions).into(),
 268            match_candidates,
 269            entries: RefCell::new(entries).into(),
 270            selected_item: 0,
 271            scroll_handle: UniformListScrollHandle::new(),
 272            resolve_completions: false,
 273            show_completion_documentation: false,
 274            ignore_completion_provider: false,
 275            last_rendered_range: RefCell::new(None).into(),
 276            markdown_element: None,
 277        }
 278    }
 279
 280    fn select_first(
 281        &mut self,
 282        provider: Option<&dyn CompletionProvider>,
 283        cx: &mut Context<Editor>,
 284    ) {
 285        let index = if self.scroll_handle.y_flipped() {
 286            self.entries.borrow().len() - 1
 287        } else {
 288            0
 289        };
 290        self.update_selection_index(index, provider, cx);
 291    }
 292
 293    fn select_last(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
 294        let index = if self.scroll_handle.y_flipped() {
 295            0
 296        } else {
 297            self.entries.borrow().len() - 1
 298        };
 299        self.update_selection_index(index, provider, cx);
 300    }
 301
 302    fn select_prev(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
 303        let index = if self.scroll_handle.y_flipped() {
 304            self.next_match_index()
 305        } else {
 306            self.prev_match_index()
 307        };
 308        self.update_selection_index(index, provider, cx);
 309    }
 310
 311    fn select_next(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
 312        let index = if self.scroll_handle.y_flipped() {
 313            self.prev_match_index()
 314        } else {
 315            self.next_match_index()
 316        };
 317        self.update_selection_index(index, provider, cx);
 318    }
 319
 320    fn update_selection_index(
 321        &mut self,
 322        match_index: usize,
 323        provider: Option<&dyn CompletionProvider>,
 324        cx: &mut Context<Editor>,
 325    ) {
 326        if self.selected_item != match_index {
 327            self.selected_item = match_index;
 328            self.scroll_handle
 329                .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 330            self.resolve_visible_completions(provider, cx);
 331            cx.notify();
 332        }
 333    }
 334
 335    fn prev_match_index(&self) -> usize {
 336        if self.selected_item > 0 {
 337            self.selected_item - 1
 338        } else {
 339            self.entries.borrow().len() - 1
 340        }
 341    }
 342
 343    fn next_match_index(&self) -> usize {
 344        if self.selected_item + 1 < self.entries.borrow().len() {
 345            self.selected_item + 1
 346        } else {
 347            0
 348        }
 349    }
 350
 351    pub fn resolve_visible_completions(
 352        &mut self,
 353        provider: Option<&dyn CompletionProvider>,
 354        cx: &mut Context<Editor>,
 355    ) {
 356        if !self.resolve_completions {
 357            return;
 358        }
 359        let Some(provider) = provider else {
 360            return;
 361        };
 362
 363        // Attempt to resolve completions for every item that will be displayed. This matters
 364        // because single line documentation may be displayed inline with the completion.
 365        //
 366        // When navigating to the very beginning or end of completions, `last_rendered_range` may
 367        // have no overlap with the completions that will be displayed, so instead use a range based
 368        // on the last rendered count.
 369        const APPROXIMATE_VISIBLE_COUNT: usize = 12;
 370        let last_rendered_range = self.last_rendered_range.borrow().clone();
 371        let visible_count = last_rendered_range
 372            .clone()
 373            .map_or(APPROXIMATE_VISIBLE_COUNT, |range| range.count());
 374        let entries = self.entries.borrow();
 375        let entry_range = if self.selected_item == 0 {
 376            0..min(visible_count, entries.len())
 377        } else if self.selected_item == entries.len() - 1 {
 378            entries.len().saturating_sub(visible_count)..entries.len()
 379        } else {
 380            last_rendered_range.map_or(0..0, |range| {
 381                min(range.start, entries.len())..min(range.end, entries.len())
 382            })
 383        };
 384
 385        // Expand the range to resolve more completions than are predicted to be visible, to reduce
 386        // jank on navigation.
 387        const EXTRA_TO_RESOLVE: usize = 4;
 388        let entry_indices = util::iterate_expanded_and_wrapped_usize_range(
 389            entry_range.clone(),
 390            EXTRA_TO_RESOLVE,
 391            EXTRA_TO_RESOLVE,
 392            entries.len(),
 393        );
 394
 395        // Avoid work by sometimes filtering out completions that already have documentation.
 396        // This filtering doesn't happen if the completions are currently being updated.
 397        let completions = self.completions.borrow();
 398        let candidate_ids = entry_indices
 399            .map(|i| entries[i].candidate_id)
 400            .filter(|i| completions[*i].documentation.is_none());
 401
 402        // Current selection is always resolved even if it already has documentation, to handle
 403        // out-of-spec language servers that return more results later.
 404        let selected_candidate_id = entries[self.selected_item].candidate_id;
 405        let candidate_ids = iter::once(selected_candidate_id)
 406            .chain(candidate_ids.filter(|id| *id != selected_candidate_id))
 407            .collect::<Vec<usize>>();
 408        drop(entries);
 409
 410        if candidate_ids.is_empty() {
 411            return;
 412        }
 413
 414        let resolve_task = provider.resolve_completions(
 415            self.buffer.clone(),
 416            candidate_ids,
 417            self.completions.clone(),
 418            cx,
 419        );
 420
 421        cx.spawn(async move |editor, cx| {
 422            if let Some(true) = resolve_task.await.log_err() {
 423                editor.update(cx, |_, cx| cx.notify()).ok();
 424            }
 425        })
 426        .detach();
 427    }
 428
 429    pub fn visible(&self) -> bool {
 430        !self.entries.borrow().is_empty()
 431    }
 432
 433    fn origin(&self) -> ContextMenuOrigin {
 434        ContextMenuOrigin::Cursor
 435    }
 436
 437    fn render(
 438        &self,
 439        style: &EditorStyle,
 440        max_height_in_lines: u32,
 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        .with_width_from_item(widest_completion_ix)
 591        .with_sizing_behavior(ListSizingBehavior::Infer);
 592
 593        Popover::new().child(list).into_any_element()
 594    }
 595
 596    fn render_aside(
 597        &mut self,
 598        editor: &Editor,
 599        max_size: Size<Pixels>,
 600        window: &mut Window,
 601        cx: &mut Context<Editor>,
 602    ) -> Option<AnyElement> {
 603        if !self.show_completion_documentation {
 604            return None;
 605        }
 606
 607        let mat = &self.entries.borrow()[self.selected_item];
 608        let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
 609            .documentation
 610            .as_ref()?
 611        {
 612            CompletionDocumentation::MultiLinePlainText(text) => div().child(text.clone()),
 613            CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.is_empty() => {
 614                let markdown = self.markdown_element.get_or_insert_with(|| {
 615                    cx.new(|cx| {
 616                        let languages = editor
 617                            .workspace
 618                            .as_ref()
 619                            .and_then(|(workspace, _)| workspace.upgrade())
 620                            .map(|workspace| workspace.read(cx).app_state().languages.clone());
 621                        let language = editor
 622                            .language_at(self.initial_position, cx)
 623                            .map(|l| l.name().to_proto());
 624                        Markdown::new(
 625                            SharedString::default(),
 626                            hover_markdown_style(window, cx),
 627                            languages,
 628                            language,
 629                            cx,
 630                        )
 631                        .copy_code_block_buttons(false)
 632                        .open_url(open_markdown_url)
 633                    })
 634                });
 635                markdown.update(cx, |markdown, cx| {
 636                    markdown.reset(parsed.clone(), cx);
 637                });
 638                div().child(markdown.clone())
 639            }
 640            CompletionDocumentation::MultiLineMarkdown(_) => return None,
 641            CompletionDocumentation::SingleLine(_) => return None,
 642            CompletionDocumentation::Undocumented => return None,
 643        };
 644
 645        Some(
 646            Popover::new()
 647                .child(
 648                    multiline_docs
 649                        .id("multiline_docs")
 650                        .px(MENU_ASIDE_X_PADDING / 2.)
 651                        .max_w(max_size.width)
 652                        .max_h(max_size.height)
 653                        .overflow_y_scroll()
 654                        .occlude(),
 655                )
 656                .into_any_element(),
 657        )
 658    }
 659
 660    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 661        let mut matches = if let Some(query) = query {
 662            fuzzy::match_strings(
 663                &self.match_candidates,
 664                query,
 665                query.chars().any(|c| c.is_uppercase()),
 666                100,
 667                &Default::default(),
 668                executor,
 669            )
 670            .await
 671        } else {
 672            self.match_candidates
 673                .iter()
 674                .enumerate()
 675                .map(|(candidate_id, candidate)| StringMatch {
 676                    candidate_id,
 677                    score: Default::default(),
 678                    positions: Default::default(),
 679                    string: candidate.string.clone(),
 680                })
 681                .collect()
 682        };
 683
 684        let mut additional_matches = Vec::new();
 685        // Deprioritize all candidates where the query's start does not match the start of any word in the candidate
 686        if let Some(query) = query {
 687            if let Some(query_start) = query.chars().next() {
 688                let (primary, secondary) = matches.into_iter().partition(|string_match| {
 689                    split_words(&string_match.string).any(|word| {
 690                        // Check that the first codepoint of the word as lowercase matches the first
 691                        // codepoint of the query as lowercase
 692                        word.chars()
 693                            .flat_map(|codepoint| codepoint.to_lowercase())
 694                            .zip(query_start.to_lowercase())
 695                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 696                    })
 697                });
 698                matches = primary;
 699                additional_matches = secondary;
 700            }
 701        }
 702
 703        let completions = self.completions.borrow_mut();
 704        if self.sort_completions {
 705            matches.sort_unstable_by_key(|mat| {
 706                // We do want to strike a balance here between what the language server tells us
 707                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 708                // `Creat` and there is a local variable called `CreateComponent`).
 709                // So what we do is: we bucket all matches into two buckets
 710                // - Strong matches
 711                // - Weak matches
 712                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 713                // and the Weak matches are the rest.
 714                //
 715                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 716                // matches, we prefer language-server sort_text first.
 717                //
 718                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 719                // Rest of the matches(weak) can be sorted as language-server expects.
 720
 721                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 722                enum MatchScore<'a> {
 723                    Strong {
 724                        score: Reverse<OrderedFloat<f64>>,
 725                        sort_text: Option<&'a str>,
 726                        sort_key: (usize, &'a str),
 727                    },
 728                    Weak {
 729                        sort_text: Option<&'a str>,
 730                        score: Reverse<OrderedFloat<f64>>,
 731                        sort_key: (usize, &'a str),
 732                    },
 733                }
 734
 735                let completion = &completions[mat.candidate_id];
 736                let sort_key = completion.sort_key();
 737                let sort_text =
 738                    if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
 739                        lsp_completion.sort_text.as_deref()
 740                    } else {
 741                        None
 742                    };
 743                let score = Reverse(OrderedFloat(mat.score));
 744
 745                if mat.score >= 0.2 {
 746                    MatchScore::Strong {
 747                        score,
 748                        sort_text,
 749                        sort_key,
 750                    }
 751                } else {
 752                    MatchScore::Weak {
 753                        sort_text,
 754                        score,
 755                        sort_key,
 756                    }
 757                }
 758            });
 759        }
 760        drop(completions);
 761
 762        matches.extend(additional_matches);
 763
 764        *self.entries.borrow_mut() = matches;
 765        self.selected_item = 0;
 766        // This keeps the display consistent when y_flipped.
 767        self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
 768    }
 769}
 770
 771#[derive(Clone)]
 772pub struct AvailableCodeAction {
 773    pub excerpt_id: ExcerptId,
 774    pub action: CodeAction,
 775    pub provider: Rc<dyn CodeActionProvider>,
 776}
 777
 778#[derive(Clone)]
 779pub struct CodeActionContents {
 780    pub tasks: Option<Rc<ResolvedTasks>>,
 781    pub actions: Option<Rc<[AvailableCodeAction]>>,
 782}
 783
 784impl CodeActionContents {
 785    fn len(&self) -> usize {
 786        match (&self.tasks, &self.actions) {
 787            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 788            (Some(tasks), None) => tasks.templates.len(),
 789            (None, Some(actions)) => actions.len(),
 790            (None, None) => 0,
 791        }
 792    }
 793
 794    fn is_empty(&self) -> bool {
 795        match (&self.tasks, &self.actions) {
 796            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 797            (Some(tasks), None) => tasks.templates.is_empty(),
 798            (None, Some(actions)) => actions.is_empty(),
 799            (None, None) => true,
 800        }
 801    }
 802
 803    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 804        self.tasks
 805            .iter()
 806            .flat_map(|tasks| {
 807                tasks
 808                    .templates
 809                    .iter()
 810                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 811            })
 812            .chain(self.actions.iter().flat_map(|actions| {
 813                actions.iter().map(|available| CodeActionsItem::CodeAction {
 814                    excerpt_id: available.excerpt_id,
 815                    action: available.action.clone(),
 816                    provider: available.provider.clone(),
 817                })
 818            }))
 819    }
 820
 821    pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
 822        match (&self.tasks, &self.actions) {
 823            (Some(tasks), Some(actions)) => {
 824                if index < tasks.templates.len() {
 825                    tasks
 826                        .templates
 827                        .get(index)
 828                        .cloned()
 829                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 830                } else {
 831                    actions.get(index - tasks.templates.len()).map(|available| {
 832                        CodeActionsItem::CodeAction {
 833                            excerpt_id: available.excerpt_id,
 834                            action: available.action.clone(),
 835                            provider: available.provider.clone(),
 836                        }
 837                    })
 838                }
 839            }
 840            (Some(tasks), None) => tasks
 841                .templates
 842                .get(index)
 843                .cloned()
 844                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 845            (None, Some(actions)) => {
 846                actions
 847                    .get(index)
 848                    .map(|available| CodeActionsItem::CodeAction {
 849                        excerpt_id: available.excerpt_id,
 850                        action: available.action.clone(),
 851                        provider: available.provider.clone(),
 852                    })
 853            }
 854            (None, None) => None,
 855        }
 856    }
 857}
 858
 859#[allow(clippy::large_enum_variant)]
 860#[derive(Clone)]
 861pub enum CodeActionsItem {
 862    Task(TaskSourceKind, ResolvedTask),
 863    CodeAction {
 864        excerpt_id: ExcerptId,
 865        action: CodeAction,
 866        provider: Rc<dyn CodeActionProvider>,
 867    },
 868}
 869
 870impl CodeActionsItem {
 871    fn as_task(&self) -> Option<&ResolvedTask> {
 872        let Self::Task(_, task) = self else {
 873            return None;
 874        };
 875        Some(task)
 876    }
 877
 878    fn as_code_action(&self) -> Option<&CodeAction> {
 879        let Self::CodeAction { action, .. } = self else {
 880            return None;
 881        };
 882        Some(action)
 883    }
 884
 885    pub fn label(&self) -> String {
 886        match self {
 887            Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
 888            Self::Task(_, task) => task.resolved_label.clone(),
 889        }
 890    }
 891}
 892
 893pub struct CodeActionsMenu {
 894    pub actions: CodeActionContents,
 895    pub buffer: Entity<Buffer>,
 896    pub selected_item: usize,
 897    pub scroll_handle: UniformListScrollHandle,
 898    pub deployed_from_indicator: Option<DisplayRow>,
 899}
 900
 901impl CodeActionsMenu {
 902    fn select_first(&mut self, cx: &mut Context<Editor>) {
 903        self.selected_item = if self.scroll_handle.y_flipped() {
 904            self.actions.len() - 1
 905        } else {
 906            0
 907        };
 908        self.scroll_handle
 909            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 910        cx.notify()
 911    }
 912
 913    fn select_last(&mut self, cx: &mut Context<Editor>) {
 914        self.selected_item = if self.scroll_handle.y_flipped() {
 915            0
 916        } else {
 917            self.actions.len() - 1
 918        };
 919        self.scroll_handle
 920            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 921        cx.notify()
 922    }
 923
 924    fn select_prev(&mut self, cx: &mut Context<Editor>) {
 925        self.selected_item = if self.scroll_handle.y_flipped() {
 926            self.next_match_index()
 927        } else {
 928            self.prev_match_index()
 929        };
 930        self.scroll_handle
 931            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 932        cx.notify();
 933    }
 934
 935    fn select_next(&mut self, cx: &mut Context<Editor>) {
 936        self.selected_item = if self.scroll_handle.y_flipped() {
 937            self.prev_match_index()
 938        } else {
 939            self.next_match_index()
 940        };
 941        self.scroll_handle
 942            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 943        cx.notify();
 944    }
 945
 946    fn prev_match_index(&self) -> usize {
 947        if self.selected_item > 0 {
 948            self.selected_item - 1
 949        } else {
 950            self.actions.len() - 1
 951        }
 952    }
 953
 954    fn next_match_index(&self) -> usize {
 955        if self.selected_item + 1 < self.actions.len() {
 956            self.selected_item + 1
 957        } else {
 958            0
 959        }
 960    }
 961
 962    fn visible(&self) -> bool {
 963        !self.actions.is_empty()
 964    }
 965
 966    fn origin(&self) -> ContextMenuOrigin {
 967        if let Some(row) = self.deployed_from_indicator {
 968            ContextMenuOrigin::GutterIndicator(row)
 969        } else {
 970            ContextMenuOrigin::Cursor
 971        }
 972    }
 973
 974    fn render(
 975        &self,
 976        _style: &EditorStyle,
 977        max_height_in_lines: u32,
 978        window: &mut Window,
 979        cx: &mut Context<Editor>,
 980    ) -> AnyElement {
 981        let actions = self.actions.clone();
 982        let selected_item = self.selected_item;
 983        let list = uniform_list(
 984            cx.entity().clone(),
 985            "code_actions_menu",
 986            self.actions.len(),
 987            move |_this, range, _, cx| {
 988                actions
 989                    .iter()
 990                    .skip(range.start)
 991                    .take(range.end - range.start)
 992                    .filter(|action| {
 993                        if action
 994                            .as_task()
 995                            .map(|task| matches!(task.task_type(), task::TaskType::Debug(_)))
 996                            .unwrap_or(false)
 997                        {
 998                            cx.has_flag::<Debugger>()
 999                        } else {
1000                            true
1001                        }
1002                    })
1003                    .enumerate()
1004                    .map(|(ix, action)| {
1005                        let item_ix = range.start + ix;
1006                        let selected = item_ix == selected_item;
1007                        let colors = cx.theme().colors();
1008                        div().min_w(px(220.)).max_w(px(540.)).child(
1009                            ListItem::new(item_ix)
1010                                .inset(true)
1011                                .toggle_state(selected)
1012                                .when_some(action.as_code_action(), |this, action| {
1013                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1014                                        cx.stop_propagation();
1015                                        if let Some(task) = editor.confirm_code_action(
1016                                            &ConfirmCodeAction {
1017                                                item_ix: Some(item_ix),
1018                                            },
1019                                            window,
1020                                            cx,
1021                                        ) {
1022                                            task.detach_and_log_err(cx)
1023                                        }
1024                                    }))
1025                                    .child(
1026                                        h_flex()
1027                                            .overflow_hidden()
1028                                            .child(
1029                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1030                                                action.lsp_action.title().replace("\n", ""),
1031                                            )
1032                                            .when(selected, |this| {
1033                                                this.text_color(colors.text_accent)
1034                                            }),
1035                                    )
1036                                })
1037                                .when_some(action.as_task(), |this, task| {
1038                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1039                                        cx.stop_propagation();
1040                                        if let Some(task) = editor.confirm_code_action(
1041                                            &ConfirmCodeAction {
1042                                                item_ix: Some(item_ix),
1043                                            },
1044                                            window,
1045                                            cx,
1046                                        ) {
1047                                            task.detach_and_log_err(cx)
1048                                        }
1049                                    }))
1050                                    .child(
1051                                        h_flex()
1052                                            .overflow_hidden()
1053                                            .child(task.resolved_label.replace("\n", ""))
1054                                            .when(selected, |this| {
1055                                                this.text_color(colors.text_accent)
1056                                            }),
1057                                    )
1058                                }),
1059                        )
1060                    })
1061                    .collect()
1062            },
1063        )
1064        .occlude()
1065        .max_h(max_height_in_lines as f32 * window.line_height())
1066        .track_scroll(self.scroll_handle.clone())
1067        .with_width_from_item(
1068            self.actions
1069                .iter()
1070                .enumerate()
1071                .max_by_key(|(_, action)| match action {
1072                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1073                    CodeActionsItem::CodeAction { action, .. } => {
1074                        action.lsp_action.title().chars().count()
1075                    }
1076                })
1077                .map(|(ix, _)| ix),
1078        )
1079        .with_sizing_behavior(ListSizingBehavior::Infer);
1080
1081        Popover::new().child(list).into_any_element()
1082    }
1083}