-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
nosleep_macos.rs
78 lines (64 loc) · 1.8 KB
/
nosleep_macos.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use std::io;
use core_foundation::base::TCFType;
use core_foundation::string::{CFString, CFStringRef};
use libc::c_int;
use crate::constants::TUNNEL_ACTIVITY_NAME;
extern "C" {
pub fn IOPMAssertionCreateWithName(
assertion_type: CFStringRef,
assertion_level: u32,
assertion_name: CFStringRef,
assertion_id: &mut u32,
) -> c_int;
pub fn IOPMAssertionRelease(assertion_id: u32) -> c_int;
}
const NUM_ASSERTIONS: usize = 2;
const ASSERTIONS: [&str; NUM_ASSERTIONS] = ["PreventUserIdleSystemSleep", "PreventSystemSleep"];
struct Assertion(u32);
impl Assertion {
pub fn make(typ: &CFString, name: &CFString) -> io::Result<Self> {
let mut assertion_id = 0;
let result = unsafe {
IOPMAssertionCreateWithName(
typ.as_concrete_TypeRef(),
255,
name.as_concrete_TypeRef(),
&mut assertion_id,
)
};
if result != 0 {
Err(io::Error::last_os_error())
} else {
Ok(Self(assertion_id))
}
}
}
impl Drop for Assertion {
fn drop(&mut self) {
unsafe {
IOPMAssertionRelease(self.0);
}
}
}
pub struct SleepInhibitor {
_assertions: Vec<Assertion>,
}
impl SleepInhibitor {
pub async fn new() -> io::Result<Self> {
let mut assertions = Vec::with_capacity(NUM_ASSERTIONS);
let assertion_name = CFString::from_static_string(concatcp!(TUNNEL_ACTIVITY_NAME));
for typ in ASSERTIONS {
assertions.push(Assertion::make(
&CFString::from_static_string(typ),
&assertion_name,
)?);
}
Ok(Self {
_assertions: assertions,
})
}
}