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