Skip to content

Visual Studio Code, rebuilt in Rust

Rust
4.5 KB
Raw Blame
//! IPowerService (workbench/services/power, the powerMonitor and powerSaveBlocker calls of
//! nativeHostMainService.ts): the queries MainThreadPower forwards and the events it sends the extension host.

use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};

use serde_json::{Value, json};

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "linux")]
use linux::{Assertion, create_assertion, release_assertion, screen_locked};
#[cfg(target_os = "linux")]
pub use linux::{animations_disabled, on_battery_power, system_idle_time, thermal_state, watch, watch_accessibility_display};
#[cfg(target_os = "macos")]
use macos::{Assertion, create_assertion, release_assertion, screen_locked};
#[cfg(target_os = "macos")]
pub use macos::{on_battery_power, system_idle_time, thermal_state, watch, watch_accessibility_display};
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
use windows::{Assertion, create_assertion, release_assertion, screen_locked};
#[cfg(target_os = "windows")]
pub use windows::{on_battery_power, system_idle_time, thermal_state, watch, watch_accessibility_display};

/// powerMonitor.getSystemIdleState (Chromium `CalculateIdleState`): locked first, then idle past the threshold.
pub fn system_idle_state(threshold: u64) -> &'static str {
    if screen_locked() {
        return "locked";
    }
    if system_idle_time() >= threshold { "idle" } else { "active" }
}

#[cfg(any(target_os = "macos", test))]
fn thermal_state_name(state: isize) -> &'static str {
    match state {
        0 => "nominal",
        1 => "fair",
        2 => "serious",
        3 => "critical",
        _ => "unknown",
    }
}

/// powerSaveBlocker: an OS assertion per blocker, by Electron's ids, which count from 0.
#[derive(Default)]
pub struct PowerSaveBlockers {
    next_id: i64,
    assertions: HashMap<i64, Assertion>,
}

impl PowerSaveBlockers {
    pub fn start(&mut self, blocker_type: &str) -> i64 {
        let id = self.next_id;
        self.next_id += 1;
        if let Some(assertion) = create_assertion(blocker_type) {
            self.assertions.insert(id, assertion);
        }
        id
    }

    pub fn stop(&mut self, id: i64) -> bool {
        let Some(assertion) = self.assertions.remove(&id) else { return false };
        release_assertion(assertion);
        true
    }

    pub fn is_started(&self, id: i64) -> bool {
        self.assertions.contains_key(&id)
    }
}

pub(crate) static BLOCKERS: LazyLock<Mutex<PowerSaveBlockers>> = LazyLock::new(Default::default);

/// mainThreadPower.ts: the answer to one `MainThreadPower` request.
pub fn request(method: &str, args: &[Value]) -> Result<Value, String> {
    let blockers = &BLOCKERS;
    let arg = |index: usize| args.get(index).cloned().unwrap_or(Value::Null);
    match method {
        "$getSystemIdleState" => Ok(json!(system_idle_state(arg(0).as_u64().unwrap_or(0)))),
        "$getSystemIdleTime" => Ok(json!(system_idle_time())),
        "$getCurrentThermalState" => Ok(json!(thermal_state())),
        "$isOnBatteryPower" => Ok(json!(on_battery_power())),
        "$startPowerSaveBlocker" => Ok(json!(blockers.lock().unwrap().start(arg(0).as_str().unwrap_or_default()))),
        "$stopPowerSaveBlocker" => Ok(json!(blockers.lock().unwrap().stop(arg(0).as_i64().unwrap_or(-1)))),
        "$isPowerSaveBlockerStarted" => Ok(json!(blockers.lock().unwrap().is_started(arg(0).as_i64().unwrap_or(-1)))),
        _ => Err(format!("MainThreadPower has no method {method}")),
    }
}

pub type PowerEvent = (&'static str, Vec<Value>);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn thermal_states_use_electrons_names() {
        let names: Vec<&str> = (-1..5).map(thermal_state_name).collect();
        assert_eq!(names, ["unknown", "nominal", "fair", "serious", "critical", "unknown"]);
    }

    #[test]
    fn power_save_blockers_count_from_zero_and_stop_once() {
        let mut blockers = PowerSaveBlockers::default();
        let first = blockers.start("prevent-app-suspension");
        let second = blockers.start("prevent-display-sleep");
        assert_eq!((first, second), (0, 1));
        assert!(blockers.is_started(first) && blockers.is_started(second));
        assert!(blockers.stop(first));
        assert!(!blockers.stop(first));
        assert!(!blockers.is_started(first));
        assert!(blockers.stop(second));
    }

    #[test]
    fn idle_state_follows_the_threshold() {
        assert_eq!(system_idle_state(u64::MAX), if screen_locked() { "locked" } else { "active" });
    }
}