Reduce cargo clippy warnings

This commit is contained in:
Kenny Levinsen
2020-04-22 01:31:22 +02:00
parent 300711affe
commit 319bcdd355
17 changed files with 168 additions and 188 deletions
+39 -42
View File
@@ -1,4 +1,5 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -50,9 +51,9 @@ impl AppInner {
outputs: Vec::new(), outputs: Vec::new(),
shell: None, shell: None,
draw_tx: tx, draw_tx: tx,
output_mode: output_mode, output_mode,
visible: true, visible: true,
scale: scale, scale,
} }
} }
@@ -71,7 +72,7 @@ impl AppInner {
.create_surface(NewProxy::implement_dummy) .create_surface(NewProxy::implement_dummy)
.unwrap(); .unwrap();
let this_is_stupid = Arc::new(Mutex::new(false)); let this_is_stupid = AtomicBool::new(false);
let shell_surface = shell let shell_surface = shell
.get_layer_surface( .get_layer_surface(
@@ -83,9 +84,7 @@ impl AppInner {
layer.implement_closure( layer.implement_closure(
move |evt, layer| match evt { move |evt, layer| match evt {
zwlr_layer_surface_v1::Event::Configure { serial, .. } => { zwlr_layer_surface_v1::Event::Configure { serial, .. } => {
let mut x = this_is_stupid.lock().unwrap(); if !this_is_stupid.compare_and_swap(false, true, Ordering::SeqCst) {
if !*x {
*x = true;
*(configured_surfaces.lock().unwrap()) += 1; *(configured_surfaces.lock().unwrap()) += 1;
layer.ack_configure(serial); layer.ack_configure(serial);
tx.send(Cmd::ForceDraw).unwrap(); tx.send(Cmd::ForceDraw).unwrap();
@@ -132,7 +131,7 @@ impl AppInner {
match self.output_mode { match self.output_mode {
OutputMode::Active => { OutputMode::Active => {
if self.shell_surfaces.len() > 0 { if !self.shell_surfaces.is_empty() {
return; return;
} }
@@ -181,7 +180,7 @@ impl AppInner {
.outputs .outputs
.iter() .iter()
.filter(|(output_id, _)| *output_id != id) .filter(|(output_id, _)| *output_id != id)
.map(|(x, y)| (x.clone(), y.clone())) .map(|(x, y)| (*x, y.clone()))
.collect(); .collect();
if output.1.as_ref().version() >= 3 { if output.1.as_ref().version() >= 3 {
output.1.release() output.1.release()
@@ -224,7 +223,7 @@ impl App {
if !inner.visible if !inner.visible
|| inner.shell_surfaces.len() != *inner.configured_surfaces.lock().unwrap() || inner.shell_surfaces.len() != *inner.configured_surfaces.lock().unwrap()
|| inner.surfaces.len() == 0 || inner.surfaces.is_empty()
{ {
// Not ready yet // Not ready yet
return Ok(()); return Ok(());
@@ -269,7 +268,7 @@ impl App {
&mut DrawContext { &mut DrawContext {
buf: &mut buf, buf: &mut buf,
bg: &self.bg, bg: &self.bg,
time: &time, time,
force, force,
}, },
(0, 0), (0, 0),
@@ -277,7 +276,7 @@ impl App {
mmap.flush().unwrap(); mmap.flush().unwrap();
if !force && !report.full_damage && report.damage.len() == 0 { if !force && !report.full_damage && report.damage.is_empty() {
// Nothing to do // Nothing to do
self.pools.never_mind(); self.pools.never_mind();
return Ok(()); return Ok(());
@@ -352,7 +351,7 @@ impl App {
} }
pub fn new(tx: Sender<Cmd>, output_mode: OutputMode, bg: Color, scale: u32) -> App { pub fn new(tx: Sender<Cmd>, output_mode: OutputMode, bg: Color, scale: u32) -> App {
let inner = Arc::new(Mutex::new(AppInner::new(tx.clone(), output_mode, scale))); let inner = Arc::new(Mutex::new(AppInner::new(tx, output_mode, scale)));
// //
// Set up modules // Set up modules
@@ -365,8 +364,7 @@ impl App {
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();
// //
// Set up global manager // Set up global manager
@@ -409,13 +407,12 @@ impl App {
// wl_shm // wl_shm
let shm_formats = Arc::new(Mutex::new(Vec::new())); let shm_formats = Arc::new(Mutex::new(Vec::new()));
let shm_formats2 = shm_formats.clone();
let shm = manager let shm = manager
.instantiate_range(1, 1, |shm| { .instantiate_range(1, 1, |shm| {
shm.implement_closure( shm.implement_closure(
move |evt, _| { move |evt, _| {
if let wl_shm::Event::Format { format } = evt { if let wl_shm::Event::Format { format } = evt {
shm_formats2.lock().unwrap().push(format); shm_formats.lock().unwrap().push(format);
} }
}, },
(), (),
@@ -450,21 +447,22 @@ impl App {
utf8, utf8,
state, state,
.. ..
} => match state { } => {
KeyState::Pressed => match keysym { if let KeyState::Pressed = state {
keysyms::XKB_KEY_Escape => kbd_clone.lock().unwrap().push_back(Cmd::Exit), match keysym {
keysyms::XKB_KEY_c if modifiers_state.lock().unwrap().ctrl => { keysyms::XKB_KEY_Escape => kbd_clone.lock().unwrap().push_back(Cmd::Exit),
kbd_clone.lock().unwrap().push_back(Cmd::Exit) keysyms::XKB_KEY_c if modifiers_state.lock().unwrap().ctrl => {
kbd_clone.lock().unwrap().push_back(Cmd::Exit)
}
v => kbd_clone.lock().unwrap().push_back(Cmd::Keyboard {
key: v,
key_state: state,
modifiers_state: *modifiers_state.lock().unwrap(),
interpreted: utf8,
}),
} }
v => kbd_clone.lock().unwrap().push_back(Cmd::Keyboard { }
key: v, }
key_state: state,
modifiers_state: modifiers_state.lock().unwrap().clone(),
interpreted: utf8,
}),
},
_ => (),
},
KbEvent::Modifiers { modifiers } => *modifiers_state.lock().unwrap() = modifiers, KbEvent::Modifiers { modifiers } => *modifiers_state.lock().unwrap() = modifiers,
_ => (), _ => (),
}) })
@@ -522,18 +520,17 @@ impl App {
vert_scroll += value; vert_scroll += value;
} }
} }
wl_pointer::Event::Button { button, state, .. } => match state { wl_pointer::Event::Button { button, state, .. } => {
wl_pointer::ButtonState::Released => { if let wl_pointer::ButtonState::Released = state {
btn = button; btn = button;
btn_clicked = true; btn_clicked = true;
} }
_ => {} }
},
wl_pointer::Event::Frame => { wl_pointer::Event::Frame => {
if vert_scroll != 0.0 || horiz_scroll != 0.0 { if vert_scroll != 0.0 || horiz_scroll != 0.0 {
pointer_clone.lock().unwrap().push_back(Cmd::MouseScroll { pointer_clone.lock().unwrap().push_back(Cmd::MouseScroll {
scroll: (horiz_scroll, vert_scroll), scroll: (horiz_scroll, vert_scroll),
pos: pos, pos,
}); });
vert_scroll = 0.0; vert_scroll = 0.0;
horiz_scroll = 0.0; horiz_scroll = 0.0;
@@ -542,7 +539,7 @@ impl App {
pointer_clone pointer_clone
.lock() .lock()
.unwrap() .unwrap()
.push_back(Cmd::MouseClick { btn: btn, pos: pos }); .push_back(Cmd::MouseClick { btn, pos });
btn_clicked = false; btn_clicked = false;
} }
} }
@@ -556,13 +553,13 @@ impl App {
display.flush().unwrap(); display.flush().unwrap();
App { App {
display: display, display,
event_queue: event_queue, event_queue,
cmd_queue: cmd_queue, cmd_queue,
pools: pools, pools,
widget: None, widget: None,
bg: bg, bg,
inner: inner, inner,
last_damage: None, last_damage: None,
last_dim: (0, 0), last_dim: (0, 0),
} }
+2 -2
View File
@@ -11,8 +11,8 @@ pub struct Buffer<'a> {
impl<'a> Buffer<'a> { impl<'a> Buffer<'a> {
pub fn new(buf: &'a mut MmapMut, dimensions: (u32, u32)) -> Buffer { pub fn new(buf: &'a mut MmapMut, dimensions: (u32, u32)) -> Buffer {
Buffer { Buffer {
buf: buf, buf,
dimensions: dimensions, dimensions,
subdimensions: None, subdimensions: None,
} }
} }
+27 -27
View File
@@ -19,8 +19,8 @@ pub enum Widget {
height: u32, height: u32,
widget: Box<Widget>, widget: Box<Widget>,
}, },
HorizontalLayout(Vec<Box<Widget>>), HorizontalLayout(Vec<Widget>),
VerticalLayout(Vec<Box<Widget>>), VerticalLayout(Vec<Widget>),
Clock { Clock {
font_size: f32, font_size: f32,
}, },
@@ -66,11 +66,11 @@ pub enum Widget {
impl Widget { impl Widget {
pub fn construct( pub fn construct(
self, self,
time: &NaiveDateTime, time: NaiveDateTime,
tx: Sender<Cmd>, tx: Sender<Cmd>,
) -> Option<Box<dyn widget::Widget + Send>> { ) -> Option<Box<dyn widget::Widget + Send>> {
match self { match self {
Widget::Margin { margins, widget } => match widget.construct(time, tx.clone()) { Widget::Margin { margins, widget } => match widget.construct(time, tx) {
Some(w) => Some(widget::Margin::new(margins, w)), Some(w) => Some(widget::Margin::new(margins, w)),
None => None, None => None,
}, },
@@ -78,7 +78,7 @@ impl Widget {
width, width,
height, height,
widget, widget,
} => match widget.construct(time, tx.clone()) { } => match widget.construct(time, tx) {
Some(w) => Some(widget::Fixed::new((width, height), w)), Some(w) => Some(widget::Fixed::new((width, height), w)),
None => None, None => None,
}, },
@@ -113,17 +113,17 @@ impl Widget {
} => Some(widgets::launcher::Launcher::new( } => Some(widgets::launcher::Launcher::new(
font_size, font_size,
length, length,
tx.clone(), tx,
app_opener, app_opener,
term_opener, term_opener,
if url_opener.len() == 0 { if url_opener.is_empty() {
"xdg_open ".to_string() "xdg_open ".to_string()
} else { } else {
url_opener url_opener
}, },
)), )),
Widget::Battery { font_size, length } => { Widget::Battery { font_size, length } => {
match widgets::battery::UpowerBattery::new(font_size, length, tx.clone()) { match widgets::battery::UpowerBattery::new(font_size, length, tx) {
Ok(w) => Some(w), Ok(w) => Some(w),
Err(_) => None, Err(_) => None,
} }
@@ -145,7 +145,7 @@ impl Widget {
} }
#[cfg(feature = "pulseaudio-widget")] #[cfg(feature = "pulseaudio-widget")]
Widget::PulseAudio { font_size, length } => { Widget::PulseAudio { font_size, length } => {
match widgets::audio::PulseAudio::new(font_size, length, tx.clone()) { match widgets::audio::PulseAudio::new(font_size, length, tx) {
Ok(w) => Some(w), Ok(w) => Some(w),
Err(_) => None, Err(_) => None,
} }
@@ -189,51 +189,51 @@ impl Default for Config {
widget: Widget::Margin { widget: Widget::Margin {
margins: (20, 20, 20, 20), margins: (20, 20, 20, 20),
widget: Box::new(Widget::VerticalLayout(vec![ widget: Box::new(Widget::VerticalLayout(vec![
Box::new(Widget::HorizontalLayout(vec![ Widget::HorizontalLayout(vec![
Box::new(Widget::Margin { Widget::Margin {
margins: (0, 88, 0, 32), margins: (0, 88, 0, 32),
widget: Box::new(Widget::VerticalLayout(vec![ widget: Box::new(Widget::VerticalLayout(vec![
Box::new(Widget::Date { font_size: 64.0 }), Widget::Date { font_size: 64.0 },
Box::new(Widget::Clock { font_size: 256.0 }), Widget::Clock { font_size: 256.0 },
])), ])),
}), },
Box::new(Widget::VerticalLayout(vec![ Widget::VerticalLayout(vec![
Box::new(Widget::Margin { Widget::Margin {
margins: (0, 0, 0, 8), margins: (0, 0, 0, 8),
widget: Box::new(Widget::Battery { widget: Box::new(Widget::Battery {
font_size: 24.0, font_size: 24.0,
length: 600, length: 600,
}), }),
}), },
Box::new(Widget::Margin { Widget::Margin {
margins: (0, 0, 0, 8), margins: (0, 0, 0, 8),
widget: Box::new(Widget::Backlight { widget: Box::new(Widget::Backlight {
device: "intel_backlight".to_string(), device: "intel_backlight".to_string(),
font_size: 24.0, font_size: 24.0,
length: 600, length: 600,
}), }),
}), },
#[cfg(feature = "pulseaudio-widget")] #[cfg(feature = "pulseaudio-widget")]
Box::new(Widget::Margin { Widget::Margin {
margins: (0, 0, 0, 8), margins: (0, 0, 0, 8),
widget: Box::new(Widget::PulseAudio { widget: Box::new(Widget::PulseAudio {
font_size: 24.0, font_size: 24.0,
length: 600, length: 600,
}), }),
}), },
])), ]),
])), ]),
Box::new(Widget::Calendar { Widget::Calendar {
font_size: 16.0, font_size: 16.0,
sections: 3, sections: 3,
}), },
Box::new(Widget::Launcher { Widget::Launcher {
font_size: 32.0, font_size: 32.0,
length: 1200, length: 1200,
app_opener: "".to_string(), app_opener: "".to_string(),
term_opener: "".to_string(), term_opener: "".to_string(),
url_opener: "".to_string(), url_opener: "".to_string(),
}), },
])), ])),
}, },
output_mode: Default::default(), output_mode: Default::default(),
+1 -1
View File
@@ -8,7 +8,7 @@ pub enum ConfigFmt {
Json, Json,
} }
pub const CONFIG_NAMES: &'static [&'static str] = &[ pub const CONFIG_NAMES: &[&str] = &[
#[cfg(feature = "yaml-cfg")] #[cfg(feature = "yaml-cfg")]
"config.yaml", "config.yaml",
#[cfg(feature = "json-cfg")] #[cfg(feature = "json-cfg")]
+4 -4
View File
@@ -40,12 +40,12 @@ impl Desktop {
keywords: desktop keywords: desktop
.get("Keywords") .get("Keywords")
.map(|x| { .map(|x| {
x.split(";") x.split(';')
.map(|y| y.trim().to_string()) .map(|y| y.trim().to_string())
.filter(|z| z != "") .filter(|z| z != "")
.collect() .collect()
}) })
.unwrap_or(vec![]), .unwrap_or_else(|| vec![]),
}), }),
None => Err(Box::new(io_error::new( None => Err(Box::new(io_error::new(
ErrorKind::NotFound, ErrorKind::NotFound,
@@ -92,7 +92,7 @@ pub fn load_desktop_files() -> Vec<Desktop> {
let xdg_data_home = match env::var_os("XDG_DATA_HOME") { let xdg_data_home = match env::var_os("XDG_DATA_HOME") {
Some(s) => s.into_string().unwrap(), Some(s) => s.into_string().unwrap(),
None => format!("{}/.local/share", home).to_string(), None => format!("{}/.local/share", home),
}; };
let xdg_data_dirs = match env::var_os("XDG_DATA_DIRS") { let xdg_data_dirs = match env::var_os("XDG_DATA_DIRS") {
Some(s) => s.into_string().unwrap(), Some(s) => s.into_string().unwrap(),
@@ -100,7 +100,7 @@ pub fn load_desktop_files() -> Vec<Desktop> {
}; };
std::iter::once(xdg_data_home.as_str()) std::iter::once(xdg_data_home.as_str())
.chain(xdg_data_dirs.split(":")) .chain(xdg_data_dirs.split(':'))
.map(|p| Desktop::parse_dir(&format!("{}/applications", p))) .map(|p| Desktop::parse_dir(&format!("{}/applications", p)))
.filter_map(Result::ok) .filter_map(Result::ok)
.flatten() .flatten()
+7 -8
View File
@@ -6,9 +6,8 @@ use std::collections::HashMap;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use rusttype::{point, Font as RustFont, Scale}; use rusttype::{point, Font as RustFont, Scale};
pub static DEJAVUSANS_MONO_FONT_DATA: &'static [u8] = pub static DEJAVUSANS_MONO_FONT_DATA: &[u8] = include_bytes!("../fonts/dejavu/DejaVuSansMono.ttf");
include_bytes!("../fonts/dejavu/DejaVuSansMono.ttf"); pub static ROBOTO_REGULAR_FONT_DATA: &[u8] = include_bytes!("../fonts/Roboto-Regular.ttf");
pub static ROBOTO_REGULAR_FONT_DATA: &'static [u8] = include_bytes!("../fonts/Roboto-Regular.ttf");
lazy_static! { lazy_static! {
pub static ref DEJAVUSANS_MONO: RustFont<'static> = pub static ref DEJAVUSANS_MONO: RustFont<'static> =
@@ -47,9 +46,9 @@ impl CachedGlyph {
render[pos as usize] = o; render[pos as usize] = o;
}); });
CachedGlyph { CachedGlyph {
origin: origin, origin,
dimensions: dimensions, dimensions,
render: render, render,
} }
} else { } else {
CachedGlyph { CachedGlyph {
@@ -92,8 +91,8 @@ impl Font {
pub fn new(font: &'static RustFont, size: f32) -> Font { pub fn new(font: &'static RustFont, size: f32) -> Font {
Font { Font {
glyphs: HashMap::new(), glyphs: HashMap::new(),
font: font, font,
size: size, size,
} }
} }
+9 -7
View File
@@ -45,7 +45,7 @@ fn main() {
Ok(dir) => dir + "/wldash", Ok(dir) => dir + "/wldash",
Err(_) => match env::var("HOME") { Err(_) => match env::var("HOME") {
Ok(home) => home + "/.config/wldash", Ok(home) => home + "/.config/wldash",
Err(_) => panic!("unable to find user folder"), _ => panic!("unable to find user folder"),
}, },
}; };
@@ -105,7 +105,7 @@ fn main() {
}, },
None => Mode::Start, None => Mode::Start,
}; };
if let Some(_) = args.next() { if args.next().is_some() {
// total = args.count + 2 (the two we skipped + the rest) // total = args.count + 2 (the two we skipped + the rest)
eprintln!("expected 0 or 1 arguments, got {}", args.count() + 2); eprintln!("expected 0 or 1 arguments, got {}", args.count() + 2);
std::process::exit(1); std::process::exit(1);
@@ -115,7 +115,7 @@ fn main() {
match mode { match mode {
Mode::ToggleVisible => { Mode::ToggleVisible => {
if let Ok(mut socket) = UnixStream::connect(socket_path.clone()) { if let Ok(mut socket) = UnixStream::connect(socket_path) {
socket.write_all(b"toggle_visible\n").unwrap(); socket.write_all(b"toggle_visible\n").unwrap();
return; return;
}; };
@@ -129,13 +129,13 @@ fn main() {
}; };
} }
Mode::Start => { Mode::Start => {
if let Ok(_) = UnixStream::connect(socket_path.clone()) { if UnixStream::connect(socket_path.clone()).is_ok() {
eprintln!("wldash is already running"); eprintln!("wldash is already running");
std::process::exit(1); std::process::exit(1);
}; };
} }
Mode::Daemonize => { Mode::Daemonize => {
if let Ok(_) = UnixStream::connect(socket_path.clone()) { if UnixStream::connect(socket_path.clone()).is_ok() {
eprintln!("wldash is already running"); eprintln!("wldash is already running");
std::process::exit(1); std::process::exit(1);
}; };
@@ -161,9 +161,11 @@ fn main() {
let tx_draw_mod = tx_draw.clone(); let tx_draw_mod = tx_draw.clone();
let (mod_tx, mod_rx) = channel(); let (mod_tx, mod_rx) = channel();
std::thread::spawn(move || { std::thread::spawn(move || {
let n = Local::now().naive_local();
// Print, write to a file, or send to an HTTP server. // Print, write to a file, or send to an HTTP server.
match config.widget.construct(&n, tx_draw_mod) { match config
.widget
.construct(Local::now().naive_local(), tx_draw_mod)
{
Some(w) => mod_tx.send(w).unwrap(), Some(w) => mod_tx.send(w).unwrap(),
None => panic!("no widget configured"), None => panic!("no widget configured"),
} }
+5 -11
View File
@@ -7,7 +7,7 @@ pub use smithay_client_toolkit::keyboard::{KeyState, ModifiersState};
pub struct DrawContext<'a> { pub struct DrawContext<'a> {
pub buf: &'a mut Buffer<'a>, pub buf: &'a mut Buffer<'a>,
pub bg: &'a Color, pub bg: &'a Color,
pub time: &'a NaiveDateTime, pub time: NaiveDateTime,
pub force: bool, pub force: bool,
} }
@@ -76,7 +76,7 @@ pub struct VerticalLayout {
#[allow(dead_code)] #[allow(dead_code)]
impl VerticalLayout { impl VerticalLayout {
pub fn new(children: Vec<Box<dyn Widget + Send>>) -> Box<VerticalLayout> { pub fn new(children: Vec<Box<dyn Widget + Send>>) -> Box<VerticalLayout> {
Box::new(VerticalLayout { children: children }) Box::new(VerticalLayout { children })
} }
} }
@@ -187,7 +187,7 @@ pub struct HorizontalLayout {
#[allow(dead_code)] #[allow(dead_code)]
impl HorizontalLayout { impl HorizontalLayout {
pub fn new(children: Vec<Box<dyn Widget + Send>>) -> Box<HorizontalLayout> { pub fn new(children: Vec<Box<dyn Widget + Send>>) -> Box<HorizontalLayout> {
Box::new(HorizontalLayout { children: children }) Box::new(HorizontalLayout { children })
} }
} }
@@ -301,10 +301,7 @@ pub struct Margin {
#[allow(dead_code)] #[allow(dead_code)]
impl Margin { impl Margin {
pub fn new(margins: (u32, u32, u32, u32), child: Box<dyn Widget + Send>) -> Box<Margin> { pub fn new(margins: (u32, u32, u32, u32), child: Box<dyn Widget + Send>) -> Box<Margin> {
Box::new(Margin { Box::new(Margin { child, margins })
child: child,
margins: margins,
})
} }
} }
@@ -378,10 +375,7 @@ pub struct Fixed {
#[allow(dead_code)] #[allow(dead_code)]
impl Fixed { impl Fixed {
pub fn new(size: (u32, u32), child: Box<dyn Widget + Send>) -> Box<Fixed> { pub fn new(size: (u32, u32), child: Box<dyn Widget + Send>) -> Box<Fixed> {
Box::new(Fixed { Box::new(Fixed { child, size })
child: child,
size: size,
})
} }
} }
+4 -4
View File
@@ -4,8 +4,8 @@ use crate::widgets::bar_widget::{BarWidget, BarWidgetImpl};
use alsa::mixer::{Mixer, Selem, SelemChannelId, SelemId}; use alsa::mixer::{Mixer, Selem, SelemChannelId, SelemId};
const CARD_NAME: &'static str = "default"; const CARD_NAME: &str = "default";
const SELEM_NAME: &'static str = "Master"; const SELEM_NAME: &str = "Master";
const SELEM_ID: u32 = 0u32; const SELEM_ID: u32 = 0u32;
#[inline] #[inline]
@@ -15,8 +15,8 @@ fn alsa_error_to_io_error(fail: &'static str, err: &alsa::Error) -> ::std::io::E
let errno = err let errno = err
.errno() .errno()
.map(|errno| format!("; errno = {}", errno)) .map(|errno| format!("; errno = {}", errno))
.unwrap_or(String::new()); .unwrap_or_default();
return ::std::io::Error::new(kind, format!("{}: {}{}", fail, func, errno)); ::std::io::Error::new(kind, format!("{}: {}{}", fail, func, errno))
} }
#[inline] #[inline]
+5 -9
View File
@@ -158,7 +158,7 @@ impl PulseAudioClient {
match req { match req {
PulseAudioClientRequest::GetDefaultDevice(s) => { PulseAudioClientRequest::GetDefaultDevice(s) => {
introspector.get_server_info(move |info| { introspector.get_server_info(move |info| {
let _res = PulseAudioClient::server_info_callback( PulseAudioClient::server_info_callback(
cl.clone(), cl.clone(),
l.clone(), l.clone(),
info, info,
@@ -260,13 +260,12 @@ impl PulseAudioClient {
} }
fn send(&self, request: PulseAudioClientRequest) -> Result<(), ::std::io::Error> { fn send(&self, request: PulseAudioClientRequest) -> Result<(), ::std::io::Error> {
let res = self.sender.send(request).map_err(|_e| { self.sender.send(request).map_err(|_e| {
::std::io::Error::new( ::std::io::Error::new(
::std::io::ErrorKind::Other, ::std::io::ErrorKind::Other,
"unable to send pulseaudio request", "unable to send pulseaudio request",
) )
}); })
res
} }
fn server_info_callback<F>(s: Arc<Mutex<Self>>, listener: F, server_info: &ServerInfo) fn server_info_callback<F>(s: Arc<Mutex<Self>>, listener: F, server_info: &ServerInfo)
@@ -371,10 +370,7 @@ impl PulseAudioSoundDevice {
cl.default_sink.to_string() cl.default_sink.to_string()
}; };
(*inner.lock().unwrap()).name = Some(name.clone()); (*inner.lock().unwrap()).name = Some(name.clone());
let device = PulseAudioSoundDevice { let device = PulseAudioSoundDevice { client: cl, inner };
client: cl,
inner: inner,
};
let (tx, rx) = channel(); let (tx, rx) = channel();
{ {
let cl = client.lock().unwrap(); let cl = client.lock().unwrap();
@@ -497,7 +493,7 @@ impl PulseAudio {
*dirty.lock().unwrap() = true; *dirty.lock().unwrap() = true;
sender.send(Cmd::Draw).unwrap(); sender.send(Cmd::Draw).unwrap();
})?; })?;
Ok(Box::new(PulseAudio { device: device })) Ok(Box::new(PulseAudio { device }))
}) })
} }
} }
+5 -9
View File
@@ -2,9 +2,10 @@ use crate::color::Color;
use crate::widget::WaitContext; use crate::widget::WaitContext;
use crate::widgets::bar_widget::{BarWidget, BarWidgetImpl}; use crate::widgets::bar_widget::{BarWidget, BarWidgetImpl};
use std::fs;
use std::fs::OpenOptions; use std::fs::OpenOptions;
use std::io::Write;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
use std::io::{Read, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
pub struct Backlight { pub struct Backlight {
@@ -14,11 +15,9 @@ pub struct Backlight {
} }
fn read_file_as_u64(path: &Path) -> Result<u64, Error> { fn read_file_as_u64(path: &Path) -> Result<u64, Error> {
let mut file = OpenOptions::new().read(true).open(path)?; let mut s = fs::read_to_string(path)?;
let mut str = String::new(); s.pop();
file.read_to_string(&mut str)?; s.parse::<u64>()
str.pop();
str.parse::<u64>()
.map_err(|_e| Error::new(ErrorKind::Other, "unable to parse value")) .map_err(|_e| Error::new(ErrorKind::Other, "unable to parse value"))
} }
@@ -101,7 +100,6 @@ impl BarWidgetImpl for Backlight {
Ok(val) => val, Ok(val) => val,
Err(err) => { Err(err) => {
eprintln!("Error while trying to change brightness: {}", err); eprintln!("Error while trying to change brightness: {}", err);
()
} }
} }
} }
@@ -111,7 +109,6 @@ impl BarWidgetImpl for Backlight {
Ok(val) => val, Ok(val) => val,
Err(err) => { Err(err) => {
eprintln!("Error while trying to change brightness: {}", err); eprintln!("Error while trying to change brightness: {}", err);
()
} }
} }
} }
@@ -125,7 +122,6 @@ impl BarWidgetImpl for Backlight {
Ok(val) => val, Ok(val) => val,
Err(err) => { Err(err) => {
eprintln!("Error while trying to change brightness: {}", err); eprintln!("Error while trying to change brightness: {}", err);
()
} }
} }
} }
+7 -7
View File
@@ -34,9 +34,9 @@ impl BarWidget {
Box::new(BarWidget { Box::new(BarWidget {
bar_impl: w, bar_impl: w,
dirty: Arc::new(Mutex::new(true)), dirty: Arc::new(Mutex::new(true)),
font: font, font,
font_size: font_size as u32, font_size: font_size as u32,
length: length, length,
}) })
} }
@@ -53,10 +53,10 @@ impl BarWidget {
Ok(Box::new(BarWidget { Ok(Box::new(BarWidget {
bar_impl: im, bar_impl: im,
dirty: dirty, dirty,
font: font, font,
font_size: font_size as u32, font_size: font_size as u32,
length: length, length,
})) }))
} }
} }
@@ -119,8 +119,8 @@ impl Widget for BarWidget {
(self.length - bar_off, self.font_size), (self.length - bar_off, self.font_size),
)?; )?;
Ok(DrawReport { Ok(DrawReport {
width: width, width,
height: height, height,
damage: vec![buf.get_signed_bounds()], damage: vec![buf.get_signed_bounds()],
full_damage: false, full_damage: false,
}) })
+3 -5
View File
@@ -8,8 +8,6 @@ use std::sync::{Arc, Mutex};
use nix::poll::{PollFd, PollFlags}; use nix::poll::{PollFd, PollFlags};
use dbus;
fn get_upower_property( fn get_upower_property(
con: &dbus::Connection, con: &dbus::Connection,
device_path: &str, device_path: &str,
@@ -44,7 +42,7 @@ struct DbusConnection(dbus::Connection);
impl std::convert::AsRef<dbus::Connection> for DbusConnection { impl std::convert::AsRef<dbus::Connection> for DbusConnection {
fn as_ref(&self) -> &dbus::Connection { fn as_ref(&self) -> &dbus::Connection {
return &self.0; &self.0
} }
} }
@@ -156,8 +154,8 @@ impl UpowerBattery {
con: DbusConnection(con), con: DbusConnection(con),
dirty, dirty,
sender, sender,
capacity: capacity, capacity,
state: state, state,
watch: fds[0], watch: fds[0],
}) })
} }
+12 -12
View File
@@ -22,10 +22,10 @@ impl Calendar {
&self, &self,
buf: &mut Buffer, buf: &mut Buffer,
background_color: &Color, background_color: &Color,
orig: &NaiveDate, orig: NaiveDate,
time: &NaiveDate, time: NaiveDate,
) -> Result<(i32, i32, i32, i32), ::std::io::Error> { ) -> Result<(i32, i32, i32, i32), ::std::io::Error> {
let mut time = time.clone(); let mut time = time;
let mut y_off = 1; let mut y_off = 1;
let mut done = false; let mut done = false;
@@ -153,7 +153,7 @@ impl Calendar {
} }
impl Calendar { impl Calendar {
pub fn new(time: &NaiveDateTime, font_size: f32, sections: u32) -> Box<Calendar> { pub fn new(time: NaiveDateTime, font_size: f32, sections: u32) -> Box<Calendar> {
let mut calendar_cache = Font::new(&DEJAVUSANS_MONO, font_size * 2.0); let mut calendar_cache = Font::new(&DEJAVUSANS_MONO, font_size * 2.0);
calendar_cache.add_str_to_cache("0123456789"); calendar_cache.add_str_to_cache("0123456789");
let mut month_cache = Font::new(&ROBOTO_REGULAR, font_size * 4.0); let mut month_cache = Font::new(&ROBOTO_REGULAR, font_size * 4.0);
@@ -166,12 +166,12 @@ impl Calendar {
cur_date: time.date(), cur_date: time.date(),
dirty: true, dirty: true,
offset: 0.0, offset: 0.0,
sections: sections, sections,
font_size: font_size as u32, font_size: font_size as u32,
calendar_cache: calendar_cache, calendar_cache,
month_cache: month_cache, month_cache,
year_cache: year_cache, year_cache,
day_cache: day_cache, day_cache,
}) })
} }
} }
@@ -233,7 +233,7 @@ impl Widget for Calendar {
} }
let cal_pad = 7 * self.font_size * 3 + self.font_size * 5; let cal_pad = 7 * self.font_size * 3 + self.font_size * 5;
for idx in 0..self.sections { for idx in 0..self.sections {
self.draw_month(&mut buf.offset((cal_pad * idx, 0))?, ctx.bg, &time, &t)?; self.draw_month(&mut buf.offset((cal_pad * idx, 0))?, ctx.bg, time, t)?;
t = if t.month() == 12 { t = if t.month() == 12 {
t.with_year(t.year() + 1).unwrap().with_month(1).unwrap() t.with_year(t.year() + 1).unwrap().with_month(1).unwrap()
@@ -242,8 +242,8 @@ impl Widget for Calendar {
}; };
} }
Ok(DrawReport { Ok(DrawReport {
width: width, width,
height: height, height,
damage: vec![buf.get_signed_bounds()], damage: vec![buf.get_signed_bounds()],
full_damage: false, full_damage: false,
}) })
+7 -7
View File
@@ -11,14 +11,14 @@ pub struct Clock {
} }
impl Clock { impl Clock {
pub fn new(time: &NaiveDateTime, size: f32) -> Box<Clock> { pub fn new(time: NaiveDateTime, size: f32) -> Box<Clock> {
let mut clock_cache = Font::new(&ROBOTO_REGULAR, size); let mut clock_cache = Font::new(&ROBOTO_REGULAR, size);
clock_cache.add_str_to_cache("0123456789:"); clock_cache.add_str_to_cache("0123456789:");
Box::new(Clock { Box::new(Clock {
cur_time: time.clone(), cur_time: time,
clock_cache: clock_cache, clock_cache,
size: size, size,
}) })
} }
} }
@@ -54,7 +54,7 @@ impl Widget for Clock {
return Ok(DrawReport::empty(width, height)); return Ok(DrawReport::empty(width, height));
} }
self.cur_time = ctx.time.clone(); self.cur_time = ctx.time;
let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?; let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?;
buf.memset(ctx.bg); buf.memset(ctx.bg);
@@ -70,8 +70,8 @@ impl Widget for Clock {
)?; )?;
Ok(DrawReport { Ok(DrawReport {
width: width, width,
height: height, height,
damage: vec![(pos.0 as i32, pos.1 as i32, width as i32, height as i32)], damage: vec![(pos.0 as i32, pos.1 as i32, width as i32, height as i32)],
full_damage: false, full_damage: false,
}) })
+7 -7
View File
@@ -11,15 +11,15 @@ pub struct Date {
} }
impl Date { impl Date {
pub fn new(time: &NaiveDateTime, size: f32) -> Box<Date> { pub fn new(time: NaiveDateTime, size: f32) -> Box<Date> {
let mut date_cache = Font::new(&ROBOTO_REGULAR, size); let mut date_cache = Font::new(&ROBOTO_REGULAR, size);
date_cache date_cache
.add_str_to_cache("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,/ "); .add_str_to_cache("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,/ ");
Box::new(Date { Box::new(Date {
cur_time: time.clone(), cur_time: time,
date_cache: date_cache, date_cache,
size: size, size,
}) })
} }
} }
@@ -43,7 +43,7 @@ impl Widget for Date {
return Ok(DrawReport::empty(width, height)); return Ok(DrawReport::empty(width, height));
} }
self.cur_time = ctx.time.clone(); self.cur_time = ctx.time;
let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?; let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?;
buf.memset(ctx.bg); buf.memset(ctx.bg);
@@ -61,8 +61,8 @@ impl Widget for Date {
)?; )?;
Ok(DrawReport { Ok(DrawReport {
width: width, width,
height: height, height,
damage: vec![(pos.0 as i32, pos.1 as i32, width as i32, height as i32)], damage: vec![(pos.0 as i32, pos.1 as i32, width as i32, height as i32)],
full_damage: false, full_damage: false,
}) })
+24 -26
View File
@@ -50,15 +50,15 @@ impl Launcher {
offset: 0, offset: 0,
font: RefCell::new(Font::new(&ROBOTO_REGULAR, font_size)), font: RefCell::new(Font::new(&ROBOTO_REGULAR, font_size)),
font_size: font_size as u32, font_size: font_size as u32,
length: length, length,
dirty: true, dirty: true,
tx: listener, tx: listener,
}) })
} }
fn draw_launcher(&self, buf: &mut Buffer, bg: &Color) -> Result<(), ::std::io::Error> { fn draw_launcher(&self, buf: &mut Buffer, bg: &Color) -> Result<(), ::std::io::Error> {
let mut x_off = if self.input.len() > 0 { let mut x_off = if !self.input.is_empty() {
let c = if self.matches.len() == 0 { let c = if self.matches.is_empty() {
Color::new(1.0, 0.5, 0.5, 1.0) Color::new(1.0, 0.5, 0.5, 1.0)
} else { } else {
Color::new(1.0, 1.0, 1.0, 1.0) Color::new(1.0, 1.0, 1.0, 1.0)
@@ -79,7 +79,7 @@ impl Launcher {
Ok(b) => b, Ok(b) => b,
Err(_) => break, Err(_) => break,
}; };
let size = if idx == self.offset && self.input.len() > 0 { let size = if idx == self.offset && !self.input.is_empty() {
let (_, indices) = let (_, indices) =
fuzzy_indices(&m.name.to_lowercase(), &self.input.to_lowercase()) fuzzy_indices(&m.name.to_lowercase(), &self.input.to_lowercase())
.unwrap_or((0, vec![])); .unwrap_or((0, vec![]));
@@ -122,7 +122,7 @@ impl Launcher {
.0 .0
+ self.font_size / 4; + self.font_size / 4;
let x_off = if self.input.len() > 0 { let x_off = if !self.input.is_empty() {
let dim = self.font.borrow_mut().auto_draw_text( let dim = self.font.borrow_mut().auto_draw_text(
&mut buf.offset((x_off, 0))?, &mut buf.offset((x_off, 0))?,
bg, bg,
@@ -160,7 +160,7 @@ impl Launcher {
.0 .0
+ self.font_size / 4; + self.font_size / 4;
if self.input.len() > 0 { if !self.input.is_empty() {
self.font.borrow_mut().auto_draw_text( self.font.borrow_mut().auto_draw_text(
&mut buf.offset((x_off, 0))?, &mut buf.offset((x_off, 0))?,
bg, bg,
@@ -175,8 +175,8 @@ impl Launcher {
fn calc(s: &str) -> Result<String, String> { fn calc(s: &str) -> Result<String, String> {
rcalc_lib::parse::eval(s, &mut rcalc_lib::parse::CalcState::new()) rcalc_lib::parse::eval(s, &mut rcalc_lib::parse::CalcState::new())
.map(|x| format!("{}", x).to_string()) .map(|x| format!("{}", x))
.map_err(|x| format!("{}", x).to_string()) .map_err(|x| format!("{}", x))
} }
fn wlcopy(s: &str) -> Result<(), String> { fn wlcopy(s: &str) -> Result<(), String> {
@@ -223,7 +223,7 @@ impl Matcher {
let mut m = self let mut m = self
.matches .matches
.iter() .iter()
.map(|(key, ma)| (ma.clone(), key.clone())) .map(|(key, ma)| (*ma, key.clone()))
.collect::<Vec<(i64, Desktop)>>(); .collect::<Vec<(i64, Desktop)>>();
m.sort_by(|(ma1, d1), (ma2, d2)| { m.sort_by(|(ma1, d1), (ma2, d2)| {
@@ -313,8 +313,8 @@ impl Widget for Launcher {
}?; }?;
Ok(DrawReport { Ok(DrawReport {
width: width, width,
height: height, height,
damage: vec![buf.get_signed_bounds()], damage: vec![buf.get_signed_bounds()],
full_damage: false, full_damage: false,
}) })
@@ -330,7 +330,7 @@ impl Widget for Launcher {
match key { match key {
keysyms::XKB_KEY_u if modifiers.ctrl => self.leave(), keysyms::XKB_KEY_u if modifiers.ctrl => self.leave(),
keysyms::XKB_KEY_BackSpace => { keysyms::XKB_KEY_BackSpace => {
if self.input.len() > 0 { if !self.input.is_empty() {
self.input = self.input[..self.input.len() - 1].to_string(); self.input = self.input[..self.input.len() - 1].to_string();
self.offset = 0; self.offset = 0;
self.result = None; self.result = None;
@@ -339,12 +339,11 @@ impl Widget for Launcher {
} }
keysyms::XKB_KEY_Return => { keysyms::XKB_KEY_Return => {
match self.input.chars().next() { match self.input.chars().next() {
Some('=') => match self.result { Some('=') => {
Some(ref v) => { if let Some(ref v) = self.result {
let _ = wlcopy(&v); let _ = wlcopy(&v);
} }
None => (), }
},
Some('!') => { Some('!') => {
let _ = Command::new("sh") let _ = Command::new("sh")
.arg("-c") .arg("-c")
@@ -367,24 +366,24 @@ impl Widget for Launcher {
&self.app_opener &self.app_opener
}; };
let lexed = if prefix.len() > 0 { let lexed = if !prefix.is_empty() {
let mut prefix = shlex::split(prefix).unwrap(); let mut prefix = shlex::split(prefix).unwrap();
prefix.push(exec); prefix.push(exec);
prefix prefix
} else { } else {
shlex::split(&exec).unwrap() shlex::split(&exec).unwrap()
}; };
if lexed.len() > 0 { if !lexed.is_empty() {
let _ = let _ =
Command::new(lexed[0].clone()).args(&lexed[1..]).spawn(); Command::new(lexed[0].clone()).args(&lexed[1..]).spawn();
self.tx.send(Cmd::Exit).unwrap(); self.tx.send(Cmd::Exit).unwrap();
} }
} }
if let Some(url) = &d.url { if let Some(url) = &d.url {
if self.url_opener.len() > 0 { if !self.url_opener.is_empty() {
let mut lexed = shlex::split(&self.url_opener).unwrap(); let mut lexed = shlex::split(&self.url_opener).unwrap();
lexed.push(url.to_string()); lexed.push(url.to_string());
if lexed.len() > 0 { if !lexed.is_empty() {
let _ = Command::new(lexed[0].clone()) let _ = Command::new(lexed[0].clone())
.args(&lexed[1..]) .args(&lexed[1..])
.spawn(); .spawn();
@@ -397,26 +396,25 @@ impl Widget for Launcher {
}; };
} }
keysyms::XKB_KEY_Right => { keysyms::XKB_KEY_Right => {
if self.matches.len() > 0 && self.offset < self.matches.len() - 1 { if !self.matches.is_empty() && self.offset < self.matches.len() - 1 {
self.offset += 1; self.offset += 1;
self.dirty = true; self.dirty = true;
} }
} }
keysyms::XKB_KEY_Left => { keysyms::XKB_KEY_Left => {
if self.matches.len() > 0 && self.offset > 0 { if !self.matches.is_empty() && self.offset > 0 {
self.offset -= 1; self.offset -= 1;
self.dirty = true; self.dirty = true;
} }
} }
_ => match interpreted { _ => {
Some(v) => { if let Some(v) = interpreted {
self.input += &v; self.input += &v;
self.offset = 0; self.offset = 0;
self.result = None; self.result = None;
self.dirty = true; self.dirty = true;
} }
None => {} }
},
} }
} }
fn mouse_click(&mut self, _: u32, _: (u32, u32)) {} fn mouse_click(&mut self, _: u32, _: (u32, u32)) {}