Visual Studio Code, rebuilt in Rust
Rust
//! The Testing view container (testingExplorerView.ts), the Test Results panel view's registration, the run glyphs
//! of testingDecorations.ts and the commands of testExplorerActions.ts.
use std::collections::HashSet;
use gpui::{ClickEvent, Context, Div, MouseButton, MouseDownEvent, Rgba, Window, div, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use crate::commands::Outcome;
use super::panel::PanelView;
use super::testing_filter::TestingFilter;
use crate::editor::OpenEditor;
use crate::menus::{MenuAction, MenuId, menu_group_actions};
use crate::testing::{ExpandState, GROUP_COVERAGE, GROUP_DEBUG, GROUP_RUN, ResultState};
/// testing.contribution.ts `Testing.ResultsPanelId`, the panel container of the Test Results view.
pub const TEST_RESULTS_VIEW_ID: &str = "workbench.panel.testResults";
/// `Testing.ExplorerViewId`, the Test Explorer view in the Testing container.
pub(super) const TESTING_VIEW: &str = "workbench.view.testing";
const ROW_HEIGHT: f32 = 22.;
const VIEW_MODE_KEY: &str = "testing.viewMode";
const VIEW_SORTING_KEY: &str = "testing.viewSorting";
const SORT_BY_LOCATION: &str = "location";
const SORT_BY_STATUS: &str = "status";
const SORT_BY_DURATION: &str = "duration";
/// The view state of the explorer and the results editor.
pub struct TestingView {
/// Rows the user collapsed; others below the roots start collapsed until expanded (`expanded`).
pub collapsed: HashSet<String>,
pub expanded: HashSet<String>,
/// The Test Results view: the opened subject, the selected and the focused row, the rows flipped from their
/// default collapse state and the tree's focus.
pub results_subject: Option<super::testing_results::InspectSubject>,
pub results_selected: Option<String>,
pub results_focused: Option<String>,
pub results_toggled: HashSet<String>,
pub results_focus: gpui::FocusHandle,
/// testResultsOutput.ts `TerminalMessagePeek`: its detached terminal and the text written to it.
pub results_terminal: Option<(u32, String)>,
/// testResultsViewContent.ts `setCallStackFrames`: the opened message's stack frames, and the collapsed frames
/// of its call stack widget by index, the message's own frame first.
pub call_stack: Vec<super::testing_results::CallStackFrame>,
pub call_stack_collapsed: HashSet<usize>,
/// Where the continuous run dropdown's chevron last painted, to anchor its menu.
pub continuous_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
/// Where the run, debug and coverage group dropdowns' chevrons last painted.
pub run_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
pub debug_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
pub coverage_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
/// The chevron whose menu showed, with that menu's `context_menus_shown` count.
pub open_dropdown: Option<(&'static str, usize)>,
pub filter: TestingFilter,
/// The tree's selected (and focused) row, its focus and scroll, and a reveal waiting for the tree's next paint.
pub selected: Option<String>,
pub tree_focus: gpui::FocusHandle,
pub scroll: gpui::ScrollHandle,
pub reveal_pending: std::cell::Cell<bool>,
/// testingExplorerView.ts `lastFocusState`: whether the tree, not the filter box, had the focus last.
pub last_focus_tree: std::cell::Cell<bool>,
}
impl TestingView {
pub fn new(cx: &mut gpui::App) -> Self {
TestingView {
collapsed: HashSet::new(),
expanded: HashSet::new(),
results_subject: None,
results_terminal: None,
call_stack: Vec::new(),
call_stack_collapsed: HashSet::new(),
results_selected: None,
results_focused: None,
results_toggled: HashSet::new(),
results_focus: cx.focus_handle(),
continuous_dropdown_bounds: Default::default(),
run_dropdown_bounds: Default::default(),
debug_dropdown_bounds: Default::default(),
coverage_dropdown_bounds: Default::default(),
open_dropdown: None,
filter: TestingFilter::new(cx),
selected: None,
tree_focus: cx.focus_handle(),
scroll: gpui::ScrollHandle::new(),
reveal_pending: std::cell::Cell::new(false),
last_focus_tree: std::cell::Cell::new(false),
}
}
}
/// testingStates icons (icons.ts `testingStatesToIcons`) and their colors (theme.ts `testStatesToIconColors`).
pub fn state_icon(state: ResultState) -> (&'static str, &'static str) {
match state {
ResultState::Errored => ("issues", "testing.iconErrored"),
ResultState::Failed => ("error", "testing.iconFailed"),
ResultState::Passed => ("pass", "testing.iconPassed"),
ResultState::Queued => ("history", "testing.iconQueued"),
ResultState::Running => ("loading", "icon.foreground"),
ResultState::Skipped => ("debug-step-over", "testing.iconSkipped"),
ResultState::Unset => ("circle-outline", "testing.iconUnset"),
}
}
impl Workbench {
/// testingExplorerView.ts `renderActivityBadge`: the spinner while a run is live, else the newest result's count
/// of `testing.countBadge` (failed by default) when not zero, else the eye while a continuous run is on.
pub(super) fn testing_badge(&self) -> Option<super::activity::Badge> {
if self.testing.is_running() {
return Some(super::activity::Badge::Icon("loading~spin"));
}
let count = self.testing.results.first().map_or(0, |last| match self.setting("testing.countBadge").as_str() {
Some("off") => 0,
Some("passed") => last.count(ResultState::Passed),
Some("skipped") => last.count(ResultState::Skipped),
_ => last.count(ResultState::Errored) + last.count(ResultState::Failed),
});
if count > 0 {
return Some(super::activity::Badge::Number(count as u64));
}
// icons.ts `testingContinuousIsOn`.
self.testing.is_continuous().then_some(super::activity::Badge::Icon("eye"))
}
/// testingExplorerView.ts `getLocalizedBadgeString`.
pub(super) fn testing_badge_description(&self, count: u64) -> String {
match self.setting("testing.countBadge").as_str() {
Some("passed") => format!("{count} passed tests"),
Some("skipped") => format!("{count} skipped tests"),
_ => format!("{count} failed tests"),
}
}
pub(super) fn register_testing_commands(&mut self) {
self.commands.register("workbench.view.testing", |workbench, _, window, cx| {
workbench.open_testing_view(true, window, cx);
Outcome::done()
});
self.register_testing_continuous_commands();
self.register_testing_profile_commands();
self.register_test_item_commands();
self.register_testing_gutter_commands();
self.register_testing_results_commands();
self.register_testing_coverage_commands();
self.register_testing_filter_commands();
self.commands.register("workbench.view.extension.test", |workbench, args, window, cx| workbench.execute_command("workbench.view.testing", args, window, cx));
for (id, group) in [("testing.runAll", GROUP_RUN), ("testing.debugAll", GROUP_DEBUG), ("testing.coverageAll", GROUP_COVERAGE)] {
self.commands.register(id, move |workbench, _, window, cx| {
let roots = workbench.testing.collection.roots.clone();
workbench.run_or_notify(&roots, group, window, cx);
Outcome::done()
});
}
// `ExecuteSelectedAction`: the view title's run of the tests the explorer shows.
for (id, group) in [("testing.runSelected", GROUP_RUN), ("testing.debugSelected", GROUP_DEBUG), ("testing.coverageSelected", GROUP_COVERAGE)] {
self.commands.register(id, move |workbench, _, window, cx| {
let (include, exclude) = workbench.testing_include_exclude(group, None);
workbench.run_tests(&include, Some(&exclude), group, window, cx);
cx.notify();
Outcome::done()
});
}
for (id, group) in [("testing.runCurrentFile", GROUP_RUN), ("testing.debugCurrentFile", GROUP_DEBUG), ("testing.coverageCurrentFile", GROUP_COVERAGE)] {
self.commands.register(id, move |workbench, _, window, cx| {
let Some(path) = workbench.editors.active().map(|editor| editor.document().path.to_string_lossy().into_owned()) else { return Outcome::done() };
let tests = workbench.top_tests_in_file(&path);
workbench.run_or_notify(&tests, group, window, cx);
Outcome::done()
});
}
for (id, group) in [("testing.runAtCursor", GROUP_RUN), ("testing.debugAtCursor", GROUP_DEBUG), ("testing.coverageAtCursor", GROUP_COVERAGE)] {
self.commands.register(id, move |workbench, _, window, cx| {
let Some(editor) = workbench.editors.active() else { return Outcome::done() };
let line = editor.selections[0].head.line as u32 + 1;
let tests = workbench.tests_at_line(&editor.document().path.to_string_lossy(), line);
workbench.run_or_notify(&tests, group, window, cx);
Outcome::done()
});
}
for (id, group) in [("testing.runTest", GROUP_RUN), ("testing.debugTest", GROUP_DEBUG)] {
self.commands.register(id, move |workbench, args, window, cx| {
let ids: Vec<String> = args.iter().filter_map(|arg| arg.as_str().or(arg["id"].as_str()).map(str::to_owned)).collect();
workbench.run_or_notify(&ids, group, window, cx);
Outcome::done()
});
}
// `vscode.runTestsById`-style entry testing.contribution.ts registers for `runTests` of a test id list.
self.commands.register("vscode.runTestsById", |workbench, args, window, cx| {
let group = args.first().and_then(Value::as_u64).unwrap_or(GROUP_RUN);
let ids: Vec<String> = args.iter().skip(1).filter_map(|arg| arg.as_str().map(str::to_owned)).collect();
Outcome::Ready(Ok(json!(workbench.run_tests(&ids, None, group, window, cx))))
});
self.commands.register("testing.cancelRun", |workbench, _, _, _| {
workbench.cancel_test_runs();
Outcome::done()
});
self.commands.register("testing.refreshTests", |workbench, args, _, cx| {
let mut controllers: Vec<String> = super::testing_item_menu::test_ids(&args).iter().map(|id| crate::testing::root_id(id).to_owned()).collect();
controllers.sort();
controllers.dedup();
workbench.refresh_tests(&controllers, cx);
Outcome::done()
});
self.commands.register("testing.cancelTestRefresh", |workbench, _, _, cx| {
workbench.testing.refreshes.clear();
cx.notify();
Outcome::done()
});
self.commands.register("testing.clearTestResults", |workbench, _, _, cx| {
workbench.testing.results.retain(|result| result.completed_at.is_none());
cx.notify();
Outcome::done()
});
self.commands.register("testing.showMostRecentOutput", |workbench, _, _, cx| {
workbench.open_panel_view(TEST_RESULTS_VIEW_ID, cx);
Outcome::done()
});
self.commands.register("testing.searchForTestExtension", |workbench, _, window, cx| workbench.execute_command("workbench.extensions.search", vec![json!("@category:\"testing\"")], window, cx));
self.commands.register("testing.collapseAll", |workbench, _, _, cx| {
workbench.testing_view.expanded.clear();
cx.notify();
Outcome::done()
});
for (id, key, value) in [
("testing.viewAsList", VIEW_MODE_KEY, "list"),
("testing.viewAsTree", VIEW_MODE_KEY, "true"),
("testing.sortByStatus", VIEW_SORTING_KEY, SORT_BY_STATUS),
("testing.sortByLocation", VIEW_SORTING_KEY, SORT_BY_LOCATION),
("testing.sortByDuration", VIEW_SORTING_KEY, SORT_BY_DURATION),
] {
self.commands.register(id, move |workbench, _, _, cx| {
workbench.workspace_storage.lock().unwrap().set(key, value.to_owned());
cx.notify();
Outcome::done()
});
}
}
/// The command's tests, else testExplorerActions.ts's "No tests found here" notification.
pub(super) fn run_or_notify(&mut self, ids: &[String], group: u64, window: &mut Window, cx: &mut Context<Self>) {
if self.run_tests(ids, None, group, window, cx).is_none() {
self.notify_error("No tests found here");
}
cx.notify();
}
/// The tests of the file that have no ancestor in it: what Run Tests in Current File runs.
fn top_tests_in_file(&self, path: &str) -> Vec<String> {
let collection = &self.testing.collection;
let in_file: HashSet<&str> = collection.items.values().filter(|item| item.path() == Some(path)).map(|item| item.id.as_str()).collect();
let mut ids: Vec<String> = in_file.iter().filter(|id| crate::testing::parent_id(id).is_none_or(|parent| !in_file.contains(parent))).map(|id| id.to_string()).collect();
ids.sort();
ids
}
/// testingDecorations.ts: the tests whose range starts on the line; the innermost at the cursor runs.
pub(super) fn tests_at_line(&self, path: &str, line: u32) -> Vec<String> {
let mut ids: Vec<String> = self.testing.collection.tests_in_file(path).filter(|item| item.start_line() == Some(line)).map(|item| item.id.clone()).collect();
ids.sort();
ids
}
/// `testing.automaticallyOpenTestResults`: `openOnTestStart` opens the results without focus.
pub(super) fn show_test_results_on_start(&mut self, run: &str, cx: &mut Context<Self>) {
// testResultsTree.ts `attachToResults`: a new run reveals its first task.
self.show_results_subject(super::testing_results::InspectSubject::Task { result: run.to_owned(), task: 0 });
self.testing_view.results_selected = Some(format!("{run}/0"));
self.testing_view.results_focused = Some(format!("{run}/0"));
if self.setting("testing.automaticallyOpenTestResults") == "openOnTestStart" {
self.open_panel_view(TEST_RESULTS_VIEW_ID, cx);
}
}
pub(super) fn test_output_changed(&mut self, _run: &str) {}
/// `openOnTestFailure` opens the results when a run ends with a failure.
pub(super) fn test_run_finished(&mut self, run: &str, cx: &mut Context<Self>) {
let failed = self.testing.results.iter().find(|result| result.id == run).is_some_and(|result| result.count(ResultState::Failed) + result.count(ResultState::Errored) > 0);
if failed && self.setting("testing.automaticallyOpenTestResults") == "openOnTestFailure" {
self.open_panel_view(TEST_RESULTS_VIEW_ID, cx);
}
}
/// testing.contribution.ts registers the Test Results container in the panel at order 3, `hideIfEmpty`: its
/// view's `when` is `testing.hasAnyResults`.
pub(super) fn register_test_results_panel_view(&mut self) {
self.register_panel_view(PanelView {
id: TEST_RESULTS_VIEW_ID,
view_id: "workbench.panel.testResults.view",
title: "Test Results",
open: |workbench, _, cx| workbench.open_panel_view(TEST_RESULTS_VIEW_ID, cx),
render: |workbench, window, cx| workbench.test_results_body(window, cx).into_any_element(),
actions: |_, _, _| gpui::Empty.into_any_element(),
visible: |workbench| !workbench.testing.results.is_empty(),
badge: |_| None,
});
}
/// `openView(Testing.ExplorerViewId, focus)`: `TestingExplorerView.focus` gives the focus back to the tree or
/// the filter box, whichever had it last.
pub(super) fn open_testing_view(&mut self, focus: bool, window: &mut Window, cx: &mut Context<Self>) {
self.show_view_container(super::view_locations::TESTING_CONTAINER, cx);
if focus {
let view = &self.testing_view;
let target = if view.last_focus_tree.get() { view.tree_focus.clone() } else { view.filter.focus.clone() };
window.focus(&target, cx);
}
}
/// Whether Testing has a view: the Test Explorer once a controller registers (its `when` is
/// `testing.providerCount > 0`), or a view contributed to `test`.
pub(super) fn testing_container_shown(&self) -> bool {
!self.testing.controllers.is_empty() || self.shown_views_of("test").iter().any(|view| self.stays_in(view, super::view_locations::TESTING_CONTAINER))
}
/// The Test Explorer pane: the welcome while no test is found, else the tests tree with the view's actions.
pub(super) fn testing_view_pane(&self, window: &Window, cx: &mut Context<Self>) -> super::view_panes::ViewPane {
let running = self.testing.is_running();
let has_tests = !self.testing.collection.roots.is_empty();
if self.testing_view.tree_focus.is_focused(window) {
self.testing_view.last_focus_tree.set(true);
} else if self.testing_view.filter.focus.is_focused(window) {
self.testing_view.last_focus_tree.set(false);
}
let mut actions = div().flex().gap(px(2.)).mr(px(4.));
if has_tests {
// testExplorerActions.ts `refreshMenus`: Refresh Tests, or Cancel Test Refresh while refreshing.
if self.testing.controllers.values().any(|controller| controller.capabilities & super::testing_service::CAPABILITY_REFRESH != 0) {
actions = actions.child(match self.testing.refreshes.is_empty() {
true => self.search_action("refresh", "testing.refreshTests", true, cx),
false => self.search_action("stop", "testing.cancelTestRefresh", true, cx),
});
}
// `getRunGroupDropdown`: a chevron beside Run Tests and Debug Tests once their group has two profiles.
let run_dropdown = self.testing.group_profile_count(GROUP_RUN) > 1;
let debug_dropdown = self.testing.group_profile_count(GROUP_DEBUG) > 1;
actions = actions.child(match running {
true => self.search_action("debug-stop", "testing.cancelRun", true, cx),
false => self.search_action("run-all", "testing.runSelected", true, cx),
});
if !running && run_dropdown {
let bounds = self.testing_view.run_dropdown_bounds.clone();
actions = actions.child(self.dropdown_chevron("testing-run-dropdown", bounds, |workbench, anchor, window, cx| workbench.show_run_group_dropdown(GROUP_RUN, anchor, window, cx), cx));
}
actions = actions.child(self.search_action("debug-alt-small", "testing.debugSelected", !running, cx));
if debug_dropdown {
let bounds = self.testing_view.debug_dropdown_bounds.clone();
actions = actions.child(self.dropdown_chevron("testing-debug-dropdown", bounds, |workbench, anchor, window, cx| workbench.show_run_group_dropdown(GROUP_DEBUG, anchor, window, cx), cx));
}
// `CoverageSelectedAction`, shown while idle once a coverage profile exists.
let coverage_profiles = self.testing.group_profile_count(GROUP_COVERAGE);
if !running && coverage_profiles > 0 {
actions = actions.child(self.search_action("run-all-coverage", "testing.coverageSelected", true, cx));
}
if !running && coverage_profiles > 1 {
let bounds = self.testing_view.coverage_dropdown_bounds.clone();
actions = actions.child(self.dropdown_chevron("testing-coverage-dropdown", bounds, |workbench, anchor, window, cx| workbench.show_run_group_dropdown(GROUP_COVERAGE, anchor, window, cx), cx));
}
// testExplorerActions.ts `continuousMenus`, ordered `RunUsing`.
if self.testing.profiles.iter().any(|profile| profile.supports_continuous_run) {
actions = actions.child(match self.testing.is_continuous_for("") {
true => self.search_action("eye-closed", "testing.stopContinuousRun", true, cx),
false => self.search_action("eye", "testing.startContinuousRun", true, cx),
});
if self.testing.continuous_dropdown_profiles().len() > 1 {
let bounds = self.testing_view.continuous_dropdown_bounds.clone();
actions = actions.child(self.dropdown_chevron("testing-continuous-run-dropdown", bounds, |workbench, anchor, window, cx| workbench.show_continuous_run_dropdown(anchor, window, cx), cx));
}
}
// `ShowMostRecentOutputAction`, navigation order `Collapse`, enabled by `testing.hasAnyResults`.
actions = actions.child(self.search_action("terminal", "testing.showMostRecentOutput", !self.testing.results.is_empty(), cx));
actions = actions.child(self.testing_more_actions(cx));
}
let mut body = div().id("testing-tree").debug_selector(|| "testing-tree".into()).track_focus(&self.testing_view.tree_focus).flex().flex_col();
if !has_tests {
// testing.contribution.ts `registerViewWelcomeContent` of the Test Explorer.
body = body.child(div().px(px(20.)).py(px(13.)).text_size(px(13.)).child("No tests have been found in this workspace yet."));
body = body.child(div().px(px(20.)).child(self.testing_button("Install Additional Test Extensions...", "testing.searchForTestExtension", cx)));
} else {
let mut rows = Vec::new();
let visible = self.testing_filtered_tests().map(|(visible, _)| visible);
for id in self.explorer_children(None) {
self.test_rows(&id, 0, visible.as_ref(), &mut rows, window, cx);
}
self.reveal_selected_test_row(rows.iter().position(|(id, _)| self.testing_view.selected.as_ref() == Some(id)), rows.len(), window);
body = body.children(rows.into_iter().map(|(_, row)| row));
}
let filter = has_tests.then(|| self.testing_filter_box(window, cx));
let summary = has_tests.then(|| self.result_summary()).flatten();
let body = div().flex_1().min_h_0().flex().flex_col().children(filter).children(summary).child(self.scrollable("testing-tree", Some(&self.testing_view.scroll), body, cx).flex_1()).into_any_element();
super::view_panes::ViewPane { id: TESTING_VIEW, title: "Test Explorer".into(), description: None, actions: has_tests.then(|| actions.into_any_element()), draws_more: has_tests, show_actions: false, body }
}
/// testingExplorerView.ts `ResultSummaryView` while no result exists: "No test results yet." in its 27px
/// container (testing.css `.result-summary-container`).
fn result_summary(&self) -> Option<Div> {
self.testing.results.is_empty().then(|| div().h(px(27.)).flex_none().px(px(12.)).pb(px(8.)).child("No test results yet."))
}
/// The view title's "...": the `viewAs`, `sortBy` and `displayAction` groups of testExplorerActions.ts.
fn testing_more_actions(&self, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
let foreground = self.foreground_or("icon.foreground");
self.icon("ellipsis", 22., 16., foreground)
.id("testing-more")
.rounded(px(4.))
.cursor_pointer()
.hover(|action| action.bg(self.color("toolbar.hoverBackground")))
.on_mouse_down(MouseButton::Left, cx.listener(|workbench, event: &MouseDownEvent, window, cx| {
cx.stop_propagation();
workbench.show_testing_more_menu(event.position, window, cx);
}))
.on_click(cx.listener(|workbench, event: &ClickEvent, window, cx| {
cx.stop_propagation();
if event.is_keyboard() {
workbench.show_testing_more_menu(event.position(), window, cx);
}
}))
.child(self.hover_target("testing-more-hover", super::hover::HoverContent::Text("More Actions...".into()), super::hover::HoverOptions::action_item()))
}
pub(super) fn show_testing_more_menu(&mut self, position: gpui::Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let actions = self.testing_more_menu_actions();
let actions = self.view_secondary_actions(TESTING_VIEW, actions);
let context = self.key_context(window);
self.show_context_menu_actions(actions, &context, gpui::Bounds::new(position, Default::default()), Vec::new(), window, cx);
}
pub(super) fn testing_more_menu_actions(&self) -> Vec<MenuAction> {
let list = self.testing_list_mode();
let sorting = self.testing_sorting();
let command = |id: &str, title: &str, checked: bool| MenuAction::Command { id: id.into(), title: title.into(), enabled: true, checked, alt: None };
vec![
command("testing.viewAsList", "View as List", list),
command("testing.viewAsTree", "View as Tree", !list),
MenuAction::Separator,
command("testing.sortByStatus", "Sort by Status", sorting == SORT_BY_STATUS),
command("testing.sortByLocation", "Sort by Location", sorting == SORT_BY_LOCATION),
command("testing.sortByDuration", "Sort by Duration", sorting == SORT_BY_DURATION),
MenuAction::Separator,
command("testing.collapseAll", "Collapse All Tests", false),
command("testing.clearTestResults", "Clear All Results", false),
]
}
/// constants.ts `TestExplorerViewMode`, stored as testingExplorerView.ts `testing.viewMode` (`list` or `true`).
pub(super) fn testing_list_mode(&self) -> bool {
self.workspace_storage.lock().unwrap().get(VIEW_MODE_KEY) == Some("list")
}
/// `TestExplorerViewSorting`, stored as `testing.viewSorting`, `location` by default.
fn testing_sorting(&self) -> String {
self.workspace_storage.lock().unwrap().get(VIEW_SORTING_KEY).unwrap_or(SORT_BY_LOCATION).to_owned()
}
/// The explorer's rows under `parent` (the top level for `None`, without the root of a single controller):
/// treeProjection.ts or listProjection.ts, sorted by testingExplorerView.ts `TreeSorter`.
pub(super) fn explorer_children(&self, parent: Option<&str>) -> Vec<String> {
let collection = &self.testing.collection;
let mut children = match (parent, self.testing_list_mode()) {
(None, _) if collection.roots.len() > 1 => collection.roots.clone(),
(None, false) => self.testing_top_level(),
(Some(id), false) => collection.children_of(id).to_vec(),
(None, true) => collection.roots.first().map(|root| self.test_leaves(root)).unwrap_or_default(),
(Some(id), true) if crate::testing::parent_id(id).is_none() => self.test_leaves(id),
(Some(_), true) => Vec::new(),
};
match self.testing_sorting().as_str() {
SORT_BY_STATUS => children.sort_by_key(|id| std::cmp::Reverse(self.testing.state_of(id).unwrap_or_default().priority())),
SORT_BY_DURATION => children.sort_by(|a, b| self.test_duration(b).unwrap_or(0.).total_cmp(&self.test_duration(a).unwrap_or(0.))),
_ => {}
}
children
}
/// listProjection.ts: the tests under the root without children, in location order.
fn test_leaves(&self, root: &str) -> Vec<String> {
let collection = &self.testing.collection;
let mut leaves = Vec::new();
let mut stack: Vec<&String> = collection.children_of(root).iter().rev().collect();
while let Some(id) = stack.pop() {
match collection.children_of(id) {
[] => leaves.push(id.clone()),
children => stack.extend(children.iter().rev()),
}
}
leaves.sort_by(|a, b| crate::testing::compare_tests(&collection.items[a], &collection.items[b]));
leaves
}
/// getComputedState.ts `getComputedDuration`: the test's own duration, else the sum of its children's.
fn test_duration(&self, id: &str) -> Option<f64> {
let own = self.testing.results.iter().find(|result| result.items.contains_key(id)).and_then(|result| result.items[id].own_duration);
if own.is_some() {
return own;
}
let durations: Vec<f64> = self.testing.collection.children_of(id).iter().filter_map(|child| self.test_duration(child)).collect();
(!durations.is_empty()).then(|| durations.iter().sum())
}
fn testing_button(&self, label: &str, command: &'static str, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
div()
.id(command)
.h(px(26.))
.w_full()
.flex()
.items_center()
.justify_center()
.rounded(px(4.))
.bg(self.color("button.background"))
.text_color(self.color("button.foreground"))
.cursor_pointer()
.child(label.to_owned())
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
workbench.execute_command(command, Vec::new(), window, cx);
}))
}
/// The rows of the test and its expanded descendants that the filter leaves `visible` (all of them without one).
fn test_rows(&self, id: &str, depth: usize, visible: Option<&HashSet<String>>, rows: &mut Vec<(String, gpui::AnyElement)>, window: &Window, cx: &mut Context<Self>) {
if visible.is_some_and(|visible| !visible.contains(id)) {
return;
}
let Some(item) = self.testing.collection.items.get(id) else { return };
let list_mode = self.testing_list_mode();
let children = self.explorer_children(Some(id));
let is_root = crate::testing::parent_id(id).is_none();
let expandable = match list_mode {
true => is_root,
false => item.expand != ExpandState::NotExpandable || !children.is_empty(),
};
let expanded = expandable && self.test_row_expanded(id);
let state = self.testing.state_of(id).unwrap_or_default();
let (icon, color) = state_icon(state);
// icons.ts: `.computed-state.retired` takes the state's retired color; Running has none.
let icon_color = match state != ResultState::Running && self.testing.is_retired(id) {
true => self.foreground_or(&format!("{color}.retired")),
false => self.foreground_or(color),
};
let twistie_color = self.foreground_or("icon.foreground");
let hover = self.color("list.hoverBackground");
let (row_id, toggle_id, menu_id, expand) = (id.to_owned(), id.to_owned(), id.to_owned(), item.expand);
// listWidget.ts: the focused tree draws the active selection colors and outlines its focused row.
let selected = self.testing_view.selected.as_deref() == Some(id);
let tree_focused = self.testing_view.tree_focus.is_focused(window);
let selection = match tree_focused {
true => self.color("list.activeSelectionBackground"),
false => self.color("list.inactiveSelectionBackground"),
};
let focus_outline = self.theme.color("list.focusOutline").or(self.theme.color("focusBorder")).filter(|_| selected && tree_focused);
let mut actions = div().ml_auto().flex();
for action in self.test_row_inline_actions(id, window) {
let MenuAction::Command { id: command, title, .. } = action else { continue };
if command == "testing.toggleContinuousRunForTest" {
actions = actions.children(self.continuous_run_action(item, cx));
continue;
}
let button = self.command_button(&command, title, vec![self.test_item_arg(id)], self.foreground_or("icon.foreground"), cx);
actions = actions.child(button.invisible().group_hover("testing-row", |action| action.visible()));
}
let mut row = div()
.id(gpui::SharedString::from(format!("test:{id}")))
.group("testing-row")
.h(px(ROW_HEIGHT))
.mx(px(self.pane_row_inset()))
.pl(px(8. * depth as f32 + 4.))
.flex()
.items_center()
.relative()
.rounded(px(4.))
.cursor_pointer()
.when(!selected, |row| row.hover(move |row| row.bg(hover)))
.when(selected, |row| row.bg(selection))
.when_some(focus_outline, |row, outline| row.child(div().absolute().inset_0().rounded(px(4.)).border_1().border_color(outline)))
.child(match expandable {
true => self.icon(if expanded { "chevron-down" } else { "chevron-right" }, 16., 16., twistie_color),
false => div().w(px(16.)).flex_none(),
})
.child(self.icon(icon, 22., 16., icon_color))
.child(div().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(item.label().to_owned()));
// listProjection.ts `ListTestItemElement.description`: the labels between the root and the test.
let description = match list_mode && !is_root {
true => Some(self.test_ancestor_labels(id)).filter(|labels| !labels.is_empty()),
false => item.item["description"].as_str().map(str::to_owned),
};
if let Some(description) = description {
row = row.child(div().ml(px(6.)).text_size(px(12.)).opacity(0.7).whitespace_nowrap().child(description));
}
// testing.css `.test-is-hidden`: dimmed, with `testing-hidden` beside it unless the row is hovered.
if self.testing.excluded.iter().any(|excluded| excluded == id) {
row = row.opacity(0.8).child(self.icon("eye-closed", 16., 16., twistie_color).ml_auto().mr(px(9.)).group_hover("testing-row", |icon| icon.invisible()));
}
row = row.child(actions).on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
workbench.show_test_item_menu(&menu_id, gpui::Bounds::new(event.position, Default::default()), window, cx);
}));
row = row.on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {
workbench.testing_view.selected = Some(row_id.clone());
window.focus(&workbench.testing_view.tree_focus.clone(), cx);
if event.click_count() == 2 {
workbench.reveal_test(&row_id, window, cx);
return;
}
if !expandable {
workbench.reveal_test(&row_id, window, cx);
return;
}
let view = &mut workbench.testing_view;
match expanded {
true => {
view.expanded.remove(&toggle_id);
view.collapsed.insert(toggle_id.clone());
}
false => {
view.collapsed.remove(&toggle_id);
view.expanded.insert(toggle_id.clone());
// testingExplorerView.ts `onDidChangeCollapseState`: expanding resolves the children.
if expand == ExpandState::Expandable {
workbench.host.send("ExtHostTesting", "$expandTest", vec![json!(toggle_id), json!(0)]);
}
}
}
cx.notify();
}));
rows.push((id.to_owned(), row.into_any_element()));
if expanded {
for child in &children {
self.test_rows(child, depth + 1, visible, rows, window, cx);
}
}
}
/// index.ts `getChildrenForParent`: a controller root starts expanded, deeper tests collapsed.
pub(super) fn test_row_expanded(&self, id: &str) -> bool {
!self.testing_view.collapsed.contains(id) && (crate::testing::parent_id(id).is_none() || self.testing_view.expanded.contains(id))
}
/// display.ts `flatTestItemDelimiter` between the labels of the test's ancestors below its root.
pub(super) fn test_ancestor_labels(&self, id: &str) -> String {
let mut labels = Vec::new();
let mut parent = crate::testing::parent_id(id);
while let Some(ancestor) = parent.filter(|ancestor| crate::testing::parent_id(ancestor).is_some()) {
labels.push(self.testing.collection.items[ancestor].label());
parent = crate::testing::parent_id(ancestor);
}
labels.reverse();
labels.join(" \u{203a} ")
}
/// testingExplorerView.ts `revealById`: `reveal(focusTarget, 0.5)` once the tree has painted with the row.
fn reveal_selected_test_row(&self, index: Option<usize>, count: usize, window: &Window) {
if !self.testing_view.reveal_pending.get() {
return;
}
let scroll = &self.testing_view.scroll;
let viewport = f32::from(scroll.bounds().size.height);
if viewport <= 0. {
window.request_animation_frame();
return;
}
self.testing_view.reveal_pending.set(false);
let Some(index) = index else { return };
let list = crate::list_tree::ListScroll { count, row_height: ROW_HEIGHT, viewport, scroll_top: -f32::from(scroll.offset().y) };
if let Some(scroll_top) = crate::list_tree::reveal_scroll_top(list, index, true) {
scroll.set_offset(gpui::point(px(0.), px(-scroll_top)));
}
}
/// testingExplorerView.ts `fillActionBar`: `MenuId.TestItem`'s `inline` group, run on the row as `TestItemContext`.
pub(super) fn test_row_inline_actions(&self, id: &str, window: &Window) -> Vec<MenuAction> {
menu_group_actions(&self.test_item_menus(), MenuId::TestItem, &self.test_item_context(id, window), |group| group == "inline")
}
/// Whether the menu the chevron `id` showed is still the one open.
pub(super) fn dropdown_open(&self, id: &str) -> bool {
self.context_menu.is_some() && self.testing_view.open_dropdown.is_some_and(|(open, shown)| open == id && shown == self.context_menus_shown)
}
/// dropdownWithPrimaryActionViewItem.ts's chevron beside its primary action, overlapping it by 3px; a press
/// shows `show` anchored at the chevron, which takes `toolbar.activeBackground` while it is open (style.css
/// `.monaco-dropdown.active .action-label`).
fn dropdown_chevron(&self, id: &'static str, bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>, show: fn(&mut Self, gpui::Bounds<gpui::Pixels>, &mut Window, &mut Context<Self>), cx: &mut Context<Self>) -> Div {
let hover = self.color("toolbar.hoverBackground");
let open = self.dropdown_open(id);
let chevron = self
.icon("chevron-down", 16., 12., self.foreground_or("icon.foreground"))
.h(px(22.))
.id(id)
.absolute()
.left(px(-3.))
.rounded(px(4.))
.cursor_pointer()
.hover(|action| action.bg(hover))
.when(open, |action| action.bg(self.color("toolbar.activeBackground")))
.child(super::output_view::bounds_tracker(bounds.clone()))
.on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _: &MouseDownEvent, window, cx| {
cx.stop_propagation();
show(workbench, bounds.get(), window, cx);
workbench.testing_view.open_dropdown = Some((id, workbench.context_menus_shown));
}));
// dropdown.css `margin-left: -3px` as a 13px slot: Taffy sizes a `flex: none` row without the negative margin,
// which pushed the view title's actions out of the side bar.
div().relative().flex_none().w(px(13.)).h(px(22.)).child(chevron)
}
/// testExplorerActions.ts `ContinuousRunTestAction`, the row's last action: shown without hover while the test
/// or a child runs continuously (testing.css `testing-is-continuous-run`), disabled under a parent's run.
fn continuous_run_action(&self, item: &crate::testing::TestItem, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
let supported = self.testing.profiles.iter().any(|profile| profile.supports_continuous_run && profile.controller_id == item.controller_id() && profile.can_run(item));
if !supported {
return None;
}
let on = self.testing.is_continuous_for(&item.id);
let enabled = on || !self.testing.is_continuous_for_a_parent_of(&item.id);
let foreground = if on { self.color("inputOption.activeForeground") } else { self.foreground_or("icon.foreground") };
let id = item.id.clone();
let mut action = self.icon("eye", 22., 16., foreground).id(gpui::SharedString::from(format!("continuous:{id}"))).rounded(px(3.));
if on {
action = action.bg(self.color("inputOption.activeBackground")).border_1().border_color(self.color("inputOption.activeBorder"));
}
if !enabled {
action = action.opacity(0.4);
} else {
action = action.cursor_pointer().on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
cx.stop_propagation();
workbench.execute_command("testing.toggleContinuousRunForTest", vec![json!(id)], window, cx);
}));
}
if on || self.testing.is_continuous_for_a_child_of(&item.id) {
return Some(action);
}
Some(action.invisible().group_hover("testing-row", |action| action.visible()))
}
/// testExplorerActions.ts `GoToTest`: the test's file at its range.
pub(super) fn reveal_test(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
let Some(item) = self.testing.collection.items.get(id) else { return };
let (Some(path), Some(line)) = (item.path().map(std::path::PathBuf::from), item.start_line()) else { return };
let column = item.item["range"]["startColumn"].as_u64().unwrap_or(1) as usize;
self.open_file(path.clone(), true, window, cx);
let line = line as usize;
self.select_range(&path, crate::anything_quick_access::TextRange { start_line_number: line, start_column: column, end_line_number: line, end_column: column }, cx);
}
/// Expands the rows above the test, as the explorer does to show it.
pub(super) fn expand_test_ancestors(&mut self, id: &str) {
let mut parent = crate::testing::parent_id(id);
while let Some(ancestor) = parent {
self.testing_view.collapsed.remove(ancestor);
self.testing_view.expanded.insert(ancestor.to_owned());
parent = crate::testing::parent_id(ancestor);
}
}
/// testingDecorations.ts `RunTestDecoration` glyph of the line: the tests starting there, the worst state of
/// them, a run icon while none ran. A click runs them with `testing.defaultGutterClickAction` (Alt runs the
/// alternate group), or shows the line's menu as a right click does.
pub(super) fn test_glyph(&self, editor: &OpenEditor, line: u32, cx: &mut Context<Self>) -> Option<gpui::AnyElement> {
// callStackWidget.ts frame editors take only its `ClickToLocationContribution`, not `TestingDecorations`.
if self.setting("testing.gutterEnabled") == false || editor.document().scheme != "file" || self.call_stack_frame(editor).is_some() {
return None;
}
let path = editor.document().path.to_string_lossy().into_owned();
let tests = self.tests_at_line(&path, line);
if tests.is_empty() {
return None;
}
let state = tests.iter().fold(ResultState::Unset, |state, id| state.max(self.testing.state_of(id).unwrap_or_default()));
let multiple = tests.len() > 1 || tests.iter().any(|id| !self.testing.collection.children_of(id).is_empty());
let (icon, color) = match state {
ResultState::Unset => (if multiple { "run-all" } else { "run" }, "testing.runAction"),
state => state_icon(state),
};
// testingDecorations.ts: `testing-run-glyph retired` when a test of the line is retired; the run icons have no retired color.
let retired = state != ResultState::Unset && state != ResultState::Running && tests.iter().any(|id| self.testing.is_retired(id));
let color: Rgba = match retired {
true => self.foreground_or(&format!("{color}.retired")),
false => self.foreground_or(color),
};
let click_action = self.setting("testing.defaultGutterClickAction");
let index = line as usize - 1;
Some(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.child(self.icon(icon, 16., 16., color))
.on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
cx.stop_propagation();
// macOS takes Ctrl+click for a right click.
if event.modifiers.control || click_action == "contextMenu" {
workbench.show_line_number_context_menu(index, event.position, false, window, cx);
return;
}
let group = match (click_action.as_str(), event.modifiers.alt) {
(Some("debug"), true) => GROUP_RUN,
(Some("debug"), false) | (Some("runWithCoverage"), true) => GROUP_DEBUG,
(Some("runWithCoverage"), false) => GROUP_COVERAGE,
(_, true) => GROUP_DEBUG,
(_, false) => GROUP_RUN,
};
workbench.run_or_notify(&tests, group, window, cx);
}))
// The editor gutter's menu, before breakpointEditorContribution.ts's glyph margin handling.
.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
cx.stop_propagation();
workbench.show_line_number_context_menu(index, event.position, false, window, cx);
}))
.into_any_element(),
)
}
}
#[cfg(test)]
mod tests;