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 resolve_completions(
286        &self,
287        _buffer: Entity<Buffer>,
288        _completion_indices: Vec<usize>,
289        _completions: Rc<RefCell<Box<[Completion]>>>,
290        _cx: &mut Context<Editor>,
291    ) -> gpui::Task<anyhow::Result<bool>> {
292        Task::ready(Ok(false))
293    }
294
295    fn apply_additional_edits_for_completion(
296        &self,
297        _buffer: Entity<Buffer>,
298        _completions: Rc<RefCell<Box<[Completion]>>>,
299        _completion_index: usize,
300        _push_to_history: bool,
301        _cx: &mut Context<Editor>,
302    ) -> gpui::Task<anyhow::Result<Option<language::Transaction>>> {
303        Task::ready(Ok(None))
304    }
305
306    fn is_completion_trigger(
307        &self,
308        _buffer: &Entity<Buffer>,
309        _position: language::Anchor,
310        _text: &str,
311        _trigger_in_words: bool,
312        _cx: &mut Context<Editor>,
313    ) -> bool {
314        true
315    }
316}
317
318impl ConsoleQueryBarCompletionProvider {
319    fn variable_list_completions(
320        &self,
321        console: &Entity<Console>,
322        buffer: &Entity<Buffer>,
323        buffer_position: language::Anchor,
324        cx: &mut Context<Editor>,
325    ) -> Task<Result<Vec<CompletionResponse>>> {
326        let (variables, string_matches) = console.update(cx, |console, cx| {
327            let mut variables = HashMap::default();
328            let mut string_matches = Vec::default();
329
330            for variable in console.variable_list.update(cx, |variable_list, cx| {
331                variable_list.completion_variables(cx)
332            }) {
333                if let Some(evaluate_name) = &variable.evaluate_name {
334                    variables.insert(evaluate_name.clone(), variable.value.clone());
335                    string_matches.push(StringMatchCandidate {
336                        id: 0,
337                        string: evaluate_name.clone(),
338                        char_bag: evaluate_name.chars().collect(),
339                    });
340                }
341
342                variables.insert(variable.name.clone(), variable.value.clone());
343
344                string_matches.push(StringMatchCandidate {
345                    id: 0,
346                    string: variable.name.clone(),
347                    char_bag: variable.name.chars().collect(),
348                });
349            }
350
351            (variables, string_matches)
352        });
353
354        let query = buffer.read(cx).text();
355
356        cx.spawn(async move |_, cx| {
357            const LIMIT: usize = 10;
358            let matches = fuzzy::match_strings(
359                &string_matches,
360                &query,
361                true,
362                LIMIT,
363                &Default::default(),
364                cx.background_executor().clone(),
365            )
366            .await;
367
368            let completions = matches
369                .iter()
370                .filter_map(|string_match| {
371                    let variable_value = variables.get(&string_match.string)?;
372
373                    Some(project::Completion {
374                        replace_range: buffer_position..buffer_position,
375                        new_text: string_match.string.clone(),
376                        label: CodeLabel {
377                            filter_range: 0..string_match.string.len(),
378                            text: format!("{} {}", string_match.string, variable_value),
379                            runs: Vec::new(),
380                        },
381                        icon_path: None,
382                        documentation: None,
383                        confirm: None,
384                        source: project::CompletionSource::Custom,
385                        insert_text_mode: None,
386                    })
387                })
388                .collect::<Vec<_>>();
389
390            Ok(vec![project::CompletionResponse {
391                is_incomplete: completions.len() >= LIMIT,
392                completions,
393            }])
394        })
395    }
396
397    fn client_completions(
398        &self,
399        console: &Entity<Console>,
400        buffer: &Entity<Buffer>,
401        buffer_position: language::Anchor,
402        cx: &mut Context<Editor>,
403    ) -> Task<Result<Vec<CompletionResponse>>> {
404        let completion_task = console.update(cx, |console, cx| {
405            console.session.update(cx, |state, cx| {
406                let frame_id = console.stack_frame_list.read(cx).opened_stack_frame_id();
407
408                state.completions(
409                    CompletionsQuery::new(buffer.read(cx), buffer_position, frame_id),
410                    cx,
411                )
412            })
413        });
414        let snapshot = buffer.read(cx).text_snapshot();
415        cx.background_executor().spawn(async move {
416            let completions = completion_task.await?;
417
418            let completions = completions
419                .into_iter()
420                .map(|completion| {
421                    let new_text = completion
422                        .text
423                        .as_ref()
424                        .unwrap_or(&completion.label)
425                        .to_owned();
426                    let buffer_text = snapshot.text();
427                    let buffer_bytes = buffer_text.as_bytes();
428                    let new_bytes = new_text.as_bytes();
429
430                    let mut prefix_len = 0;
431                    for i in (0..new_bytes.len()).rev() {
432                        if buffer_bytes.ends_with(&new_bytes[0..i]) {
433                            prefix_len = i;
434                            break;
435                        }
436                    }
437
438                    let buffer_offset = buffer_position.to_offset(&snapshot);
439                    let start = buffer_offset - prefix_len;
440                    let start = snapshot.clip_offset(start, Bias::Left);
441                    let start = snapshot.anchor_before(start);
442                    let replace_range = start..buffer_position;
443
444                    project::Completion {
445                        replace_range,
446                        new_text,
447                        label: CodeLabel {
448                            filter_range: 0..completion.label.len(),
449                            text: completion.label,
450                            runs: Vec::new(),
451                        },
452                        icon_path: None,
453                        documentation: None,
454                        confirm: None,
455                        source: project::CompletionSource::BufferWord {
456                            word_range: buffer_position..language::Anchor::MAX,
457                            resolved: false,
458                        },
459                        insert_text_mode: None,
460                    }
461                })
462                .collect();
463
464            Ok(vec![project::CompletionResponse {
465                completions,
466                is_incomplete: false,
467            }])
468        })
469    }
470}