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