Visual Studio Code, rebuilt in Rust
Rust
use std::path::Path;
use gpui::TestAppContext;
use serde_json::json;
use super::*;
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;
#[test]
fn token_text_shows_tabs_as_arrows_spaces_as_dots_and_elides_past_40_characters() {
assert_eq!(render_token_text("\ta b"), "\u{2192}a\u{00B7}b");
assert_eq!(render_token_text(&"x".repeat(40)), "x".repeat(40));
let long = format!("{}{}", "a".repeat(30), "b".repeat(30));
assert_eq!(render_token_text(&long), format!("{}…{}", "a".repeat(20), "b".repeat(20)));
}
fn decoded(foreground: &str, background: &str) -> Decoded {
Decoded { foreground: Some(foreground.into()), background: Some(background.into()), ..Default::default() }
}
fn row(key: &str, value: &str) -> (String, Value_) {
(key.to_string(), Value_::text(value))
}
#[test]
fn metadata_rows_list_the_colors_their_contrast_and_the_font_styles() {
let textmate = Decoded { bold: true, italic: true, ..decoded("#FFFFFF", "#000000") };
let rows = format_metadata(None, Some(&textmate));
let expected = [row("foreground", "#FFFFFF"), row("background", "#000000"), row("contrast ratio", "21.00")];
assert_eq!(rows[..3], expected);
assert_eq!(rows[3], ("font style".to_string(), Value_::Runs(vec![("bold".into(), false), (" ".into(), false), ("italic".into(), false)])));
}
#[test]
fn a_translucent_background_has_no_contrast_ratio_and_no_font_style_has_no_row() {
let rows = format_metadata(None, Some(&decoded("#D4D4D4", "#1E1E1E80")));
assert_eq!(rows[2], ("Contrast ratio cannot be precise for background colors that use transparency".to_string(), Value_::Runs(Vec::new())));
assert_eq!(rows.len(), 3);
}
#[test]
fn a_translucent_foreground_is_blended_onto_the_background_for_the_contrast_ratio() {
let rows = format_metadata(None, Some(&decoded("#FFFFFF80", "#000000")));
let blended = make_opaque(parse_hex("#FFFFFF80").unwrap(), parse_hex("#000000").unwrap());
assert_eq!(blended, parse_hex("#808080").unwrap());
assert_eq!(rows[2], row("contrast ratio", &format!("{:.2}", contrast_ratio(blended, parse_hex("#000000").unwrap()))));
}
#[test]
fn what_the_semantic_token_sets_wins_and_shows_in_italics() {
let semantic = Decoded { foreground: Some("#4FC1FF".into()), background: None, bold: true, ..Default::default() };
let textmate = Decoded { italic: true, ..decoded("#9CDCFE", "#1F1F1F") };
let rows = format_metadata(Some(&semantic), Some(&textmate));
assert_eq!(rows[0], ("foreground".to_string(), Value_::Runs(vec![("#4FC1FF".into(), true)])));
assert_eq!(rows[1], row("background", "#1F1F1F"));
assert_eq!(rows[3], ("font style".to_string(), Value_::Runs(vec![("bold".into(), true), (" ".into(), false), ("italic".into(), false)])));
}
#[test]
fn the_matching_theme_rule_is_the_most_specific_selector_of_the_innermost_matching_scope() {
let rules = [
json!({ "settings": { "foreground": "#000000" } }),
json!({ "scope": "comment", "settings": { "foreground": "#111111" } }),
json!({ "scope": "source.ts comment.line, string", "settings": { "foreground": "#222222" } }),
json!({ "scope": ["comment.line"], "settings": { "foreground": "#333333" } }),
json!({ "scope": "source", "settings": { "fontStyle": "italic" } }),
];
let comment = ["source.ts", "comment.line.double-slash.ts"];
assert_eq!(find_matching_theme_rule(&rules, &comment), Some(("source.ts comment.line".into(), "{\n\t\"foreground\": \"#222222\"\n}".into())));
let outside = ["source.js", "comment.block.js"];
assert_eq!(find_matching_theme_rule(&rules, &outside).unwrap().0, "comment");
let keyword = ["source.ts", "keyword.ts"];
assert_eq!(find_matching_theme_rule(&rules, &keyword), Some(("source".into(), "{\n\t\"fontStyle\": \"italic\"\n}".into())));
assert_eq!(find_matching_theme_rule(&rules, &["text.plain"]), None);
}
#[test]
fn of_equally_specific_selectors_the_later_rule_wins() {
let rules = [json!({ "scope": "comment", "settings": { "foreground": "#111111" } }), json!({ "scope": "comment", "settings": { "foreground": "#222222" } })];
assert_eq!(find_matching_theme_rule(&rules, &["comment"]).unwrap().1, "{\n\t\"foreground\": \"#222222\"\n}");
}
fn textmate_at(document: &TextDocument, position: Position) -> Option<TextMateToken> {
document.tokens.token_at(&document.lines, position.line, position.column)
}
/// `_getTokensAtPosition` tokenizes anew, so a line past `editor.maxTokenizationLineLength` has its tokens here.
#[test]
fn a_line_past_the_tokenization_limit_is_tokenized_for_the_inspector() {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();
let languages = Languages::new(&extensions);
let theme = load_theme(&extensions, "Dark Modern").unwrap();
let path = std::env::temp_dir().join(format!("code-gpui-inspect-long-{}.ts", std::process::id()));
std::fs::write(&path, format!("let a = 1;\n// {}\n", "x".repeat(20_001))).unwrap();
let document = TextDocument::read(&path, &languages, &crate::default_settings().lock().unwrap()).unwrap();
std::fs::remove_file(&path).unwrap();
let position = Position::new(1, 4);
let inspection = inspect(&document, position, &theme, None, textmate_at(&document, position)).expect("a TextMate token");
assert_eq!(&inspection.tables[0][..2], &[row("language", "typescript"), row("standard token type", "Comment")]);
}
#[test]
fn a_typescript_comment_shows_its_scopes_innermost_first_and_the_theme_comment_rule() {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();
let languages = Languages::new(&extensions);
let theme = load_theme(&extensions, "Dark Modern").unwrap();
let path = std::env::temp_dir().join(format!("code-gpui-inspect-tokens-{}.ts", std::process::id()));
std::fs::write(&path, "let a = 1;\n// note\n").unwrap();
let document = TextDocument::read(&path, &languages, &crate::default_settings().lock().unwrap()).unwrap();
std::fs::remove_file(&path).unwrap();
let inspection = inspect(&document, Position::new(1, 4), &theme, None, textmate_at(&document, Position::new(1, 4))).unwrap();
assert_eq!(inspection.text, "\u{00B7}note");
assert_eq!(inspection.length, 5);
assert_eq!(&inspection.tables[0][..3], &[row("language", "typescript"), row("standard token type", "Comment"), row("foreground", "#6A9955")]);
let scopes = Value_::Scopes(vec!["comment.line.double-slash.ts".into(), "source.ts".into()]);
let rule = Value_::ThemeRule { selector: "comment".into(), settings: "{\n\t\"foreground\": \"#6A9955\"\n}".into(), struck: false };
assert_eq!(inspection.tables[1], [("textmate scopes".to_string(), scopes), ("foreground".to_string(), rule)]);
assert_eq!(inspection.tables.len(), 2);
}
#[test]
fn a_semantic_token_adds_its_table_and_strikes_the_textmate_rule_it_overrides() {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();
let languages = Languages::new(&extensions);
let theme = load_theme(&extensions, "Dark Modern").unwrap();
let path = std::env::temp_dir().join(format!("code-gpui-inspect-semantic-{}.ts", std::process::id()));
std::fs::write(&path, "const answer = 1;\n").unwrap();
let document = TextDocument::read(&path, &languages, &crate::default_settings().lock().unwrap()).unwrap();
std::fs::remove_file(&path).unwrap();
let legend = SemanticTokensLegend { token_types: vec!["variable".into()], token_modifiers: vec!["declaration".into(), "readonly".into()] };
// `answer` at 0:6, a variable declaration, which Dark Modern colors apart from the TextMate constant.
let tokens = (vec![0, 6, 6, 0, 0b01], legend);
let inspection = inspect(&document, Position::new(0, 8), &theme, Some(&tokens), textmate_at(&document, Position::new(0, 8))).unwrap();
assert_eq!((inspection.text.as_str(), inspection.length), ("answer", 6));
assert_eq!(inspection.tables[0][2], ("foreground".to_string(), Value_::Runs(vec![("#9CDCFE".into(), true)])));
assert_eq!(&inspection.tables[1][..2], &[row("semantic token type", "variable"), row("modifiers", "declaration")]);
let foreground = &inspection.tables[1][2];
assert_eq!(foreground.0, "foreground");
let Value_::ScopeRule { scope, selectors, .. } = &foreground.1 else { panic!("a TextMate rule styles {foreground:?}") };
assert_eq!(scope, "variable.other.readwrite");
assert!(selectors.contains(&"variable".to_string()), "{selectors:?}");
let textmate = inspection.tables[2].iter().find(|(key, _)| key == "foreground").expect("the TextMate rule row");
assert!(matches!(textmate.1, Value_::ThemeRule { struck: true, .. }), "{textmate:?}");
}
#[gpui::test]
fn the_command_toggles_the_widget_and_escape_or_another_model_stops_it(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
let theme = load_theme(&[themes], "Dark Modern").unwrap();
let dir = std::env::temp_dir().join(format!("code-gpui-inspect-tokens-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (first, second) = (dir.join("a.txt"), dir.join("b.txt"));
std::fs::write(&first, "a b\n").unwrap();
std::fs::write(&second, "c\n").unwrap();
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));
let toggle = |cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("editor.action.inspectTMScopes", vec![], window, cx));
let shown = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.inspect_tokens.shown.is_some());
workbench.update_in(cx, |workbench, window, cx| {
workbench.open_file(first.clone(), true, window, cx);
window.focus(&workbench.editor_focus, cx);
});
cx.run_until_parked();
toggle(cx);
assert!(shown(cx));
toggle(cx);
assert!(!shown(cx), "the command toggles");
toggle(cx);
cx.simulate_event(KeyUpEvent { keystroke: gpui::Keystroke::parse("escape").unwrap() });
assert!(!shown(cx), "Escape stops it");
toggle(cx);
workbench.update_in(cx, |workbench, window, cx| workbench.open_file(second.clone(), true, window, cx));
cx.run_until_parked();
assert!(!shown(cx), "another model stops it");
std::fs::remove_dir_all(&dir).unwrap();
}