From 25eaa19998f750ecd07f56b48380368141caa02c Mon Sep 17 00:00:00 2001 From: Tassilo Horn Date: Sun, 17 Jan 2021 10:36:39 +0100 Subject: [PATCH] Forgot to add demon.rs; Make event recording work --- src/bin/swayrd.rs | 2 +- src/demon.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++ src/ipc.rs | 3 ++- 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 src/demon.rs diff --git a/src/bin/swayrd.rs b/src/bin/swayrd.rs index ad15e32..a35cfc9 100644 --- a/src/bin/swayrd.rs +++ b/src/bin/swayrd.rs @@ -14,7 +14,7 @@ fn main() { let win_props_for_ev_handler = win_props.clone(); let subscriber_handle = - thread::spawn(|| demon::monitor_window_events(win_props_for_ev_handler)); + thread::spawn(move || demon::monitor_window_events(win_props_for_ev_handler)); let subscriber_result = subscriber_handle.join(); match subscriber_result { diff --git a/src/demon.rs b/src/demon.rs new file mode 100644 index 0000000..d1084dc --- /dev/null +++ b/src/demon.rs @@ -0,0 +1,59 @@ +use crate::ipc; +use serde_json::Deserializer; +use std::collections::HashMap; +use std::process as proc; +use std::sync::Arc; +use std::sync::RwLock; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub fn monitor_window_events(win_props: Arc>>) { + let child = proc::Command::new("swaymsg") + .arg("--monitor") + .arg("--raw") + .arg("-t") + .arg("subscribe") + .arg("[\"window\"]") + .stdout(proc::Stdio::piped()) + .spawn() + .expect("Failed to subscribe to window events"); + let stdout: std::process::ChildStdout = child.stdout.unwrap(); + let stream = Deserializer::from_reader(stdout).into_iter::(); + for res in stream { + match res { + Ok(win_ev) => handle_window_event(win_ev, win_props.clone()), + Err(err) => panic!("{:?}", err), + } + } +} + +fn handle_window_event( + ev: ipc::WindowEvent, + win_props: Arc>>, +) { + match ev.change { + ipc::WindowEventType::Focus => { + let mut write_lock = win_props.write().unwrap(); + if let Some(mut wp) = write_lock.get_mut(&ev.container.id) { + wp.last_focus_time = get_epoch_time_as_millis(); + } else { + write_lock.insert( + ev.container.id, + ipc::WindowProps { + last_focus_time: get_epoch_time_as_millis(), + }, + ); + } + } + ipc::WindowEventType::Close => { + win_props.write().unwrap().remove(&ev.container.id); + } + _ => (), + } +} + +fn get_epoch_time_as_millis() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("Couldn't get epoch time!") + .as_millis() +} diff --git a/src/ipc.rs b/src/ipc.rs index 567f3a6..dac246e 100644 --- a/src/ipc.rs +++ b/src/ipc.rs @@ -215,7 +215,8 @@ pub struct WindowEvent { pub container: Node, } +#[derive(Debug)] pub struct WindowProps { /// Milliseconds since UNIX epoch. - last_focus_time: u128, + pub last_focus_time: u128, }