code_context_menus.rs

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