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