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