From 94cb31baa5aff6914423396bb15beb576d14c1c2 Mon Sep 17 00:00:00 2001 From: Tassilo Horn Date: Sun, 17 Jan 2021 11:22:38 +0100 Subject: [PATCH] Open Unix socket for handling clients --- src/bin/swayrd.rs | 2 ++ src/demon.rs | 36 ++++++++++++++++++++++++++++++++++++ src/ipc.rs | 4 ++-- 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/bin/swayrd.rs b/src/bin/swayrd.rs index a35cfc9..ec21f89 100644 --- a/src/bin/swayrd.rs +++ b/src/bin/swayrd.rs @@ -16,6 +16,8 @@ fn main() { let subscriber_handle = thread::spawn(move || demon::monitor_window_events(win_props_for_ev_handler)); + demon::serve_client_requests(win_props); + let subscriber_result = subscriber_handle.join(); match subscriber_result { Ok(()) => println!("Subscriber thread shut down cleanly."), diff --git a/src/demon.rs b/src/demon.rs index d1084dc..dd7c857 100644 --- a/src/demon.rs +++ b/src/demon.rs @@ -1,9 +1,12 @@ use crate::ipc; use serde_json::Deserializer; use std::collections::HashMap; +use std::io::Write; +use std::os::unix::net::{UnixListener, UnixStream}; use std::process as proc; use std::sync::Arc; use std::sync::RwLock; +use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; pub fn monitor_window_events(win_props: Arc>>) { @@ -57,3 +60,36 @@ fn get_epoch_time_as_millis() -> u128 { .expect("Couldn't get epoch time!") .as_millis() } + +pub fn serve_client_requests( + win_props: Arc>>, +) -> std::io::Result<()> { + // FIXME: Use sensible path. + let listener = UnixListener::bind("/home/horn/tmp/SWAYR_SOCKET")?; + + for stream in listener.incoming() { + match stream { + Ok(stream) => { + /* connection succeeded */ + let wp_clone = win_props.clone(); + thread::spawn(move || handle_client_request(stream, wp_clone)); + } + Err(err) => { + /* connection failed */ + eprintln!("Could not accept client request: {:?}", err); + break; + } + } + } + Ok(()) +} + +fn handle_client_request( + mut stream: UnixStream, + win_props: Arc>>, +) { + let json = serde_json::to_string(&*win_props.read().unwrap()).unwrap(); + if let Err(err) = stream.write_all(json.as_bytes()) { + eprintln!("Error writing to client: {:?}", err); + } +} diff --git a/src/ipc.rs b/src/ipc.rs index dac246e..fad30e3 100644 --- a/src/ipc.rs +++ b/src/ipc.rs @@ -1,7 +1,7 @@ extern crate serde; extern crate serde_json; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::process as proc; @@ -215,7 +215,7 @@ pub struct WindowEvent { pub container: Node, } -#[derive(Debug)] +#[derive(Debug, Deserialize, Serialize)] pub struct WindowProps { /// Milliseconds since UNIX epoch. pub last_focus_time: u128,