tauri_plugin_nosleep/
lib.rs1use nosleep::{NoSleep, NoSleepType};
2use serde::{ser::Serializer, Serialize};
3use std::sync::Mutex;
4use tauri::{
5 command,
6 plugin::{Builder, TauriPlugin},
7 AppHandle, Manager, Runtime, State, Window,
8};
9
10type Result<T> = std::result::Result<T, Error>;
11
12#[derive(Debug, thiserror::Error)]
13pub enum Error {
14 #[error(transparent)]
15 ScreenLockError(#[from] nosleep::Error),
16}
17
18impl Serialize for Error {
19 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
20 where
21 S: Serializer,
22 {
23 serializer.serialize_str(self.to_string().as_ref())
24 }
25}
26
27pub struct NoSleepState {
28 no_sleep: Mutex<NoSleep>,
29}
30
31#[command]
32async fn block<R: Runtime>(
33 _app: AppHandle<R>,
34 _window: Window<R>,
35 state: State<'_, NoSleepState>,
36 no_sleep_type: NoSleepType,
37) -> Result<()> {
38 state.no_sleep.lock().unwrap().start(no_sleep_type)?;
39 Ok(())
40}
41
42#[command]
43async fn unblock<R: Runtime>(
44 _app: AppHandle<R>,
45 _window: Window<R>,
46 state: State<'_, NoSleepState>,
47) -> Result<()> {
48 state.no_sleep.lock().unwrap().stop()?;
49 Ok(())
50}
51
52pub fn init<R: Runtime>() -> TauriPlugin<R> {
54 Builder::new("nosleep")
55 .invoke_handler(tauri::generate_handler![block, unblock])
56 .setup(|app| {
57 app.manage(NoSleepState {
58 no_sleep: Mutex::new(NoSleep::new()?),
59 });
60 Ok(())
61 })
62 .build()
63}