Visual Studio Code, rebuilt in Rust
Rust
//! The Debug Console tree's find widget: repl.ts `FindReplAction` opens abstractTree.ts `FindController` over the
//! REPL elements, matched by `getKeyboardNavigationLabel` (`IReplElement.toString(true)`).
use std::ops::Range;
use gpui::{Context, Div, HighlightStyle, InteractiveElement, Keystroke, MouseButton, StyledText, Window};
use serde_json::json;
use super::Workbench;
use super::debug_hover::FindQuery;
use super::explorer_find::{INPUT_WIDTH, TreeFindLook, label_matches};
use super::input_box_view::InputId;
use crate::debug::session::{ReplElement, Variable};
use crate::input_box::InputBox;
/// abstractTree.ts `AbstractFindController.open`: `paddingTop: 30` over the rows while the widget shows.
pub(super) const FIND_PADDING: f32 = 30.;
/// The labels a REPL element is found by: `ReplEvaluationInput` and `ReplEvaluationResult` are two tree rows the
/// port draws as one element.
pub(super) fn repl_element_labels(element: &ReplElement) -> Vec<String> {
match element {
ReplElement::Output { value, source, count, .. } => vec![repl_output_label(value, source.as_ref().map(|(path, _)| path.as_str()), *count)],
ReplElement::Variable { variable, .. } => vec![expression_label(variable)],
ReplElement::Evaluation { input, result, .. } => {
let mut labels = vec![input.clone()];
labels.extend(result.iter().map(expression_label));
labels
}
}
}
/// replModel.ts `ReplOutputElement.toString(true)`: the value once per repeat, then the source's file name.
pub(super) fn repl_output_label(value: &str, source_path: Option<&str>, count: u32) -> String {
let mut text = value.to_owned();
for _ in 1..count {
if !text.ends_with('\n') {
text.push('\n');
}
text.push_str(value);
}
if let Some(path) = source_path {
text.push(' ');
text.push_str(path.rsplit('/').next().unwrap_or_default());
}
text
}
/// debugModel.ts `ExpressionContainer.toString`.
fn expression_label(variable: &Variable) -> String {
format!("{}\n{}", variable.name, variable.value)
}
impl Workbench {
pub(super) fn repl_find_query(&self) -> Option<FindQuery> {
let find = &self.debug_console.find;
if !find.open || find.input.value.is_empty() {
return None;
}
Some(FindQuery { pattern: find.input.value.clone(), fuzzy: self.repl_find_fuzzy(), filter_mode: self.repl_find_filter_mode() })
}
fn repl_find_filter_mode(&self) -> bool {
self.debug_console.find.filter_mode.unwrap_or_else(|| self.setting("workbench.list.defaultFindMode") == json!("filter"))
}
fn repl_find_fuzzy(&self) -> bool {
self.debug_console.find.fuzzy.unwrap_or_else(|| self.setting("workbench.list.defaultFindMatchType") != json!("contiguous"))
}
/// `FindFilter.filter` in filter mode: an element shows when one of its labels matches.
pub(super) fn repl_find_keeps(&self, element: &ReplElement) -> bool {
let Some(query) = self.repl_find_query().filter(|query| query.filter_mode) else { return true };
repl_element_labels(element).iter().any(|label| label_matches(&query.pattern, label, query.fuzzy).is_some())
}
/// The matched chars of a label, for its `HighlightedLabel`.
fn repl_find_highlights(&self, label: &str) -> Vec<Range<usize>> {
self.repl_find_query().and_then(|query| label_matches(&query.pattern, label, query.fuzzy)).unwrap_or_default()
}
/// replViewer.ts `renderExpression`: the matches of `name\nvalue` that fall in the name.
pub(super) fn repl_find_name_highlights(&self, variable: &Variable) -> Vec<Range<usize>> {
let name_chars = variable.name.chars().count();
let mut highlights = self.repl_find_highlights(&expression_label(variable));
highlights.retain(|range| range.start < name_chars);
for range in &mut highlights {
range.end = range.end.min(name_chars);
}
highlights
}
/// `ReplEvaluationInputsRenderer`: the input as a `HighlightedLabel`.
pub(super) fn repl_input_label(&self, input: &str) -> StyledText {
let color = self.color("list.highlightForeground");
let byte = |chars: usize| input.char_indices().nth(chars).map_or(input.len(), |(byte, _)| byte);
let styles: Vec<_> = self.repl_find_highlights(input).into_iter().map(|range| (byte(range.start)..byte(range.end), HighlightStyle { color: Some(color.into()), ..Default::default() })).collect();
StyledText::new(input.to_owned()).with_highlights(styles)
}
/// repl.ts `openFind`, `AbstractFindController.open`: the widget shows with the last pattern selected, or an
/// open one takes the focus.
pub(super) fn open_repl_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let find = &mut self.debug_console.find;
window.focus(&find.focus.clone(), cx);
if !find.open {
find.open = true;
find.input.set_value(find.previous_pattern.clone());
}
find.input.select_all();
find.history.add_to_history(&find.input.value, true);
self.blink_caret(InputId::ReplFind, window, cx);
cx.notify();
}
/// `AbstractFindController.close`: the pattern is kept for the next open, and the tree takes the focus.
pub(super) fn close_repl_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let find = &mut self.debug_console.find;
if !find.open {
return;
}
find.open = false;
find.previous_pattern = std::mem::take(&mut find.input.value);
find.input = InputBox::default();
find.view.reset();
window.focus(&self.debug_console.focus, cx);
cx.notify();
}
/// `FindController.mode` and `matchType`.
pub(super) fn toggle_repl_find(&mut self, mode: bool, cx: &mut Context<Self>) {
match mode {
true => self.debug_console.find.filter_mode = Some(!self.repl_find_filter_mode()),
false => self.debug_console.find.fuzzy = Some(!self.repl_find_fuzzy()),
}
cx.notify();
}
pub(super) fn edit_repl_find_input(&mut self, edit: impl FnOnce(&mut InputBox), cx: &mut Context<Self>) {
edit(&mut self.debug_console.find.input);
cx.notify();
}
/// `FindWidget`'s keydown: Enter returns to the tree, Up and Down walk the history, Down past its end returns to
/// the tree; Escape is the tree's `list.closeFind`.
pub(super) fn repl_find_input_key(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
let modifiers = keystroke.modifiers;
if modifiers.platform || modifiers.alt || modifiers.shift || modifiers.control {
return false;
}
let find = &mut self.debug_console.find;
match keystroke.key.as_str() {
"escape" => self.close_repl_find(window, cx),
"enter" | "down" if keystroke.key == "enter" || find.history.is_last() || find.history.is_nowhere() => {
find.history.add_to_history(&find.input.value, false);
window.focus(&self.debug_console.focus, cx);
}
"down" => {
let value = find.history.show_next_value(&find.input.value);
self.edit_repl_find_input(|input| input.set_value(value), cx);
}
"up" => {
if let Some(value) = find.history.show_previous_value(&find.input.value) {
self.edit_repl_find_input(|input| input.set_value(value), cx);
}
}
_ => return false,
}
cx.notify();
true
}
/// `FindController.render`: "No results found." when no element of the shown console matches.
pub(super) fn repl_find_message(&self, elements: &[&ReplElement]) -> Option<String> {
let query = self.repl_find_query()?;
let found = elements.iter().any(|element| repl_element_labels(element).iter().any(|label| label_matches(&query.pattern, label, query.fuzzy).is_some()));
(!found && !elements.is_empty()).then(|| "No results found.".to_owned())
}
pub(super) fn repl_find_widget(&self, elements: &[&ReplElement], window: &Window, cx: &mut Context<Self>) -> Option<Div> {
if !self.debug_console.find.open {
return None;
}
let look = TreeFindLook { input: InputId::ReplFind, message: self.repl_find_message(elements), filter_mode: self.repl_find_filter_mode(), fuzzy: self.repl_find_fuzzy(), input_width: INPUT_WIDTH };
let widget = self.tree_find_widget(look, |workbench, window, cx| workbench.close_repl_find(window, cx), window, cx);
// The console's mouse down focuses its input.
Some(widget.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()))
}
}