use nanoserde::{DeBin, SerBin}; use std::{io::Read, path::Path, sync::mpsc}; pub const DEFAULT_FIFO: &str = "/tmp/deerwm"; #[derive(PartialEq, Clone, Debug, DeBin, SerBin)] pub enum Command { Nothing, Quit, } /// Starts a thread that recieves commands from the fifo specified. pub fn command_reciever(fifo_path: &str) -> mpsc::Receiver { let (tx, rx) = mpsc::channel(); // Open FIFO to listen for commands on if Path::new(fifo_path).exists() { std::fs::remove_file(fifo_path).unwrap(); } unix_named_pipe::create(fifo_path, None).expect("failed to create fifo"); let mut cmd_fifo = unix_named_pipe::open_read(fifo_path).expect("failed to open fifo for reading"); // Spawn the recieving thread std::thread::spawn(move || { let mut cmd_buf = [0; 256]; let mut quit = false; while !quit { // Read data from fifo if let Ok(n) = cmd_fifo.read(&mut cmd_buf) { // Do not bother trying to parse if there is no data if n > 0 { // Try to parse bytes into `Command` // TODO: try to handle the case of more than one command being in the buffer??? if let Ok(cmd) = Command::de_bin(&mut 0, &cmd_buf[..n]) { println!("Received: {:?}", cmd); if cmd == Command::Quit { quit = true; } tx.send(cmd).unwrap(); } } } } }); rx }