console.rs

  1use super::{
  2    stack_frame_list::{StackFrameList, StackFrameListEvent},
  3    variable_list::VariableList,
  4};
  5use anyhow::Result;
  6use collections::HashMap;
  7use dap::OutputEvent;
  8use editor::{Bias, CompletionProvider, Editor, EditorElement, EditorStyle, ExcerptId};
  9use fuzzy::StringMatchCandidate;
 10use gpui::{
 11    Context, Entity, FocusHandle, Focusable, Render, Subscription, Task, TextStyle, WeakEntity,
 12};
 13use language::{Buffer, CodeLabel, ToOffset};
 14use menu::Confirm;
 15use project::{
 16    Completion,
 17    debugger::session::{CompletionsQuery, OutputToken, Session},
 18};
 19use settings::Settings;
 20use std::{cell::RefCell, rc::Rc, usize};
 21use theme::ThemeSettings;
 22use ui::{Divider, prelude::*};
 23
 24pub struct Console {
 25    console: Entity<Editor>,
 26    query_bar: Entity<Editor>,
 27    session: Entity<Session>,
 28    _subscriptions: Vec<Subscription>,
 29    variable_list: Entity<VariableList>,
 30    stack_frame_list: Entity<StackFrameList>,
 31    last_token: OutputToken,
 32    update_output_task: Task<()>,
 33    focus_handle: FocusHandle,
 34}
 35
 36impl Console {
 37    pub fn new(
 38        session: Entity<Session>,
 39        stack_frame_list: Entity<StackFrameList>,
 40        variable_list: Entity<VariableList>,
 41        window: &mut Window,
 42        cx: &mut Context<Self>,
 43    ) -> Self {
 44        let console = cx.new(|cx| {
 45            let mut editor = Editor::multi_line(window, cx);
 46            editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
 47            editor.set_read_only(true);
 48            editor.disable_scrollbars_and_minimap(window, cx);
 49            editor.set_show_gutter(false, cx);
 50            editor.set_show_runnables(false, cx);
 51            editor.set_show_breakpoints(false, cx);
 52            editor.set_show_code_actions(false, cx);
 53            editor.set_show_line_numbers(false, cx);
 54            editor.set_show_git_diff_gutter(false, cx);
 55            editor.set_autoindent(false);
 56            editor.set_input_enabled(false);
 57            editor.set_use_autoclose(false);
 58            editor.set_show_wrap_guides(false, cx);
 59            editor.set_show_indent_guides(false, cx);
 60            editor.set_show_edit_predictions(Some(false), window, cx);
 61            editor.set_use_modal_editing(false);
 62            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
 63            editor
 64        });
 65        let focus_handle = cx.focus_handle();
 66
 67        let this = cx.weak_entity();
 68        let query_bar = cx.new(|cx| {
 69            let mut editor = Editor::single_line(window, cx);
 70            editor.set_placeholder_text("Evaluate an expression", cx);
 71            editor.set_use_autoclose(false);
 72            editor.set_show_gutter(false, cx);
 73            editor.set_show_wrap_guides(false, cx);
 74            editor.set_show_indent_guides(false, cx);
 75            editor.set_completion_provider(Some(Box::new(ConsoleQueryBarCompletionProvider(this))));
 76
 77            editor
 78        });
 79
 80        let _subscriptions = vec![
 81            cx.subscribe(&stack_frame_list, Self::handle_stack_frame_list_events),
 82            cx.on_focus_in(&focus_handle, window, |console, window, cx| {
 83                if console.is_running(cx) {
 84                    console.query_bar.focus_handle(cx).focus(window);
 85                }
 86            }),
 87        ];
 88
 89        Self {
 90            session,
 91            console,
 92            query_bar,
 93            variable_list,
 94            _subscriptions,
 95            stack_frame_list,
 96            update_output_task: Task::ready(()),
 97            last_token: OutputToken(0),
 98            focus_handle,
 99        }
100    }
101
102    #[cfg(test)]
103    pub(crate) fn editor(&self) -> &Entity<Editor> {
104        &self.console
105    }
106
107    fn is_running(&self, cx: &Context<Self>) -> bool {
108        self.session.read(cx).is_local()
109    }
110
111    fn handle_stack_frame_list_events(
112        &mut self,
113        _: Entity<StackFrameList>,
114        event: &StackFrameListEvent,
115        cx: &mut Context<Self>,
116    ) {
117        match event {
118            StackFrameListEvent::SelectedStackFrameChanged(_) => cx.notify(),
119            StackFrameListEvent::BuiltEntries => {}
120        }
121    }
122
123    pub(crate) fn show_indicator(&self, cx: &App) -> bool {
124        self.session.read(cx).has_new_output(self.last_token)
125    }
126
127    pub fn add_messages<'a>(
128        &mut self,
129        events: impl Iterator<Item = &'a OutputEvent>,
130        window: &mut Window,
131        cx: &mut App,
132    ) {
133        self.console.update(cx, |console, cx| {
134            let mut to_insert = String::default();
135            for event in events {
136                use std::fmt::Write;
137
138                _ = write!(to_insert, "{}\n", event.output.trim_end());
139            }
140
141            console.set_read_only(false);
142            console.move_to_end(&editor::actions::MoveToEnd, window, cx);
143            console.insert(&to_insert, window, cx);
144            console.set_read_only(true);
145
146            cx.notify();
147        });
148    }
149
150    pub fn evaluate(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
151        let expression = self.query_bar.update(cx, |editor, cx| {
152            let expression = editor.text(cx);
153            cx.defer_in(window, |editor, window, cx| {
154                editor.clear(window, cx);
155            });
156
157            expression
158        });
159
160        self.session.update(cx, |session, cx| {
161            session
162                .evaluate(
163                    expression,
164                    Some(dap::EvaluateArgumentsContext::Repl),
165                    self.stack_frame_list.read(cx).opened_stack_frame_id(),
166                    None,
167                    cx,
168                )
169                .detach();
170        });
171    }
172
173    fn render_console(&self, cx: &Context<Self>) -> impl IntoElement {
174        EditorElement::new(&self.console, self.editor_style(cx))
175    }
176
177    fn editor_style(&self, cx: &Context<Self>) -> EditorStyle {
178        let settings = ThemeSettings::get_global(cx);
179        let text_style = TextStyle {
180            color: if self.console.read(cx).read_only(cx) {
181                cx.theme().colors().text_disabled
182            } else {
183                cx.theme().colors().text
184            },
185            font_family: settings.buffer_font.family.clone(),
186            font_features: settings.buffer_font.features.clone(),
187            font_size: settings.buffer_font_size(cx).into(),
188            font_weight: settings.buffer_font.weight,
189            line_height: relative(settings.buffer_line_height.value()),
190            ..Default::default()
191        };
192        EditorStyle {
193            background: cx.theme().colors().editor_background,
194            local_player: cx.theme().players().local(),
195            text: text_style,
196            ..Default::default()
197        }
198    }
199
200    fn render_query_bar(&self, cx: &Context<Self>) -> impl IntoElement {
201        EditorElement::new(&self.query_bar, self.editor_style(cx))
202    }
203}
204
205impl Render for Console {
206    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
207        let session = self.session.clone();
208        let token = self.last_token;
209        self.update_output_task = cx.spawn_in(window, async move |this, cx| {
210            _ = session.update_in(cx, move |session, window, cx| {
211                let (output, last_processed_token) = session.output(token);
212
213                _ = this.update(cx, |this, cx| {
214                    if last_processed_token == this.last_token {
215                        return;
216                    }
217                    this.add_messages(output, window, cx);
218
219                    this.last_token = last_processed_token;
220                });
221            });
222        });
223
224        v_flex()
225            .track_focus(&self.focus_handle)
226            .key_context("DebugConsole")
227            .on_action(cx.listener(Self::evaluate))
228            .size_full()
229            .child(self.render_console(cx))
230            .when(self.is_running(cx), |this| {
231                this.child(Divider::horizontal())
232                    .child(self.render_query_bar(cx))
233            })
234            .border_2()
235    }
236}
237
238impl Focusable for Console {
239    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
240        self.focus_handle.clone()
241    }
242}
243
244struct ConsoleQueryBarCompletionProvider(WeakEntity<Console>);
245
246impl CompletionProvider for ConsoleQueryBarCompletionProvider {
247    fn completions(
248        &self,
249        _excerpt_id: ExcerptId,
250        buffer: &Entity<Buffer>,
251        buffer_position: language::Anchor,
252        _trigger: editor::CompletionContext,
253        _window: &mut Window,
254        cx: &mut Context<Editor>,
255    ) -> Task<Result<Option<Vec<Completion>>>> {
256        let Some(console) = self.0.upgrade() else {
257            return Task::ready(Ok(None));
258        };
259
260        let support_completions = console
261            .read(cx)
262            .session
263            .read(cx)
264            .capabilities()
265            .supports_completions_request
266            .unwrap_or_default();
267
268        if support_completions {
269            self.client_completions(&console, buffer, buffer_position, cx)
270        } else {
271            self.variable_list_completions(&console, buffer, buffer_position, cx)
272        }
273    }
274
275    fn resolve_completions(
276        &self,
277        _buffer: Entity<Buffer>,
278        _completion_indices: Vec<usize>,
279        _completions: Rc<RefCell<Box<[Completion]>>>,
280        _cx: &mut Context<Editor>,
281    ) -> gpui::Task<anyhow::Result<bool>> {
282        Task::ready(Ok(false))
283    }
284
285    fn apply_additional_edits_for_completion(
286        &self,
287        _buffer: Entity<Buffer>,
288        _completions: Rc<RefCell<Box<[Completion]>>>,
289        _completion_index: usize,
290        _push_to_history: bool,
291        _cx: &mut Context<Editor>,
292    ) -> gpui::Task<anyhow::Result<Option<language::Transaction>>> {
293        Task::ready(Ok(None))
294    }
295
296    fn is_completion_trigger(
297        &self,
298        _buffer: &Entity<Buffer>,
299        _position: language::Anchor,
300        _text: &str,
301        _trigger_in_words: bool,
302        _cx: &mut Context<Editor>,
303    ) -> bool {
304        true
305    }
306}
307
308impl ConsoleQueryBarCompletionProvider {
309    fn variable_list_completions(
310        &self,
311        console: &Entity<Console>,
312        buffer: &Entity<Buffer>,
313        buffer_position: language::Anchor,
314        cx: &mut Context<Editor>,
315    ) -> Task<Result<Option<Vec<Completion>>>> {
316        let (variables, string_matches) = console.update(cx, |console, cx| {
317            let mut variables = HashMap::default();
318            let mut string_matches = Vec::default();
319
320            for variable in console.variable_list.update(cx, |variable_list, cx| {
321                variable_list.completion_variables(cx)
322            }) {
323                if let Some(evaluate_name) = &variable.evaluate_name {
324                    variables.insert(evaluate_name.clone(), variable.value.clone());
325                    string_matches.push(StringMatchCandidate {
326                        id: 0,
327                        string: evaluate_name.clone(),
328                        char_bag: evaluate_name.chars().collect(),
329                    });
330                }
331
332                variables.insert(variable.name.clone(), variable.value.clone());
333
334                string_matches.push(StringMatchCandidate {
335                    id: 0,
336                    string: variable.name.clone(),
337                    char_bag: variable.name.chars().collect(),
338                });
339            }
340
341            (variables, string_matches)
342        });
343
344        let query = buffer.read(cx).text();
345
346        cx.spawn(async move |_, cx| {
347            let matches = fuzzy::match_strings(
348                &string_matches,
349                &query,
350                true,
351                10,
352                &Default::default(),
353                cx.background_executor().clone(),
354            )
355            .await;
356
357            Ok(Some(
358                matches
359                    .iter()
360                    .filter_map(|string_match| {
361                        let variable_value = variables.get(&string_match.string)?;
362
363                        Some(project::Completion {
364                            replace_range: buffer_position..buffer_position,
365                            new_text: string_match.string.clone(),
366                            label: CodeLabel {
367                                filter_range: 0..string_match.string.len(),
368                                text: format!("{} {}", string_match.string, variable_value),
369                                runs: Vec::new(),
370                            },
371                            icon_path: None,
372                            documentation: None,
373                            confirm: None,
374                            source: project::CompletionSource::Custom,
375                            insert_text_mode: None,
376                        })
377                    })
378                    .collect(),
379            ))
380        })
381    }
382
383    fn client_completions(
384        &self,
385        console: &Entity<Console>,
386        buffer: &Entity<Buffer>,
387        buffer_position: language::Anchor,
388        cx: &mut Context<Editor>,
389    ) -> Task<Result<Option<Vec<Completion>>>> {
390        let completion_task = console.update(cx, |console, cx| {
391            console.session.update(cx, |state, cx| {
392                let frame_id = console.stack_frame_list.read(cx).opened_stack_frame_id();
393
394                state.completions(
395                    CompletionsQuery::new(buffer.read(cx), buffer_position, frame_id),
396                    cx,
397                )
398            })
399        });
400        let snapshot = buffer.read(cx).text_snapshot();
401        cx.background_executor().spawn(async move {
402            let completions = completion_task.await?;
403
404            Ok(Some(
405                completions
406                    .into_iter()
407                    .map(|completion| {
408                        let new_text = completion
409                            .text
410                            .as_ref()
411                            .unwrap_or(&completion.label)
412                            .to_owned();
413                        let buffer_text = snapshot.text();
414                        let buffer_bytes = buffer_text.as_bytes();
415                        let new_bytes = new_text.as_bytes();
416
417                        let mut prefix_len = 0;
418                        for i in (0..new_bytes.len()).rev() {
419                            if buffer_bytes.ends_with(&new_bytes[0..i]) {
420                                prefix_len = i;
421                                break;
422                            }
423                        }
424
425                        let buffer_offset = buffer_position.to_offset(&snapshot);
426                        let start = buffer_offset - prefix_len;
427                        let start = snapshot.clip_offset(start, Bias::Left);
428                        let start = snapshot.anchor_before(start);
429                        let replace_range = start..buffer_position;
430
431                        project::Completion {
432                            replace_range,
433                            new_text,
434                            label: CodeLabel {
435                                filter_range: 0..completion.label.len(),
436                                text: completion.label,
437                                runs: Vec::new(),
438                            },
439                            icon_path: None,
440                            documentation: None,
441                            confirm: None,
442                            source: project::CompletionSource::BufferWord {
443                                word_range: buffer_position..language::Anchor::MAX,
444                                resolved: false,
445                            },
446                            insert_text_mode: None,
447                        }
448                    })
449                    .collect(),
450            ))
451        })
452    }
453}