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, CompletionResponse,
 17    debugger::session::{CompletionsQuery, OutputToken, Session, SessionEvent},
 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(Rc::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.subscribe_in(&session, window, |this, _, event, window, cx| {
 83                if let SessionEvent::ConsoleOutput = event {
 84                    this.update_output(window, cx)
 85                }
 86            }),
 87            cx.on_focus(&focus_handle, window, |console, window, cx| {
 88                if console.is_running(cx) {
 89                    console.query_bar.focus_handle(cx).focus(window);
 90                }
 91            }),
 92        ];
 93
 94        Self {
 95            session,
 96            console,
 97            query_bar,
 98            variable_list,
 99            _subscriptions,
100            stack_frame_list,
101            update_output_task: Task::ready(()),
102            last_token: OutputToken(0),
103            focus_handle,
104        }
105    }
106
107    #[cfg(test)]
108    pub(crate) fn editor(&self) -> &Entity<Editor> {
109        &self.console
110    }
111
112    fn is_running(&self, cx: &Context<Self>) -> bool {
113        self.session.read(cx).is_running()
114    }
115
116    fn handle_stack_frame_list_events(
117        &mut self,
118        _: Entity<StackFrameList>,
119        event: &StackFrameListEvent,
120        cx: &mut Context<Self>,
121    ) {
122        match event {
123            StackFrameListEvent::SelectedStackFrameChanged(_) => cx.notify(),
124            StackFrameListEvent::BuiltEntries => {}
125        }
126    }
127
128    pub(crate) fn show_indicator(&self, cx: &App) -> bool {
129        self.session.read(cx).has_new_output(self.last_token)
130    }
131
132    pub fn add_messages<'a>(
133        &mut self,
134        events: impl Iterator<Item = &'a OutputEvent>,
135        window: &mut Window,
136        cx: &mut App,
137    ) {
138        self.console.update(cx, |console, cx| {
139            let mut to_insert = String::default();
140            for event in events {
141                use std::fmt::Write;
142
143                _ = write!(to_insert, "{}\n", event.output.trim_end());
144            }
145
146            console.set_read_only(false);
147            console.move_to_end(&editor::actions::MoveToEnd, window, cx);
148            console.insert(&to_insert, window, cx);
149            console.set_read_only(true);
150
151            cx.notify();
152        });
153    }
154
155    pub fn evaluate(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
156        let expression = self.query_bar.update(cx, |editor, cx| {
157            let expression = editor.text(cx);
158            cx.defer_in(window, |editor, window, cx| {
159                editor.clear(window, cx);
160            });
161
162            expression
163        });
164
165        self.session.update(cx, |session, cx| {
166            session
167                .evaluate(
168                    expression,
169                    Some(dap::EvaluateArgumentsContext::Repl),
170                    self.stack_frame_list.read(cx).opened_stack_frame_id(),
171                    None,
172                    cx,
173                )
174                .detach();
175        });
176    }
177
178    fn render_console(&self, cx: &Context<Self>) -> impl IntoElement {
179        EditorElement::new(&self.console, Self::editor_style(&self.console, cx))
180    }
181
182    fn editor_style(editor: &Entity<Editor>, cx: &Context<Self>) -> EditorStyle {
183        let is_read_only = editor.read(cx).read_only(cx);
184        let settings = ThemeSettings::get_global(cx);
185        let theme = cx.theme();
186        let text_style = TextStyle {
187            color: if is_read_only {
188                theme.colors().text_muted
189            } else {
190                theme.colors().text
191            },
192            font_family: settings.buffer_font.family.clone(),
193            font_features: settings.buffer_font.features.clone(),
194            font_size: settings.buffer_font_size(cx).into(),
195            font_weight: settings.buffer_font.weight,
196            line_height: relative(settings.buffer_line_height.value()),
197            ..Default::default()
198        };
199        EditorStyle {
200            background: theme.colors().editor_background,
201            local_player: theme.players().local(),
202            text: text_style,
203            ..Default::default()
204        }
205    }
206
207    fn render_query_bar(&self, cx: &Context<Self>) -> impl IntoElement {
208        EditorElement::new(&self.query_bar, Self::editor_style(&self.query_bar, cx))
209    }
210
211    fn update_output(&mut self, window: &mut Window, cx: &mut Context<Self>) {
212        let session = self.session.clone();
213        let token = self.last_token;
214
215        self.update_output_task = cx.spawn_in(window, async move |this, cx| {
216            _ = session.update_in(cx, move |session, window, cx| {
217                let (output, last_processed_token) = session.output(token);
218
219                _ = this.update(cx, |this, cx| {
220                    if last_processed_token == this.last_token {
221                        return;
222                    }
223                    this.add_messages(output, window, cx);
224
225                    this.last_token = last_processed_token;
226                });
227            });
228        });
229    }
230}
231
232impl Render for Console {
233    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
234        v_flex()
235            .track_focus(&self.focus_handle)
236            .key_context("DebugConsole")
237            .on_action(cx.listener(Self::evaluate))
238            .size_full()
239            .child(self.render_console(cx))
240            .when(self.is_running(cx), |this| {
241                this.child(Divider::horizontal())
242                    .child(self.render_query_bar(cx))
243            })
244            .border_2()
245    }
246}
247
248impl Focusable for Console {
249    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
250        self.focus_handle.clone()
251    }
252}
253
254struct ConsoleQueryBarCompletionProvider(WeakEntity<Console>);
255
256impl CompletionProvider for ConsoleQueryBarCompletionProvider {
257    fn completions(
258        &self,
259        _excerpt_id: ExcerptId,
260        buffer: &Entity<Buffer>,
261        buffer_position: language::Anchor,
262        _trigger: editor::CompletionContext,
263        _window: &mut Window,
264        cx: &mut Context<Editor>,
265    ) -> Task<Result<Vec<CompletionResponse>>> {
266        let Some(console) = self.0.upgrade() else {
267            return Task::ready(Ok(Vec::new()));
268        };
269
270        let support_completions = console
271            .read(cx)
272            .session
273            .read(cx)
274            .capabilities()
275            .supports_completions_request
276            .unwrap_or_default();
277
278        if support_completions {
279            self.client_completions(&console, buffer, buffer_position, cx)
280        } else {
281            self.variable_list_completions(&console, buffer, buffer_position, cx)
282        }
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        _menu_is_open: bool,
303        _cx: &mut Context<Editor>,
304    ) -> bool {
305        true
306    }
307}
308
309impl ConsoleQueryBarCompletionProvider {
310    fn variable_list_completions(
311        &self,
312        console: &Entity<Console>,
313        buffer: &Entity<Buffer>,
314        buffer_position: language::Anchor,
315        cx: &mut Context<Editor>,
316    ) -> Task<Result<Vec<CompletionResponse>>> {
317        let (variables, string_matches) = console.update(cx, |console, cx| {
318            let mut variables = HashMap::default();
319            let mut string_matches = Vec::default();
320
321            for variable in console.variable_list.update(cx, |variable_list, cx| {
322                variable_list.completion_variables(cx)
323            }) {
324                if let Some(evaluate_name) = &variable.evaluate_name {
325                    variables.insert(evaluate_name.clone(), variable.value.clone());
326                    string_matches.push(StringMatchCandidate {
327                        id: 0,
328                        string: evaluate_name.clone(),
329                        char_bag: evaluate_name.chars().collect(),
330                    });
331                }
332
333                variables.insert(variable.name.clone(), variable.value.clone());
334
335                string_matches.push(StringMatchCandidate {
336                    id: 0,
337                    string: variable.name.clone(),
338                    char_bag: variable.name.chars().collect(),
339                });
340            }
341
342            (variables, string_matches)
343        });
344
345        let query = buffer.read(cx).text();
346
347        cx.spawn(async move |_, cx| {
348            const LIMIT: usize = 10;
349            let matches = fuzzy::match_strings(
350                &string_matches,
351                &query,
352                true,
353                LIMIT,
354                &Default::default(),
355                cx.background_executor().clone(),
356            )
357            .await;
358
359            let completions = matches
360                .iter()
361                .filter_map(|string_match| {
362                    let variable_value = variables.get(&string_match.string)?;
363
364                    Some(project::Completion {
365                        replace_range: buffer_position..buffer_position,
366                        new_text: string_match.string.clone(),
367                        label: CodeLabel {
368                            filter_range: 0..string_match.string.len(),
369                            text: format!("{} {}", string_match.string, variable_value),
370                            runs: Vec::new(),
371                        },
372                        icon_path: None,
373                        documentation: None,
374                        confirm: None,
375                        source: project::CompletionSource::Custom,
376                        insert_text_mode: None,
377                    })
378                })
379                .collect::<Vec<_>>();
380
381            Ok(vec![project::CompletionResponse {
382                is_incomplete: completions.len() >= LIMIT,
383                completions,
384            }])
385        })
386    }
387
388    fn client_completions(
389        &self,
390        console: &Entity<Console>,
391        buffer: &Entity<Buffer>,
392        buffer_position: language::Anchor,
393        cx: &mut Context<Editor>,
394    ) -> Task<Result<Vec<CompletionResponse>>> {
395        let completion_task = console.update(cx, |console, cx| {
396            console.session.update(cx, |state, cx| {
397                let frame_id = console.stack_frame_list.read(cx).opened_stack_frame_id();
398
399                state.completions(
400                    CompletionsQuery::new(buffer.read(cx), buffer_position, frame_id),
401                    cx,
402                )
403            })
404        });
405        let snapshot = buffer.read(cx).text_snapshot();
406        cx.background_executor().spawn(async move {
407            let completions = completion_task.await?;
408
409            let completions = completions
410                .into_iter()
411                .map(|completion| {
412                    let new_text = completion
413                        .text
414                        .as_ref()
415                        .unwrap_or(&completion.label)
416                        .to_owned();
417                    let buffer_text = snapshot.text();
418                    let buffer_bytes = buffer_text.as_bytes();
419                    let new_bytes = new_text.as_bytes();
420
421                    let mut prefix_len = 0;
422                    for i in (0..new_bytes.len()).rev() {
423                        if buffer_bytes.ends_with(&new_bytes[0..i]) {
424                            prefix_len = i;
425                            break;
426                        }
427                    }
428
429                    let buffer_offset = buffer_position.to_offset(&snapshot);
430                    let start = buffer_offset - prefix_len;
431                    let start = snapshot.clip_offset(start, Bias::Left);
432                    let start = snapshot.anchor_before(start);
433                    let replace_range = start..buffer_position;
434
435                    project::Completion {
436                        replace_range,
437                        new_text,
438                        label: CodeLabel {
439                            filter_range: 0..completion.label.len(),
440                            text: completion.label,
441                            runs: Vec::new(),
442                        },
443                        icon_path: None,
444                        documentation: None,
445                        confirm: None,
446                        source: project::CompletionSource::BufferWord {
447                            word_range: buffer_position..language::Anchor::MAX,
448                            resolved: false,
449                        },
450                        insert_text_mode: None,
451                    }
452                })
453                .collect();
454
455            Ok(vec![project::CompletionResponse {
456                completions,
457                is_incomplete: false,
458            }])
459        })
460    }
461}