From 013b5dccb482971c080edf056cd09621a3392669 Mon Sep 17 00:00:00 2001 From: Nolan Darilek Date: Tue, 17 May 2022 14:25:24 -0500 Subject: [PATCH] Optionally restore original power scheme when window loses focus. --- src/lib.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index de7b78a..62defe4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,11 +1,58 @@ -use bevy::prelude::*; +use bevy::{prelude::*, window::WindowFocused}; #[cfg(windows)] -use windows::Win32::System::{Power, SystemServices::GUID_MIN_POWER_SAVINGS}; +use windows::{ + core::GUID, + Win32::System::{Power, SystemServices::GUID_MIN_POWER_SAVINGS}, +}; -fn setup() { +#[derive(Clone, Copy, Default)] +pub struct FullThrottleConfig { + pub restore_original_scheme_on_unfocus: bool, +} + +#[cfg(windows)] +#[derive(Deref, DerefMut)] +struct DefaultScheme(GUID); + +#[cfg(not(windows))] +struct DefaultScheme(); + +#[allow(unused_mut, unused_variables)] +fn setup(mut commands: Commands) { #[cfg(windows)] unsafe { - Power::PowerSetActiveScheme(None, &GUID_MIN_POWER_SAVINGS); + let mut active: *mut GUID = std::ptr::null_mut(); + Power::PowerGetActiveScheme(None, &mut active); + if let Some(active) = active.as_ref() { + let scheme = DefaultScheme(*active); + commands.insert_resource(scheme); + } + } +} + +#[allow(unused_variables)] +fn focus_change( + config: Option>, + mut focus: EventReader, + scheme: Res, +) { + let config: FullThrottleConfig = config + .map(|v| *v) + .unwrap_or_else(|| FullThrottleConfig::default()); + for event in focus.iter() { + if event.focused { + #[cfg(windows)] + unsafe { + Power::PowerSetActiveScheme(None, &GUID_MIN_POWER_SAVINGS); + } + } else { + #[cfg(windows)] + if config.restore_original_scheme_on_unfocus { + unsafe { + Power::PowerSetActiveScheme(None, &**scheme); + } + } + } } } @@ -13,6 +60,6 @@ pub struct FullThrottlePlugin; impl Plugin for FullThrottlePlugin { fn build(&self, app: &mut App) { - app.add_startup_system(setup); + app.add_startup_system(setup).add_system(focus_change); } }