From 62829525d4a3586cf7f824a075f1c4c794381f0b Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Tue, 7 Apr 2020 08:03:07 -0400 Subject: [PATCH] updates every 250 milliseconds --- src/main.rs | 59 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 43 insertions(+), 16 deletions(-) diff --git a/src/main.rs b/src/main.rs index 441b9eb..f81d1aa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,14 @@ mod xsetroot; use chrono::prelude::*; -use std::fmt; -use std::io::prelude::*; -use std::io::BufReader; -use std::sync::{Arc, Mutex}; -use std::thread; -use std::os::unix::net::{UnixStream, UnixListener}; +use std::{ + fmt, + io::{prelude::*, BufReader}, + net::Shutdown, + os::unix::net::{UnixListener, UnixStream}, + sync::{Arc, Mutex}, + thread, time, +}; use xsetroot::XSetRoot; type MTState = Arc>; @@ -18,25 +20,46 @@ fn handle_client(stream: UnixStream, st: MTState) { let _ = write!(&stream, "OK"); let mut data = st.lock().unwrap(); - data.msg = msg; - data.show(); + data.msg = msg.trim().to_string(); + stream.shutdown(Shutdown::Both).expect("socket to close"); } -fn main() -> std::io::Result::<()> { - let mut st: State = State::init(); - st.msg = "coi rodo .ui.".to_string(); +const UPDATE_FREQUENCY: u64 = 250; + +fn update_every_so_often(st: MTState) { + loop { + let so_often = time::Duration::from_millis(UPDATE_FREQUENCY); + thread::sleep(so_often); + + { + let data = st.lock().unwrap(); + data.show(); + } + } +} + +fn main() -> std::io::Result<()> { + let st: State = State::init(); st.show(); let mtst = Arc::new(Mutex::new(st)); + // start update thread + { + let mtst = mtst.clone(); + thread::spawn(move || update_every_so_often(mtst)); + } + + let _ = std::fs::remove_file("/home/cadey/tmp/cabytcini.sock")?; let listener = UnixListener::bind("/home/cadey/tmp/cabytcini.sock")?; for stream in listener.incoming() { match stream { Ok(stream) => { - thread::spawn(|| handle_client(stream, mtst.clone())); - }, + let mtst = mtst.clone(); + thread::spawn(move || handle_client(stream, mtst)); + } Err(err) => { break; - }, + } } } @@ -61,8 +84,12 @@ impl State { } fn show(&self) { - let now = Local::now(); + let now = Local::now().format("%H:%M M%m %-d %a"); let xsr = XSetRoot::init(); - xsr.render(format!("{} | {}", self, now.format("%H:%M M%m %-d %a"))); + if self.msg == "" { + xsr.render(format!("{}", now)) + } else { + xsr.render(format!("{} | {}", self.msg, now)); + } } }