Fix some clippy lints and run cargo fmt (#603)

This commit is contained in:
ElKowar 2022-10-24 19:41:16 +02:00 committed by GitHub
parent 471f1a117d
commit f37f3ca3d8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 57 additions and 87 deletions

View file

@ -269,7 +269,7 @@ impl App {
/// Thus, when a variable changes, the run-while conditions of all variables
/// that mention the changed variable need to be reevaluated and reapplied.
fn apply_run_while_expressions_mentioning(&mut self, name: &VarName) {
let mentioning_vars = match self.eww_config.get_run_while_mentions_of(&name) {
let mentioning_vars = match self.eww_config.get_run_while_mentions_of(name) {
Some(x) => x,
None => return,
};
@ -342,17 +342,17 @@ impl App {
)?;
let root_widget = crate::widgets::build_widget::build_gtk_widget(
&mut *self.scope_graph.borrow_mut(),
&mut self.scope_graph.borrow_mut(),
Rc::new(self.eww_config.get_widget_definitions().clone()),
window_scope,
window_def.widget.clone(),
None,
)?;
let monitor_geometry = get_monitor_geometry(monitor.or(window_def.monitor.clone()))?;
let monitor_geometry = get_monitor_geometry(monitor.or_else(|| window_def.monitor.clone()))?;
let mut eww_window = initialize_window(monitor_geometry, root_widget, window_def, window_scope)?;
eww_window.gtk_window.style_context().add_class(&window_name.to_string());
eww_window.gtk_window.style_context().add_class(window_name);
// initialize script var handlers for variables. As starting a scriptvar with the script_var_handler is idempodent,
// we can just start script vars that are already running without causing issues
@ -415,7 +415,7 @@ impl App {
if let Err(err) = self.css_provider.load_from_data(css.as_bytes()) {
static PATTERN: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new(r"[^:]*:(\d+):(\d+)(.*)$").unwrap());
let nice_error_option: Option<_> = try {
let captures = PATTERN.captures(&err.message())?;
let captures = PATTERN.captures(err.message())?;
let line = captures.get(1).unwrap().as_str().parse::<usize>().ok()?;
let msg = captures.get(3).unwrap().as_str();
let db = error_handling_ctx::FILE_DATABASE.read().ok()?;
@ -479,7 +479,7 @@ fn initialize_window(
window.show_all();
Ok(EwwWindow { name: window_def.name.clone(), gtk_window: window, scope_index: window_scope, destroy_event_handler_id: None })
Ok(EwwWindow { name: window_def.name, gtk_window: window, scope_index: window_scope, destroy_event_handler_id: None })
}
/// Apply the provided window-positioning rules to the window.
@ -552,7 +552,7 @@ fn get_monitor_geometry(identifier: Option<MonitorIdentifier>) -> Result<gdk::Re
/// Outside of x11, only [MonitorIdentifier::Numeric] is supported
pub fn get_monitor_from_display(display: &gdk::Display, identifier: &MonitorIdentifier) -> Option<gdk::Monitor> {
match identifier {
MonitorIdentifier::Numeric(num) => return display.monitor(*num),
MonitorIdentifier::Numeric(num) => display.monitor(*num),
#[cfg(not(feature = "x11"))]
MonitorIdentifier::Name(_) => return None,
@ -566,9 +566,9 @@ pub fn get_monitor_from_display(display: &gdk::Display, identifier: &MonitorIden
}
}
}
None
}
}
return None;
}
pub fn get_window_rectangle(geometry: WindowGeometry, screen_rect: gdk::Rectangle) -> gdk::Rectangle {

View file

@ -26,7 +26,7 @@ macro_rules! loop_select_exiting {
($($content:tt)*) => {
loop {
tokio::select! {
Ok(()) = crate::application_lifecycle::recv_exit() => {
Ok(()) = $crate::application_lifecycle::recv_exit() => {
break;
}
$($content)*

View file

@ -24,7 +24,7 @@ pub fn read_from_eww_paths(eww_paths: &EwwPaths) -> Result<EwwConfig> {
}
/// Eww configuration structure.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Default)]
pub struct EwwConfig {
widgets: HashMap<String, WidgetDefinition>,
windows: HashMap<String, WindowDefinition>,
@ -35,18 +35,6 @@ pub struct EwwConfig {
run_while_mentions: HashMap<VarName, Vec<VarName>>,
}
impl Default for EwwConfig {
fn default() -> Self {
Self {
widgets: HashMap::new(),
windows: HashMap::new(),
initial_variables: HashMap::new(),
script_vars: HashMap::new(),
run_while_mentions: HashMap::new(),
}
}
}
impl EwwConfig {
/// Load an [`EwwConfig`] from the config dir of the given [`crate::EwwPaths`], reading the main config file.
pub fn read_from_dir(files: &mut FileDatabase, eww_paths: &EwwPaths) -> Result<Self> {
@ -58,10 +46,10 @@ impl EwwConfig {
// run some validations on the configuration
let magic_globals: Vec<_> = inbuilt::INBUILT_VAR_NAMES
.into_iter()
.iter()
.chain(inbuilt::MAGIC_CONSTANT_NAMES)
.into_iter()
.map(|x| VarName::from(x.clone()))
.map(|x| VarName::from(*x))
.collect();
yuck::config::validate::validate(&config, magic_globals)?;

View file

@ -60,7 +60,7 @@ pub fn get_temperatures() -> String {
"{{ {} }}",
c.components()
.iter()
.map(|c| format!(r#""{}": {}"#, c.label().to_uppercase().replace(" ", "_"), c.temperature()))
.map(|c| format!(r#""{}": {}"#, c.label().to_uppercase().replace(' ', "_"), c.temperature()))
.join(",")
)
}

View file

@ -94,7 +94,6 @@ mod platform {
#[cfg(feature = "x11")]
mod platform {
use anyhow::{Context, Result};
use gdkx11;
use gtk::{self, prelude::*};
use x11rb::protocol::xproto::ConnectionExt;

View file

@ -65,7 +65,7 @@ pub enum Action {
WithServer(ActionWithServer),
}
#[derive(Subcommand, Debug, Serialize, Deserialize, PartialEq)]
#[derive(Subcommand, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum ActionClientOnly {
/// Print and watch the eww logs
#[clap(name = "logs")]

View file

@ -57,8 +57,7 @@ pub fn init(evt_send: UnboundedSender<DaemonCommand>) -> ScriptVarHandlerHandle
})
})
.expect("Failed to start script-var-handler thread");
let handle = ScriptVarHandlerHandle { msg_send, thread_handle };
handle
ScriptVarHandlerHandle { msg_send, thread_handle }
}
/// Handle to the script-var handling system.
@ -229,7 +228,7 @@ impl ListenVarHandler {
}
let (cancel_send, mut cancel_recv) = cancellation::create();
self.listen_process_handles.insert(var.name.clone(), cancel_send.clone());
self.listen_process_handles.insert(var.name.clone(), cancel_send);
let evt_send = self.evt_send.clone();
tokio::spawn(async move {

View file

@ -568,7 +568,7 @@ mod internal {
))
.collect::<Vec<_>>()
)
.replace("\"", "'")
.replace('\"', "'")
));
if let Some(created_by) = scope.ancestor {
output.push_str(&format!(" \"{:?}\" -> \"{:?}\"[label=\"ancestor\"]\n", created_by, scope_index));
@ -581,7 +581,7 @@ mod internal {
" \"{:?}\" -> \"{:?}\" [color = \"red\", label = \"{}\"]\n",
parent,
child,
format!(":{} `{:?}`", edge.attr_name, edge.expression).replace("\"", "'")
format!(":{} `{:?}`", edge.attr_name, edge.expression).replace('\"', "'")
));
}
}
@ -590,7 +590,7 @@ mod internal {
" \"{:?}\" -> \"{:?}\" [color = \"blue\", label = \"{}\"]\n",
child,
parent,
format!("inherits({:?})", edge.references).replace("\"", "'")
format!("inherits({:?})", edge.references).replace('\"', "'")
));
}

View file

@ -123,7 +123,7 @@ pub fn replace_env_var_references(input: String) -> String {
pub fn unindent(text: &str) -> String {
// take all the lines of our text and skip over the first empty ones
let lines = text.lines().skip_while(|x| *x == "");
let lines = text.lines().skip_while(|x| x.is_empty());
// find the smallest indentation
let min = lines
.clone()

View file

@ -228,10 +228,8 @@ fn build_loop_special_widget(
Listener {
needed_variables: widget_use.elements_expr.collect_var_refs(),
f: Box::new({
let custom_widget_invocation = custom_widget_invocation.clone();
let widget_defs = widget_defs.clone();
let elements_expr = widget_use.elements_expr.clone();
let elements_expr_span = widget_use.elements_expr_span.clone();
let elements_expr_span = widget_use.elements_expr_span;
let element_name = widget_use.element_name.clone();
let body: WidgetUse = widget_use.body.as_ref().clone();
let created_children = Rc::new(RefCell::new(Vec::<gtk::Widget>::new()));
@ -243,7 +241,7 @@ fn build_loop_special_widget(
.as_json_value()?
.as_array()
.context("Not an array value")?
.into_iter()
.iter()
.map(DynVal::from)
.collect_vec();
let mut created_children = created_children.borrow_mut();

View file

@ -40,7 +40,7 @@ macro_rules! def_widget {
$args.scope_graph.register_listener(
$args.calling_scope,
crate::state::scope::Listener {
$crate::state::scope::Listener {
needed_variables: required_vars,
f: Box::new({
// create a weak reference to the widget, such that this listener doesn't prevent the actual widget from

View file

@ -45,7 +45,7 @@ where
{
if !args.is_empty() {
let cmd = cmd.replace("{}", &format!("{}", args[0]));
args.iter().enumerate().fold(cmd.to_string(), |acc, (i, arg)| acc.replace(&format!("{{{}}}", i), &format!("{}", arg)))
args.iter().enumerate().fold(cmd, |acc, (i, arg)| acc.replace(&format!("{{{}}}", i), &format!("{}", arg)))
} else {
cmd.to_string()
}

View file

@ -137,22 +137,22 @@ impl WidgetImpl for TransformPriv {
cr.save()?;
let translate_x = match &*self.translate_x.borrow() {
Some(tx) => NumWithUnit::from_str(&tx)?.pixels_relative_to(total_width as i32) as f64,
Some(tx) => NumWithUnit::from_str(tx)?.pixels_relative_to(total_width as i32) as f64,
None => 0.0,
};
let translate_y = match &*self.translate_y.borrow() {
Some(ty) => NumWithUnit::from_str(&ty)?.pixels_relative_to(total_height as i32) as f64,
Some(ty) => NumWithUnit::from_str(ty)?.pixels_relative_to(total_height as i32) as f64,
None => 0.0,
};
let scale_x = match &*self.scale_x.borrow() {
Some(sx) => NumWithUnit::from_str(&sx)?.perc_relative_to(total_width as i32) as f64 / 100.0,
Some(sx) => NumWithUnit::from_str(sx)?.perc_relative_to(total_width as i32) as f64 / 100.0,
None => 1.0,
};
let scale_y = match &*self.scale_y.borrow() {
Some(sy) => NumWithUnit::from_str(&sy)?.perc_relative_to(total_height as i32) as f64 / 100.0,
Some(sy) => NumWithUnit::from_str(sy)?.perc_relative_to(total_height as i32) as f64 / 100.0,
None => 1.0,
};
@ -162,7 +162,7 @@ impl WidgetImpl for TransformPriv {
// Children widget
if let Some(child) = &*self.content.borrow() {
widget.propagate_draw(child, &cr);
widget.propagate_draw(child, cr);
}
cr.restore()?;

View file

@ -272,7 +272,7 @@ pub(super) fn resolve_orientable_attrs(bargs: &mut BuilderArgs, gtk_widget: &gtk
// concrete widgets
const WIDGET_NAME_COMBO_BOX_TEXT: &'static str = "combo-box-text";
const WIDGET_NAME_COMBO_BOX_TEXT: &str = "combo-box-text";
/// @widget combo-box-text
/// @desc A combo box allowing the user to choose between several items.
fn build_gtk_combo_box_text(bargs: &mut BuilderArgs) -> Result<gtk::ComboBoxText> {

View file

@ -32,6 +32,7 @@ impl Span {
self.0 = self.1;
self
}
pub fn shifted(mut self, n: isize) -> Self {
self.0 = isize::max(0, self.0 as isize + n) as usize;
self.1 = isize::max(0, self.0 as isize + n) as usize;

View file

@ -4,20 +4,7 @@ use serde::{Deserialize, Serialize};
/// The name of a variable
#[repr(transparent)]
#[derive(
Clone,
Hash,
PartialEq,
Eq,
Serialize,
Deserialize,
AsRef,
From,
FromStr,
Display,
DebugCustom,
RefCast,
)]
#[derive(Clone, Hash, PartialEq, Eq, Serialize, Deserialize, AsRef, From, FromStr, Display, DebugCustom, RefCast)]
#[debug(fmt = "VarName({})", .0)]
pub struct VarName(pub String);
@ -47,20 +34,7 @@ impl From<AttrName> for VarName {
/// The name of an attribute
#[repr(transparent)]
#[derive(
Clone,
Hash,
PartialEq,
Eq,
Serialize,
Deserialize,
AsRef,
From,
FromStr,
Display,
DebugCustom,
RefCast,
)]
#[derive(Clone, Hash, PartialEq, Eq, Serialize, Deserialize, AsRef, From, FromStr, Display, DebugCustom, RefCast)]
#[debug(fmt="AttrName({})", .0)]
pub struct AttrName(pub String);

View file

@ -104,7 +104,7 @@ impl SimplExpr {
/// If a var-ref links to another var-ref, that other var-ref is used.
/// If a referenced variable is not found in the given hashmap, returns the var-ref unchanged.
pub fn resolve_one_level(self, variables: &HashMap<VarName, SimplExpr>) -> Self {
self.map_var_refs(|span, name| variables.get(&name).cloned().unwrap_or_else(|| Self::VarRef(span, name)))
self.map_var_refs(|span, name| variables.get(&name).cloned().unwrap_or(Self::VarRef(span, name)))
}
/// resolve variable references in the expression. Fails if a variable cannot be resolved.
@ -298,7 +298,7 @@ fn call_expr_function(name: &str, args: Vec<DynVal>) -> Result<DynVal, EvalError
let string = string.as_string()?;
let pattern = regex::Regex::new(&pattern.as_string()?)?;
let replacement = replacement.as_string()?;
Ok(DynVal::from(pattern.replace_all(&string, replacement.replace("$", "$$").replace("\\", "$")).into_owned()))
Ok(DynVal::from(pattern.replace_all(&string, replacement.replace('$', "$$").replace('\\', "$")).into_owned()))
}
_ => Err(EvalError::WrongArgCount(name.to_string())),
},

View file

@ -111,8 +111,8 @@ regex_rules! {
r"\s+" => |_| Token::Skip,
r";.*"=> |_| Token::Comment,
r"[a-zA-Z_][a-zA-Z0-9_-]*" => |x| Token::Ident(x),
r"[+-]?(?:[0-9]+[.])?[0-9]+" => |x| Token::NumLit(x)
r"[a-zA-Z_][a-zA-Z0-9_-]*" => Token::Ident,
r"[+-]?(?:[0-9]+[.])?[0-9]+" => Token::NumLit
}
#[derive(Debug)]

View file

@ -11,10 +11,7 @@ pub enum MonitorIdentifier {
impl MonitorIdentifier {
pub fn is_numeric(&self) -> bool {
match self {
Self::Numeric(_) => true,
_ => false,
}
matches!(self, Self::Numeric(_))
}
}

View file

@ -105,7 +105,7 @@ pub fn validate_variables_in_widget_use(
}
for child in widget.children.iter() {
let _ = validate_variables_in_widget_use(defs, variables, child, is_in_definition)?;
validate_variables_in_widget_use(defs, variables, child, is_in_definition)?;
}
} else if let WidgetUse::Loop(widget) = widget {
let unknown_var = widget
@ -120,7 +120,7 @@ pub fn validate_variables_in_widget_use(
}
let mut variables = variables.clone();
variables.insert(widget.element_name.clone());
let _ = validate_variables_in_widget_use(defs, &variables, &widget.body, is_in_definition)?;
validate_variables_in_widget_use(defs, &variables, &widget.body, is_in_definition)?;
}
Ok(())

View file

@ -63,9 +63,9 @@ regex_rules! {
r"\]" => |_| Token::RBrack,
r"true" => |_| Token::True,
r"false" => |_| Token::False,
r#"[+-]?(?:[0-9]+[.])?[0-9]+"# => |x| Token::NumLit(x),
r#":[^\s\)\]}]+"# => |x| Token::Keyword(x),
r#"[a-zA-Z_!\?<>/\.\*-\+\-][^\s{}\(\)\[\](){}]*"# => |x| Token::Symbol(x),
r#"[+-]?(?:[0-9]+[.])?[0-9]+"# => Token::NumLit,
r#":[^\s\)\]}]+"# => Token::Keyword,
r#"[a-zA-Z_!\?<>/\.\*-\+\-][^\s{}\(\)\[\](){}]*"# => Token::Symbol,
r#";.*"# => |_| Token::Comment,
r"[ \t\n\f]+" => |_| Token::Skip
}

14
rustfmt.toml Normal file
View file

@ -0,0 +1,14 @@
unstable_features = true
fn_single_line = false
max_width = 130
reorder_impl_items = true
merge_imports = true
normalize_comments = true
use_field_init_shorthand = true
#wrap_comments = true
combine_control_expr = false
condense_wildcard_suffixes = true
format_code_in_doc_comments = true
format_macro_matchers = true
format_strings = true
use_small_heuristics = "Max"