Name threads, cargo fmt

This commit is contained in:
Kenny Levinsen
2019-08-28 18:06:07 +02:00
parent bbfdb56d70
commit 46a1c9e701
6 changed files with 199 additions and 149 deletions
+67 -41
View File
@@ -8,14 +8,14 @@ use chrono::Local;
use smithay_client_toolkit::keyboard::{keysyms, map_keyboard_auto, Event as KbEvent, KeyState}; use smithay_client_toolkit::keyboard::{keysyms, map_keyboard_auto, Event as KbEvent, KeyState};
use smithay_client_toolkit::utils::DoubleMemPool; use smithay_client_toolkit::utils::DoubleMemPool;
use wayland_client::protocol::{wl_compositor, wl_pointer, wl_shm, wl_surface, wl_output}; use wayland_client::protocol::{wl_compositor, wl_output, wl_pointer, wl_shm, wl_surface};
use wayland_client::{Display, EventQueue, GlobalEvent, GlobalManager, NewProxy}; use wayland_client::{Display, EventQueue, GlobalEvent, GlobalManager, NewProxy};
use wayland_protocols::wlr::unstable::layer_shell::v1::client::{ use wayland_protocols::wlr::unstable::layer_shell::v1::client::{
zwlr_layer_shell_v1, zwlr_layer_surface_v1, zwlr_layer_shell_v1, zwlr_layer_surface_v1,
}; };
use crate::color::Color;
use crate::buffer::Buffer; use crate::buffer::Buffer;
use crate::color::Color;
use crate::cmd::Cmd; use crate::cmd::Cmd;
@@ -46,8 +46,8 @@ struct AppInner {
} }
impl AppInner { impl AppInner {
fn new(tx: Sender<Cmd>, output_mode: OutputMode) -> AppInner{ fn new(tx: Sender<Cmd>, output_mode: OutputMode) -> AppInner {
AppInner{ AppInner {
compositor: None, compositor: None,
surfaces: Vec::new(), surfaces: Vec::new(),
shell_surfaces: Vec::new(), shell_surfaces: Vec::new(),
@@ -67,10 +67,10 @@ impl AppInner {
dimensions: (u32, u32), dimensions: (u32, u32),
configured_surfaces: Arc<Mutex<usize>>, configured_surfaces: Arc<Mutex<usize>>,
tx: Sender<Cmd>, tx: Sender<Cmd>,
output: Option<&wl_output::WlOutput> output: Option<&wl_output::WlOutput>,
) -> ( ) -> (
wl_surface::WlSurface, wl_surface::WlSurface,
zwlr_layer_surface_v1::ZwlrLayerSurfaceV1 zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
) { ) {
let surface = compositor let surface = compositor
.create_surface(NewProxy::implement_dummy) .create_surface(NewProxy::implement_dummy)
@@ -130,16 +130,29 @@ impl AppInner {
if self.shell_surfaces.len() > 0 { if self.shell_surfaces.len() > 0 {
return; return;
} }
let (surface, shell_surface) = AppInner::add_shell_surface(&compositor, &shell, self.dimensions, self.configured_surfaces.clone(), self.draw_tx.clone(), None); let (surface, shell_surface) = AppInner::add_shell_surface(
&compositor,
&shell,
self.dimensions,
self.configured_surfaces.clone(),
self.draw_tx.clone(),
None,
);
self.surfaces = vec![surface]; self.surfaces = vec![surface];
self.shell_surfaces = vec![shell_surface]; self.shell_surfaces = vec![shell_surface];
}
},
OutputMode::All => { OutputMode::All => {
let mut surfaces = Vec::new(); let mut surfaces = Vec::new();
let mut shell_surfaces = Vec::new(); let mut shell_surfaces = Vec::new();
for output in self.outputs.iter() { for output in self.outputs.iter() {
let (surface, shell_surface) = AppInner::add_shell_surface(&compositor, &shell, self.dimensions, self.configured_surfaces.clone(), self.draw_tx.clone(), Some(&output.1)); let (surface, shell_surface) = AppInner::add_shell_surface(
&compositor,
&shell,
self.dimensions,
self.configured_surfaces.clone(),
self.draw_tx.clone(),
Some(&output.1),
);
surfaces.push(surface); surfaces.push(surface);
shell_surfaces.push(shell_surface); shell_surfaces.push(shell_surface);
} }
@@ -162,7 +175,12 @@ impl AppInner {
fn remove_output(&mut self, id: u32) { fn remove_output(&mut self, id: u32) {
let old_output = self.outputs.iter().find(|(output_id, _)| *output_id == id); let old_output = self.outputs.iter().find(|(output_id, _)| *output_id == id);
if let Some(output) = old_output { if let Some(output) = old_output {
let new_outputs = self.outputs.iter().filter(|(output_id, _)| *output_id != id).map(|(x, y)| (x.clone(), y.clone())).collect(); let new_outputs = self
.outputs
.iter()
.filter(|(output_id, _)| *output_id != id)
.map(|(x, y)| (x.clone(), y.clone()))
.collect();
if output.1.as_ref().version() >= 3 { if output.1.as_ref().version() >= 3 {
output.1.release() output.1.release()
} }
@@ -297,7 +315,9 @@ impl App {
} }
pub fn with_modules<F>(&self, f: F) pub fn with_modules<F>(&self, f: F)
where F: Fn(&Module) { where
F: Fn(&Module),
{
for m in self.modules.iter() { for m in self.modules.iter() {
f(m); f(m);
} }
@@ -349,37 +369,38 @@ impl App {
let (display, mut event_queue) = Display::connect_to_env().unwrap(); let (display, mut event_queue) = Display::connect_to_env().unwrap();
let display_wrapper = display let display_wrapper = display
.as_ref() .as_ref()
.make_wrapper(&event_queue.get_token()) .make_wrapper(&event_queue.get_token())
.unwrap() .unwrap()
.into(); .into();
// //
// Set up global manager // Set up global manager
// //
let inner_global = inner.clone(); let inner_global = inner.clone();
let manager = GlobalManager::new_with_cb(&display_wrapper, move |event, registry| match event { let manager =
GlobalEvent::New { GlobalManager::new_with_cb(&display_wrapper, move |event, registry| match event {
id, GlobalEvent::New {
ref interface, id,
version, ref interface,
} => { version,
if let "wl_output" = &interface[..] { } => {
let output = registry.bind(version, id, move |output| { if let "wl_output" = &interface[..] {
output.implement_closure (move |_, _| {}, ()) let output = registry
}).unwrap(); .bind(version, id, move |output| {
inner_global.lock().unwrap().add_output(id, output); output.implement_closure(move |_, _| {}, ())
})
.unwrap();
inner_global.lock().unwrap().add_output(id, output);
}
} }
} GlobalEvent::Removed { id, ref interface } => {
GlobalEvent::Removed { id, ref interface } => { if let "wl_output" = &interface[..] {
if let "wl_output" = &interface[..] { inner_global.lock().unwrap().remove_output(id);
inner_global.lock().unwrap().remove_output(id); }
} }
} });
});
// double sync to retrieve the global list // double sync to retrieve the global list
// and the globals metadata // and the globals metadata
@@ -447,16 +468,18 @@ impl App {
// //
// Prepare shell so that we can create our shell surface // Prepare shell so that we can create our shell surface
// //
inner.lock().unwrap().set_shell(Some(if let Ok(layer) = manager.instantiate_exact( inner.lock().unwrap().set_shell(Some(
1, if let Ok(layer) = manager.instantiate_exact(
|layer: NewProxy<zwlr_layer_shell_v1::ZwlrLayerShellV1>| { 1,
layer.implement_closure(|_, _| {}, ()) |layer: NewProxy<zwlr_layer_shell_v1::ZwlrLayerShellV1>| {
layer.implement_closure(|_, _| {}, ())
},
) {
layer
} else {
panic!("server didn't advertise `zwlr_layer_shell_v1`");
}, },
) { ));
layer
} else {
panic!("server didn't advertise `zwlr_layer_shell_v1`");
}));
// //
// Calculate window dimensions // Calculate window dimensions
@@ -470,7 +493,10 @@ impl App {
} }
// Add padding // Add padding
inner.lock().unwrap().set_dimensions((dimensions.0 + 40, dimensions.1 + 40)); inner
.lock()
.unwrap()
.set_dimensions((dimensions.0 + 40, dimensions.1 + 40));
inner.lock().unwrap().outputs_changed(); inner.lock().unwrap().outputs_changed();
event_queue.sync_roundtrip().unwrap(); event_queue.sync_roundtrip().unwrap();
+45 -34
View File
@@ -1,18 +1,18 @@
use std::io::{Read, Write, BufRead, BufReader};
use std::os::unix::io::AsRawFd;
use std::sync::mpsc::channel;
use std::env; use std::env;
use std::os::unix::net::{UnixStream, UnixListener}; use std::io::{BufRead, BufReader, Read, Write};
use std::os::unix::io::AsRawFd;
use std::os::unix::net::{UnixListener, UnixStream};
use std::sync::mpsc::channel;
use nix::poll::{poll, PollFd, PollFlags}; use nix::poll::{poll, PollFd, PollFlags};
use os_pipe::pipe; use os_pipe::pipe;
mod app;
mod buffer; mod buffer;
mod cmd;
mod color; mod color;
mod draw; mod draw;
mod modules; mod modules;
mod app;
mod cmd;
use app::{App, OutputMode}; use app::{App, OutputMode};
use cmd::Cmd; use cmd::Cmd;
@@ -87,38 +87,49 @@ fn main() {
app.wipe(); app.wipe();
let worker_queue = app.cmd_queue(); let worker_queue = app.cmd_queue();
std::thread::spawn(move || loop { let _ = std::thread::Builder::new()
let cmd = rx_draw.recv().unwrap(); .name("cmd_proxy".to_string())
worker_queue.lock().unwrap().push_back(cmd); .spawn(move || loop {
tx_pipe.write_all(&[0x1]).unwrap(); let cmd = rx_draw.recv().unwrap();
}); worker_queue.lock().unwrap().push_back(cmd);
tx_pipe.write_all(&[0x1]).unwrap();
});
let ipc_queue = app.cmd_queue(); let ipc_queue = app.cmd_queue();
std::thread::spawn(move || loop { let _ = std::thread::Builder::new()
for stream in listener.incoming() { .name("ipc_server".to_string())
match stream { .spawn(move || loop {
Ok(stream) => { for stream in listener.incoming() {
let client_queue = ipc_queue.clone(); match stream {
let mut client_pipe = ipc_pipe.try_clone().unwrap(); Ok(stream) => {
std::thread::spawn(move || { let client_queue = ipc_queue.clone();
let r = BufReader::new(stream); let mut client_pipe = ipc_pipe.try_clone().unwrap();
for line in r.lines() { let _ = std::thread::Builder::new()
match line { .name("ipc_client".to_string())
Ok(v) => match v.as_str() { .spawn(move || {
"kill" => client_queue.lock().unwrap().push_back(Cmd::Exit), let r = BufReader::new(stream);
"toggle_visible" => client_queue.lock().unwrap().push_back(Cmd::ToggleVisible), for line in r.lines() {
v => eprintln!("unknown command: {}", v), match line {
}, Ok(v) => match v.as_str() {
Err(_) => return, "kill" => {
} client_queue.lock().unwrap().push_back(Cmd::Exit)
client_pipe.write_all(&[0x1]).unwrap(); }
} "toggle_visible" => client_queue
}); .lock()
.unwrap()
.push_back(Cmd::ToggleVisible),
v => eprintln!("unknown command: {}", v),
},
Err(_) => return,
}
client_pipe.write_all(&[0x1]).unwrap();
}
});
}
Err(_) => break,
} }
Err(_) => break,
} }
} });
});
let mut fds = [ let mut fds = [
PollFd::new(app.event_queue().get_connection_fd(), PollFlags::POLLIN), PollFd::new(app.event_queue().get_connection_fd(), PollFlags::POLLIN),
+45 -43
View File
@@ -1,8 +1,8 @@
use crate::buffer::Buffer; use crate::buffer::Buffer;
use crate::cmd::Cmd;
use crate::color::Color; use crate::color::Color;
use crate::draw::{draw_bar, draw_box, Font, ROBOTO_REGULAR}; use crate::draw::{draw_bar, draw_box, Font, ROBOTO_REGULAR};
use crate::modules::module::{Input, ModuleImpl}; use crate::modules::module::{Input, ModuleImpl};
use crate::cmd::Cmd;
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -134,52 +134,54 @@ impl UpowerBattery {
let d = UpowerBattery::from_device("BAT0")?; let d = UpowerBattery::from_device("BAT0")?;
let path = d.device_path.clone(); let path = d.device_path.clone();
let inner = d.inner.clone(); let inner = d.inner.clone();
thread::spawn(move || { let _ = thread::Builder::new()
let con = dbus::Connection::get_private(dbus::BusType::System) .name("battery_monitor".to_string())
.expect("Failed to establish D-Bus connection."); .spawn(move || {
let rule = format!( let con = dbus::Connection::get_private(dbus::BusType::System)
"type='signal',\ .expect("Failed to establish D-Bus connection.");
path='{}',\ let rule = format!(
interface='org.freedesktop.DBus.Properties',\ "type='signal',\
member='PropertiesChanged'", path='{}',\
path interface='org.freedesktop.DBus.Properties',\
); member='PropertiesChanged'",
path
);
// First we're going to get an (irrelevant) NameAcquired event. // First we're going to get an (irrelevant) NameAcquired event.
con.incoming(10_000).next(); con.incoming(10_000).next();
con.add_match(&rule) con.add_match(&rule)
.expect("Failed to add D-Bus match rule."); .expect("Failed to add D-Bus match rule.");
loop { loop {
if con.incoming(10_000).next().is_some() { if con.incoming(10_000).next().is_some() {
let capacity = get_upower_property(&con, &path, "Percentage") let capacity = get_upower_property(&con, &path, "Percentage")
.unwrap() .unwrap()
.get1::<dbus::arg::Variant<f64>>() .get1::<dbus::arg::Variant<f64>>()
.unwrap() .unwrap()
.0; .0;
let state = match get_upower_property(&con, &path, "State") let state = match get_upower_property(&con, &path, "State")
.unwrap() .unwrap()
.get1::<dbus::arg::Variant<u32>>() .get1::<dbus::arg::Variant<u32>>()
.unwrap() .unwrap()
.0 .0
{ {
1 => UpowerBatteryState::Charging, 1 => UpowerBatteryState::Charging,
2 => UpowerBatteryState::Discharging, 2 => UpowerBatteryState::Discharging,
3 => UpowerBatteryState::Empty, 3 => UpowerBatteryState::Empty,
4 => UpowerBatteryState::Full, 4 => UpowerBatteryState::Full,
5 => UpowerBatteryState::NotCharging, 5 => UpowerBatteryState::NotCharging,
6 => UpowerBatteryState::Discharging, 6 => UpowerBatteryState::Discharging,
_ => UpowerBatteryState::Unknown, _ => UpowerBatteryState::Unknown,
}; };
let mut inner = inner.lock().unwrap(); let mut inner = inner.lock().unwrap();
inner.state = state; inner.state = state;
inner.capacity = capacity; inner.capacity = capacity;
inner.dirty = true; inner.dirty = true;
listener.send(Cmd::Draw).unwrap(); listener.send(Cmd::Draw).unwrap();
}
} }
} });
});
Ok(d) Ok(d)
} }
+14 -12
View File
@@ -1,8 +1,8 @@
use crate::buffer::Buffer; use crate::buffer::Buffer;
use crate::cmd::Cmd;
use crate::color::Color; use crate::color::Color;
use crate::draw::{Font, ROBOTO_REGULAR}; use crate::draw::{Font, ROBOTO_REGULAR};
use crate::modules::module::{Input, ModuleImpl}; use crate::modules::module::{Input, ModuleImpl};
use crate::cmd::Cmd;
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
@@ -17,19 +17,21 @@ pub struct Clock {
impl Clock { impl Clock {
pub fn new(ch: Sender<Cmd>) -> Clock { pub fn new(ch: Sender<Cmd>) -> Clock {
std::thread::spawn(move || loop { let _ = std::thread::Builder::new()
let n = Local::now(); .name("clock_ticker".to_string())
let target = (n + Duration::seconds(60)) .spawn(move || loop {
.with_second(0) let n = Local::now();
.unwrap() let target = (n + Duration::seconds(60))
.with_nanosecond(0) .with_second(0)
.unwrap(); .unwrap()
.with_nanosecond(0)
.unwrap();
let d = target - n; let d = target - n;
std::thread::sleep(d.to_std().unwrap()); std::thread::sleep(d.to_std().unwrap());
ch.send(Cmd::Draw).unwrap(); ch.send(Cmd::Draw).unwrap();
}); });
let mut date_cache = Font::new(&ROBOTO_REGULAR, 64.0); let mut date_cache = Font::new(&ROBOTO_REGULAR, 64.0);
date_cache date_cache
+26 -17
View File
@@ -1,13 +1,13 @@
use crate::buffer::Buffer; use crate::buffer::Buffer;
use crate::cmd::Cmd;
use crate::color::Color; use crate::color::Color;
use crate::draw::{Font, ROBOTO_REGULAR}; use crate::draw::{Font, ROBOTO_REGULAR};
use crate::modules::module::{Input, ModuleImpl}; use crate::modules::module::{Input, ModuleImpl};
use crate::cmd::Cmd;
use std::sync::mpsc::Sender;
use std::cell::RefCell; use std::cell::RefCell;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::io::Read; use std::io::Read;
use std::sync::mpsc::Sender;
use atty::Stream; use atty::Stream;
use chrono::{DateTime, Local}; use chrono::{DateTime, Local};
@@ -133,16 +133,21 @@ impl Launcher {
) -> Result<Vec<(i32, i32, i32, i32)>, ::std::io::Error> { ) -> Result<Vec<(i32, i32, i32, i32)>, ::std::io::Error> {
buf.memset(bg); buf.memset(bg);
let x_off = self.font.borrow_mut().auto_draw_text( let x_off = self
&mut buf.subdimensions((0, 0, 1232, 32))?, .font
bg, .borrow_mut()
&Color::new(1.0, 1.0, 0.0, 1.0), .auto_draw_text(
"=", &mut buf.subdimensions((0, 0, 1232, 32))?,
)?.0 + 8; bg,
&Color::new(1.0, 1.0, 0.0, 1.0),
"=",
)?
.0
+ 8;
let x_off = if self.input.len() > 0 { let x_off = if self.input.len() > 0 {
let dim = self.font.borrow_mut().auto_draw_text( let dim = self.font.borrow_mut().auto_draw_text(
&mut buf.subdimensions((x_off, 0, 1232-x_off, 32))?, &mut buf.subdimensions((x_off, 0, 1232 - x_off, 32))?,
bg, bg,
&Color::new(1.0, 1.0, 1.0, 1.0), &Color::new(1.0, 1.0, 1.0, 1.0),
&self.input[1..], &self.input[1..],
@@ -172,17 +177,21 @@ impl Launcher {
) -> Result<Vec<(i32, i32, i32, i32)>, ::std::io::Error> { ) -> Result<Vec<(i32, i32, i32, i32)>, ::std::io::Error> {
buf.memset(bg); buf.memset(bg);
let x_off = self
let x_off = self.font.borrow_mut().auto_draw_text( .font
&mut buf.subdimensions((0, 0, 1232, 32))?, .borrow_mut()
bg, .auto_draw_text(
&Color::new(1.0, 1.0, 0.0, 1.0), &mut buf.subdimensions((0, 0, 1232, 32))?,
"!", bg,
)?.0 + 8; &Color::new(1.0, 1.0, 0.0, 1.0),
"!",
)?
.0
+ 8;
if self.input.len() > 0 { if self.input.len() > 0 {
self.font.borrow_mut().auto_draw_text( self.font.borrow_mut().auto_draw_text(
&mut buf.subdimensions((x_off, 0, 1232-x_off, 32))?, &mut buf.subdimensions((x_off, 0, 1232 - x_off, 32))?,
bg, bg,
&Color::new(1.0, 1.0, 1.0, 1.0), &Color::new(1.0, 1.0, 1.0, 1.0),
&self.input[1..], &self.input[1..],
+2 -2
View File
@@ -1,7 +1,7 @@
pub mod module;
pub mod backlight; pub mod backlight;
pub mod battery; pub mod battery;
pub mod calendar; pub mod calendar;
pub mod clock; pub mod clock;
pub mod launcher; pub mod launcher;
pub mod sound; pub mod module;
pub mod sound;