Skip to main content

wallr_core/ipc/
mod.rs

1use serde::{Deserialize, Serialize};
2use std::path::Path;
3use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
4use tokio::net::{UnixListener, UnixStream};
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7#[serde(tag = "command", rename_all = "snake_case")]
8pub enum IpcCommand {
9    Pause {
10        #[serde(default)]
11        monitor: Option<String>,
12    },
13    Resume {
14        #[serde(default)]
15        monitor: Option<String>,
16    },
17    Reload,
18    Seek {
19        timestamp_ms: u64,
20        #[serde(default)]
21        monitor: Option<String>,
22    },
23    Preview {
24        path: String,
25        effect: Option<crate::animation::Effect>,
26        duration_ms: Option<u32>,
27        #[serde(default)]
28        no_theme: bool,
29        #[serde(default)]
30        theme_override: Option<crate::config::ThemeProvider>,
31        #[serde(default)]
32        monitor: Option<String>,
33        #[serde(default)]
34        scaling_mode: Option<crate::config::ScalingMode>,
35    },
36    Stop,
37    Status,
38    Info {
39        #[serde(default)]
40        monitor: Option<String>,
41    },
42    MonitorList,
43    MonitorCurrent,
44    Blank {
45        #[serde(default)]
46        monitor: Option<String>,
47    },
48    Restore {
49        #[serde(default)]
50        monitor: Option<String>,
51    },
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct IpcResponse {
56    pub success: bool,
57    pub message: Option<String>,
58}
59
60#[derive(Debug, thiserror::Error)]
61pub enum IpcError {
62    #[error("daemon not running: {0}")]
63    DaemonNotRunning(String),
64    #[error("IPC I/O error: {0}")]
65    Io(#[from] std::io::Error),
66    #[error("protocol serialization/deserialization error: {0}")]
67    Protocol(#[from] serde_json::Error),
68}
69
70pub async fn send_ipc_command<P: AsRef<Path>>(
71    socket_path: P,
72    command: IpcCommand,
73) -> Result<IpcResponse, IpcError> {
74    let mut stream = UnixStream::connect(socket_path)
75        .await
76        .map_err(|e| IpcError::DaemonNotRunning(e.to_string()))?;
77
78    let req_data = serde_json::to_vec(&command)?;
79    stream.write_all(&req_data).await?;
80    stream.write_all(b"\n").await?;
81    stream.flush().await?;
82
83    let mut reader = BufReader::new(stream);
84    let mut response_line = String::new();
85    reader.read_line(&mut response_line).await?;
86
87    let response: IpcResponse = serde_json::from_str(&response_line)?;
88    Ok(response)
89}
90
91pub async fn start_ipc_server<P, F, Fut>(socket_path: P, handler: F) -> Result<(), IpcError>
92where
93    P: AsRef<Path>,
94    F: Fn(IpcCommand) -> Fut + Send + Sync + 'static,
95    Fut: std::future::Future<Output = IpcResponse> + Send + 'static,
96{
97    let path = socket_path.as_ref();
98    if path.exists() {
99        let _ = std::fs::remove_file(path);
100    }
101
102    let listener = UnixListener::bind(path)?;
103    let handler = std::sync::Arc::new(handler);
104
105    tokio::spawn(async move {
106        loop {
107            match listener.accept().await {
108                Ok((stream, _)) => {
109                    let handler_clone = handler.clone();
110                    tokio::spawn(async move {
111                        let (reader, mut writer) = tokio::io::split(stream);
112                        let mut reader = BufReader::new(reader);
113                        let mut line = String::new();
114
115                        if let Ok(n) = reader.read_line(&mut line).await
116                            && n > 0
117                            && let Ok(cmd) = serde_json::from_str::<IpcCommand>(&line)
118                        {
119                            let response = handler_clone(cmd).await;
120                            if let Ok(res_data) = serde_json::to_vec(&response) {
121                                let _ = writer.write_all(&res_data).await;
122                                let _ = writer.write_all(b"\n").await;
123                                let _ = writer.flush().await;
124                            }
125                        }
126                    });
127                }
128                Err(e) => {
129                    tracing::error!("IPC accept error: {:?}", e);
130                }
131            }
132        }
133    });
134
135    Ok(())
136}