Visual Studio Code, rebuilt in Rust
Rust
//! userActivityService.ts with domActivityTracker.ts: the window counts as active while key or mouse presses keep
//! coming, checked every 30 s; two checks without one release it and it turns inactive 10 s later. The extension host
//! hears the change as `window.state.active` (mainThreadWindow.ts). A progress running over 15 s while the window is
//! active holds it active until the progress ends (progressService.ts `withProgress`).
use std::collections::HashMap;
use std::time::Duration;
use gpui::{Context, Task};
use serde_json::json;
use super::Workbench;
const CHECK_INTERVAL: Duration = Duration::from_secs(30);
const MIN_INTERVALS_WITHOUT_ACTIVITY: u32 = 2;
const MARK_INACTIVE_DEBOUNCE: Duration = Duration::from_secs(10);
/// progressService.ts `markActive({ extendOnly: true, whenHeldFor: 15_000 })`.
const PROGRESS_HELD_FOR: Duration = Duration::from_secs(15);
pub struct UserActivity {
is_active: bool,
/// userActivityService.ts `active`: the marks held.
active: u32,
intervals_without_activity: u32,
interval: Option<Task<()>>,
mark_inactive: Option<Task<()>>,
/// Per progress handle: the timer before its mark, or None once the mark is held.
progress_marks: HashMap<u64, Option<Task<()>>>,
}
impl Default for UserActivity {
fn default() -> Self {
UserActivity {
is_active: true,
active: 0,
intervals_without_activity: MIN_INTERVALS_WITHOUT_ACTIVITY,
interval: None,
mark_inactive: None,
progress_marks: HashMap::new(),
}
}
}
impl Workbench {
/// `onActivity`: a key or mouse press anywhere in the window.
pub(super) fn user_activity(&mut self, cx: &mut Context<Self>) {
if self.user_activity.intervals_without_activity == MIN_INTERVALS_WITHOUT_ACTIVITY {
self.mark_user_active();
self.user_activity.interval = Some(cx.spawn(async move |workbench, cx| {
loop {
cx.background_executor().timer(CHECK_INTERVAL).await;
match workbench.update(cx, |workbench, cx| workbench.activity_interval(cx)) {
Ok(false) => {}
_ => return,
}
}
}));
}
self.user_activity.intervals_without_activity = 0;
}
/// One check without activity; the second releases the active mark. Returns whether the checks stop.
fn activity_interval(&mut self, cx: &mut Context<Self>) -> bool {
self.user_activity.intervals_without_activity += 1;
if self.user_activity.intervals_without_activity != MIN_INTERVALS_WITHOUT_ACTIVITY {
return false;
}
self.release_user_active(cx);
true
}
/// `markActive()`: the first mark turns the window active and cancels a pending inactive mark.
fn mark_user_active(&mut self) {
self.user_activity.active += 1;
if self.user_activity.active == 1 {
self.set_user_active(true);
self.user_activity.mark_inactive = None;
}
}
/// Disposing a `markActive()`: the last release turns the window inactive after the debounce.
fn release_user_active(&mut self, cx: &mut Context<Self>) {
self.user_activity.active -= 1;
if self.user_activity.active == 0 {
self.user_activity.mark_inactive = Some(cx.spawn(async move |workbench, cx| {
cx.background_executor().timer(MARK_INACTIVE_DEBOUNCE).await;
workbench.update(cx, |workbench, _| workbench.set_user_active(false)).ok();
}));
}
}
/// progressService.ts `withProgress`'s `activeLock`: only while active, a mark taken once the progress ran 15 s.
pub(crate) fn hold_active_during_progress(&mut self, handle: u64, cx: &mut Context<Self>) {
if !self.user_activity.is_active {
return;
}
let timer = cx.spawn(async move |workbench, cx| {
cx.background_executor().timer(PROGRESS_HELD_FOR).await;
workbench
.update(cx, |workbench, _| {
workbench.mark_user_active();
workbench.user_activity.progress_marks.insert(handle, None);
})
.ok();
});
self.user_activity.progress_marks.insert(handle, Some(timer));
}
/// The progress ended: its pending timer is dropped, or its held mark released.
pub(crate) fn release_progress_activity(&mut self, handle: u64, cx: &mut Context<Self>) {
if let Some(None) = self.user_activity.progress_marks.remove(&handle) {
self.release_user_active(cx);
}
}
/// mainThreadWindow.ts `$getInitialState`: `hostService.hasFocus` and `userActivityService.isActive`.
pub(crate) fn window_initial_state(&self, window: &gpui::Window) -> serde_json::Value {
json!({ "isFocused": window.is_window_active(), "isActive": self.user_activity.is_active })
}
fn set_user_active(&mut self, active: bool) {
if self.user_activity.is_active != active {
self.user_activity.is_active = active;
self.host.send("ExtHostWindow", "$onDidChangeWindowActive", vec![json!(active)]);
}
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use gpui::TestAppContext;
use serde_json::{Value, json};
use super::*;
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;
#[gpui::test]
fn the_window_turns_inactive_after_two_quiet_checks_and_the_debounce(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 (sender, messages) = std::sync::mpsc::channel();
let (_, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
let active_changes = || messages.try_iter().filter(|message| message.method == "$onDidChangeWindowActive").map(|message| message.args).collect::<Vec<Vec<Value>>>();
cx.run_until_parked();
cx.executor().advance_clock(CHECK_INTERVAL * 2 + MARK_INACTIVE_DEBOUNCE - Duration::from_secs(1));
assert!(active_changes().is_empty());
cx.executor().advance_clock(Duration::from_secs(1));
assert_eq!(active_changes(), [vec![json!(false)]]);
cx.simulate_keystrokes("x");
assert_eq!(active_changes(), [vec![json!(true)]]);
cx.executor().advance_clock(CHECK_INTERVAL + Duration::from_secs(20));
cx.simulate_keystrokes("x");
// Without that press the window would turn inactive at 70 s; with it, at 100 s.
cx.executor().advance_clock(CHECK_INTERVAL + Duration::from_secs(19));
assert!(active_changes().is_empty(), "a press between checks keeps the window active");
}
/// progressService.ts `withProgress`: a progress held over 15 s keeps the window active until it ends.
#[gpui::test]
fn a_long_progress_holds_the_window_active_until_it_ends(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 (sender, messages) = std::sync::mpsc::channel();
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
let active_changes = || messages.try_iter().filter(|message| message.method == "$onDidChangeWindowActive").map(|message| message.args).collect::<Vec<Vec<Value>>>();
cx.run_until_parked();
let progress = |method: &str, args: Vec<Value>, cx: &mut gpui::VisualTestContext| {
workbench.update_in(cx, |workbench, window, cx| match method {
"start" => _ = workbench.start_progress(&args, window, cx),
_ => _ = workbench.end_progress(&args, window, cx),
});
};
progress("start", vec![json!(1), json!({ "location": 10, "title": "Indexing" })], cx);
cx.executor().advance_clock(Duration::from_secs(100));
assert!(active_changes().is_empty(), "the progress mark outlives the quiet checks");
progress("end", vec![json!(1)], cx);
cx.executor().advance_clock(MARK_INACTIVE_DEBOUNCE - Duration::from_secs(1));
assert!(active_changes().is_empty());
cx.executor().advance_clock(Duration::from_secs(1));
assert_eq!(active_changes(), [vec![json!(false)]]);
progress("start", vec![json!(2), json!({ "location": 10, "title": "Indexing" })], cx);
cx.executor().advance_clock(Duration::from_secs(20));
assert!(active_changes().is_empty(), "extendOnly: a progress does not turn an inactive window active");
progress("end", vec![json!(2)], cx);
}
#[gpui::test]
fn the_initial_window_state_is_the_window_focus(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 (sender, _messages) = std::sync::mpsc::channel();
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
let state = |cx: &mut gpui::VisualTestContext| cx.update(|window, cx| workbench.read(cx).window_initial_state(window));
cx.update(|window, _| window.activate_window());
cx.run_until_parked();
assert_eq!(state(cx), json!({ "isFocused": true, "isActive": true }));
cx.deactivate_window();
assert_eq!(state(cx), json!({ "isFocused": false, "isActive": true }));
}
}