diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index 8167c2e6b9b..7eca7f2f206 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -51,9 +51,9 @@ use crate::{ DisplayChanges, DisplayEvent, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, - PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton, - PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, - ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer, + PlatformKeyboardLayout, PlatformKeyboardMapper, Point, PowerMode, Priority, PromptBuilder, + PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, + Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer, SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem, ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId, WindowInvalidator, WindowingRequest, @@ -939,6 +939,7 @@ pub struct App { pub(crate) reduce_motion: bool, /// Origin of the shared clock that phase-locks synced repeating animations. pub(crate) synced_animation_epoch: Instant, + power_mode: PowerMode, /// Whether the app was created by [`Application::new_inaccessible`]. No /// accesskit APIs will be called when this flag is set. pub(crate) accessibility_force_disabled: bool, @@ -973,6 +974,7 @@ impl App { let entities = EntityMap::new(); let keyboard_layout = platform.keyboard_layout(); let keyboard_mapper = platform.keyboard_mapper(); + let power_mode = platform.power_mode(); #[cfg(any(test, gpui_leak_detection))] let _ref_counts = entities.ref_counts_drop_handle(); @@ -1048,6 +1050,7 @@ impl App { cursor_hide_mode: CursorHideMode::default(), reduce_motion: false, synced_animation_epoch, + power_mode, accessibility_force_disabled: false, #[cfg(any(test, feature = "test-support", debug_assertions))] @@ -1150,6 +1153,16 @@ impl App { } })); + platform.on_power_mode_change(Box::new({ + let app = Rc::downgrade(&app); + move || { + if let Some(app) = app.upgrade() { + let power_mode = app.borrow().platform.power_mode(); + app.borrow_mut().power_mode = power_mode; + } + } + })); + platform.on_quit(Box::new({ let cx = Rc::downgrade(&app); move || { @@ -1814,6 +1827,12 @@ impl App { self.text_rendering_mode.get() } + /// Returns the operating system's power mode, or [`PowerMode::Unknown`] + /// when the platform cannot determine it. + pub fn power_mode(&self) -> PowerMode { + self.power_mode + } + /// Writes data to the platform clipboard. pub fn write_to_clipboard(&self, item: ClipboardItem) { self.platform.write_to_clipboard(item) diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index 90b3bc39e3a..a99c4ba3e46 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -514,6 +514,14 @@ pub trait Platform: 'static { fn on_thermal_state_change(&self, callback: Box); fn prevent_idle_sleep(&self, reason: &str) -> Task>; + /// Returns the operating system's power mode, or [`PowerMode::Unknown`] + /// when the platform cannot determine it. + fn power_mode(&self) -> PowerMode { + PowerMode::Unknown + } + /// Registers a callback invoked when the reported power mode changes. + fn on_power_mode_change(&self, _callback: Box) {} + /// Sets the application's process-wide identity and user-visible name. /// /// The identifier is used for platform identity mechanisms such as the @@ -701,6 +709,20 @@ pub struct SystemNotificationResponse { pub action_id: Option, } +/// The operating system's preference for energy use versus performance. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PowerMode { + /// The platform cannot determine the mode, or cannot distinguish the + /// active mode from other non-low-power modes. + Unknown, + /// The system prioritizes reducing energy use. + LowPower, + /// The system balances energy use and performance. + Balanced, + /// The system prioritizes performance over energy use. + HighPower, +} + /// Thermal state of the system #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ThermalState { diff --git a/crates/gpui/src/profiler/journal.rs b/crates/gpui/src/profiler/journal.rs index 39df15d5173..28c66b6e809 100644 --- a/crates/gpui/src/profiler/journal.rs +++ b/crates/gpui/src/profiler/journal.rs @@ -165,6 +165,8 @@ pub enum FrameSkipReason { InactiveFrameRateLimit, /// Thermal throttling deferred drawing. ThermalFrameRateLimit, + /// Low power mode deferred drawing. + LowPowerFrameRateLimit, } /// A completed frame request that returned without drawing a new frame. diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 006692dcc92..0d83066db80 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -146,15 +146,6 @@ struct FrameDirtyAccumulator { invalidations: u64, } -/// Why GPUI capped a window's frame rate. -#[derive(Clone, Copy)] -enum FrameRateLimit { - /// The window isn't focused. - Inactive, - /// The system is under thermal pressure. - Thermal, -} - #[derive(Clone)] pub(crate) struct WindowInvalidator { inner: Rc>, @@ -1332,6 +1323,47 @@ pub(crate) struct InputRateTracker { sustain_duration: Duration, } +const THIRTY_FPS_INTERVAL: Duration = Duration::from_micros(33333); +const SIXTY_FPS_INTERVAL: Duration = Duration::from_micros(16667); +const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1); + +/// Display-link timestamps can straddle a target interval by fractions of a +/// millisecond. Accepting that callback preserves an even display-frame divisor +/// instead of occasionally waiting for an additional refresh. +fn frame_request_arrived_too_early(elapsed: Duration, minimum_interval: Duration) -> bool { + elapsed < minimum_interval.saturating_sub(FRAME_INTERVAL_TOLERANCE) +} + +fn minimum_frame_interval( + should_throttle: bool, + inactive_without_high_rate_input: bool, + inactive_frame_interval: Option, + thermal_state: ThermalState, + power_mode: crate::PowerMode, +) -> Option { + let low_power_mode_enabled = power_mode == crate::PowerMode::LowPower; + if !should_throttle { + None + } else if inactive_without_high_rate_input { + match (inactive_frame_interval, low_power_mode_enabled) { + (Some(inactive_frame_interval), true) => { + Some(inactive_frame_interval.max(THIRTY_FPS_INTERVAL)) + } + (inactive_frame_interval, false) => inactive_frame_interval, + (None, true) => Some(THIRTY_FPS_INTERVAL), + } + } else if low_power_mode_enabled { + Some(THIRTY_FPS_INTERVAL) + } else if matches!( + thermal_state, + ThermalState::Critical | ThermalState::Serious + ) { + Some(SIXTY_FPS_INTERVAL) + } else { + None + } +} + impl Default for InputRateTracker { fn default() -> Self { Self { @@ -1830,31 +1862,37 @@ impl Window { let force_render = mem::take(&mut deferred_force_render) || request_frame_options.force_render; - let thermal_state = handle - .update(&mut cx, |_, _, cx| cx.thermal_state()) + let power_state = handle + .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode())) .log_err(); // Throttle frame rate based on conditions: // - Thermal pressure (Serious/Critical): cap to ~60fps - // - Inactive window (not focused): cap to ~30fps to save energy - let min_frame_interval = if request_frame_options.require_presentation - || (!request_frame_options.force_render - && next_frame_callbacks.borrow().is_empty()) - { - None - } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() { - inactive_frame_interval.map(|interval| (interval, FrameRateLimit::Inactive)) - } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state { - Some((Duration::from_micros(16667), FrameRateLimit::Thermal)) - } else { - None - }; + // - Low power mode: cap to ~30fps + // - Inactive window (not focused): use its configured frame interval + let should_throttle = !request_frame_options.require_presentation + && (request_frame_options.force_render + || !next_frame_callbacks.borrow().is_empty()); + let inactive_without_high_rate_input = should_throttle + && !active.get() + && !input_rate_tracker.borrow_mut().is_high_rate(); + let (thermal_state, power_mode) = + power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown)); + let min_frame_interval = minimum_frame_interval( + should_throttle, + inactive_without_high_rate_input, + inactive_frame_interval, + thermal_state, + power_mode, + ); let now = Instant::now(); - #[cfg_attr(not(feature = "profiler"), expect(unused_variables))] - if let Some((min_interval, limit)) = min_frame_interval { + if let Some(min_interval) = min_frame_interval { if let Some(last_frame) = last_frame_time.get() - && now.duration_since(last_frame) < min_interval + && frame_request_arrived_too_early( + now.duration_since(last_frame), + min_interval, + ) { // Don't lose a pending forced render to throttling. deferred_force_render |= force_render; @@ -1873,13 +1911,12 @@ impl Window { profiler::journal::record_frame_skipped( window_id, Instant::now(), - match limit { - FrameRateLimit::Inactive => { - profiler::journal::FrameSkipReason::InactiveFrameRateLimit - } - FrameRateLimit::Thermal => { - profiler::journal::FrameSkipReason::ThermalFrameRateLimit - } + if inactive_without_high_rate_input { + profiler::journal::FrameSkipReason::InactiveFrameRateLimit + } else if power_mode == crate::PowerMode::LowPower { + profiler::journal::FrameSkipReason::LowPowerFrameRateLimit + } else { + profiler::journal::FrameSkipReason::ThermalFrameRateLimit }, ); return; @@ -7919,9 +7956,9 @@ mod tests { FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _, InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, PlatformInput, Point, Render, RequestFrameOptions, - ScaledPixels, StatefulInteractiveElement as _, Styled, TestAppContext, TouchDragEvent, - TouchEvent, TouchId, TouchPhase, Underline, UnderlineStyle, Window, WindowAppearance, - WindowOptions, canvas, div, hsla, point, px, size, + ScaledPixels, StatefulInteractiveElement as _, Styled, TestAppContext, ThermalState, + TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline, UnderlineStyle, Window, + WindowAppearance, WindowOptions, canvas, div, hsla, point, px, size, }; #[gpui::test] @@ -8429,6 +8466,64 @@ mod tests { .unwrap(); } + #[test] + fn frame_throttle_accepts_display_link_rounding() { + assert!(!super::frame_request_arrived_too_early( + Duration::from_micros(16_666), + super::SIXTY_FPS_INTERVAL, + )); + assert!(!super::frame_request_arrived_too_early( + Duration::from_micros(33_332), + super::THIRTY_FPS_INTERVAL, + )); + } + + #[test] + fn frame_throttle_rejects_an_extra_display_refresh() { + assert!(super::frame_request_arrived_too_early( + Duration::from_micros(8_333), + super::SIXTY_FPS_INTERVAL, + )); + assert!(super::frame_request_arrived_too_early( + Duration::from_micros(16_666), + super::THIRTY_FPS_INTERVAL, + )); + } + + #[test] + fn power_modes_preserve_frame_limits() { + for (power_mode, active_interval, thermal_interval) in [ + ( + crate::PowerMode::LowPower, + Some(super::THIRTY_FPS_INTERVAL), + super::THIRTY_FPS_INTERVAL, + ), + (crate::PowerMode::Unknown, None, super::SIXTY_FPS_INTERVAL), + (crate::PowerMode::Balanced, None, super::SIXTY_FPS_INTERVAL), + (crate::PowerMode::HighPower, None, super::SIXTY_FPS_INTERVAL), + ] { + assert_eq!( + super::minimum_frame_interval(true, false, None, ThermalState::Nominal, power_mode), + active_interval, + ); + assert_eq!( + super::minimum_frame_interval(true, false, None, ThermalState::Serious, power_mode), + Some(thermal_interval), + ); + let inactive_interval = Duration::from_millis(100); + assert_eq!( + super::minimum_frame_interval( + true, + true, + Some(inactive_interval), + ThermalState::Nominal, + power_mode, + ), + Some(inactive_interval), + ); + } + } + struct EmptyView; impl Render for EmptyView { diff --git a/crates/gpui_apple/src/gpui_apple.rs b/crates/gpui_apple/src/gpui_apple.rs index f3ce55a202c..1e3d0e58515 100644 --- a/crates/gpui_apple/src/gpui_apple.rs +++ b/crates/gpui_apple/src/gpui_apple.rs @@ -9,7 +9,7 @@ mod dispatcher; pub mod keychain; mod metal_atlas; pub mod metal_renderer; -pub mod thermal; +pub mod process_info; #[cfg(feature = "font-kit")] mod open_type; diff --git a/crates/gpui_apple/src/process_info.rs b/crates/gpui_apple/src/process_info.rs new file mode 100644 index 00000000000..a988581141d --- /dev/null +++ b/crates/gpui_apple/src/process_info.rs @@ -0,0 +1,182 @@ +use block2::RcBlock; +use futures::{StreamExt, channel::mpsc}; +use gpui::{ForegroundExecutor, PowerMode, Task, ThermalState}; +use objc2::{rc::Retained, runtime::ProtocolObject}; +use objc2_foundation::{ + NSNotification, NSNotificationCenter, NSNotificationName, NSObjectProtocol, NSProcessInfo, + NSProcessInfoPowerStateDidChangeNotification, NSProcessInfoThermalState, + NSProcessInfoThermalStateDidChangeNotification, +}; + +pub fn thermal_state() -> ThermalState { + match NSProcessInfo::processInfo().thermalState() { + NSProcessInfoThermalState::Fair => ThermalState::Fair, + NSProcessInfoThermalState::Serious => ThermalState::Serious, + NSProcessInfoThermalState::Critical => ThermalState::Critical, + _ => ThermalState::Nominal, + } +} + +pub fn power_mode() -> PowerMode { + if NSProcessInfo::processInfo().isLowPowerModeEnabled() { + PowerMode::LowPower + } else { + // This API does not distinguish Automatic from High Power Mode on macOS. + PowerMode::Unknown + } +} + +pub fn observe_thermal_state( + executor: &ForegroundExecutor, + callback: Box, +) -> ProcessInfoObserver { + // Foundation requires reading thermalState before registering for changes. + // https://developer.apple.com/documentation/foundation/processinfo/thermalstatedidchangenotification + thermal_state(); + ProcessInfoObserver::new( + unsafe { NSProcessInfoThermalStateDidChangeNotification }, + executor, + callback, + ) +} + +pub fn observe_power_mode( + executor: &ForegroundExecutor, + callback: Box, +) -> ProcessInfoObserver { + ProcessInfoObserver::new( + unsafe { NSProcessInfoPowerStateDidChangeNotification }, + executor, + callback, + ) +} + +pub struct ProcessInfoObserver { + center: Retained, + observer: Retained>, + _task: Task<()>, +} + +impl ProcessInfoObserver { + fn new( + name: &NSNotificationName, + executor: &ForegroundExecutor, + callback: Box, + ) -> Self { + Self::with_center( + NSNotificationCenter::defaultCenter(), + name, + executor, + callback, + ) + } + + fn with_center( + center: Retained, + name: &NSNotificationName, + executor: &ForegroundExecutor, + mut callback: Box, + ) -> Self { + let (sender, mut receiver) = mpsc::unbounded(); + let block = RcBlock::new(move |_: std::ptr::NonNull| { + // Notifications can arrive synchronously or off-thread. Defer application + // callbacks so they cannot reenter GPUI while it is already borrowed. + if sender.unbounded_send(()).is_err() { + log::debug!("process info observer stopped before notification delivery"); + } + }); + let observer = unsafe { + center.addObserverForName_object_queue_usingBlock( + Some(name), + Some(&NSProcessInfo::processInfo()), + None, + &block, + ) + }; + let task = executor.spawn(async move { + while receiver.next().await.is_some() { + callback(); + } + }); + Self { + center, + observer, + _task: task, + } + } +} + +impl Drop for ProcessInfoObserver { + fn drop(&mut self) { + unsafe { + self.center.removeObserver(self.observer.as_ref()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{cell::Cell, rc::Rc}; + + fn post_notification(center: &NSNotificationCenter, name: &NSNotificationName) { + unsafe { + center.postNotificationName_object(name, Some(&NSProcessInfo::processInfo())); + } + } + + #[gpui::test] + fn notifications_are_deferred_and_cancelled_on_drop(cx: &mut gpui::TestAppContext) { + for name in unsafe { + [ + NSProcessInfoPowerStateDidChangeNotification, + NSProcessInfoThermalStateDidChangeNotification, + ] + } { + check_notification_lifecycle(cx, name); + } + } + + fn check_notification_lifecycle( + cx: &mut gpui::TestAppContext, + name: &'static NSNotificationName, + ) { + // Tests cannot share the default center because they run concurrently. + let center = NSNotificationCenter::new(); + let calls = Rc::new(Cell::new(0)); + let observer = ProcessInfoObserver::with_center( + center.clone(), + name, + &cx.foreground_executor, + Box::new({ + let calls = calls.clone(); + move || calls.set(calls.get() + 1) + }), + ); + post_notification(¢er, name); + assert_eq!(calls.get(), 0); + cx.run_until_parked(); + assert_eq!(calls.get(), 1); + + cx.background_executor + .spawn({ + let center = center.clone(); + let name = name.to_string(); + async move { + post_notification(¢er, &objc2_foundation::NSString::from_str(&name)) + } + }) + .detach(); + assert_eq!(calls.get(), 1); + cx.run_until_parked(); + assert_eq!(calls.get(), 2); + + post_notification(¢er, name); + drop(observer); + cx.run_until_parked(); + assert_eq!(calls.get(), 2); + post_notification(¢er, name); + cx.run_until_parked(); + assert_eq!(calls.get(), 2); + } +} diff --git a/crates/gpui_apple/src/thermal.rs b/crates/gpui_apple/src/thermal.rs deleted file mode 100644 index 24cc84e6baa..00000000000 --- a/crates/gpui_apple/src/thermal.rs +++ /dev/null @@ -1,113 +0,0 @@ -use block2::RcBlock; -use futures::{StreamExt, channel::mpsc}; -use gpui::{ForegroundExecutor, Task, ThermalState}; -use objc2::{rc::Retained, runtime::ProtocolObject}; -use objc2_foundation::{ - NSNotification, NSNotificationCenter, NSObjectProtocol, NSProcessInfo, - NSProcessInfoThermalState, NSProcessInfoThermalStateDidChangeNotification, -}; - -pub fn thermal_state() -> ThermalState { - match NSProcessInfo::processInfo().thermalState() { - NSProcessInfoThermalState::Fair => ThermalState::Fair, - NSProcessInfoThermalState::Serious => ThermalState::Serious, - NSProcessInfoThermalState::Critical => ThermalState::Critical, - _ => ThermalState::Nominal, - } -} - -pub struct ThermalObserver { - center: Retained, - observer: Retained>, - _task: Task<()>, -} - -impl ThermalObserver { - pub fn new(executor: &ForegroundExecutor, callback: Box) -> Self { - Self::with_center(NSNotificationCenter::defaultCenter(), executor, callback) - } - - fn with_center( - center: Retained, - executor: &ForegroundExecutor, - mut callback: Box, - ) -> Self { - let (sender, mut receiver) = mpsc::unbounded(); - let block = RcBlock::new(move |_: std::ptr::NonNull| { - // NotificationCenter can call synchronously or off-thread. Never enter - // application code here: GPUI may already be borrowed on the main thread. - if sender.unbounded_send(()).is_err() { - log::debug!("thermal observer stopped before notification delivery"); - } - }); - let observer = unsafe { - center.addObserverForName_object_queue_usingBlock( - Some(NSProcessInfoThermalStateDidChangeNotification), - Some(&NSProcessInfo::processInfo()), - None, - &block, - ) - }; - let task = executor.spawn(async move { - while receiver.next().await.is_some() { - callback(); - } - }); - Self { - center, - observer, - _task: task, - } - } -} - -impl Drop for ThermalObserver { - fn drop(&mut self) { - unsafe { - self.center.removeObserver(self.observer.as_ref()); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::{cell::Cell, rc::Rc}; - - // Tests run concurrently in one process, so they cannot share the default center. - fn post_thermal_notification(center: &NSNotificationCenter) { - unsafe { - center.postNotificationName_object( - NSProcessInfoThermalStateDidChangeNotification, - Some(&NSProcessInfo::processInfo()), - ); - } - } - - #[gpui::test] - fn notifications_are_deferred_and_cancelled_on_drop(cx: &mut gpui::TestAppContext) { - let center = NSNotificationCenter::new(); - let calls = Rc::new(Cell::new(0)); - let observer = ThermalObserver::with_center( - center.clone(), - &cx.foreground_executor, - Box::new({ - let calls = calls.clone(); - move || calls.set(calls.get() + 1) - }), - ); - let post_notification = || post_thermal_notification(¢er); - post_notification(); - assert_eq!(calls.get(), 0); - cx.run_until_parked(); - assert_eq!(calls.get(), 1); - - post_notification(); - drop(observer); - cx.run_until_parked(); - assert_eq!(calls.get(), 1); - post_notification(); - cx.run_until_parked(); - assert_eq!(calls.get(), 1); - } -} diff --git a/crates/gpui_ios/src/ios/platform.rs b/crates/gpui_ios/src/ios/platform.rs index 13538a3d3e2..f1c5be758de 100644 --- a/crates/gpui_ios/src/ios/platform.rs +++ b/crates/gpui_ios/src/ios/platform.rs @@ -20,11 +20,11 @@ use gpui::{ Action, AnyWindowHandle, AppLifecyclePhase, BackgroundExecutor, ClipboardItem, CursorStyle, DummyKeyboardMapper, ForegroundExecutor, Keymap, Menu, MenuItem, PathPromptOptions, Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, - PlatformWindow, Result, Task, ThermalState, WindowAppearance, WindowParams, + PlatformWindow, PowerMode, Result, Task, ThermalState, WindowAppearance, WindowParams, }; use gpui_apple::{ AppleDispatcher, keychain, main_thread_marker, - thermal::{self, ThermalObserver}, + process_info::{self, ProcessInfoObserver}, }; use objc2::{MainThreadOnly, rc::Retained, runtime::ProtocolObject}; use objc2_foundation::{ @@ -51,7 +51,8 @@ pub(crate) struct IosPlatformState { background_executor: BackgroundExecutor, foreground_executor: ForegroundExecutor, text_system: Arc, - thermal_observer: RefCell>, + thermal_observer: RefCell>, + power_mode_observer: RefCell>, display_observers: RefCell>>>, display_task: RefCell>>, displays_changed_callback: CallbackSlot>, @@ -75,6 +76,7 @@ impl IosPlatform { foreground_executor: ForegroundExecutor::new(dispatcher), text_system, thermal_observer: RefCell::new(None), + power_mode_observer: RefCell::new(None), display_observers: RefCell::new(Vec::new()), display_task: RefCell::new(None), displays_changed_callback: CallbackSlot::default(), @@ -459,14 +461,23 @@ impl Platform for IosPlatform { } fn thermal_state(&self) -> ThermalState { - thermal::thermal_state() + process_info::thermal_state() } fn on_thermal_state_change(&self, callback: Box) { - let observer = ThermalObserver::new(&self.0.foreground_executor, callback); + let observer = process_info::observe_thermal_state(&self.0.foreground_executor, callback); self.0.thermal_observer.replace(Some(observer)); } + fn power_mode(&self) -> PowerMode { + process_info::power_mode() + } + + fn on_power_mode_change(&self, callback: Box) { + let observer = process_info::observe_power_mode(&self.0.foreground_executor, callback); + self.0.power_mode_observer.replace(Some(observer)); + } + fn keyboard_layout(&self) -> Box { Box::new(IosKeyboardLayout) } diff --git a/crates/gpui_linux/src/linux.rs b/crates/gpui_linux/src/linux.rs index e4da54b52b4..c5afc4a0f5d 100644 --- a/crates/gpui_linux/src/linux.rs +++ b/crates/gpui_linux/src/linux.rs @@ -3,6 +3,8 @@ mod display_connection; mod headless; mod keyboard; mod platform; +#[cfg(any(feature = "wayland", feature = "x11"))] +mod power; mod system_notifications; #[cfg(any(feature = "wayland", feature = "x11"))] mod text_system; diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs index 0c5370db6ca..b24300bbc25 100644 --- a/crates/gpui_linux/src/linux/platform.rs +++ b/crates/gpui_linux/src/linux/platform.rs @@ -39,7 +39,7 @@ use gpui::{ Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor, GraphicalEnvironment, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, - PlatformWindow, Result, RunnableVariant, Task, ThermalState, WindowAppearance, + PlatformWindow, PowerMode, Result, RunnableVariant, Task, ThermalState, WindowAppearance, WindowButtonLayout, WindowParams, WindowingModes, WindowingRequest, }; #[cfg(any(feature = "wayland", feature = "x11"))] @@ -71,11 +71,11 @@ pub(crate) struct PlatformHandlers { pub(crate) keyboard_layout_change: Option>, pub(crate) system_sleep: Option>, pub(crate) system_wake: Option>, + pub(crate) power_mode_change: Option>, pub(crate) displays_changed: Option>, } -/// A logind `PrepareForSleep` signal, forwarded from the D-Bus listener to -/// the client's event loop. +/// A system power change, forwarded from D-Bus to the client's event loop. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr( not(all(target_os = "linux", any(feature = "wayland", feature = "x11"))), @@ -84,6 +84,7 @@ pub(crate) struct PlatformHandlers { pub(crate) enum SystemPowerEvent { Sleep, Wake, + ModeChanged(PowerMode), } pub(crate) struct LinuxCommon { @@ -104,6 +105,9 @@ pub(crate) struct LinuxCommon { )] power_sender: Sender, power_listener_started: bool, + power_mode: PowerMode, + #[cfg(any(feature = "wayland", feature = "x11"))] + power_mode_listener: Option>, /// Runs after each foreground runnable registered by [`LinuxCommon::register_sources`]. /// /// X11 uses this to handle events that a runnable's requests read into xcb's queue, where @@ -148,6 +152,9 @@ impl LinuxCommon { ), power_sender, power_listener_started: false, + power_mode: PowerMode::Unknown, + #[cfg(any(feature = "wayland", feature = "x11"))] + power_mode_listener: None, after_runnable: None, }; @@ -216,9 +223,16 @@ impl LinuxCommon { Ok(()) } - /// Runs the app's sleep or wake callback, without `common` borrowed, since the callback + /// Runs the app's power callback, without `common` borrowed, since the callback /// can call back into the platform. fn handle_system_power_event(common: &RefCell, event: SystemPowerEvent) { + if let SystemPowerEvent::ModeChanged(mode) = event { + let mut common = common.borrow_mut(); + if common.power_mode == mode { + return; + } + common.power_mode = mode; + } fn slot( callbacks: &mut PlatformHandlers, event: SystemPowerEvent, @@ -226,6 +240,7 @@ impl LinuxCommon { match event { SystemPowerEvent::Sleep => &mut callbacks.system_sleep, SystemPowerEvent::Wake => &mut callbacks.system_wake, + SystemPowerEvent::ModeChanged(_) => &mut callbacks.power_mode_change, } } let callback = slot(&mut common.borrow_mut().callbacks, event).take(); @@ -589,6 +604,34 @@ impl Platform for LinuxPlatform { ThermalState::Nominal } + fn power_mode(&self) -> PowerMode { + self.with_common(|common| common.power_mode) + } + + fn on_power_mode_change(&self, callback: Box) { + self.with_common(|common| { + common.callbacks.power_mode_change = Some(callback); + #[cfg(any(feature = "wayland", feature = "x11"))] + if common.power_mode_listener.is_none() { + let sender = common.power_sender.clone(); + common.power_mode_listener = Some(common.background_executor.spawn(async move { + let result = async { + let connection = ashpd::zbus::Connection::system().await?; + crate::linux::power::monitor_power_mode(&connection, |mode| { + sender.send(SystemPowerEvent::ModeChanged(mode))?; + Ok(()) + }) + .await + } + .await; + if let Err(error) = result { + log::debug!("failed to monitor system power mode: {error:?}"); + } + })); + } + }); + } + #[cfg(not(any(feature = "wayland", feature = "x11")))] fn prevent_idle_sleep(&self, reason: &str) -> Task> { Task::ready(Err(anyhow!( @@ -1714,6 +1757,43 @@ mod tests { use super::*; use gpui::{Point, px}; + #[test] + fn power_mode_callbacks_can_reenter_and_replace_themselves() -> anyhow::Result<()> { + let event_loop = EventLoop::<()>::try_new()?; + let (common, _, _) = LinuxCommon::new(event_loop.get_signal()); + let common = Rc::new(RefCell::new(common)); + let calls = Rc::new(RefCell::new(Vec::new())); + common.borrow_mut().callbacks.power_mode_change = Some(Box::new({ + let common = Rc::downgrade(&common); + let calls = calls.clone(); + move || { + let common = common.upgrade().expect("common is alive"); + calls.borrow_mut().push((common.borrow().power_mode, false)); + common.borrow_mut().callbacks.power_mode_change = Some(Box::new({ + let common = Rc::downgrade(&common); + let calls = calls.clone(); + move || { + let common = common.upgrade().expect("common is alive"); + calls.borrow_mut().push((common.borrow().power_mode, true)); + } + })); + } + })); + // Repeated reports of the same mode must not invoke the callback again. + for mode in [ + PowerMode::LowPower, + PowerMode::LowPower, + PowerMode::Balanced, + ] { + LinuxCommon::handle_system_power_event(&common, SystemPowerEvent::ModeChanged(mode)); + } + assert_eq!( + *calls.borrow(), + [(PowerMode::LowPower, false), (PowerMode::Balanced, true)] + ); + Ok(()) + } + #[cfg(any(feature = "wayland", feature = "x11"))] #[test] fn rejects_null_xkb_context() { diff --git a/crates/gpui_linux/src/linux/power.rs b/crates/gpui_linux/src/linux/power.rs new file mode 100644 index 00000000000..83a75921ee8 --- /dev/null +++ b/crates/gpui_linux/src/linux/power.rs @@ -0,0 +1,265 @@ +use ashpd::zbus::{ + Connection, Proxy, + fdo::PropertiesProxy, + proxy::{Builder, CacheProperties}, +}; +use futures::{StreamExt as _, stream}; +use gpui::PowerMode; + +// The UPower namespace replaced net.hadess in v0.20; prefer it while retaining +// compatibility with older daemons. +// https://upower.pages.freedesktop.org/power-profiles-daemon/gdbus-org.freedesktop.UPower.PowerProfiles.html +// https://gitlab.freedesktop.org/upower/power-profiles-daemon/-/releases/0.20 +const POWER_PROFILES_SERVICES: [(&str, &str); 2] = [ + ( + "org.freedesktop.UPower.PowerProfiles", + "/org/freedesktop/UPower/PowerProfiles", + ), + ("net.hadess.PowerProfiles", "/net/hadess/PowerProfiles"), +]; + +fn power_mode(profile: &str) -> PowerMode { + match profile { + "power-saver" => PowerMode::LowPower, + "balanced" => PowerMode::Balanced, + "performance" => PowerMode::HighPower, + _ => PowerMode::Unknown, + } +} + +pub(super) async fn monitor_power_mode( + connection: &Connection, + mut on_change: impl FnMut(PowerMode) -> anyhow::Result<()>, +) -> anyhow::Result<()> { + let mut proxies = Vec::new(); + let mut changes = Vec::new(); + for (service, path) in POWER_PROFILES_SERVICES { + let proxy = Builder::>::new(connection) + .destination(service)? + .path(path)? + .interface(service)? + .cache_properties(CacheProperties::No) + .build() + .await?; + let properties = PropertiesProxy::builder(connection) + .destination(service)? + .path(path)? + .build() + .await?; + changes.push( + properties + .receive_properties_changed() + .await? + .map(|_| ()) + .boxed(), + ); + changes.push(proxy.receive_owner_changed().await?.map(|_| ()).boxed()); + proxies.push(proxy); + } + let mut changes = stream::select_all(changes); + let mut previous_mode = None; + loop { + // Subscribe before reading, and bypass property caches so service loss + // cannot leave us reporting the previous owner's profile. + let mut mode = PowerMode::Unknown; + for proxy in &proxies { + match proxy.get_property::("ActiveProfile").await { + Ok(profile) => { + mode = power_mode(&profile); + break; + } + Err(error) => log::debug!( + "could not query power profile from {}: {error}", + proxy.destination() + ), + } + } + if previous_mode != Some(mode) { + on_change(mode)?; + previous_mode = Some(mode); + } + if changes.next().await.is_none() { + on_change(PowerMode::Unknown)?; + anyhow::bail!("power profile notification streams closed"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::Context as _; + use futures::channel::mpsc; + use std::{ + collections::HashMap, + io::{BufRead as _, BufReader}, + process::{Child, Stdio}, + sync::Arc, + time::Duration, + }; + + struct TestBus(Child); + + impl TestBus { + #[expect( + clippy::disallowed_methods, + reason = "this integration test owns and reaps a real D-Bus daemon" + )] + fn start() -> anyhow::Result<(Self, String)> { + let child = gpui_util::new_std_command("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .spawn()?; + let mut bus = Self(child); + let stdout = bus + .0 + .stdout + .take() + .context("missing D-Bus address output")?; + let mut address = String::new(); + BufReader::new(stdout).read_line(&mut address)?; + Ok((bus, address.trim().to_owned())) + } + } + + impl Drop for TestBus { + fn drop(&mut self) { + if let Err(error) = self.0.kill() { + log::warn!("failed to stop test D-Bus daemon: {error}"); + } + if let Err(error) = self.0.wait() { + log::warn!("failed to reap test D-Bus daemon: {error}"); + } + } + } + + macro_rules! mock_profiles { + ($name:ident, $interface:literal) => { + struct $name(Arc>); + + #[ashpd::zbus::interface(name = $interface, crate = "ashpd::zbus")] + impl $name { + #[zbus(property)] + fn active_profile(&self) -> String { + self.0.lock().clone() + } + } + }; + } + + mock_profiles!(ModernProfiles, "org.freedesktop.UPower.PowerProfiles"); + mock_profiles!(LegacyProfiles, "net.hadess.PowerProfiles"); + + #[test] + fn maps_profiles_without_guessing_unknown_values() { + for (profile, expected) in [ + ("power-saver", PowerMode::LowPower), + ("balanced", PowerMode::Balanced), + ("performance", PowerMode::HighPower), + ("custom", PowerMode::Unknown), + ("", PowerMode::Unknown), + ] { + assert_eq!(power_mode(profile), expected); + } + } + + #[test] + #[expect( + clippy::disallowed_methods, + reason = "real D-Bus I/O requires a wall-clock timeout, not a GPUI scheduler timer" + )] + fn monitors_profiles_and_service_restarts() -> anyhow::Result<()> { + smol::block_on(futures::future::select( + Box::pin(check_service_lifecycle()), + Box::pin(async { + smol::Timer::after(Duration::from_secs(15)).await; + anyhow::bail!("timed out monitoring mock power profiles") + }), + )) + .factor_first() + .0 + } + + async fn check_service_lifecycle() -> anyhow::Result<()> { + let (_bus, address) = TestBus::start()?; + let modern_profile = Arc::new(parking_lot::Mutex::new("balanced".to_owned())); + let legacy_profile = Arc::new(parking_lot::Mutex::new("balanced".to_owned())); + let server = ashpd::zbus::connection::Builder::address(address.as_str())? + .serve_at( + POWER_PROFILES_SERVICES[0].1, + ModernProfiles(modern_profile.clone()), + )? + .serve_at( + POWER_PROFILES_SERVICES[1].1, + LegacyProfiles(legacy_profile.clone()), + )? + .build() + .await?; + let connection = ashpd::zbus::connection::Builder::address(address.as_str())? + .build() + .await?; + let (sender, mut receiver) = mpsc::unbounded(); + let monitor = smol::spawn({ + let connection = connection.clone(); + async move { + monitor_power_mode(&connection, |mode| { + sender.unbounded_send(mode)?; + Ok(()) + }) + .await + } + }); + assert_eq!(receiver.next().await, Some(PowerMode::Unknown)); + + for ((service, path), active_profile) in POWER_PROFILES_SERVICES + .into_iter() + .zip([&modern_profile, &legacy_profile]) + { + server.request_name(service).await?; + assert_eq!(receiver.next().await, Some(PowerMode::Balanced)); + for (profile, expected) in [ + ("power-saver", PowerMode::LowPower), + ("performance", PowerMode::HighPower), + ("custom", PowerMode::Unknown), + ("balanced", PowerMode::Balanced), + ] { + *active_profile.lock() = profile.to_owned(); + server + .emit_signal( + None::<&str>, + path, + "org.freedesktop.DBus.Properties", + "PropertiesChanged", + &( + service, + HashMap::from([( + "ActiveProfile", + ashpd::zbus::zvariant::Value::from(profile), + )]), + Vec::<&str>::new(), + ), + ) + .await?; + assert_eq!(receiver.next().await, Some(expected)); + } + server.release_name(service).await?; + assert_eq!(receiver.next().await, Some(PowerMode::Unknown)); + server.request_name(service).await?; + assert_eq!(receiver.next().await, Some(PowerMode::Balanced)); + server.release_name(service).await?; + assert_eq!(receiver.next().await, Some(PowerMode::Unknown)); + } + *legacy_profile.lock() = "power-saver".to_owned(); + *modern_profile.lock() = "performance".to_owned(); + server.request_name(POWER_PROFILES_SERVICES[1].0).await?; + assert_eq!(receiver.next().await, Some(PowerMode::LowPower)); + server.request_name(POWER_PROFILES_SERVICES[0].0).await?; + assert_eq!(receiver.next().await, Some(PowerMode::HighPower)); + server.release_name(POWER_PROFILES_SERVICES[0].0).await?; + assert_eq!(receiver.next().await, Some(PowerMode::LowPower)); + server.release_name(POWER_PROFILES_SERVICES[1].0).await?; + assert_eq!(receiver.next().await, Some(PowerMode::Unknown)); + drop(monitor); + Ok(()) + } +} diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs index 798262d47e3..aa0bc2d9ac2 100644 --- a/crates/gpui_macos/src/platform.rs +++ b/crates/gpui_macos/src/platform.rs @@ -13,13 +13,13 @@ use gpui::{ Action, ActivationPolicy, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor, GraphicalEnvironment, KeyContext, Keymap, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions, Platform, PlatformDisplay, PlatformKeyboardLayout, - PlatformKeyboardMapper, PlatformTextSystem, PlatformWindow, Result, SystemMenuType, Task, - ThermalState, WindowAppearance, WindowKind, WindowParams, WindowingRequest, + PlatformKeyboardMapper, PlatformTextSystem, PlatformWindow, PowerMode, Result, SystemMenuType, + Task, ThermalState, WindowAppearance, WindowKind, WindowParams, WindowingRequest, popup::PopupNotSupportedError, }; use gpui_apple::{ keychain, - thermal::{self, ThermalObserver}, + process_info::{self, ProcessInfoObserver}, }; use gpui_util::{ResultExt, new_std_command}; use itertools::Itertools; @@ -151,7 +151,6 @@ unsafe fn build_classes() { sel!(onSystemSleep:), on_system_sleep as extern "C-unwind" fn(_, Sel, *mut AnyObject), ); - decl.add_method( sel!(onSystemWake:), on_system_wake as extern "C-unwind" fn(_, Sel, *mut AnyObject), @@ -176,7 +175,8 @@ pub(crate) struct MacPlatformState { find_pasteboard: Pasteboard, reopen: Option>, on_keyboard_layout_change: Option>, - thermal_observer: Option, + thermal_observer: Option, + power_mode_observer: Option, on_displays_changed: Option>, on_system_sleep: Option>, on_system_wake: Option>, @@ -254,6 +254,7 @@ impl MacPlatform { dock_menu: None, on_keyboard_layout_change: None, thermal_observer: None, + power_mode_observer: None, on_displays_changed: None, on_system_sleep: None, on_system_wake: None, @@ -1059,7 +1060,7 @@ impl Platform for MacPlatform { } fn on_thermal_state_change(&self, callback: Box) { - let observer = ThermalObserver::new(&self.foreground_executor(), callback); + let observer = process_info::observe_thermal_state(&self.foreground_executor(), callback); self.0.lock().thermal_observer = Some(observer); } @@ -1068,13 +1069,18 @@ impl Platform for MacPlatform { self.ensure_system_power_observers(); } + fn on_power_mode_change(&self, callback: Box) { + let observer = process_info::observe_power_mode(&self.foreground_executor(), callback); + self.0.lock().power_mode_observer = Some(observer); + } + fn on_system_wake(&self, callback: Box) { self.0.lock().on_system_wake = Some(callback); self.ensure_system_power_observers(); } fn thermal_state(&self) -> ThermalState { - thermal::thermal_state() + process_info::thermal_state() } fn prevent_idle_sleep(&self, reason: &str) -> Task> { @@ -1084,6 +1090,10 @@ impl Platform for MacPlatform { ))) } + fn power_mode(&self) -> PowerMode { + process_info::power_mode() + } + fn show_system_notification(&self, notification: gpui::SystemNotification) { let mut state = self.0.lock(); let executor = state.foreground_executor.clone(); @@ -1319,7 +1329,6 @@ extern "C-unwind" fn did_finish_launching(this: &AnyObject, _: Sel, _: *mut AnyO name: ns_string("NSApplicationDidChangeScreenParametersNotification"), object: ptr::null_mut::() ]; - let platform = get_mac_platform(this); let callback = { let mut state = platform.0.lock(); diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs index 98a13f304c8..da719662473 100644 --- a/crates/gpui_windows/src/directx_renderer.rs +++ b/crates/gpui_windows/src/directx_renderer.rs @@ -409,7 +409,7 @@ impl DirectXRenderer { /// goes through MetalRenderer; this is the Windows analogue). Draws into /// the existing render target, copies it into a `D3D11_USAGE_STAGING` /// texture, maps it, and converts BGRA to RGBA. - #[cfg(any(test, feature = "test-support"))] + #[cfg(feature = "test-support")] pub(crate) fn render_to_image( &mut self, scene: &Scene, diff --git a/crates/gpui_windows/src/platform.rs b/crates/gpui_windows/src/platform.rs index 095e009e23e..72731ecb036 100644 --- a/crates/gpui_windows/src/platform.rs +++ b/crates/gpui_windows/src/platform.rs @@ -28,7 +28,7 @@ use windows::{ Ole::*, Power::*, SystemInformation::*, - SystemServices::POWER_REQUEST_CONTEXT_VERSION, + SystemServices::{GUID_POWER_SAVING_STATUS, POWER_REQUEST_CONTEXT_VERSION}, Threading::{POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, REASON_CONTEXT_0}, }, UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*}, @@ -71,6 +71,7 @@ pub struct WindowsPlatform { invalidate_devices: Arc, handle: HWND, suspend_resume_notification: RefCell>, + power_saving_notification: RefCell>, disable_direct_composition: bool, has_package_identity: bool, app_identity: RefCell>, @@ -98,6 +99,7 @@ pub(crate) struct WindowsPlatformState { /// thread; see [`DrawCoordinator`]. pub(crate) draw_coordinator: Rc, directx_devices: RefCell>, + low_power_mode_enabled: Cell, } #[derive(Default)] @@ -111,6 +113,7 @@ struct PlatformCallbacks { keyboard_layout_change: Cell>>, system_sleep: Cell>>, system_wake: Cell>>, + low_power_mode_change: Cell>>, displays_changed: Cell>>, } @@ -127,6 +130,7 @@ impl WindowsPlatformState { cursor_visible: Arc::new(AtomicBool::new(true)), draw_coordinator: Rc::new(DrawCoordinator::new()), directx_devices: RefCell::new(directx_devices), + low_power_mode_enabled: Cell::new(false), menus: RefCell::new(Vec::new()), } } @@ -240,6 +244,14 @@ impl WindowsPlatform { .inner .take() .context("CreateWindowExW did not run correctly")??; + let mut power_status = SYSTEM_POWER_STATUS::default(); + match unsafe { GetSystemPowerStatus(&mut power_status) } { + Ok(()) => inner + .state + .low_power_mode_enabled + .set(power_status.SystemStatusFlag == 1), + Err(error) => log::warn!("Failed to query Windows battery saver status: {error}"), + } let dispatcher = context .dispatcher .take() @@ -278,6 +290,7 @@ impl WindowsPlatform { text_system, direct_write_text_system, suspend_resume_notification: RefCell::new(None), + power_saving_notification: RefCell::new(None), disable_direct_composition, has_package_identity: has_package_identity(), drop_target_helper, @@ -877,6 +890,33 @@ impl Platform for WindowsPlatform { } } + fn power_mode(&self) -> PowerMode { + if self.inner.state.low_power_mode_enabled.get() { + PowerMode::LowPower + } else { + PowerMode::HighPower + } + } + + fn on_power_mode_change(&self, callback: Box) { + self.inner + .state + .callbacks + .low_power_mode_change + .set(Some(callback)); + let mut notification = self.power_saving_notification.borrow_mut(); + if notification.is_none() { + *notification = unsafe { + RegisterPowerSettingNotification( + HANDLE(self.handle.0), + &GUID_POWER_SAVING_STATUS, + DEVICE_NOTIFY_WINDOW_HANDLE, + ) + .log_err() + }; + } + } + fn set_app_identity(&self, identifier: &str, name: &str) { // If the process has package identity, it's automatally granted an AUMID by the system. if self.has_package_identity { @@ -1198,7 +1238,7 @@ impl WindowsPlatformInner { | WM_GPUI_KEYBOARD_LAYOUT_CHANGED | WM_GPUI_DISPLAYS_CHANGED | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(msg, wparam, lparam), - WM_POWERBROADCAST => self.handle_power_broadcast(wparam), + WM_POWERBROADCAST => self.handle_power_broadcast(wparam, lparam), WM_DISPLAYCHANGE => self.handle_display_change(handle), WM_QUERYENDSESSION => Some(1), WM_ENDSESSION if wparam.0 != 0 => self.handle_end_session(), @@ -1380,7 +1420,7 @@ impl WindowsPlatformInner { Some(0) } - fn handle_power_broadcast(&self, wparam: WPARAM) -> Option { + fn handle_power_broadcast(&self, wparam: WPARAM, lparam: LPARAM) -> Option { match wparam.0 as u32 { PBT_APMSUSPEND => { self.with_callback(|callbacks| &callbacks.system_sleep, |callback| callback()); @@ -1388,6 +1428,16 @@ impl WindowsPlatformInner { PBT_APMRESUMEAUTOMATIC => { self.with_callback(|callbacks| &callbacks.system_wake, |callback| callback()); } + PBT_POWERSETTINGCHANGE => { + if let Some(enabled) = unsafe { power_saving_status(lparam) } { + if self.state.low_power_mode_enabled.replace(enabled) != enabled { + self.with_callback( + |callbacks| &callbacks.low_power_mode_change, + |callback| callback(), + ); + } + } + } _ => {} } Some(1) @@ -1406,6 +1456,23 @@ impl WindowsPlatformInner { } } +unsafe fn power_saving_status(lparam: LPARAM) -> Option { + let setting = unsafe { (lparam.0 as *const POWERBROADCAST_SETTING).as_ref()? }; + if setting.PowerSetting != GUID_POWER_SAVING_STATUS || setting.DataLength != 4 { + return None; + } + let data = unsafe { + std::ptr::addr_of!(setting.Data) + .cast::() + .read_unaligned() + }; + match data { + 0 => Some(false), + 1 => Some(true), + _ => None, + } +} + impl Drop for WindowsPlatform { fn drop(&mut self) { if let Some(stop) = self.vsync_stop.borrow_mut().take() { @@ -1416,6 +1483,9 @@ impl Drop for WindowsPlatform { // SAFETY: notification was returned by RegisterSuspendResumeNotification. UnregisterSuspendResumeNotification(notification).log_err(); } + if let Some(notification) = self.power_saving_notification.borrow_mut().take() { + UnregisterPowerSettingNotification(notification).log_err(); + } DestroyWindow(self.handle) .context("Destroying platform window") .log_err(); diff --git a/crates/gpui_windows/src/window.rs b/crates/gpui_windows/src/window.rs index c467101fc8a..d6d1d264000 100644 --- a/crates/gpui_windows/src/window.rs +++ b/crates/gpui_windows/src/window.rs @@ -1041,7 +1041,7 @@ impl PlatformWindow for WindowsWindow { .log_err(); } - #[cfg(any(test, feature = "test-support"))] + #[cfg(feature = "test-support")] fn render_to_image(&self, scene: &Scene) -> anyhow::Result { self.state .renderer