| 1 | use std::rc::Rc; |
| 2 | |
| 3 | use gpui::{ |
| 4 | Action, AnyElement, App, AppContext, Context, DismissEvent, Empty, Entity, EventEmitter, |
| 5 | Half as _, HighlightStyle, InteractiveElement as _, IntoElement, ParentElement, Pixels, Point, |
| 6 | Render, RenderOnce, SharedString, Styled, StyledText, Subscription, WeakEntity, Window, |
| 7 | deferred, div, prelude::FluentBuilder, px, relative, |
| 8 | }; |
| 9 | use lsp_types::CompletionItem; |
| 10 | |
| 11 | const MAX_MENU_HEIGHT: Pixels = px(240.); |
| 12 | const POPOVER_GAP: Pixels = px(4.); |
| 13 | |
| 14 | use crate::{ |
| 15 | ActiveTheme, IndexPath, Selectable, actions, h_flex, |
| 16 | input::{ |
| 17 | self, EditorState, |
| 18 | popovers::{editor_popover, render_markdown}, |
| 19 | }, |
| 20 | label::Label, |
| 21 | list::{List, ListDelegate, ListEvent, ListState}, |
| 22 | }; |
| 23 | |
| 24 | struct ContextMenuDelegate { |
| 25 | query: SharedString, |
| 26 | menu: Entity<CompletionMenu>, |
| 27 | items: Vec<Rc<CompletionItem>>, |
| 28 | selected_ix: usize, |
| 29 | } |
| 30 | |
| 31 | impl ContextMenuDelegate { |
| 32 | fn set_items(&mut self, items: Vec<CompletionItem>) { |
| 33 | self.items = items.into_iter().map(Rc::new).collect(); |
| 34 | self.selected_ix = 0; |
| 35 | } |
| 36 | |
| 37 | fn selected_item(&self) -> Option<&Rc<CompletionItem>> { |
| 38 | self.items.get(self.selected_ix) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | #[derive(IntoElement)] |
| 43 | struct CompletionMenuItem { |
| 44 | ix: usize, |
| 45 | item: Rc<CompletionItem>, |
| 46 | children: Vec<AnyElement>, |
| 47 | selected: bool, |
| 48 | highlight_prefix: SharedString, |
| 49 | } |
| 50 | |
| 51 | impl CompletionMenuItem { |
| 52 | fn new(ix: usize, item: Rc<CompletionItem>) -> Self { |
| 53 | Self { |
| 54 | ix, |
| 55 | item, |
| 56 | children: vec![], |
| 57 | selected: false, |
| 58 | highlight_prefix: "".into(), |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | fn highlight_prefix(mut self, s: impl Into<SharedString>) -> Self { |
| 63 | self.highlight_prefix = s.into(); |
| 64 | self |
| 65 | } |
| 66 | } |
| 67 | impl Selectable for CompletionMenuItem { |
| 68 | fn selected(mut self, selected: bool) -> Self { |
| 69 | self.selected = selected; |
| 70 | self |
| 71 | } |
| 72 | |
| 73 | fn is_selected(&self) -> bool { |
| 74 | self.selected |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | impl ParentElement for CompletionMenuItem { |
| 79 | fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { |
| 80 | self.children.extend(elements); |
| 81 | } |
| 82 | } |
| 83 | impl RenderOnce for CompletionMenuItem { |
| 84 | fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement { |
| 85 | let item = self.item; |
| 86 | |
| 87 | let deprecated = item.deprecated.unwrap_or(false); |
| 88 | let matched_len = item |
| 89 | .filter_text |
| 90 | .as_ref() |
| 91 | .map(|s| s.len()) |
| 92 | .unwrap_or(self.highlight_prefix.len()) |
| 93 | .min(item.label.len()); |
| 94 | |
| 95 | let highlights = vec![( |
| 96 | 0..matched_len, |
| 97 | HighlightStyle { |
| 98 | color: Some(cx.theme().blue), |
| 99 | ..Default::default() |
| 100 | }, |
| 101 | )]; |
| 102 | |
| 103 | h_flex() |
| 104 | .id(self.ix) |
| 105 | .gap_2() |
| 106 | .p_1() |
| 107 | .text_xs() |
| 108 | .line_height(relative(1.)) |
| 109 | .rounded(cx.theme().radius.half()) |
| 110 | .when(item.deprecated.unwrap_or(false), |this| this.line_through()) |
| 111 | .hover(|this| this.bg(cx.theme().accent.opacity(0.8))) |
| 112 | .when(self.selected, |this| { |
| 113 | this.bg(cx.theme().tokens.accent) |
| 114 | .text_color(cx.theme().accent_foreground) |
| 115 | }) |
| 116 | .child(div().child(StyledText::new(item.label.clone()).with_highlights(highlights))) |
| 117 | .when(item.detail.is_some(), |this| { |
| 118 | this.child( |
| 119 | Label::new(item.detail.as_deref().unwrap_or("").to_string()) |
| 120 | .text_color(cx.theme().muted_foreground) |
| 121 | .when(deprecated, |this| this.line_through()) |
| 122 | .italic(), |
| 123 | ) |
| 124 | }) |
| 125 | .children(self.children) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | impl EventEmitter<DismissEvent> for ContextMenuDelegate {} |
| 130 | |
| 131 | impl ListDelegate for ContextMenuDelegate { |
| 132 | type Item = CompletionMenuItem; |
| 133 | |
| 134 | fn items_count(&self, _: usize, _: &gpui::App) -> usize { |
| 135 | self.items.len() |
| 136 | } |
| 137 | |
| 138 | fn render_item( |
| 139 | &mut self, |
| 140 | ix: crate::IndexPath, |
| 141 | _: &mut Window, |
| 142 | _: &mut Context<ListState<Self>>, |
| 143 | ) -> Option<Self::Item> { |
| 144 | let item = self.items.get(ix.row)?; |
| 145 | Some(CompletionMenuItem::new(ix.row, item.clone()).highlight_prefix(self.query.clone())) |
| 146 | } |
| 147 | |
| 148 | fn set_selected_index( |
| 149 | &mut self, |
| 150 | ix: Option<crate::IndexPath>, |
| 151 | _: &mut Window, |
| 152 | cx: &mut Context<ListState<Self>>, |
| 153 | ) { |
| 154 | self.selected_ix = ix.map(|i| i.row).unwrap_or(0); |
| 155 | cx.notify(); |
| 156 | } |
| 157 | |
| 158 | fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context<ListState<Self>>) { |
| 159 | let Some(item) = self.selected_item() else { |
| 160 | return; |
| 161 | }; |
| 162 | |
| 163 | self.menu.update(cx, |this, cx| { |
| 164 | this.select_item(&item, window, cx); |
| 165 | }); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /// A context menu for code completions and code actions. |
| 170 | pub struct CompletionMenu { |
| 171 | offset: usize, |
| 172 | editor: WeakEntity<EditorState>, |
| 173 | list: Entity<ListState<ContextMenuDelegate>>, |
| 174 | open: bool, |
| 175 | |
| 176 | /// The offset of the first character that triggered the completion. |
| 177 | pub(crate) trigger_start_offset: Option<usize>, |
| 178 | query: SharedString, |
| 179 | _subscriptions: Vec<Subscription>, |
| 180 | } |
| 181 | |
| 182 | impl CompletionMenu { |
| 183 | /// Creates a new `CompletionMenu` with the given offset and completion items. |
| 184 | /// |
| 185 | /// NOTE: This element should not call from EditorState::new, unless that will stack overflow. |
| 186 | pub(crate) fn new( |
| 187 | editor: Entity<EditorState>, |
| 188 | window: &mut Window, |
| 189 | cx: &mut App, |
| 190 | ) -> Entity<Self> { |
| 191 | cx.new(|cx| { |
| 192 | let view = cx.entity(); |
| 193 | let menu = ContextMenuDelegate { |
| 194 | query: SharedString::default(), |
| 195 | menu: view, |
| 196 | items: vec![], |
| 197 | selected_ix: 0, |
| 198 | }; |
| 199 | |
| 200 | let list = cx.new(|cx| ListState::new(menu, window, cx)); |
| 201 | |
| 202 | let _subscriptions = |
| 203 | vec![ |
| 204 | cx.subscribe(&list, |this: &mut Self, _, ev: &ListEvent, cx| { |
| 205 | match ev { |
| 206 | ListEvent::Confirm(_) => { |
| 207 | this.dismiss(cx); |
| 208 | } |
| 209 | _ => {} |
| 210 | } |
| 211 | cx.notify(); |
| 212 | }), |
| 213 | ]; |
| 214 | |
| 215 | Self { |
| 216 | offset: 0, |
| 217 | editor: editor.downgrade(), |
| 218 | list, |
| 219 | open: false, |
| 220 | trigger_start_offset: None, |
| 221 | query: SharedString::default(), |
| 222 | _subscriptions, |
| 223 | } |
| 224 | }) |
| 225 | } |
| 226 | |
| 227 | fn select_item(&mut self, item: &CompletionItem, window: &mut Window, cx: &mut Context<Self>) { |
| 228 | let item = item.clone(); |
| 229 | let range = self.trigger_start_offset.unwrap_or(self.offset)..self.offset; |
| 230 | |
| 231 | let editor = self.editor.clone(); |
| 232 | |
| 233 | cx.spawn_in(window, async move |_, cx| { |
| 234 | editor.update_in(cx, |editor, window, cx| { |
| 235 | editor.insert_completion(&item, range, window, cx); |
| 236 | }) |
| 237 | }) |
| 238 | .detach(); |
| 239 | |
| 240 | self.dismiss(cx); |
| 241 | } |
| 242 | |
| 243 | pub(crate) fn handle_action( |
| 244 | &mut self, |
| 245 | action: Box<dyn Action>, |
| 246 | window: &mut Window, |
| 247 | cx: &mut Context<Self>, |
| 248 | ) -> bool { |
| 249 | if !self.open { |
| 250 | return false; |
| 251 | } |
| 252 | |
| 253 | cx.propagate(); |
| 254 | if input::Enter::is_primary(&*action) { |
| 255 | self.on_action_enter(window, cx); |
| 256 | } else if action.partial_eq(&input::Escape) { |
| 257 | self.on_action_escape(window, cx); |
| 258 | } else if action.partial_eq(&input::MoveUp) { |
| 259 | self.on_action_up(window, cx); |
| 260 | } else if action.partial_eq(&input::MoveDown) { |
| 261 | self.on_action_down(window, cx); |
| 262 | } else { |
| 263 | return false; |
| 264 | } |
| 265 | |
| 266 | true |
| 267 | } |
| 268 | |
| 269 | fn on_action_enter(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 270 | let Some(item) = self.list.read(cx).delegate().selected_item().cloned() else { |
| 271 | return; |
| 272 | }; |
| 273 | self.select_item(&item, window, cx); |
| 274 | } |
| 275 | |
| 276 | fn on_action_escape(&mut self, _: &mut Window, cx: &mut Context<Self>) { |
| 277 | self.dismiss(cx); |
| 278 | } |
| 279 | |
| 280 | fn on_action_up(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 281 | self.list.update(cx, |this, cx| { |
| 282 | this.on_action_select_prev(&actions::SelectUp, window, cx) |
| 283 | }); |
| 284 | } |
| 285 | |
| 286 | fn on_action_down(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 287 | self.list.update(cx, |this, cx| { |
| 288 | this.on_action_select_next(&actions::SelectDown, window, cx) |
| 289 | }); |
| 290 | } |
| 291 | |
| 292 | /// Synchronize a hidden editor menu without dismissing a newer response. |
| 293 | pub(crate) fn hide(&mut self, cx: &mut Context<Self>) { |
| 294 | self.open = false; |
| 295 | self.trigger_start_offset = None; |
| 296 | cx.notify(); |
| 297 | } |
| 298 | |
| 299 | /// Dismiss the menu in response to a user action. |
| 300 | fn dismiss(&mut self, cx: &mut Context<Self>) { |
| 301 | self.hide(cx); |
| 302 | let editor = self.editor.clone(); |
| 303 | cx.spawn(async move |_, cx| { |
| 304 | let _ = editor.update(cx, |editor, cx| editor.dismiss_completion_overlay(cx)); |
| 305 | }) |
| 306 | .detach(); |
| 307 | } |
| 308 | |
| 309 | /// Sets the trigger start offset if it is not already set. |
| 310 | pub(crate) fn update_query(&mut self, start_offset: usize, query: impl Into<SharedString>) { |
| 311 | if self.trigger_start_offset.is_none() { |
| 312 | self.trigger_start_offset = Some(start_offset); |
| 313 | } |
| 314 | self.query = query.into(); |
| 315 | } |
| 316 | |
| 317 | pub(crate) fn show( |
| 318 | &mut self, |
| 319 | offset: usize, |
| 320 | items: impl Into<Vec<CompletionItem>>, |
| 321 | window: &mut Window, |
| 322 | cx: &mut Context<Self>, |
| 323 | ) { |
| 324 | let items = items.into(); |
| 325 | self.offset = offset; |
| 326 | self.open = true; |
| 327 | self.list.update(cx, |this, cx| { |
| 328 | let longest_ix = items |
| 329 | .iter() |
| 330 | .enumerate() |
| 331 | .max_by_key(|(_, item)| { |
| 332 | item.label.len() + item.detail.as_ref().map(|d| d.len()).unwrap_or(0) |
| 333 | }) |
| 334 | .map(|(ix, _)| ix) |
| 335 | .unwrap_or(0); |
| 336 | |
| 337 | this.delegate_mut().query = self.query.clone(); |
| 338 | this.delegate_mut().set_items(items); |
| 339 | this.set_selected_index(Some(IndexPath::new(0)), window, cx); |
| 340 | this.set_item_to_measure_index(IndexPath::new(longest_ix), window, cx); |
| 341 | }); |
| 342 | |
| 343 | cx.notify(); |
| 344 | } |
| 345 | |
| 346 | fn origin(&self, cx: &App) -> Option<Point<Pixels>> { |
| 347 | let editor = self.editor.upgrade()?; |
| 348 | let editor = editor.read(cx); |
| 349 | let Some((cursor_bounds, line_height)) = editor.cursor_layout() else { |
| 350 | return None; |
| 351 | }; |
| 352 | let cursor_origin = cursor_bounds.origin; |
| 353 | |
| 354 | let scroll_origin = editor.scroll_offset(); |
| 355 | |
| 356 | Some( |
| 357 | scroll_origin + cursor_origin - editor.input_bounds().origin |
| 358 | + Point::new(-px(4.), line_height + px(4.)), |
| 359 | ) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | impl Render for CompletionMenu { |
| 364 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 365 | if !self.open { |
| 366 | return Empty.into_any_element(); |
| 367 | } |
| 368 | |
| 369 | if self.list.read(cx).delegate().items.is_empty() { |
| 370 | self.open = false; |
| 371 | return Empty.into_any_element(); |
| 372 | } |
| 373 | |
| 374 | let Some(pos) = self.origin(cx) else { |
| 375 | return Empty.into_any_element(); |
| 376 | }; |
| 377 | |
| 378 | let selected_documentation = self |
| 379 | .list |
| 380 | .read(cx) |
| 381 | .delegate() |
| 382 | .selected_item() |
| 383 | .and_then(|item| item.documentation.clone()); |
| 384 | |
| 385 | let Some(editor) = self.editor.upgrade() else { |
| 386 | return Empty.into_any_element(); |
| 387 | }; |
| 388 | let configured_max = editor.read(cx).lsp().completion_menu.max_width; |
| 389 | let max_width = configured_max.min(window.bounds().size.width - pos.x); |
| 390 | let abs_pos = editor.read(cx).input_bounds().origin + pos; |
| 391 | let vertical_layout = |
| 392 | abs_pos.x + configured_max + POPOVER_GAP + configured_max + POPOVER_GAP |
| 393 | > window.bounds().size.width; |
| 394 | |
| 395 | deferred( |
| 396 | div() |
| 397 | .absolute() |
| 398 | .left(pos.x) |
| 399 | .top(pos.y) |
| 400 | .flex() |
| 401 | .flex_row() |
| 402 | .gap(POPOVER_GAP) |
| 403 | .items_start() |
| 404 | .when(vertical_layout, |this| this.flex_col()) |
| 405 | .child( |
| 406 | editor_popover("completion-menu", cx) |
| 407 | .max_w(max_width) |
| 408 | .min_w(px(120.)) |
| 409 | .child(List::new(&self.list).max_h(MAX_MENU_HEIGHT)), |
| 410 | ) |
| 411 | .when_some(selected_documentation, |this, documentation| { |
| 412 | let mut doc = match documentation { |
| 413 | lsp_types::Documentation::String(s) => s.clone(), |
| 414 | lsp_types::Documentation::MarkupContent(mc) => mc.value.clone(), |
| 415 | }; |
| 416 | if vertical_layout { |
| 417 | doc = doc.split("\n").next().unwrap_or_default().to_string(); |
| 418 | } |
| 419 | |
| 420 | this.child( |
| 421 | div().child( |
| 422 | editor_popover("completion-menu", cx) |
| 423 | .w(configured_max) |
| 424 | .px_2() |
| 425 | .child(render_markdown("doc", doc, window, cx)), |
| 426 | ), |
| 427 | ) |
| 428 | }) |
| 429 | .on_mouse_down_out(cx.listener(|this, _, _, cx| { |
| 430 | this.dismiss(cx); |
| 431 | })), |
| 432 | ) |
| 433 | .into_any_element() |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | #[cfg(test)] |
| 438 | mod tests { |
| 439 | use super::*; |
| 440 | |
| 441 | #[gpui::test] |
| 442 | fn hiding_an_old_menu_does_not_dismiss_a_new_completion_response( |
| 443 | cx: &mut gpui::TestAppContext, |
| 444 | ) { |
| 445 | cx.update(crate::init); |
| 446 | let window = cx.add_empty_window(); |
| 447 | let (editor, menu) = window.update(|window, cx| { |
| 448 | let editor = cx.new(|cx| EditorState::new(window, cx).default_value("co")); |
| 449 | let menu = CompletionMenu::new(editor.clone(), window, cx); |
| 450 | let old_items = vec![CompletionItem { |
| 451 | label: "const".into(), |
| 452 | ..Default::default() |
| 453 | }]; |
| 454 | editor.update(cx, |editor, cx| { |
| 455 | editor.present_completion_items(0, "c", old_items.clone(), cx); |
| 456 | }); |
| 457 | menu.update(cx, |menu, cx| { |
| 458 | menu.update_query(0, "c"); |
| 459 | menu.show(1, old_items, window, cx); |
| 460 | // The overlay observes the old request being hidden while a |
| 461 | // replacement request is pending. Its deferred dismissal must |
| 462 | // not act on the replacement response that arrives next. |
| 463 | menu.hide(cx); |
| 464 | }); |
| 465 | editor.update(cx, |editor, cx| { |
| 466 | editor.present_completion_items( |
| 467 | 0, |
| 468 | "co", |
| 469 | vec![CompletionItem { |
| 470 | label: "const".into(), |
| 471 | ..Default::default() |
| 472 | }], |
| 473 | cx, |
| 474 | ); |
| 475 | }); |
| 476 | (editor, menu) |
| 477 | }); |
| 478 | |
| 479 | cx.run_until_parked(); |
| 480 | |
| 481 | cx.read(|cx| { |
| 482 | let completion = editor.read(cx).completion_menu_state(); |
| 483 | assert!(completion.open, "an old menu dismissed the new response"); |
| 484 | assert_eq!(completion.query, "co"); |
| 485 | assert_eq!(completion.items.len(), 1); |
| 486 | assert_eq!(completion.items[0].label, "const"); |
| 487 | }); |
| 488 | drop(menu); |
| 489 | } |
| 490 | } |