Visual Studio Code, rebuilt in Rust
Rust
//! workbench/services/activity (activityService.ts) and the badge of compositeBarActions.ts: each view container
//! collects activities (a view's `$setBadge`, progress shown on the container, the SCM and Extensions counts) and its
//! activity bar item shows one badge, progress first, then the sum of the number badges.
use std::collections::HashMap;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use gpui::{Animation, AnimationExt, AnyElement, Context, Div, InteractiveElement, IntoElement, ParentElement, Styled, Transformation, Window, div, percentage, prelude::FluentBuilder, px, relative, svg};
use serde_json::Value;
use super::Workbench;
/// progressService.ts `showOnActivityBar`: the badge waits for `options.delay` (300 by default) and stays at least
/// 300 ms once shown.
const PROGRESS_DELAY: Duration = Duration::from_millis(300);
const PROGRESS_MIN_TIME: Duration = Duration::from_millis(300);
/// progressService.css `.progress-badge > .badge-content::before`: the 13px sync glyph of its data URL mask.
const PROGRESS_ICON: &str = include_str!("activity/progress-badge.svg");
pub(super) fn progress_badge_icon(color: gpui::Rgba) -> AnyElement {
svg().external_path(progress_icon_path()).size(px(13.)).text_color(color).into_any_element()
}
/// gpui draws svgs from paths: the glyph is written once to the temporary folder.
fn progress_icon_path() -> &'static str {
static PATH: OnceLock<String> = OnceLock::new();
PATH.get_or_init(|| {
let path = std::env::temp_dir().join(format!("vsrustium-progress-badge-{}.svg", std::process::id()));
std::fs::write(&path, PROGRESS_ICON).expect("the temporary folder is writable");
path.to_string_lossy().into_owned()
})
}
#[derive(Clone, Debug, PartialEq)]
pub(super) enum Badge {
Number(u64),
Progress,
/// `IconBadge`: a codicon id, `~spin` turning it.
Icon(&'static str),
}
/// What an activity bar item's badge shows.
#[derive(Clone, Debug, PartialEq)]
pub(super) enum BadgeContent {
Progress,
Icon(&'static str),
Text(String),
}
/// A container's `ProgressBadge` from a running `withProgress`: shown after its delay, kept its minimum time.
struct ProgressActivity {
container: String,
shown: Option<Instant>,
}
/// progressIndicator.ts `ScopedProgressIndicator` under a `withCompositeProgress`: discrete, worked of total, or
/// infinite (`showWhile`). A discrete runner gone infinite stays infinite: `worked` on a done runner has no total.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum CompositeProgress {
Discrete { total: f64, worked: f64 },
Infinite { after_discrete: bool },
}
/// The progress bar of a container (`withPaneCompositeProgress`) or of a view (`withViewProgress`), by its id.
struct ScopedProgress {
scope: String,
state: CompositeProgress,
/// `ProgressBar.show(delay)`: hidden until `options.delay` passes.
visible: bool,
}
#[derive(Default)]
pub(super) struct Activities {
progress: HashMap<u64, ProgressActivity>,
bars: HashMap<u64, ScopedProgress>,
}
/// compositeBarActions.ts `getVisibleBadges` and `updateActivity`: progress wins over icons, icons over numbers (the
/// first icon shows); numbers add up and show as `1K`, `1K+` past 999. `None` shows no badge.
pub(super) fn visible_badge(badges: &[Badge]) -> Option<BadgeContent> {
if badges.contains(&Badge::Progress) {
return Some(BadgeContent::Progress);
}
if let Some(icon) = badges.iter().find_map(|badge| if let Badge::Icon(icon) = badge { Some(*icon) } else { None }) {
return Some(BadgeContent::Icon(icon));
}
let total: u64 = badges.iter().map(|badge| if let Badge::Number(number) = badge { *number } else { 0 }).sum();
if total == 0 {
return None;
}
if total <= 999 {
return Some(BadgeContent::Text(total.to_string()));
}
let thousands = total as f64 / 1000.;
let floor = thousands.floor();
Some(BadgeContent::Text(if thousands > floor { format!("{floor}K+") } else { format!("{floor}K") }))
}
impl Workbench {
/// The view container of a view id, as `getViewContainerByViewId` for the views the port has.
pub(super) fn view_container_of_view(&self, view: &str) -> Option<String> {
match view {
"workbench.explorer.fileView" | "outline" | "timeline" => return Some("workbench.view.explorer".into()),
"workbench.scm" | "workbench.scm.repositories" | "workbench.scm.history" => return Some("workbench.view.scm".into()),
_ => {}
}
let key = &self.tree_views.views.iter().find(|contributed| contributed.id == view)?.container;
Some(match key.as_str() {
"explorer" => "workbench.view.explorer".into(),
"scm" => "workbench.view.scm".into(),
"debug" => "workbench.view.debug".into(),
"test" => "workbench.view.testing".into(),
key => self.tree_views.containers.iter().find(|container| container.key == key)?.id.to_owned(),
})
}
/// `getViewContainerActivities`: the container's badges this frame.
pub(super) fn container_badges(&self, container: &str) -> Vec<Badge> {
let mut badges = Vec::new();
if self.activities.progress.values().any(|progress| progress.container == container && progress.shown.is_some()) {
badges.push(Badge::Progress);
}
// viewPane.ts `updateBadge`: a view's badge goes to its container (`showViewActivity`).
for view in &self.tree_views.views {
if self.view_container_of_view(view.id).as_deref() != Some(container) {
continue;
}
if let Some(value) = self.tree_view_badge(view.id).and_then(|badge| badge["value"].as_u64()) {
badges.push(Badge::Number(value));
}
}
match container {
"workbench.view.explorer" => {
badges.push(Badge::Number(self.dirty_working_copy_count()));
}
"workbench.view.scm" => badges.push(Badge::Number(self.scm_badge())),
"workbench.view.extensions" => badges.push(Badge::Number(self.extensions_badge().map_or(0, |(count, _)| count as u64))),
"workbench.view.testing" => badges.extend(self.testing_badge()),
// debugService.ts `onDidChangeCallStack`: the Call Stack's container counts the sessions without a parent.
"workbench.view.debug" => badges.push(Badge::Number(self.debug.sessions.iter().filter(|session| session.parent.is_none()).count() as u64)),
_ => {}
}
badges
}
pub(super) fn container_activity_badge(&self, container: &str) -> Option<Div> {
if !self.badges_enabled(container) {
return None;
}
Some(self.activity_badge(visible_badge(&self.container_badges(container))?))
}
pub(super) fn activity_badge(&self, content: BadgeContent) -> Div {
let foreground = self.color("activityBarBadge.foreground");
let badge = div()
.absolute()
.top(px(18.))
.right(px(3.))
.h(px(16.))
.rounded(px(20.))
.flex()
.items_center()
.justify_center()
.bg(self.color("activityBarBadge.background"))
.text_color(foreground)
.when_some(self.theme.color("contrastBorder"), |badge, border| badge.border_1().border_color(border));
match content {
BadgeContent::Text(text) => badge.min_w(px(16.)).px(px(4.)).text_size(px(9.)).font_weight(gpui::FontWeight::SEMIBOLD).line_height(px(16.)).child(text),
BadgeContent::Progress => badge.w(px(16.)).child(progress_badge_icon(foreground)),
// activityaction.css `.badge .codicon.badge-content`: the 13px glyph.
BadgeContent::Icon(icon) => badge.w(px(16.)).child(self.badge_icon(icon, 13., foreground)),
}
}
/// An `IconBadge`'s codicon; codicon-animations.css `spin`: one turn in 1.5s in 30 steps.
pub(super) fn badge_icon(&self, icon: &'static str, size: f32, color: gpui::Rgba) -> AnyElement {
let Some(name) = icon.strip_suffix("~spin") else { return self.icon(icon, size, size, color).into_any_element() };
svg()
.external_path(crate::codicons::svg_path(&self.app_root, crate::symbol_icons::svg_name(name)).to_string_lossy().into_owned())
.size(px(size))
.text_color(color)
.with_animation("activity-badge-spin", Animation::new(Duration::from_millis(1500)).repeat(), |icon, delta| icon.with_transformation(Transformation::rotate(percentage((delta * 30.).floor() / 30.))))
.into_any_element()
}
/// `showOnActivityBar` and `withCompositeProgress` for `$startProgress` at a view container or view location
/// (Explorer, Source Control, Extensions, or an id): the badge, and the progress bar of the container or the view.
pub(crate) fn start_activity_progress(&mut self, handle: u64, location: &Value, delay: Option<u64>, total: Option<f64>, window: &mut Window, cx: &mut Context<Self>) {
let (container, scope) = match location {
Value::Number(number) => match number.as_u64() {
Some(1) => ("workbench.view.explorer".to_owned(), "workbench.view.explorer".to_owned()),
Some(3) => ("workbench.view.scm".to_owned(), "workbench.view.scm".to_owned()),
Some(5) => ("workbench.view.extensions".to_owned(), "workbench.view.extensions".to_owned()),
_ => return,
},
Value::String(id) if id.starts_with("workbench.view.") => (id.clone(), id.clone()),
Value::String(view) => match self.view_container_of_view(view) {
Some(container) => (container, view.clone()),
None => return,
},
_ => return,
};
let state = match total {
Some(total) => CompositeProgress::Discrete { total, worked: 0. },
None => CompositeProgress::Infinite { after_discrete: false },
};
self.activities.bars.insert(handle, ScopedProgress { scope, state, visible: delay.is_none() });
if let Some(delay) = delay {
cx.spawn_in(window, async move |workbench, cx| {
cx.background_executor().timer(Duration::from_millis(delay)).await;
let _ = workbench.update(cx, |workbench, cx| {
if let Some(bar) = workbench.activities.bars.get_mut(&handle) {
bar.visible = true;
cx.notify();
}
});
})
.detach();
}
self.activities.progress.insert(handle, ProgressActivity { container, shown: None });
let delay = delay.map_or(PROGRESS_DELAY, Duration::from_millis);
cx.spawn_in(window, async move |workbench, cx| {
cx.background_executor().timer(delay).await;
let _ = workbench.update(cx, |workbench, cx| {
let now = cx.background_executor().now();
if let Some(progress) = workbench.activities.progress.get_mut(&handle) {
progress.shown = Some(now);
cx.notify();
}
});
})
.detach();
}
/// `withCompositeProgress` `updateProgress` for a reported step: an increment works the discrete bar, starting one
/// of `step.total` (100 by default) on an infinite bar; a step without one turns the bar infinite.
pub(crate) fn report_activity_progress(&mut self, handle: u64, step: &Value, cx: &mut Context<Self>) {
let Some(bar) = self.activities.bars.get_mut(&handle) else { return };
bar.state = match (bar.state, step["increment"].as_f64()) {
(CompositeProgress::Discrete { total, worked }, Some(increment)) => CompositeProgress::Discrete { total, worked: worked + increment },
(CompositeProgress::Infinite { after_discrete: false }, Some(increment)) => CompositeProgress::Discrete { total: step["total"].as_f64().unwrap_or(100.), worked: increment },
(CompositeProgress::Discrete { .. }, None) => CompositeProgress::Infinite { after_discrete: true },
(state, _) => state,
};
cx.notify();
}
/// The 2px `progressBar.background` bar of the latest shown progress at `scope`, a container or view id: worked
/// of total (progressbar.ts `worked`), else the infinite bit. The caller places it.
pub(super) fn scoped_progress_bar(&self, scope: &str) -> Option<Div> {
let (_, progress) = self.activities.bars.iter().filter(|(_, bar)| bar.visible && bar.scope == scope).max_by_key(|(handle, _)| **handle)?;
let color = self.color("progressBar.background");
let bar = div().absolute().left_0().w_full().h(px(2.)).overflow_hidden().debug_selector(|| "scoped-progress-bar".into());
// `.max(0.)` turns the NaN of an extension's `total: 0` into an empty bar.
Some(match progress.state {
CompositeProgress::Discrete { total, worked } => bar.child(div().h_full().w(relative((worked.min(total) / total).max(0.) as f32)).bg(color).debug_selector(|| "scoped-progress-worked".into())),
CompositeProgress::Infinite { .. } => bar.child(super::quick_input_view::infinite_progress_bit("scoped-progress", color)),
})
}
/// The progress ended: its bar goes (`done`), an unshown badge goes, a shown one after its minimum time.
pub(crate) fn end_activity_progress(&mut self, handle: u64, window: &mut Window, cx: &mut Context<Self>) {
if self.activities.bars.remove(&handle).is_some() {
cx.notify();
}
let Some(progress) = self.activities.progress.get(&handle) else { return };
let Some(shown) = progress.shown else {
self.activities.progress.remove(&handle);
return;
};
let remaining = (shown + PROGRESS_MIN_TIME).saturating_duration_since(cx.background_executor().now());
cx.spawn_in(window, async move |workbench, cx| {
cx.background_executor().timer(remaining).await;
let _ = workbench.update(cx, |workbench, cx| {
workbench.activities.progress.remove(&handle);
cx.notify();
});
})
.detach();
}
}
#[cfg(test)]
mod tests {
use super::{Badge, BadgeContent, visible_badge};
#[test]
fn progress_wins_and_numbers_add_up() {
assert_eq!(visible_badge(&[Badge::Number(2), Badge::Progress]), Some(BadgeContent::Progress));
assert_eq!(visible_badge(&[Badge::Number(2), Badge::Icon("loading~spin")]), Some(BadgeContent::Icon("loading~spin")));
assert_eq!(visible_badge(&[Badge::Number(2), Badge::Number(3)]), Some(BadgeContent::Text("5".into())));
assert_eq!(visible_badge(&[Badge::Number(0)]), None);
assert_eq!(visible_badge(&[]), None);
}
#[test]
fn numbers_past_999_show_thousands() {
assert_eq!(visible_badge(&[Badge::Number(999)]), Some(BadgeContent::Text("999".into())));
assert_eq!(visible_badge(&[Badge::Number(1000)]), Some(BadgeContent::Text("1K".into())));
assert_eq!(visible_badge(&[Badge::Number(1500)]), Some(BadgeContent::Text("1K+".into())));
}
}