Visual Studio Code, rebuilt in Rust
Rust
//! IPowerService on macOS: CoreGraphics idle time and session lock, IOKit power sources and assertions, and the
//! NSWorkspace and NSProcessInfo notifications.
use std::ptr::NonNull;
use std::sync::{Mutex, Once};
use block2::RcBlock;
use core_foundation::base::{CFType, TCFType};
use core_foundation::boolean::CFBoolean;
use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
use core_foundation::number::CFNumber;
use core_foundation::string::{CFString, CFStringRef};
use futures::channel::mpsc::UnboundedSender;
use objc2_app_kit::{NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification, NSWorkspaceDidWakeNotification, NSWorkspaceWillPowerOffNotification, NSWorkspaceWillSleepNotification};
use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSNotificationCenter, NSOperationQueue, NSProcessInfo, NSProcessInfoThermalStateDidChangeNotification, NSString};
use serde_json::json;
use super::{PowerEvent, thermal_state_name};
#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
fn CGEventSourceSecondsSinceLastEventType(source: i32, event_type: u32) -> f64;
fn CGSessionCopyCurrentDictionary() -> CFDictionaryRef;
}
#[link(name = "IOKit", kind = "framework")]
unsafe extern "C" {
fn IOPSCopyPowerSourcesInfo() -> *const std::ffi::c_void;
fn IOPSGetProvidingPowerSourceType(snapshot: *const std::ffi::c_void) -> CFStringRef;
fn IOPSNotificationCreateRunLoopSource(callback: extern "C" fn(*mut std::ffi::c_void), context: *mut std::ffi::c_void) -> *const std::ffi::c_void;
fn IOPMAssertionCreateWithName(assertion_type: CFStringRef, level: u32, name: CFStringRef, id: *mut u32) -> i32;
fn IOPMAssertionRelease(id: u32) -> i32;
fn IOPMCopyCPUPowerStatus(status: *mut CFDictionaryRef) -> i32;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFRunLoopGetMain() -> *const std::ffi::c_void;
fn CFRunLoopAddSource(run_loop: *const std::ffi::c_void, source: *const std::ffi::c_void, mode: CFStringRef);
static kCFRunLoopDefaultMode: CFStringRef;
}
unsafe extern "C" {
fn notify_register_dispatch(name: *const std::ffi::c_char, token: *mut i32, queue: *const std::ffi::c_void, handler: &block2::DynBlock<dyn Fn(i32)>) -> u32;
static _dispatch_main_q: std::ffi::c_void;
}
/// kCGEventSourceStateCombinedSessionState and kCGAnyInputEventType.
const COMBINED_SESSION_STATE: i32 = 0;
const ANY_INPUT_EVENT: u32 = u32::MAX;
const ASSERTION_LEVEL_ON: u32 = 255;
/// powerMonitor.getSystemIdleTime: whole seconds since the last input event.
pub fn system_idle_time() -> u64 {
// SAFETY: takes two constants and returns seconds; no pointers pass.
unsafe { CGEventSourceSecondsSinceLastEventType(COMBINED_SESSION_STATE, ANY_INPUT_EVENT) as u64 }
}
pub(super) fn screen_locked() -> bool {
// SAFETY: returns an owned dictionary or null, checked below.
let dictionary = unsafe { CGSessionCopyCurrentDictionary() };
if dictionary.is_null() {
return false;
}
// SAFETY: non-null and owned (Copy rule), so the wrapper releases it once.
let dictionary: CFDictionary<CFString, CFType> = unsafe { CFDictionary::wrap_under_create_rule(dictionary) };
dictionary.find(CFString::new("CGSSessionScreenIsLocked")).and_then(|value| value.downcast::<CFBoolean>()).is_some_and(bool::from)
}
/// powerMonitor.getCurrentThermalState: NSProcessInfo's state by Electron's names.
pub fn thermal_state() -> &'static str {
thermal_state_name(NSProcessInfo::processInfo().thermalState().0)
}
/// powerMonitor.isOnBatteryPower: the providing power source is the battery (kIOPMBatteryPowerKey).
pub fn on_battery_power() -> bool {
// SAFETY: `snapshot` is non-null and owned, released by its wrapper at the end; `source` follows the Get rule, and its wrapper retains it.
unsafe {
let snapshot = IOPSCopyPowerSourcesInfo();
if snapshot.is_null() {
return false;
}
let source = IOPSGetProvidingPowerSourceType(snapshot);
let on_battery = !source.is_null() && CFString::wrap_under_get_rule(source).to_string() == "Battery Power";
CFType::wrap_under_create_rule(snapshot as _);
on_battery
}
}
/// The macOS CPU speed limit in percent (Electron's `speed-limit-change`), 100 when the system reports none.
fn speed_limit() -> i64 {
let mut status: CFDictionaryRef = std::ptr::null();
// SAFETY: `status` is a local the call fills with an owned dictionary.
if unsafe { IOPMCopyCPUPowerStatus(&mut status) } != 0 || status.is_null() {
return 100;
}
// SAFETY: non-null and owned (Copy rule), so the wrapper releases it once.
let status: CFDictionary<CFString, CFType> = unsafe { CFDictionary::wrap_under_create_rule(status) };
status.find(CFString::new("CPU_Speed_Limit")).and_then(|value| value.downcast::<CFNumber>()).and_then(|number| number.to_i64()).unwrap_or(100)
}
pub(super) type Assertion = u32;
/// An IOPM assertion for a powerSaveBlocker type; `None` when IOKit refuses it.
pub(super) fn create_assertion(blocker_type: &str) -> Option<Assertion> {
let assertion_type = match blocker_type {
"prevent-display-sleep" => "NoDisplaySleepAssertion",
_ => "NoIdleSleepAssertion",
};
let mut assertion = 0;
let name = CFString::new("Electron");
// SAFETY: both CFStrings live to the end of the statement; `assertion` is a local the call fills.
let created = unsafe { IOPMAssertionCreateWithName(CFString::new(assertion_type).as_concrete_TypeRef(), ASSERTION_LEVEL_ON, name.as_concrete_TypeRef(), &mut assertion) };
(created == 0).then_some(assertion)
}
pub(super) fn release_assertion(assertion: u32) {
// SAFETY: takes the assertion id IOPMAssertionCreateWithName returned; no pointers pass.
unsafe { IOPMAssertionRelease(assertion) };
}
static EVENTS: Mutex<Vec<UnboundedSender<PowerEvent>>> = Mutex::new(Vec::new());
static OBSERVING: Once = Once::new();
static ON_BATTERY: Mutex<Option<bool>> = Mutex::new(None);
fn send(event: PowerEvent) {
EVENTS.lock().unwrap().retain(|events| events.unbounded_send(event.clone()).is_ok());
}
/// powerMonitor's events as ExtHostPower methods, delivered on the main thread to every receiver: suspend and resume,
/// shutdown, screen lock, thermal state, battery and speed limit changes. The observers live as long as the app.
pub fn watch(events: UnboundedSender<PowerEvent>) {
EVENTS.lock().unwrap().push(events);
OBSERVING.call_once(observe_power_events);
}
fn observe_power_events() {
let queue = NSOperationQueue::mainQueue();
let observe = |center: &NSNotificationCenter, name: &NSString, event: fn() -> PowerEvent| {
let block = RcBlock::new(move |_: NonNull<NSNotification>| send(event()));
// SAFETY: the center copies the block; `name` and `queue` are alive for the call.
let observer = unsafe { center.addObserverForName_object_queue_usingBlock(Some(name), None, Some(&queue), &block) };
// The center keeps the block; the token is never removed, the app observes until it quits.
std::mem::forget(observer);
};
let workspace = NSWorkspace::sharedWorkspace().notificationCenter();
// SAFETY: an AppKit constant, set before any app code runs.
observe(&workspace, unsafe { NSWorkspaceWillSleepNotification }, || ("$onDidSuspend", Vec::new()));
// SAFETY: an AppKit constant, set before any app code runs.
observe(&workspace, unsafe { NSWorkspaceDidWakeNotification }, || ("$onDidResume", Vec::new()));
// SAFETY: an AppKit constant, set before any app code runs.
observe(&workspace, unsafe { NSWorkspaceWillPowerOffNotification }, || ("$onWillShutdown", Vec::new()));
let distributed = NSDistributedNotificationCenter::defaultCenter();
observe(&distributed, &NSString::from_str("com.apple.screenIsLocked"), || ("$onDidLockScreen", Vec::new()));
observe(&distributed, &NSString::from_str("com.apple.screenIsUnlocked"), || ("$onDidUnlockScreen", Vec::new()));
// SAFETY: a Foundation constant, set before any app code runs.
observe(&NSNotificationCenter::defaultCenter(), unsafe { NSProcessInfoThermalStateDidChangeNotification }, || ("$onDidChangeThermalState", vec![json!(thermal_state())]));
*ON_BATTERY.lock().unwrap() = Some(on_battery_power());
// SAFETY: the callback is a static fn that reads no context; the source is added to the main run loop and never removed.
unsafe {
let source = IOPSNotificationCreateRunLoopSource(power_sources_changed, std::ptr::null_mut());
CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
}
let mut token = 0;
let handler = RcBlock::new(move |_: i32| send(("$onDidChangeSpeedLimit", vec![json!(speed_limit())])));
// SAFETY: the name is a C literal, `token` a local and the main queue a static; libnotify copies the block.
unsafe { notify_register_dispatch(c"com.apple.system.power.CPU".as_ptr(), &mut token, &_dispatch_main_q as *const _, &handler) };
}
/// Electron's `nativeTheme` `updated` for `prefersReducedMotion` (accessibilityService.ts): the macOS accessibility
/// display options changed. Call once; the observer lives as long as the app.
pub fn watch_accessibility_display(changed: UnboundedSender<()>) {
let block = RcBlock::new(move |_: NonNull<NSNotification>| drop(changed.unbounded_send(())));
let center = NSWorkspace::sharedWorkspace().notificationCenter();
// SAFETY: the center copies the block; the name is an AppKit constant, and the queue is alive for the call.
let observer = unsafe { center.addObserverForName_object_queue_usingBlock(Some(NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification), None, Some(&NSOperationQueue::mainQueue()), &block) };
std::mem::forget(observer);
}
/// powerMonitor `on-ac` and `on-battery`: sent when the providing source changes, not on every battery update.
extern "C" fn power_sources_changed(_: *mut std::ffi::c_void) {
let on_battery = on_battery_power();
let mut last = ON_BATTERY.lock().unwrap();
if *last == Some(on_battery) {
return;
}
*last = Some(on_battery);
send(("$onDidChangeOnBatteryPower", vec![json!(on_battery)]));
}