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::{CompletionProvider, Editor, EditorElement, EditorStyle, ExcerptId};
  9use fuzzy::StringMatchCandidate;
 10use gpui::{Context, Entity, Render, Subscription, Task, TextStyle, WeakEntity};
 11use language::{Buffer, CodeLabel};
 12use menu::Confirm;
 13use project::{
 14    Completion,
 15    debugger::session::{CompletionsQuery, OutputToken, Session},
 16};
 17use settings::Settings;
 18use std::{cell::RefCell, rc::Rc, usize};
 19use theme::ThemeSettings;
 20use ui::prelude::*;
 21
 22pub struct Console {
 23    console: Entity<Editor>,
 24    query_bar: Entity<Editor>,
 25    session: Entity<Session>,
 26    _subscriptions: Vec<Subscription>,
 27    variable_list: Entity<VariableList>,
 28    stack_frame_list: Entity<StackFrameList>,
 29    last_token: OutputToken,
 30    update_output_task: Task<()>,
 31}
 32
 33impl Console {
 34    pub fn new(
 35        session: Entity<Session>,
 36        stack_frame_list: Entity<StackFrameList>,
 37        variable_list: Entity<VariableList>,
 38        window: &mut Window,
 39        cx: &mut Context<Self>,
 40    ) -> Self {
 41        let console = cx.new(|cx| {
 42            let mut editor = Editor::multi_line(window, cx);
 43            editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
 44            editor.set_read_only(true);
 45            editor.set_show_gutter(true, cx);
 46            editor.set_show_runnables(false, cx);
 47            editor.set_show_breakpoints(false, cx);
 48            editor.set_show_code_actions(false, cx);
 49            editor.set_show_line_numbers(false, cx);
 50            editor.set_show_git_diff_gutter(false, cx);
 51            editor.set_autoindent(false);
 52            editor.set_input_enabled(false);
 53            editor.set_use_autoclose(false);
 54            editor.set_show_wrap_guides(false, cx);
 55            editor.set_show_indent_guides(false, cx);
 56            editor.set_show_edit_predictions(Some(false), window, cx);
 57            editor
 58        });
 59
 60        let this = cx.weak_entity();
 61        let query_bar = cx.new(|cx| {
 62            let mut editor = Editor::single_line(window, cx);
 63            editor.set_placeholder_text("Evaluate an expression", cx);
 64            editor.set_use_autoclose(false);
 65            editor.set_show_gutter(false, cx);
 66            editor.set_show_wrap_guides(false, cx);
 67            editor.set_show_indent_guides(false, cx);
 68            editor.set_completion_provider(Some(Box::new(ConsoleQueryBarCompletionProvider(this))));
 69
 70            editor
 71        });
 72
 73        let _subscriptions =
 74            vec![cx.subscribe(&stack_frame_list, Self::handle_stack_frame_list_events)];
 75
 76        Self {
 77            session,
 78            console,
 79            query_bar,
 80            variable_list,
 81            _subscriptions,
 82            stack_frame_list,
 83            update_output_task: Task::ready(()),
 84            last_token: OutputToken(0),
 85        }
 86    }
 87
 88    #[cfg(any(test, feature = "test-support"))]
 89    pub fn editor(&self) -> &Entity<Editor> {
 90        &self.console
 91    }
 92
 93    #[cfg(any(test, feature = "test-support"))]
 94    pub fn query_bar(&self) -> &Entity<Editor> {
 95        &self.query_bar
 96    }
 97
 98    fn is_local(&self, cx: &Context<Self>) -> bool {
 99        self.session.read(cx).is_local()
100    }
101
102    fn handle_stack_frame_list_events(
103        &mut self,
104        _: Entity<StackFrameList>,
105        event: &StackFrameListEvent,
106        cx: &mut Context<Self>,
107    ) {
108        match event {
109            StackFrameListEvent::SelectedStackFrameChanged(_) => cx.notify(),
110        }
111    }
112
113    pub fn add_messages<'a>(
114        &mut self,
115        events: impl Iterator<Item = &'a OutputEvent>,
116        window: &mut Window,
117        cx: &mut App,
118    ) {
119        self.console.update(cx, |console, cx| {
120            let mut to_insert = String::default();
121            for event in events {
122                use std::fmt::Write;
123
124                _ = write!(to_insert, "{}\n", event.output.trim_end());
125            }
126
127            console.set_read_only(false);
128            console.move_to_end(&editor::actions::MoveToEnd, window, cx);
129            console.insert(&to_insert, window, cx);
130            console.set_read_only(true);
131
132            cx.notify();
133        });
134    }
135
136    pub fn evaluate(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
137        let expression = self.query_bar.update(cx, |editor, cx| {
138            let expression = editor.text(cx);
139
140            editor.clear(window, cx);
141
142            expression
143        });
144
145        self.session.update(cx, |state, cx| {
146            state.evaluate(
147                expression,
148                Some(dap::EvaluateArgumentsContext::Variables),
149                self.stack_frame_list.read(cx).current_stack_frame_id(),
150                None,
151                cx,
152            );
153        });
154    }
155
156    fn render_console(&self, cx: &Context<Self>) -> impl IntoElement {
157        let settings = ThemeSettings::get_global(cx);
158        let text_style = TextStyle {
159            color: if self.console.read(cx).read_only(cx) {
160                cx.theme().colors().text_disabled
161            } else {
162                cx.theme().colors().text
163            },
164            font_family: settings.buffer_font.family.clone(),
165            font_features: settings.buffer_font.features.clone(),
166            font_size: settings.buffer_font_size(cx).into(),
167            font_weight: settings.buffer_font.weight,
168            line_height: relative(settings.buffer_line_height.value()),
169            ..Default::default()
170        };
171
172        EditorElement::new(
173            &self.console,
174            EditorStyle {
175                background: cx.theme().colors().editor_background,
176                local_player: cx.theme().players().local(),
177                text: text_style,
178                ..Default::default()
179            },
180        )
181    }
182
183    fn render_query_bar(&self, cx: &Context<Self>) -> impl IntoElement {
184        let settings = ThemeSettings::get_global(cx);
185        let text_style = TextStyle {
186            color: if self.console.read(cx).read_only(cx) {
187                cx.theme().colors().text_disabled
188            } else {
189                cx.theme().colors().text
190            },
191            font_family: settings.ui_font.family.clone(),
192            font_features: settings.ui_font.features.clone(),
193            font_fallbacks: settings.ui_font.fallbacks.clone(),
194            font_size: TextSize::Editor.rems(cx).into(),
195            font_weight: settings.ui_font.weight,
196            line_height: relative(1.3),
197            ..Default::default()
198        };
199
200        EditorElement::new(
201            &self.query_bar,
202            EditorStyle {
203                background: cx.theme().colors().editor_background,
204                local_player: cx.theme().players().local(),
205                text: text_style,
206                ..Default::default()
207            },
208        )
209    }
210}
211
212impl Render for Console {
213    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
214        let session = self.session.clone();
215        let token = self.last_token;
216        self.update_output_task = cx.spawn_in(window, async move |this, cx| {
217            _ = session.update_in(cx, move |session, window, cx| {
218                let (output, last_processed_token) = session.output(token);
219
220                _ = this.update(cx, |this, cx| {
221                    if last_processed_token == this.last_token {
222                        return;
223                    }
224                    this.add_messages(output, window, cx);
225
226                    this.last_token = last_processed_token;
227                });
228            });
229        });
230
231        v_flex()
232            .key_context("DebugConsole")
233            .on_action(cx.listener(Self::evaluate))
234            .size_full()
235            .child(self.render_console(cx))
236            .when(self.is_local(cx), |this| {
237                this.child(self.render_query_bar(cx))
238                    .pt(DynamicSpacing::Base04.rems(cx))
239            })
240            .border_2()
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<gpui::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<gpui::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                            old_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.clone(), variable_value),
369                                runs: Vec::new(),
370                            },
371                            icon_path: None,
372                            documentation: None,
373                            confirm: None,
374                            source: project::CompletionSource::Custom,
375                        })
376                    })
377                    .collect(),
378            ))
379        })
380    }
381
382    fn client_completions(
383        &self,
384        console: &Entity<Console>,
385        buffer: &Entity<Buffer>,
386        buffer_position: language::Anchor,
387        cx: &mut Context<Editor>,
388    ) -> Task<Result<Option<Vec<Completion>>>> {
389        let completion_task = console.update(cx, |console, cx| {
390            console.session.update(cx, |state, cx| {
391                let frame_id = console.stack_frame_list.read(cx).current_stack_frame_id();
392
393                state.completions(
394                    CompletionsQuery::new(buffer.read(cx), buffer_position, frame_id),
395                    cx,
396                )
397            })
398        });
399
400        cx.background_executor().spawn(async move {
401            Ok(Some(
402                completion_task
403                    .await?
404                    .iter()
405                    .map(|completion| project::Completion {
406                        old_range: buffer_position..buffer_position, // TODO(debugger): change this
407                        new_text: completion.text.clone().unwrap_or(completion.label.clone()),
408                        label: CodeLabel {
409                            filter_range: 0..completion.label.len(),
410                            text: completion.label.clone(),
411                            runs: Vec::new(),
412                        },
413                        icon_path: None,
414                        documentation: None,
415                        confirm: None,
416                        source: project::CompletionSource::Custom,
417                    })
418                    .collect(),
419            ))
420        })
421    }
422}