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