Visual Studio Code, rebuilt in Rust
Rust
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, OnceLock};
/// codicons.ts: the icons the workbench registers as another codicon's glyph, by its id or by its code point
/// (`register('drop-down-button', 0xeab4)`, chevron-down's; mapping.json lists none of these).
const DERIVED: [(&str, &str); 24] = [
("drop-down-button", "chevron-down"),
("symbol-customcolor", "symbol-color"),
("workspace-unspecified", "workspace-unknown"),
("git-fetch", "repo-fetch"),
("lightbulb-sparkle-autofix", "lightbulb-sparkle"),
("debug-breakpoint-pending", "issue-draft"),
("dialog-error", "error"),
("dialog-warning", "warning"),
("dialog-info", "info"),
("dialog-close", "close"),
("tree-item-expanded", "chevron-down"),
("tree-filter-on-type-on", "list-filter"),
("tree-filter-on-type-off", "list-selection"),
("tree-filter-clear", "close"),
("tree-item-loading", "loading"),
("menu-selection", "check"),
("menu-submenu", "chevron-right"),
("menubar-more", "more"),
("scrollbar-button-left", "triangle-left"),
("scrollbar-button-right", "triangle-right"),
("scrollbar-button-up", "triangle-up"),
("scrollbar-button-down", "triangle-down"),
("toolbar-more", "more"),
("quick-input-back", "arrow-left"),
];
/// The SVG for a codicon name. codiconsLibrary.ts registers aliases (`plus`, `gist-new`) under the code point of
/// another icon, and src/icons ships one file per code point; mapping.json lists the names of each code point.
pub fn svg_path(app_root: &Path, name: &str) -> PathBuf {
static ALIASES: OnceLock<HashMap<String, String>> = OnceLock::new();
let icons = app_root.join("node_modules/@vscode/codicons/src/icons");
let aliases = ALIASES.get_or_init(|| read_aliases(&app_root.join("node_modules/@vscode/codicons/src/template/mapping.json"), &icons));
let name = DERIVED.iter().find(|(derived, _)| *derived == name).map_or(name, |(_, glyph)| glyph);
icons.join(format!("{}.svg", aliases.get(name).map_or(name, String::as_str)))
}
/// iconRegistry.ts `_resolveIconDefinition`'s walk: `id`, then each registered default after it, ending at a codicon
/// with a font character. The defaults come from port/tools/gen-icon-registry.ts. A ThemeIcon id's `~modifier`
/// (`sync~spin`) is a CSS class of its own upstream, not part of the glyph's id.
pub fn icon_ids(id: &str) -> Vec<&str> {
static DEFAULTS: LazyLock<HashMap<String, String>> = LazyLock::new(|| serde_json::from_str(include_str!("icon_registry.json")).expect("icon_registry.json is a map of ids"));
let mut ids = vec![id.split_once('~').map_or(id, |(id, _)| id)];
while let Some(default) = DEFAULTS.get(*ids.last().expect("starts with id")) {
ids.push(default);
}
ids
}
fn read_aliases(mapping: &Path, icons: &Path) -> HashMap<String, String> {
let Ok(text) = std::fs::read_to_string(mapping) else { return HashMap::new() };
let groups: HashMap<String, Vec<String>> = serde_json::from_str(&text).expect("codicons mapping.json is a map of code points to names");
let mut aliases = HashMap::new();
for names in groups.into_values() {
let Some(file) = names.iter().find(|name| icons.join(format!("{name}.svg")).exists()) else { continue };
for name in &names {
if name != file {
aliases.insert(name.clone(), file.clone());
}
}
}
aliases
}
#[cfg(test)]
mod tests {
#[test]
fn an_alias_resolves_to_the_file_of_its_code_point() {
let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
assert!(super::svg_path(&app_root, "plus").ends_with("add.svg"));
assert!(super::svg_path(&app_root, "gear").ends_with("gear.svg"));
assert!(super::svg_path(&app_root, "git-fetch").ends_with("repo-fetch.svg"));
assert!(super::svg_path(&app_root, "toolbar-more").ends_with("ellipsis.svg"));
}
#[test]
fn a_registered_icon_resolves_through_its_defaults() {
assert_eq!(super::icon_ids("explorer-view-icon"), ["explorer-view-icon", "files"]);
assert_eq!(super::icon_ids("folding-manual-collapsed"), ["folding-manual-collapsed", "folding-collapsed", "chevron-right"]);
assert_eq!(super::icon_ids("gear"), ["gear"]);
assert_eq!(super::icon_ids("debug-start"), ["debug-start"]);
assert_eq!(super::icon_ids("sync~spin"), ["sync"]);
}
/// Every codicon and registered icon upstream knows draws the SVG of the code point codicon.css gives it, as
/// `Workbench::turned_icon` resolves it. Extension `$(id)`s go the same way; an unregistered one (copilot's
/// `$(symbol)`) has no glyph upstream either.
#[test]
fn every_icon_id_draws_the_svg_of_its_code_point() {
let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
let mut code_points = std::collections::BTreeMap::new();
let register = regex::Regex::new(r"register\('([\w-]+)', (?:0x([0-9a-fA-F]+)|'([\w-]+)')\)").unwrap();
for file in ["src/vs/base/common/codiconsLibrary.ts", "src/vs/base/common/codicons.ts"] {
let source = std::fs::read_to_string(app_root.join(file)).unwrap();
for captures in register.captures_iter(&source) {
let code_point = match (captures.get(2), captures.get(3)) {
(Some(hex), _) => u32::from_str_radix(hex.as_str(), 16).unwrap(),
(_, Some(alias)) => code_points[alias.as_str()],
_ => unreachable!(),
};
code_points.insert(captures[1].to_owned(), code_point);
}
}
let registry: std::collections::HashMap<String, String> = serde_json::from_str(include_str!("icon_registry.json")).unwrap();
let mapping: std::collections::HashMap<u32, Vec<String>> =
serde_json::from_str(&std::fs::read_to_string(app_root.join("node_modules/@vscode/codicons/src/template/mapping.json")).unwrap()).unwrap();
let mut wrong = Vec::new();
for id in code_points.keys().chain(registry.keys()) {
let codicon = *super::icon_ids(id).last().unwrap();
let path = super::svg_path(&app_root, crate::symbol_icons::svg_name(codicon));
let file = path.file_stem().unwrap().to_string_lossy().into_owned();
if !path.exists() || !mapping[&code_points[codicon]].contains(&file) {
wrong.push(format!("{id}: {file}"));
}
}
assert!(code_points.len() > 600, "{} codicons", code_points.len());
assert_eq!(wrong, Vec::<String>::new());
}
}