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