Skip to content

Commit 61d401a

Browse files
committed
fix(macos): use native idle-sleep assertions
1 parent f3e538c commit 61d401a

4 files changed

Lines changed: 63 additions & 11 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ metal = "0.29.0"
5757
objc2 = "0.6.4"
5858
objc2-app-kit = "0.3.2"
5959
objc2-core-audio = "0.3.2"
60+
objc2-core-foundation = "0.3.2"
6061
objc2-foundation = "0.3.2"
6162
objc2-quartz-core = { version = "0.3.2", features = ["CALayer"] }
6263
objc2-service-management = { version = "0.3.2", features = ["SMAppService"] }

‎docs/features/README.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,14 +241,23 @@ Settings // settings
241241
├── While dictating -> Mute / Pause media / Do nothing
242242
│ └── Intentional capture only, not ordinary shortcut chords
243243
└── Sound volume -> Immediate feedback setting; zero suppresses tones
244+
245+
Intentional recording // recording.environment
246+
├── Acquire native macOS no-idle-sleep assertion
247+
│ └── Failure -> Warn and continue recording
248+
└── Finish/cancel -> Release the assertion
249+
// no caffeinate child process or executable-policy dialog
244250
```
245251
246252
Successful settings saves persist and project changes at safe runtime boundaries.
247253
Persistence, conflict, and ownership checks live in
248254
[app_settings.rs](../../src/app_settings.rs),
249255
[recording_environment.rs](../../src/recording_environment.rs), and
250256
[audio.rs](../../src/audio.rs). Settings previews do not prove physical device
251-
switching or native mute support; muting is best-effort, not universal.
257+
switching or native mute support; muting is best-effort, not universal. The
258+
recording-environment ownership checks cover overlapping acquisition and release,
259+
not a managed-device policy or native power assertion. An opt-in native assertion
260+
smoke exercises IOKit without starting microphone capture.
252261
253262
**Easy to misread:** an open microphone is not an active recording. Sleeping
254263
Commands still needs open input; it is not Release when idle.

‎src/recording_environment.rs‎

Lines changed: 51 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::ffi::c_void;
22
use std::mem::size_of;
33
use std::path::Path;
4-
use std::process::{Child, Command};
4+
use std::process::Command;
55
use std::ptr::NonNull;
66
use std::sync::mpsc::{self, Sender};
77
use std::thread;
@@ -11,10 +11,12 @@ use objc2_core_audio::{
1111
kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyElementMain,
1212
kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeOutput, kAudioObjectSystemObject,
1313
};
14+
use objc2_core_foundation::CFString;
1415

1516
use crate::app_settings::{self, RecordingAudioBehavior};
1617

1718
const VIRTUAL_MAIN_VOLUME: u32 = u32::from_be_bytes(*b"vmvc");
19+
const POWER_ASSERTION_LEVEL_ON: u32 = 255;
1820
const PAUSE_MUSIC: &str = r#"
1921
try
2022
if application "Music" is running then
@@ -146,27 +148,60 @@ pub fn prevent_sleep() -> Option<PreventSleep> {
146148
}
147149

148150
pub struct PreventSleep {
149-
process: Child,
151+
assertion_id: u32,
150152
}
151153

152154
impl PreventSleep {
153155
fn start() -> std::io::Result<Self> {
154-
Ok(Self {
155-
process: Command::new("/usr/bin/caffeinate")
156-
.args(["-i", "-w"])
157-
.arg(std::process::id().to_string())
158-
.spawn()?,
159-
})
156+
let assertion_type = CFString::from_static_str("NoIdleSleepAssertion");
157+
let assertion_name = CFString::from_static_str("HEX intentional recording");
158+
let mut assertion_id = 0;
159+
// SAFETY: Both Core Foundation strings remain alive for the call and
160+
// assertion_id points to writable, correctly sized storage. IOKit
161+
// retains the assertion independently until IOPMAssertionRelease.
162+
let status = unsafe {
163+
IOPMAssertionCreateWithName(
164+
(&*assertion_type as *const CFString).cast(),
165+
POWER_ASSERTION_LEVEL_ON,
166+
(&*assertion_name as *const CFString).cast(),
167+
&mut assertion_id,
168+
)
169+
};
170+
if status != 0 {
171+
return Err(std::io::Error::other(format!(
172+
"IOPMAssertionCreateWithName failed with IOReturn 0x{:08x}",
173+
status as u32
174+
)));
175+
}
176+
Ok(Self { assertion_id })
160177
}
161178
}
162179

163180
impl Drop for PreventSleep {
164181
fn drop(&mut self) {
165-
let _ = self.process.kill();
166-
let _ = self.process.wait();
182+
// SAFETY: assertion_id was returned by a successful create call and
183+
// this guard is its sole owner, so release occurs exactly once.
184+
let status = unsafe { IOPMAssertionRelease(self.assertion_id) };
185+
if status != 0 {
186+
tracing::warn!(
187+
status = format_args!("0x{:08x}", status as u32),
188+
"could not release idle-sleep assertion"
189+
);
190+
}
167191
}
168192
}
169193

194+
#[link(name = "IOKit", kind = "framework")]
195+
unsafe extern "C" {
196+
fn IOPMAssertionCreateWithName(
197+
assertion_type: *const c_void,
198+
assertion_level: u32,
199+
assertion_name: *const c_void,
200+
assertion_id: *mut u32,
201+
) -> i32;
202+
fn IOPMAssertionRelease(assertion_id: u32) -> i32;
203+
}
204+
170205
enum AudioBehaviorGuard {
171206
Muted { device: u32, previous: f32 },
172207
Paused { players: Vec<String> },
@@ -396,6 +431,12 @@ mod tests {
396431
drop(controller.begin());
397432
}
398433

434+
#[test]
435+
#[ignore = "exercises the native macOS idle-sleep assertion"]
436+
fn native_idle_sleep_assertion_acquires_and_releases() {
437+
drop(PreventSleep::start().unwrap());
438+
}
439+
399440
#[test]
400441
fn overlapping_sessions_restore_only_after_the_last_session() {
401442
let (controller, events) = observed_controller();

0 commit comments

Comments
 (0)