Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
codex-rs/utils/sleep-inhibitor/BUILD.bazel
Normal file
6
codex-rs/utils/sleep-inhibitor/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "sleep-inhibitor",
|
||||
crate_name = "codex_utils_sleep_inhibitor",
|
||||
)
|
||||
28
codex-rs/utils/sleep-inhibitor/Cargo.toml
Normal file
28
codex-rs/utils/sleep-inhibitor/Cargo.toml
Normal file
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "codex-utils-sleep-inhibitor"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
tracing = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
core-foundation = "0.9"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Power",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
12
codex-rs/utils/sleep-inhibitor/src/dummy.rs
Normal file
12
codex-rs/utils/sleep-inhibitor/src/dummy.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct SleepInhibitor;
|
||||
|
||||
impl SleepInhibitor {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(&mut self) {}
|
||||
|
||||
pub(crate) fn release(&mut self) {}
|
||||
}
|
||||
27
codex-rs/utils/sleep-inhibitor/src/iokit_bindings.rs
Normal file
27
codex-rs/utils/sleep-inhibitor/src/iokit_bindings.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
/* automatically generated by rust-bindgen 0.71.1 */
|
||||
|
||||
pub const kIOReturnSuccess: u32 = 0;
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct __CFString {
|
||||
_unused: [u8; 0],
|
||||
}
|
||||
pub type CFStringRef = *const __CFString;
|
||||
pub type kern_return_t = ::std::os::raw::c_int;
|
||||
pub type IOReturn = kern_return_t;
|
||||
pub type IOPMAssertionID = u32;
|
||||
pub type IOPMAssertionLevel = u32;
|
||||
pub const kIOPMAssertionLevelOff: _bindgen_ty_36 = 0;
|
||||
pub const kIOPMAssertionLevelOn: _bindgen_ty_36 = 255;
|
||||
pub type _bindgen_ty_36 = ::std::os::raw::c_uint;
|
||||
unsafe extern "C" {
|
||||
pub fn IOPMAssertionRelease(AssertionID: IOPMAssertionID) -> IOReturn;
|
||||
}
|
||||
unsafe extern "C" {
|
||||
pub fn IOPMAssertionCreateWithName(
|
||||
AssertionType: CFStringRef,
|
||||
AssertionLevel: IOPMAssertionLevel,
|
||||
AssertionName: CFStringRef,
|
||||
AssertionID: *mut IOPMAssertionID,
|
||||
) -> IOReturn;
|
||||
}
|
||||
113
codex-rs/utils/sleep-inhibitor/src/lib.rs
Normal file
113
codex-rs/utils/sleep-inhibitor/src/lib.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
//! Cross-platform helper for preventing idle sleep while a turn is running.
|
||||
//!
|
||||
//! Platform-specific behavior:
|
||||
//! - macOS: Uses native IOKit power assertions instead of spawning `caffeinate`.
|
||||
//! - Linux: Spawns `systemd-inhibit` or `gnome-session-inhibit` while active.
|
||||
//! - Windows: Uses `PowerCreateRequest` + `PowerSetRequest` with
|
||||
//! `PowerRequestSystemRequired`.
|
||||
//! - Other platforms: No-op backend.
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
||||
mod dummy;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_inhibitor;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_inhibitor;
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
||||
use dummy as imp;
|
||||
#[cfg(target_os = "linux")]
|
||||
use linux_inhibitor as imp;
|
||||
#[cfg(target_os = "macos")]
|
||||
use macos as imp;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_inhibitor as imp;
|
||||
|
||||
/// Keeps the machine awake while a turn is in progress when enabled.
|
||||
#[derive(Debug)]
|
||||
pub struct SleepInhibitor {
|
||||
enabled: bool,
|
||||
turn_running: bool,
|
||||
platform: imp::SleepInhibitor,
|
||||
}
|
||||
|
||||
impl SleepInhibitor {
|
||||
pub fn new(enabled: bool) -> Self {
|
||||
Self {
|
||||
enabled,
|
||||
turn_running: false,
|
||||
platform: imp::SleepInhibitor::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the active turn state; turns sleep prevention on/off as needed.
|
||||
pub fn set_turn_running(&mut self, turn_running: bool) {
|
||||
self.turn_running = turn_running;
|
||||
if !self.enabled {
|
||||
self.release();
|
||||
return;
|
||||
}
|
||||
|
||||
if turn_running {
|
||||
self.acquire();
|
||||
} else {
|
||||
self.release();
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire(&mut self) {
|
||||
self.platform.acquire();
|
||||
}
|
||||
|
||||
fn release(&mut self) {
|
||||
self.platform.release();
|
||||
}
|
||||
|
||||
/// Return the latest turn-running state requested by the caller.
|
||||
pub fn is_turn_running(&self) -> bool {
|
||||
self.turn_running
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SleepInhibitor;
|
||||
|
||||
#[test]
|
||||
fn sleep_inhibitor_toggles_without_panicking() {
|
||||
let mut inhibitor = SleepInhibitor::new(/*enabled*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ true);
|
||||
assert!(inhibitor.is_turn_running());
|
||||
inhibitor.set_turn_running(/*turn_running*/ false);
|
||||
assert!(!inhibitor.is_turn_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_inhibitor_disabled_does_not_panic() {
|
||||
let mut inhibitor = SleepInhibitor::new(/*enabled*/ false);
|
||||
inhibitor.set_turn_running(/*turn_running*/ true);
|
||||
assert!(inhibitor.is_turn_running());
|
||||
inhibitor.set_turn_running(/*turn_running*/ false);
|
||||
assert!(!inhibitor.is_turn_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_inhibitor_multiple_true_calls_are_idempotent() {
|
||||
let mut inhibitor = SleepInhibitor::new(/*enabled*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_inhibitor_can_toggle_multiple_times() {
|
||||
let mut inhibitor = SleepInhibitor::new(/*enabled*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ false);
|
||||
inhibitor.set_turn_running(/*turn_running*/ true);
|
||||
inhibitor.set_turn_running(/*turn_running*/ false);
|
||||
}
|
||||
}
|
||||
230
codex-rs/utils/sleep-inhibitor/src/linux_inhibitor.rs
Normal file
230
codex-rs/utils/sleep-inhibitor/src/linux_inhibitor.rs
Normal file
@@ -0,0 +1,230 @@
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::Child;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
use tracing::warn;
|
||||
|
||||
const ASSERTION_REASON: &str = "Codex is running an active turn";
|
||||
const APP_ID: &str = "codex";
|
||||
// Keep the blocker process alive "long enough" without needing restarts.
|
||||
// This is `i32::MAX` seconds, which is accepted by common `sleep` implementations.
|
||||
const BLOCKER_SLEEP_SECONDS: &str = "2147483647";
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct LinuxSleepInhibitor {
|
||||
state: InhibitState,
|
||||
preferred_backend: Option<LinuxBackend>,
|
||||
missing_backend_logged: bool,
|
||||
}
|
||||
|
||||
pub(crate) use LinuxSleepInhibitor as SleepInhibitor;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
enum InhibitState {
|
||||
#[default]
|
||||
Inactive,
|
||||
Active {
|
||||
backend: LinuxBackend,
|
||||
child: Child,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum LinuxBackend {
|
||||
SystemdInhibit,
|
||||
GnomeSessionInhibit,
|
||||
}
|
||||
|
||||
impl LinuxSleepInhibitor {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(&mut self) {
|
||||
if let InhibitState::Active { backend, child } = &mut self.state {
|
||||
match child.try_wait() {
|
||||
Ok(None) => return,
|
||||
Ok(Some(status)) => {
|
||||
warn!(
|
||||
?backend,
|
||||
?status,
|
||||
"Linux sleep inhibitor backend exited unexpectedly; attempting fallback"
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(
|
||||
?backend,
|
||||
reason = %error,
|
||||
"Failed to query Linux sleep inhibitor backend status; attempting restart"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.state = InhibitState::Inactive;
|
||||
let should_log_backend_failures = !self.missing_backend_logged;
|
||||
let backends = match self.preferred_backend {
|
||||
Some(LinuxBackend::SystemdInhibit) => [
|
||||
LinuxBackend::SystemdInhibit,
|
||||
LinuxBackend::GnomeSessionInhibit,
|
||||
],
|
||||
Some(LinuxBackend::GnomeSessionInhibit) => [
|
||||
LinuxBackend::GnomeSessionInhibit,
|
||||
LinuxBackend::SystemdInhibit,
|
||||
],
|
||||
None => [
|
||||
LinuxBackend::SystemdInhibit,
|
||||
LinuxBackend::GnomeSessionInhibit,
|
||||
],
|
||||
};
|
||||
|
||||
for backend in backends {
|
||||
match spawn_backend(backend) {
|
||||
Ok(mut child) => match child.try_wait() {
|
||||
Ok(None) => {
|
||||
self.state = InhibitState::Active { backend, child };
|
||||
self.preferred_backend = Some(backend);
|
||||
self.missing_backend_logged = false;
|
||||
return;
|
||||
}
|
||||
Ok(Some(status)) => {
|
||||
if should_log_backend_failures {
|
||||
warn!(
|
||||
?backend,
|
||||
?status,
|
||||
"Linux sleep inhibitor backend exited immediately"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
if should_log_backend_failures {
|
||||
warn!(
|
||||
?backend,
|
||||
reason = %error,
|
||||
"Failed to query Linux sleep inhibitor backend status after spawn"
|
||||
);
|
||||
}
|
||||
if let Err(kill_error) = child.kill()
|
||||
&& !child_exited(&kill_error)
|
||||
{
|
||||
warn!(
|
||||
?backend,
|
||||
reason = %kill_error,
|
||||
"Failed to stop Linux sleep inhibitor backend after status probe failure"
|
||||
);
|
||||
}
|
||||
if let Err(wait_error) = child.wait()
|
||||
&& !child_exited(&wait_error)
|
||||
{
|
||||
warn!(
|
||||
?backend,
|
||||
reason = %wait_error,
|
||||
"Failed to reap Linux sleep inhibitor backend after status probe failure"
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
if should_log_backend_failures && error.kind() != std::io::ErrorKind::NotFound {
|
||||
warn!(
|
||||
?backend,
|
||||
reason = %error,
|
||||
"Failed to start Linux sleep inhibitor backend"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if should_log_backend_failures {
|
||||
warn!("No Linux sleep inhibitor backend is available");
|
||||
self.missing_backend_logged = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn release(&mut self) {
|
||||
match std::mem::take(&mut self.state) {
|
||||
InhibitState::Inactive => {}
|
||||
InhibitState::Active { backend, mut child } => {
|
||||
if let Err(error) = child.kill()
|
||||
&& !child_exited(&error)
|
||||
{
|
||||
warn!(?backend, reason = %error, "Failed to stop Linux sleep inhibitor backend");
|
||||
}
|
||||
if let Err(error) = child.wait()
|
||||
&& !child_exited(&error)
|
||||
{
|
||||
warn!(?backend, reason = %error, "Failed to reap Linux sleep inhibitor backend");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LinuxSleepInhibitor {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_backend(backend: LinuxBackend) -> Result<Child, std::io::Error> {
|
||||
// Ensure the helper receives SIGTERM when the original parent dies.
|
||||
// `parent_pid` is captured before spawn and checked in `pre_exec` to avoid
|
||||
// the fork/exec race where the parent exits before PDEATHSIG is armed.
|
||||
// SAFETY: `getpid` has no preconditions and is safe to call here.
|
||||
let parent_pid = unsafe { libc::getpid() };
|
||||
let mut command = match backend {
|
||||
LinuxBackend::SystemdInhibit => {
|
||||
let mut command = Command::new("systemd-inhibit");
|
||||
command.args([
|
||||
"--what=idle",
|
||||
"--mode=block",
|
||||
"--who",
|
||||
APP_ID,
|
||||
"--why",
|
||||
ASSERTION_REASON,
|
||||
"--",
|
||||
"sleep",
|
||||
BLOCKER_SLEEP_SECONDS,
|
||||
]);
|
||||
command
|
||||
}
|
||||
LinuxBackend::GnomeSessionInhibit => {
|
||||
let mut command = Command::new("gnome-session-inhibit");
|
||||
command.args([
|
||||
"--inhibit",
|
||||
"idle",
|
||||
"--reason",
|
||||
ASSERTION_REASON,
|
||||
"sleep",
|
||||
BLOCKER_SLEEP_SECONDS,
|
||||
]);
|
||||
command
|
||||
}
|
||||
};
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
|
||||
// SAFETY: `pre_exec` must be registered before spawn. The closure only
|
||||
// performs libc setup for the child process and returns an `io::Error`
|
||||
// when parent-death signal setup fails.
|
||||
unsafe {
|
||||
command.pre_exec(move || {
|
||||
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) == -1 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
if libc::getppid() != parent_pid {
|
||||
libc::raise(libc::SIGTERM);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
command.spawn()
|
||||
}
|
||||
|
||||
fn child_exited(error: &std::io::Error) -> bool {
|
||||
matches!(error.kind(), std::io::ErrorKind::InvalidInput)
|
||||
}
|
||||
107
codex-rs/utils/sleep-inhibitor/src/macos.rs
Normal file
107
codex-rs/utils/sleep-inhibitor/src/macos.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
use core_foundation::base::TCFType;
|
||||
use core_foundation::string::CFString;
|
||||
use tracing::warn;
|
||||
|
||||
#[allow(
|
||||
dead_code,
|
||||
non_camel_case_types,
|
||||
non_snake_case,
|
||||
non_upper_case_globals,
|
||||
clippy::all
|
||||
)]
|
||||
mod iokit {
|
||||
#[link(name = "IOKit", kind = "framework")]
|
||||
unsafe extern "C" {}
|
||||
|
||||
include!("iokit_bindings.rs");
|
||||
}
|
||||
|
||||
type IOPMAssertionID = iokit::IOPMAssertionID;
|
||||
type IOPMAssertionLevel = iokit::IOPMAssertionLevel;
|
||||
type IOReturn = iokit::IOReturn;
|
||||
|
||||
const ASSERTION_REASON: &str = "Codex is running an active turn";
|
||||
// Apple exposes this assertion type as a `CFSTR(...)` macro, so bindgen cannot generate a
|
||||
// reusable `CFStringRef` constant for it.
|
||||
const ASSERTION_TYPE_PREVENT_USER_IDLE_SYSTEM_SLEEP: &str = "PreventUserIdleSystemSleep";
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct SleepInhibitor {
|
||||
assertion: Option<MacSleepAssertion>,
|
||||
}
|
||||
|
||||
impl SleepInhibitor {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(&mut self) {
|
||||
if self.assertion.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
match MacSleepAssertion::create(ASSERTION_REASON) {
|
||||
Ok(assertion) => {
|
||||
self.assertion = Some(assertion);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(
|
||||
iokit_error = error,
|
||||
"Failed to create macOS sleep-prevention assertion"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn release(&mut self) {
|
||||
self.assertion = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MacSleepAssertion {
|
||||
id: IOPMAssertionID,
|
||||
}
|
||||
|
||||
impl MacSleepAssertion {
|
||||
fn create(name: &str) -> Result<Self, IOReturn> {
|
||||
let assertion_type = CFString::new(ASSERTION_TYPE_PREVENT_USER_IDLE_SYSTEM_SLEEP);
|
||||
let assertion_name = CFString::new(name);
|
||||
let mut id: IOPMAssertionID = 0;
|
||||
// `core-foundation` and the generated bindings each declare an opaque `__CFString` type,
|
||||
// so we cast to the bindgen pointer aliases before crossing the FFI boundary.
|
||||
let assertion_type_ref: iokit::CFStringRef = assertion_type.as_concrete_TypeRef().cast();
|
||||
let assertion_name_ref: iokit::CFStringRef = assertion_name.as_concrete_TypeRef().cast();
|
||||
let result = unsafe {
|
||||
// SAFETY: `assertion_type_ref` and `assertion_name_ref` are valid `CFStringRef`s and
|
||||
// `&mut id` is a valid out-pointer for `IOPMAssertionCreateWithName` to initialize.
|
||||
iokit::IOPMAssertionCreateWithName(
|
||||
assertion_type_ref,
|
||||
iokit::kIOPMAssertionLevelOn as IOPMAssertionLevel,
|
||||
assertion_name_ref,
|
||||
&mut id,
|
||||
)
|
||||
};
|
||||
if result == iokit::kIOReturnSuccess as IOReturn {
|
||||
Ok(Self { id })
|
||||
} else {
|
||||
Err(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MacSleepAssertion {
|
||||
fn drop(&mut self) {
|
||||
let result = unsafe {
|
||||
// SAFETY: `self.id` was returned by `IOPMAssertionCreateWithName` and this `Drop`
|
||||
// implementation releases it exactly once when the owning assertion is dropped.
|
||||
iokit::IOPMAssertionRelease(self.id)
|
||||
};
|
||||
if result != iokit::kIOReturnSuccess as IOReturn {
|
||||
warn!(
|
||||
iokit_error = result,
|
||||
"Failed to release macOS sleep-prevention assertion"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
119
codex-rs/utils/sleep-inhibitor/src/windows_inhibitor.rs
Normal file
119
codex-rs/utils/sleep-inhibitor/src/windows_inhibitor.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use std::ffi::OsStr;
|
||||
use std::iter::once;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use tracing::warn;
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
use windows_sys::Win32::System::Power::POWER_REQUEST_TYPE;
|
||||
use windows_sys::Win32::System::Power::PowerClearRequest;
|
||||
use windows_sys::Win32::System::Power::PowerCreateRequest;
|
||||
use windows_sys::Win32::System::Power::PowerRequestSystemRequired;
|
||||
use windows_sys::Win32::System::Power::PowerSetRequest;
|
||||
use windows_sys::Win32::System::SystemServices::POWER_REQUEST_CONTEXT_VERSION;
|
||||
use windows_sys::Win32::System::Threading::POWER_REQUEST_CONTEXT_SIMPLE_STRING;
|
||||
use windows_sys::Win32::System::Threading::REASON_CONTEXT;
|
||||
use windows_sys::Win32::System::Threading::REASON_CONTEXT_0;
|
||||
|
||||
const ASSERTION_REASON: &str = "Codex is running an active turn";
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct WindowsSleepInhibitor {
|
||||
request: Option<PowerRequest>,
|
||||
}
|
||||
|
||||
pub(crate) use WindowsSleepInhibitor as SleepInhibitor;
|
||||
|
||||
impl WindowsSleepInhibitor {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(&mut self) {
|
||||
if self.request.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
match PowerRequest::new_system_required(ASSERTION_REASON) {
|
||||
Ok(request) => {
|
||||
self.request = Some(request);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(
|
||||
reason = %error,
|
||||
"Failed to acquire Windows sleep-prevention request"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn release(&mut self) {
|
||||
self.request = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PowerRequest {
|
||||
handle: windows_sys::Win32::Foundation::HANDLE,
|
||||
request_type: POWER_REQUEST_TYPE,
|
||||
}
|
||||
|
||||
impl PowerRequest {
|
||||
fn new_system_required(reason: &str) -> Result<Self, String> {
|
||||
let mut wide_reason: Vec<u16> = OsStr::new(reason).encode_wide().chain(once(0)).collect();
|
||||
let context = REASON_CONTEXT {
|
||||
Version: POWER_REQUEST_CONTEXT_VERSION,
|
||||
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
|
||||
Reason: REASON_CONTEXT_0 {
|
||||
SimpleReasonString: wide_reason.as_mut_ptr(),
|
||||
},
|
||||
};
|
||||
// SAFETY: `context` points to a valid `REASON_CONTEXT` for the duration
|
||||
// of the call and Windows copies the relevant data before returning.
|
||||
let handle = unsafe { PowerCreateRequest(&context) };
|
||||
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
|
||||
let error = std::io::Error::last_os_error();
|
||||
return Err(format!("PowerCreateRequest failed: {error}"));
|
||||
}
|
||||
|
||||
// Match macOS `PreventUserIdleSystemSleep`: prevent idle system sleep
|
||||
// without forcing the display to stay on.
|
||||
let request_type = PowerRequestSystemRequired;
|
||||
// SAFETY: `handle` is a live power request handle and `request_type` is a
|
||||
// valid power request enum value.
|
||||
if unsafe { PowerSetRequest(handle, request_type) } == 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
// SAFETY: `handle` was returned by `PowerCreateRequest` and has not
|
||||
// been closed yet on this error path.
|
||||
let _ = unsafe { CloseHandle(handle) };
|
||||
return Err(format!("PowerSetRequest failed: {error}"));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
handle,
|
||||
request_type,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PowerRequest {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: `self.handle` is the handle owned by this `PowerRequest`, and
|
||||
// `self.request_type` is the request type that was set on acquire.
|
||||
if unsafe { PowerClearRequest(self.handle, self.request_type) } == 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
warn!(
|
||||
reason = %error,
|
||||
"Failed to clear Windows sleep-prevention request"
|
||||
);
|
||||
}
|
||||
// SAFETY: `self.handle` is owned by this struct and closed exactly once
|
||||
// in `Drop`.
|
||||
if unsafe { CloseHandle(self.handle) } == 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
warn!(
|
||||
reason = %error,
|
||||
"Failed to close Windows sleep-prevention request handle"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user