Skip to content

Commit

Permalink
feat: simplify API (breaking) (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
pevers committed Mar 17, 2024
1 parent 11512c1 commit 90147f1
Show file tree
Hide file tree
Showing 11 changed files with 249 additions and 283 deletions.
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,21 @@
Cross-platform library to block the power save function in the OS.

```rust
use nosleep::{NoSleep, NoSleepType};
use nosleep::{NoSleep, NoSleepTrait};
let mut nosleep = NoSleep::new().unwrap();
nosleep
.start(NoSleepType::PreventUserIdleDisplaySleep)
.prevent_display_sleep() // or prevent_system_sleep()
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(180_000));
nosleep.stop().unwrap(); // Not strictly needed
```
```

## Supported Platforms

| Platform | Status |
|----------|--------|
| Linux | ✔️ |
| macOS | ✔️ |
| Windows | ✔️ |
| iOS | ⚠️ |
| Android ||
7 changes: 3 additions & 4 deletions nosleep-mac-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
name = "nosleep-mac-sys"
description = "Block power save mode for macOS"
authors = ["Peter Evers"]
version = "0.2.1"
version = "0.3.0"
edition = "2021"
rust-version = "1.57"
homepage = "https://github.com/pevers/nosleep-mac-sys"
repository = "https://github.com/pevers/nosleep-mac-sys"
license = "MIT"
keywords = ["nosleep", "powersave", "caffeine"]
keywords = ["nosleep", "powersave", "caffeine", "prevent-sleep", "prevent-display-lock", "prevent-system-lock"]
readme = "README.md"

build = "build.rs"
Expand All @@ -17,7 +16,7 @@ build = "build.rs"
objc-foundation = "0.1.1"
objc_id = "0.1.1"
snafu = "0.7.0"
nosleep-types = { path = "../nosleep-types", version = "0.2.0" }
nosleep-types = { path = "../nosleep-types", version = "0.3.0" }

[build-dependencies]
cc = "1.0.73"
136 changes: 53 additions & 83 deletions nosleep-mac-sys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
//! Thin wrapper utility that provides utility
//! methods to block and unblock the macOS power save mode
//! Block the power save functionality on macOS

#![allow(improper_ctypes)]

use std::ops::Deref;

use nosleep_types::NoSleepType;
use nosleep_types::{NoSleepError, NoSleepTrait};
use objc_foundation::{INSString, NSString};
use objc_id::Id;
use snafu::{prelude::*, Backtrace};

mod sys {
use objc_foundation::NSString;

Expand All @@ -19,120 +17,92 @@ mod sys {
handle: *mut std::os::raw::c_uint,
) -> std::os::raw::c_int;
pub fn stop(handle: std::os::raw::c_uint);
//pub fn isStarted(handle: std::os::raw::c_uint) -> bool;
}
}

#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Could not prevent power save mode for option {:?}", option))]
PreventPowerSaveMode {
option: NoSleepType,
backtrace: Backtrace,
},
}

pub type Result<T, E = Error> = std::result::Result<T, E>;

fn nosleep_ns_string(nosleep_type: &NoSleepType) -> Id<NSString> {
match nosleep_type {
NoSleepType::PreventUserIdleDisplaySleep => {
NSString::from_str("PreventUserIdleDisplaySleep")
}
NoSleepType::PreventUserIdleSystemSleep => NSString::from_str("PreventUserIdleSystemSleep"),
}
}

/// Returned by [`NoSleep::start`] to handle
/// the power save block
struct NoSleepHandle {
handle: u32,
}

impl NoSleepHandle {
/// Stop blocking the system from entering power save mode
pub fn stop(self: &NoSleepHandle) -> Result<()> {
unsafe {
sys::stop(self.handle);
}
Ok(())
}
}
pub struct NoSleep {
// The unblock handle
no_sleep_handle: Option<NoSleepHandle>,
no_sleep_handle: Option<u32>,
}

impl NoSleep {
pub fn new() -> Result<NoSleep> {
impl NoSleepTrait for NoSleep {
fn new() -> Result<NoSleep, NoSleepError> {
Ok(NoSleep {
no_sleep_handle: None,
})
}

/// Blocks the system from entering low-power (sleep) mode by
/// making a synchronous call to the macOS `IOPMAssertionCreateWithName` system call.
/// If [`self::stop`] is not called, then he lock will be cleaned up
/// when the process PID exits.
pub fn start(&mut self, nosleep_type: NoSleepType) -> Result<()> {
// Clear any previous handles held
fn prevent_display_sleep(&mut self) -> Result<(), NoSleepError> {
self.stop()?;

let mut handle = 0u32;
let ret = unsafe { sys::start(nosleep_ns_string(&nosleep_type).deref(), &mut handle) };
let ret = unsafe {
sys::start(
NSString::from_str("PreventUserIdleDisplaySleep").deref(),
&mut handle,
)
};
if ret != 0 {
return PreventPowerSaveModeSnafu {
option: nosleep_type,
}
.fail();
return Err(NoSleepError::PreventSleep {
reason: ret.to_string(),
});
}
self.no_sleep_handle = Some(NoSleepHandle { handle });
self.no_sleep_handle = Some(handle);
Ok(())
}

/// Stop blocking the system from entering power save mode
pub fn stop(&self) -> Result<()> {
fn prevent_system_sleep(&mut self) -> Result<(), NoSleepError> {
self.stop()?;

let mut handle = 0u32;
let ret = unsafe {
sys::start(
NSString::from_str("PreventUserIdleSystemSleep").deref(),
&mut handle,
)
};
if ret != 0 {
return Err(NoSleepError::PreventSleep {
reason: ret.to_string(),
});
}
self.no_sleep_handle = Some(handle);
Ok(())
}

fn stop(&mut self) -> Result<(), NoSleepError> {
if let Some(handle) = &self.no_sleep_handle {
handle.stop()?;
unsafe {
sys::stop(*handle);
}
self.no_sleep_handle.take();
}
Ok(())
}
}

/// TODO: Check if this still fits within the API
/// Checks if the power save block is active
/// for a provided [`u32`] from [`start`]
// pub fn is_started(no_sleep_handle: u32) -> bool {
// unsafe { sys::isStarted(no_sleep_handle) }
// }

#[cfg(test)]
mod tests {
use crate::{NoSleep, NoSleepType};
use nosleep_types::NoSleepTrait;

use super::NoSleep;

#[test]
fn test_start() {
fn test_prevent_display_sleep() {
let mut nosleep = NoSleep::new().unwrap();
nosleep
.start(NoSleepType::PreventUserIdleDisplaySleep)
.unwrap();
nosleep.prevent_display_sleep().unwrap();
}

#[test]
fn test_prevent_system_sleep() {
let mut nosleep = NoSleep::new().unwrap();
nosleep.prevent_system_sleep().unwrap();
}

#[test]
fn test_stop() {
let mut nosleep = NoSleep::new().unwrap();
nosleep
.start(NoSleepType::PreventUserIdleDisplaySleep)
.unwrap();
nosleep.prevent_display_sleep().unwrap();
nosleep.stop().unwrap();
}

// #[test]
// fn test_is_started() {
// assert_eq!(false, is_started(1));
// let ret = start(NoSleepType::PreventUserIdleDisplaySleep).unwrap();
// assert_eq!(true, is_started(ret));
// stop(ret);
// assert_eq!(false, is_started(ret));
// }
}
8 changes: 3 additions & 5 deletions nosleep-nix/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@
name = "nosleep-nix"
description = "Block power save mode cross platform"
authors = ["Peter Evers"]
version = "0.2.1"
version = "0.3.0"
edition = "2021"
rust-version = "1.57"
homepage = "https://github.com/pevers/nosleep"
repository = "https://github.com/pevers/nosleep"
license = "MIT"
keywords = ["nosleep", "powersave", "caffeine"]
keywords = ["nosleep", "powersave", "caffeine", "prevent-sleep", "prevent-display-lock", "prevent-system-lock"]
readme = "README.md"

[dependencies]
nosleep-types = { path = "../nosleep-types", version = "0.2.0" }
nosleep-types = { path = "../nosleep-types", version = "0.3.0" }
dbus = "0.9.5"
snafu = "0.7.0"

0 comments on commit 90147f1

Please sign in to comment.