├── src ├── lib.rs ├── platform_impl │ ├── mod.rs │ ├── windows │ │ └── power_monitor.rs │ ├── linux │ │ └── power_monitor.rs │ └── macos │ │ └── power_monitor.rs └── monitor.rs ├── .gitignore ├── rustfmt.toml ├── README.md ├── examples ├── winit.rs └── tao.rs ├── Cargo.toml └── LICENSE /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod monitor; 2 | mod platform_impl; 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | target/ 3 | .vscode/ 4 | .DS_Store -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 100 2 | hard_tabs = false 3 | tab_spaces = 2 4 | newline_style = "Unix" 5 | use_small_heuristics = "Default" 6 | reorder_imports = true 7 | reorder_modules = true 8 | remove_nested_parens = true 9 | edition = "2021" 10 | merge_derives = true 11 | use_try_shorthand = false 12 | use_field_init_shorthand = false 13 | force_explicit_abi = true 14 | -------------------------------------------------------------------------------- /src/platform_impl/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(target_os = "macos")] 2 | #[path = "macos/power_monitor.rs"] 3 | mod monitor; 4 | #[cfg(target_os = "windows")] 5 | #[path = "windows/power_monitor.rs"] 6 | mod monitor; 7 | 8 | #[cfg(any( 9 | target_os = "linux", 10 | target_os = "dragonfly", 11 | target_os = "freebsd", 12 | target_os = "netbsd", 13 | target_os = "openbsd" 14 | ))] 15 | #[path = "linux/power_monitor.rs"] 16 | mod monitor; 17 | 18 | pub use monitor::*; 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Power State Plugin (PSP) 2 | Rust Cross-platform Power State Plugin (PSP). 3 | 4 | Using an MPSC channel for emitting events when screen-locked, unlocked, sleep, wake up. 5 | 6 | ## Support Platform 7 | - [x] macOS 8 | - [x] Windows 9 | - [x] Unix (with D-Bus only) 10 | 11 | ## Events 12 | 13 | #### ScreenLocked 14 | When you logout the session or close your laptop lid 15 | 16 | #### ScreenUnlocked 17 | When you login the session or open the laptop lid 18 | 19 | #### Resume 20 | Resume from sleep mode 21 | 22 | #### Suspend 23 | Turn your computer into sleep mode 24 | 25 | ## Examples 26 | 27 | ### With [Tao](https://github.com/tauri-apps/tao) 28 | ``` 29 | cargo run --example tao 30 | ``` 31 | 32 | ### With [winit](https://github.com/rust-windowing/winit) 33 | ``` 34 | cargo run --example winit 35 | ``` 36 | -------------------------------------------------------------------------------- /examples/winit.rs: -------------------------------------------------------------------------------- 1 | use psp::monitor::PowerMonitor; 2 | use winit::{ 3 | event::{Event, WindowEvent}, 4 | event_loop::{ControlFlow, EventLoop}, 5 | window::WindowBuilder, 6 | }; 7 | 8 | fn main() { 9 | let event_loop = EventLoop::new(); 10 | let window = WindowBuilder::new().build(&event_loop).unwrap(); 11 | 12 | let power_monitor = PowerMonitor::new(); 13 | let power_event_channel = power_monitor.event_receiver(); 14 | if let Err(msg) = power_monitor.start_listening() { 15 | println!("Failed to start listening to power events: {}", msg); 16 | return; 17 | } 18 | 19 | event_loop.run(move |event, _, control_flow| { 20 | *control_flow = ControlFlow::Wait; 21 | 22 | match event { 23 | Event::WindowEvent { 24 | event: WindowEvent::CloseRequested, 25 | window_id, 26 | } if window_id == window.id() => *control_flow = ControlFlow::Exit, 27 | _ => (), 28 | } 29 | 30 | if let Ok(event) = power_event_channel.try_recv() { 31 | println!("{event:?}"); 32 | } 33 | }); 34 | } 35 | -------------------------------------------------------------------------------- /examples/tao.rs: -------------------------------------------------------------------------------- 1 | use psp::monitor::PowerMonitor; 2 | use tao::{ 3 | event::{Event, WindowEvent}, 4 | event_loop::{ControlFlow, EventLoop}, 5 | window::WindowBuilder, 6 | }; 7 | 8 | fn main() { 9 | let event_loop = EventLoop::new(); 10 | 11 | let window = WindowBuilder::new() 12 | .with_title("Window") 13 | .build(&event_loop) 14 | .unwrap(); 15 | 16 | let power_monitor = PowerMonitor::new(); 17 | let power_event_channel = power_monitor.event_receiver(); 18 | if let Err(msg) = power_monitor.start_listening() { 19 | println!("Failed to start listening to power events: {}", msg); 20 | return; 21 | } 22 | 23 | event_loop.run(move |event, _, control_flow| { 24 | *control_flow = ControlFlow::Wait; 25 | 26 | match event { 27 | Event::WindowEvent { 28 | event: WindowEvent::CloseRequested, 29 | .. 30 | } => *control_flow = ControlFlow::Exit, 31 | Event::MainEventsCleared => { 32 | window.request_redraw(); 33 | } 34 | _ => (), 35 | } 36 | 37 | if let Ok(event) = power_event_channel.try_recv() { 38 | println!("{event:?}"); 39 | } 40 | }); 41 | } 42 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "psp" 3 | description = "Cross-platform power state events plugin" 4 | version = "0.1.0" 5 | edition = "2021" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | [features] 9 | default = [] 10 | 11 | [dependencies] 12 | libc = "0.2" 13 | crossbeam-channel = "0.5" 14 | 15 | [target."cfg(target_os = \"macos\")".dependencies] 16 | objc = "0.2" 17 | cocoa = "0.24" 18 | core-foundation = "0.9" 19 | core-graphics = "0.22" 20 | dispatch = "0.2" 21 | scopeguard = "1.1" 22 | png = "0.17" 23 | 24 | [target."cfg(target_os = \"windows\")".dependencies] 25 | windows = { version = "0.48", features = [ 26 | "Win32_Foundation", 27 | "Win32_Graphics_Gdi", 28 | "Win32_System_LibraryLoader", 29 | "Win32_System_Power", 30 | "Win32_System_RemoteDesktop", 31 | "Win32_System_SystemServices", 32 | "Win32_UI_Controls", 33 | "Win32_UI_WindowsAndMessaging", 34 | ] } 35 | 36 | [target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies] 37 | zbus = "3" 38 | tokio = { version = "1", features = ["full"] } 39 | 40 | [dev-dependencies] 41 | tao = "0.20.0" 42 | winit = "0.28.6" 43 | -------------------------------------------------------------------------------- /src/monitor.rs: -------------------------------------------------------------------------------- 1 | use crossbeam_channel::{unbounded, Receiver, Sender}; 2 | use std::sync::OnceLock; 3 | 4 | use crate::platform_impl; 5 | 6 | #[derive(Debug, Clone, Copy)] 7 | pub enum PowerState { 8 | Unknown, 9 | Suspend, 10 | Resume, 11 | ScreenLocked, 12 | ScreenUnlocked, 13 | } 14 | 15 | static STATE_CHANNEL: OnceLock<(Sender, Receiver)> = 16 | OnceLock::<(Sender, Receiver)>::new(); 17 | 18 | pub struct PowerEventChannel {} 19 | 20 | impl PowerEventChannel { 21 | pub fn receiver() -> Receiver { 22 | let (_, rx) = STATE_CHANNEL.get_or_init(unbounded); 23 | rx.clone() 24 | } 25 | 26 | pub fn sender() -> Sender { 27 | let (tx, _) = STATE_CHANNEL.get_or_init(unbounded); 28 | tx.clone() 29 | } 30 | } 31 | 32 | pub struct PowerMonitor { 33 | monitor: platform_impl::PowerMonitor, 34 | } 35 | 36 | impl PowerMonitor { 37 | pub fn new() -> Self { 38 | let monitor = platform_impl::PowerMonitor::new(); 39 | Self { monitor } 40 | } 41 | 42 | pub fn start_listening(&self) -> Result<(), &'static str> { 43 | self.monitor.start_listening() 44 | } 45 | 46 | pub fn event_receiver(&self) -> Receiver { 47 | PowerEventChannel::receiver() 48 | } 49 | } 50 | 51 | impl Default for PowerMonitor { 52 | fn default() -> Self { 53 | Self::new() 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/platform_impl/windows/power_monitor.rs: -------------------------------------------------------------------------------- 1 | use crate::monitor::{PowerEventChannel, PowerState}; 2 | use windows::{ 3 | s, 4 | Win32::{ 5 | Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}, 6 | System::{ 7 | LibraryLoader::GetModuleHandleA, 8 | Power::RegisterPowerSettingNotification, 9 | RemoteDesktop::{WTSRegisterSessionNotification, NOTIFY_FOR_THIS_SESSION}, 10 | SystemServices::GUID_POWERSCHEME_PERSONALITY, 11 | }, 12 | UI::WindowsAndMessaging::{ 13 | CreateWindowExA, DefWindowProcA, IsWindow, RegisterClassA, CW_USEDEFAULT, 14 | PBT_APMRESUMESUSPEND, PBT_APMSUSPEND, WINDOW_EX_STYLE, WM_POWERBROADCAST, 15 | WM_WTSSESSION_CHANGE, WNDCLASSA, WS_OVERLAPPEDWINDOW, WTS_SESSION_LOCK, WTS_SESSION_UNLOCK, 16 | }, 17 | }, 18 | }; 19 | 20 | #[allow(dead_code)] 21 | pub struct PowerMonitor { 22 | hwnd: HWND, 23 | } 24 | 25 | impl PowerMonitor { 26 | pub fn new() -> Self { 27 | unsafe { 28 | let hwnd = create_power_events_listener().unwrap(); 29 | Self { hwnd } 30 | } 31 | } 32 | 33 | pub fn start_listening(&self) -> std::result::Result<(), &'static str> { 34 | unsafe { 35 | if RegisterPowerSettingNotification(HANDLE(self.hwnd.0), &GUID_POWERSCHEME_PERSONALITY, 0) 36 | .is_err() 37 | { 38 | return Err("Failed to register power setting notification"); 39 | }; 40 | if !WTSRegisterSessionNotification(self.hwnd, NOTIFY_FOR_THIS_SESSION).as_bool() { 41 | return Err("Failed to register session notification"); 42 | }; 43 | } 44 | Ok(()) 45 | } 46 | } 47 | 48 | impl Default for PowerMonitor { 49 | fn default() -> Self { 50 | Self::new() 51 | } 52 | } 53 | 54 | unsafe fn create_power_events_listener() -> std::result::Result { 55 | let instance = GetModuleHandleA(None).unwrap_or_default(); 56 | 57 | let window_class = s!("__psp_event_listener"); 58 | 59 | let wnd_class = WNDCLASSA { 60 | hInstance: instance, 61 | lpszClassName: window_class, 62 | lpfnWndProc: Some(wndproc), 63 | ..Default::default() 64 | }; 65 | 66 | RegisterClassA(&wnd_class); 67 | 68 | let hwnd = CreateWindowExA( 69 | WINDOW_EX_STYLE::default(), 70 | window_class, 71 | s!("__psp_dummy_window"), 72 | WS_OVERLAPPEDWINDOW, 73 | CW_USEDEFAULT, 74 | CW_USEDEFAULT, 75 | CW_USEDEFAULT, 76 | CW_USEDEFAULT, 77 | None, 78 | None, 79 | instance, 80 | None, 81 | ); 82 | 83 | if !IsWindow(hwnd).as_bool() { 84 | return Err("Unable to get valid mutable pointer for CreateWindowEx"); 85 | } 86 | 87 | Ok(hwnd) 88 | } 89 | 90 | extern "system" fn wndproc(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { 91 | unsafe { 92 | match message { 93 | WM_POWERBROADCAST => match wparam.0 as u32 { 94 | PBT_APMRESUMESUSPEND => { 95 | let sender = PowerEventChannel::sender(); 96 | let _ = sender.send(PowerState::Resume); 97 | } 98 | PBT_APMSUSPEND => { 99 | let sender = PowerEventChannel::sender(); 100 | let _ = sender.send(PowerState::Suspend); 101 | } 102 | _ => {} 103 | }, 104 | WM_WTSSESSION_CHANGE => match wparam.0 as u32 { 105 | WTS_SESSION_LOCK => { 106 | let sender = PowerEventChannel::sender(); 107 | let _ = sender.send(PowerState::ScreenLocked); 108 | } 109 | WTS_SESSION_UNLOCK => { 110 | let sender = PowerEventChannel::sender(); 111 | let _ = sender.send(PowerState::ScreenUnlocked); 112 | } 113 | _ => {} 114 | }, 115 | _ => {} 116 | } 117 | DefWindowProcA(window, message, wparam, lparam) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/platform_impl/linux/power_monitor.rs: -------------------------------------------------------------------------------- 1 | use crate::monitor::{PowerEventChannel, PowerState}; 2 | use std::thread; 3 | use tokio::task::JoinHandle; 4 | use zbus::{dbus_proxy, zvariant::OwnedObjectPath, Result}; 5 | 6 | #[dbus_proxy( 7 | default_service = "org.freedesktop.login1", 8 | default_path = "/org/freedesktop/login1", 9 | interface = "org.freedesktop.login1.Manager" 10 | )] 11 | trait Manager { 12 | /// PrepareForShutdown signal 13 | #[dbus_proxy(signal)] 14 | fn prepare_for_shutdown(&self, start: bool) -> zbus::Result<()>; 15 | /// PrepareForSleep signal 16 | #[dbus_proxy(signal)] 17 | fn prepare_for_sleep(&self, start: bool) -> zbus::Result<()>; 18 | /// GetSession method 19 | fn get_session(&self, session_id: &str) -> zbus::Result; 20 | } 21 | 22 | #[dbus_proxy( 23 | interface = "org.freedesktop.login1.Session", 24 | default_service = "org.freedesktop.login1", 25 | default_path = "/org/freedesktop/login1/session/auto" 26 | )] 27 | trait Session { 28 | #[dbus_proxy(signal)] 29 | fn unlock(&self) -> zbus::Result<()>; 30 | 31 | #[dbus_proxy(property)] 32 | fn locked_hint(&self) -> Result; 33 | #[dbus_proxy(property)] 34 | fn id(&self) -> zbus::Result; 35 | } 36 | 37 | #[allow(dead_code)] 38 | pub struct PowerMonitor {} 39 | 40 | impl PowerMonitor { 41 | pub fn new() -> Self { 42 | Self {} 43 | } 44 | } 45 | 46 | impl PowerMonitor { 47 | pub fn start_listening(&self) -> std::result::Result<(), &'static str> { 48 | let system_bus_result = zbus::blocking::Connection::system(); 49 | if system_bus_result.is_err() { 50 | return Err("D-Bus not available"); 51 | } 52 | 53 | let system_bus = system_bus_result.unwrap(); 54 | let manager_proxy = ManagerProxyBlocking::new(&system_bus).unwrap(); 55 | 56 | let suspend_monitor_result = get_suspend_monitor(&manager_proxy); 57 | if suspend_monitor_result.is_err() { 58 | return Err("Suspend state not available"); 59 | } 60 | let (mut prepare_for_shutdown, mut prepare_for_sleep) = suspend_monitor_result.unwrap(); 61 | 62 | let lock_monitor_result = get_lock_monitor(system_bus, manager_proxy); 63 | if lock_monitor_result.is_err() { 64 | return Err("Screen lock state not available"); 65 | } 66 | let (mut unlock, mut locked_hint) = lock_monitor_result.unwrap(); 67 | 68 | thread::spawn(move || { 69 | let runtime = tokio::runtime::Runtime::new().unwrap(); 70 | runtime.block_on(async { 71 | let mut handles: Vec> = vec![]; 72 | handles.push(tokio::spawn(async move { 73 | while let Some(signal) = prepare_for_shutdown.next() { 74 | let args = signal.args().unwrap(); 75 | dbg!(args); 76 | } 77 | })); 78 | handles.push(tokio::spawn(async move { 79 | while let Some(signal) = prepare_for_sleep.next() { 80 | let args = signal.args().unwrap(); 81 | dbg!(args); 82 | } 83 | })); 84 | handles.push(tokio::spawn(async move { 85 | while let Some(v) = locked_hint.next() { 86 | let status = v.get().unwrap(); 87 | if status { 88 | let sender = PowerEventChannel::sender(); 89 | let _ = sender.send(PowerState::ScreenLocked); 90 | } 91 | } 92 | })); 93 | handles.push(tokio::spawn(async move { 94 | while unlock.next().is_some() { 95 | let sender = PowerEventChannel::sender(); 96 | let _ = sender.send(PowerState::ScreenUnlocked); 97 | } 98 | })); 99 | 100 | for handle in handles { 101 | let _ = handle.await; 102 | } 103 | }); 104 | }); 105 | 106 | Ok(()) 107 | } 108 | } 109 | 110 | fn get_suspend_monitor<'a>( 111 | manager_proxy: &ManagerProxyBlocking<'a>, 112 | ) -> Result<(PrepareForShutdownIterator<'a>, PrepareForSleepIterator<'a>)> { 113 | // not yet tested 114 | let prepare_for_shutdown = manager_proxy.receive_prepare_for_shutdown().unwrap(); 115 | // not yet tested 116 | let prepare_for_sleep = manager_proxy.receive_prepare_for_sleep().unwrap(); 117 | Ok((prepare_for_shutdown, prepare_for_sleep)) 118 | } 119 | 120 | fn get_lock_monitor( 121 | system_bus: zbus::blocking::Connection, 122 | manager_proxy: ManagerProxyBlocking<'_>, 123 | ) -> Result<( 124 | UnlockIterator<'_>, 125 | zbus::blocking::PropertyIterator<'_, bool>, 126 | )> { 127 | let session_proxy = SessionProxyBlocking::new(&system_bus).unwrap(); 128 | let session_id: String = session_proxy.id().unwrap(); 129 | let session_obj_path: OwnedObjectPath = manager_proxy.get_session(&session_id).unwrap(); 130 | 131 | let login_session_proxy = SessionProxyBlocking::builder(&system_bus) 132 | .path(session_obj_path) 133 | .unwrap() 134 | .build() 135 | .unwrap(); 136 | let unlock = login_session_proxy.receive_unlock().unwrap(); 137 | let locked_hint = login_session_proxy.receive_locked_hint_changed(); 138 | 139 | Ok((unlock, locked_hint)) 140 | } 141 | -------------------------------------------------------------------------------- /src/platform_impl/macos/power_monitor.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Once; 2 | 3 | use crate::monitor::{PowerEventChannel, PowerState}; 4 | use cocoa::{ 5 | base::{id, nil}, 6 | foundation::NSString, 7 | }; 8 | use libc::c_void; 9 | use objc::{class, msg_send, sel, sel_impl}; 10 | use objc::{ 11 | declare::ClassDecl, 12 | runtime::{Class, Object, Sel}, 13 | }; 14 | 15 | struct PowerMonitorClass(*const Class); 16 | unsafe impl Send for PowerMonitorClass {} 17 | unsafe impl Sync for PowerMonitorClass {} 18 | 19 | pub struct PowerMonitor { 20 | monitor: id, 21 | } 22 | 23 | impl PowerMonitor { 24 | pub fn new() -> Self { 25 | unsafe { 26 | let power_monitor_class = get_or_init_power_monitor_class(); 27 | let monitor: id = msg_send![power_monitor_class, alloc]; 28 | let monitor: id = msg_send![monitor, init]; 29 | 30 | Self { monitor } 31 | } 32 | } 33 | 34 | pub fn start_listening(&self) -> Result<(), &'static str> { 35 | unsafe { 36 | let _: id = msg_send![self.monitor, init_monitor]; 37 | } 38 | Ok(()) 39 | } 40 | } 41 | 42 | impl Default for PowerMonitor { 43 | fn default() -> Self { 44 | Self::new() 45 | } 46 | } 47 | 48 | extern "C" fn init_monitor(this: &Object, _sel: Sel) -> id { 49 | unsafe { 50 | let this: id = msg_send![this, init]; 51 | if this != nil { 52 | let notification_center: &Object = 53 | msg_send![class!(NSDistributedNotificationCenter), defaultCenter]; 54 | 55 | let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace]; 56 | let ws_notification_center: &Object = msg_send![workspace, notificationCenter]; 57 | 58 | let () = msg_send![ 59 | notification_center, 60 | addObserver: this 61 | selector: sel!(onScreenLocked:) 62 | name: NSString::alloc(nil).init_str("com.apple.screenIsLocked") 63 | object: nil 64 | ]; 65 | 66 | let () = msg_send![ 67 | notification_center, 68 | addObserver: this 69 | selector: sel!(onScreenUnlocked:) 70 | name: NSString::alloc(nil).init_str("com.apple.screenIsUnlocked") 71 | object: nil 72 | ]; 73 | 74 | let () = msg_send![ 75 | ws_notification_center, 76 | addObserver: this 77 | selector: sel!(onSuspend:) 78 | name: NSString::alloc(nil).init_str("NSWorkspaceWillSleepNotification") 79 | object: nil 80 | ]; 81 | 82 | let () = msg_send![ 83 | ws_notification_center, 84 | addObserver: this 85 | selector: sel!(onResume:) 86 | name: NSString::alloc(nil).init_str("NSWorkspaceDidWakeNotification") 87 | object: nil 88 | ]; 89 | } 90 | this 91 | } 92 | } 93 | 94 | extern "C" fn on_screen_locked(_this: &Object, _sel: Sel, _state: *mut c_void) { 95 | let sender = PowerEventChannel::sender(); 96 | let _ = sender.send(PowerState::ScreenLocked); 97 | } 98 | 99 | extern "C" fn on_screen_unlocked(_this: &Object, _sel: Sel, _state: *mut c_void) { 100 | let sender = PowerEventChannel::sender(); 101 | let _ = sender.send(PowerState::ScreenUnlocked); 102 | } 103 | 104 | extern "C" fn on_suspend(_this: &Object, _sel: Sel, _state: *mut c_void) { 105 | let sender = PowerEventChannel::sender(); 106 | let _ = sender.send(PowerState::Suspend); 107 | } 108 | 109 | extern "C" fn on_resume(_this: &Object, _sel: Sel, _state: *mut c_void) { 110 | let sender = PowerEventChannel::sender(); 111 | let _ = sender.send(PowerState::Resume); 112 | } 113 | 114 | extern "C" fn dealloc(this: &Object, _sel: Sel) { 115 | unsafe { 116 | let notification_center: &Object = 117 | msg_send![class!(NSDistributedNotificationCenter), defaultCenter]; 118 | let () = msg_send![notification_center, removeObserver: this]; 119 | 120 | let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace]; 121 | let ws_notification_center: &Object = msg_send![workspace, notificationCenter]; 122 | let () = msg_send![ws_notification_center, removeObserver: this]; 123 | 124 | let () = msg_send![this, dealloc]; 125 | } 126 | } 127 | 128 | fn get_or_init_power_monitor_class() -> *const Class { 129 | static mut POWER_MONITOR_CLASS: *const Class = 0 as *const Class; 130 | static INIT_POWER_MONITOR_CLASS: Once = Once::new(); 131 | 132 | INIT_POWER_MONITOR_CLASS.call_once(|| unsafe { 133 | let superclass = class!(NSObject); 134 | let mut decl = ClassDecl::new("TaoPowerMonitor", superclass).unwrap(); 135 | 136 | decl.add_method( 137 | sel!(init_monitor), 138 | init_monitor as extern "C" fn(&Object, Sel) -> id, 139 | ); 140 | decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); 141 | decl.add_method( 142 | sel!(onScreenLocked:), 143 | on_screen_locked as extern "C" fn(&Object, Sel, *mut c_void), 144 | ); 145 | decl.add_method( 146 | sel!(onScreenUnlocked:), 147 | on_screen_unlocked as extern "C" fn(&Object, Sel, *mut c_void), 148 | ); 149 | decl.add_method( 150 | sel!(onSuspend:), 151 | on_suspend as extern "C" fn(&Object, Sel, *mut c_void), 152 | ); 153 | decl.add_method( 154 | sel!(onResume:), 155 | on_resume as extern "C" fn(&Object, Sel, *mut c_void), 156 | ); 157 | POWER_MONITOR_CLASS = decl.register(); 158 | }); 159 | 160 | unsafe { POWER_MONITOR_CLASS } 161 | } 162 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------