Visual Studio Code, rebuilt in Rust
Rust
//! testingOutputPeek.ts: `vscode.peekTestError` and the `TestResultsPeek` it opens at a failed test's message,
//! with the message as its body (`TestResultsViewContent` with the history split hidden, its default).
use gpui::{AnyElement, Context, Window, div, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use super::peek_view::{PeekKind, PeekLayout};
use super::testing_results::{InspectSubject, message_text};
use crate::commands::Outcome;
use crate::editor::{OpenEditor, Position, VerticalReveal};
use crate::testing::{ResultItem, ResultState, TestResult};
/// testingOutputPeek.ts `_getMaximumHeightInLines`: "41 is experimentally determined to be the overhead of the peek
/// view itself".
const PEEK_OVERHEAD: f32 = 41.;
/// The content's padding and line height (`results_content`).
const CONTENT_PADDING: f32 = 16.;
const CONTENT_LINE_HEIGHT: f32 = 18.;
pub(super) struct TestingPeek {
pub(super) layout: PeekLayout,
subject: InspectSubject,
}
/// `getFailedCandidateMessage`: in a failed task, the last error message with a location (the test's own as the
/// fallback), else the first other message.
fn failed_candidate(item: &ResultItem) -> Option<(usize, usize, Value)> {
let fallback = (!item.item["uri"].is_null() && !item.item["range"].is_null()).then(|| json!({ "uri": item.item["uri"], "range": item.item["range"] }));
let mut best: Option<(usize, usize, Value)> = None;
for (task_index, task) in item.tasks.iter().enumerate() {
for (index, message) in task.messages.iter().enumerate() {
let Some(location) = Some(&message["location"]).filter(|location| !location.is_null()).cloned().or_else(|| fallback.clone()) else { continue };
if !matches!(task.state, ResultState::Failed | ResultState::Errored) || (best.is_some() && message["type"] != 0) {
continue;
}
best = Some((task_index, index, location));
}
}
best
}
impl Workbench {
pub(super) fn register_testing_peek_commands(&mut self) {
self.commands.register("vscode.peekTestError", |workbench, args, window, cx| {
let peeked = args.first().and_then(Value::as_str).is_some_and(|id| workbench.peek_test_error(id, window, cx));
Outcome::Ready(Ok(json!(peeked)))
});
self.commands.register("editor.closeTestPeek", |workbench, _, window, cx| {
workbench.close_testing_peek(window, cx);
Outcome::done()
});
}
/// testing.contribution.ts `vscode.peekTestError`: the newest result with the test, its own failure first, else
/// the first child's (`tryPeekFirstError`).
pub(super) fn peek_test_error(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
let Some(result) = self.testing.results.iter().find(|result| result.items.contains_key(id)) else { return false };
let Some((test, (task, message, location))) = first_failure(result, id) else { return false };
let subject = InspectSubject::Message { result: result.id.clone(), task, test, message };
self.show_testing_peek(subject, &location, window, cx);
true
}
/// `showPeekFromUri` with `selectionRevealType: NearTopIfOutsideViewport`, then `TestResultsPeek.setModel`.
fn show_testing_peek(&mut self, subject: InspectSubject, location: &Value, window: &mut Window, cx: &mut Context<Self>) {
let Some(path) = location["uri"]["path"].as_str().map(std::path::PathBuf::from) else { return };
let range = &location["range"];
let at = |key: &str| range[key].as_u64().unwrap_or(1) as usize;
self.close_testing_peek(window, cx);
self.open_file(path.clone(), true, window, cx);
let range = crate::anything_quick_access::TextRange { start_line_number: at("startLineNumber"), start_column: at("startColumn"), end_line_number: at("endLineNumber"), end_column: at("endColumn") };
self.select_range_revealed(&path, range, VerticalReveal::NearTopIfOutsideViewport, cx);
if self.editors.active().is_none_or(|editor| editor.document().path != path) {
return;
}
// `_getMaximumHeightInLines` from the content height, at most half the visible lines.
let lines = self.subject_text(&subject).unwrap_or_default().lines().count() as f32;
let viewport = self.editors.viewport;
let height = ((lines * CONTENT_LINE_HEIGHT + CONTENT_PADDING + PEEK_OVERHEAD) / viewport.line_height + 1.).min((viewport.height / viewport.line_height).round() / 2.);
let layout = self.open_peek_zone_lines(Position::new(at("startLineNumber").saturating_sub(1), at("startColumn").saturating_sub(1)), height, 0.7);
self.testing_peek = Some(TestingPeek { layout, subject });
cx.notify();
}
pub(super) fn close_testing_peek(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(peek) = self.testing_peek.take() else { return };
self.close_peek_zone(&peek.layout, None);
window.focus(&self.editor_focus, cx);
cx.notify();
}
/// `testing.isPeekVisible` on the editor that has the peek.
pub(super) fn testing_peek_context(&self, editor: &OpenEditor, context: &mut std::collections::HashMap<String, Value>) {
if self.testing_peek.as_ref().is_some_and(|peek| peek.layout.model_id == editor.model_id) {
context.insert("testing.isPeekVisible".into(), json!(true));
}
}
/// `TestResultsPeek`: `showInPlace` titles it with the message's first line and the test's label; the error
/// colors of `applyTheme`; the head's `MenuId.TestPeekTitle` actions and the close action.
pub(super) fn testing_peek_widget(&self, editor: &OpenEditor, content_left: f32, char_width: f32, cx: &mut Context<Self>) -> Option<AnyElement> {
let (label, description, text) = self.testing_peek_message()?;
let title = self.peek_title_parts(div().id("testing-peek-title"), label, description, String::new());
let actions = vec![self.peek_action("close", "Close", "editor.closeTestPeek", cx).into_any_element()];
let head = self.peek_head(title, actions).bg(self.color("editor.background")).child(div().absolute().inset_0().bg(self.color("testing.peekHeaderBackground")));
let lines: Vec<_> = text.lines().map(|line| div().whitespace_nowrap().child(line.to_owned())).collect();
self.peek_zone(PeekKind::Testing, editor, content_left, char_width, head.relative(), |_, _, _| {
let content = div().id("testing-peek-content").size_full().overflow_y_scroll().p(px(CONTENT_PADDING / 2.)).font_family("Menlo").text_size(px(12.)).line_height(px(CONTENT_LINE_HEIGHT)).flex().flex_col().children(lines);
(content.into_any_element(), false)
}, cx)
}
/// The peek's title (the message's first line), its description (the test's label) and the message.
fn testing_peek_message(&self) -> Option<(String, String, String)> {
let InspectSubject::Message { result, task, test, message } = &self.testing_peek.as_ref()?.subject else { return None };
let item = self.testing.results.iter().find(|candidate| candidate.id == *result)?.items.get(test)?;
let text = super::debug_console::strip_ansi(message_text(&item.tasks[*task].messages[*message]));
let label = text.lines().next().unwrap_or_default().to_owned();
Some((label, crate::command_palette::strip_icons(item.label()).trim().to_owned(), text))
}
}
/// The test's own failure, else the first failed descendant's in tree order (`result.tests` below the test).
fn first_failure(result: &TestResult, id: &str) -> Option<(String, (usize, usize, Value))> {
let item = &result.items[id];
if let Some(candidate) = failed_candidate(item) {
return Some((id.to_owned(), candidate));
}
item.children.iter().filter(|child| result.items.contains_key(*child)).find_map(|child| first_failure(result, child))
}
#[cfg(test)]
mod tests;