correct clippy scoping #81

This commit is contained in:
Alexander Mohr 2025-07-13 12:45:01 +02:00
parent 7cc910d3af
commit b44de0c47a
5 changed files with 33 additions and 34 deletions

View file

@ -2,7 +2,9 @@ use std::{
collections::HashMap, collections::HashMap,
env, env,
ffi::OsStr, ffi::OsStr,
fs, io, fs,
hash::BuildHasher,
io,
os::unix::{fs::PermissionsExt, prelude::CommandExt}, os::unix::{fs::PermissionsExt, prelude::CommandExt},
path::{Path, PathBuf}, path::{Path, PathBuf},
process::{Command, Stdio}, process::{Command, Stdio},
@ -124,12 +126,10 @@ pub fn get_locale_variants() -> Vec<String> {
} }
/// Lookup a value from a hashmap with respect to current locale /// Lookup a value from a hashmap with respect to current locale
// implicit hasher does not make sense here, it is only for desktop files
#[allow(clippy::implicit_hasher)]
#[must_use] #[must_use]
pub fn lookup_name_with_locale( pub fn lookup_name_with_locale<S: BuildHasher>(
locale_variants: &[String], locale_variants: &[String],
variants: &HashMap<String, String>, variants: &HashMap<String, String, S>,
fallback: &str, fallback: &str,
) -> Option<String> { ) -> Option<String> {
locale_variants locale_variants
@ -272,9 +272,10 @@ pub fn load_cache_file(cache_path: &PathBuf) -> Result<HashMap<String, i64>, Err
/// # Errors /// # Errors
/// `Error::Parsing` if converting into toml was not possible /// `Error::Parsing` if converting into toml was not possible
/// `Error::Io` if storing the file failed. /// `Error::Io` if storing the file failed.
// implicit hasher does not make sense here, it is only for desktop files pub fn save_cache_file<S: BuildHasher>(
#[allow(clippy::implicit_hasher)] path: &PathBuf,
pub fn save_cache_file(path: &PathBuf, data: &HashMap<String, i64>) -> Result<(), Error> { data: &HashMap<String, i64, S>,
) -> Result<(), Error> {
// Convert the HashMap to TOML string // Convert the HashMap to TOML string
let toml_string = let toml_string =
toml::ser::to_string(&data).map_err(|e| Error::ParsingError(e.to_string()))?; toml::ser::to_string(&data).map_err(|e| Error::ParsingError(e.to_string()))?;

View file

@ -8,23 +8,21 @@ use std::{
}; };
use crossbeam::channel::{self, Sender}; use crossbeam::channel::{self, Sender};
use gdk4::glib::SignalHandlerId;
use gdk4::prelude::ObjectExt;
use gdk4::{ use gdk4::{
Display, Rectangle, Display, Rectangle,
gio::File, gio::File,
glib::{self, MainContext, Propagation}, glib::{self, MainContext, Propagation, SignalHandlerId},
prelude::{Cast, DisplayExt, MonitorExt, SurfaceExt}, prelude::{Cast, DisplayExt, MonitorExt, ObjectExt, SurfaceExt},
}; };
use gtk4::prelude::{AdjustmentExt, EventControllerExt};
use gtk4::{ use gtk4::{
Align, Application, ApplicationWindow, CssProvider, EventControllerKey, Expander, FlowBox, Align, Application, ApplicationWindow, CssProvider, EventControllerKey, Expander, FlowBox,
FlowBoxChild, GestureClick, Image, Label, ListBox, ListBoxRow, NaturalWrapMode, Ordering, FlowBoxChild, GestureClick, Image, Label, ListBox, ListBoxRow, NaturalWrapMode, Ordering,
Orientation, PolicyType, ScrolledWindow, SearchEntry, Widget, Orientation, PolicyType, ScrolledWindow, SearchEntry, Widget,
glib::ControlFlow, glib::ControlFlow,
prelude::{ prelude::{
ApplicationExt, ApplicationExtManual, BoxExt, EditableExt, FlowBoxChildExt, AdjustmentExt, ApplicationExt, ApplicationExtManual, BoxExt, EditableExt,
GestureSingleExt, GtkWindowExt, ListBoxRowExt, NativeExt, OrientableExt, WidgetExt, EventControllerExt, FlowBoxChildExt, GestureSingleExt, GtkWindowExt, ListBoxRowExt,
NativeExt, OrientableExt, WidgetExt,
}, },
}; };
use gtk4_layer_shell::{Edge, KeyboardMode, LayerShell}; use gtk4_layer_shell::{Edge, KeyboardMode, LayerShell};
@ -164,10 +162,6 @@ pub struct MenuItem<T: Clone> {
/// Allows to store arbitrary additional information /// Allows to store arbitrary additional information
pub data: Option<T>, pub data: Option<T>,
// /// If set to true, the item is _not_ an intermediate thing
// /// and is acceptable, i.e. will close the UI
// pub allow_submit: bool,
// todo
/// Score the item got in the current search /// Score the item got in the current search
search_sort_score: f64, search_sort_score: f64,
/// True if the item is visible /// True if the item is visible
@ -985,7 +979,7 @@ fn setup_key_event_handler<T: Clone + 'static + Send>(
custom_keys: Option<&CustomKeys>, custom_keys: Option<&CustomKeys>,
) { ) {
fn connect_key_handler< fn connect_key_handler<
T: gtk4::prelude::ObjectExt + Clone + 'static + WidgetExt, T: ObjectExt + Clone + 'static + WidgetExt,
Menu: Clone + 'static + Send, Menu: Clone + 'static + Send,
>( >(
widget: &T, widget: &T,
@ -1028,7 +1022,6 @@ fn is_key_match(
} }
} }
#[allow(clippy::cast_sign_loss)] // ok because we only need positive values
fn handle_key_press<T: Clone + 'static + Send>( fn handle_key_press<T: Clone + 'static + Send>(
ui: &Rc<UiElements<T>>, ui: &Rc<UiElements<T>>,
meta: &Rc<MetaData<T>>, meta: &Rc<MetaData<T>>,
@ -1059,6 +1052,8 @@ fn handle_key_press<T: Clone + 'static + Send>(
} else { } else {
pos pos
}; };
// position will not be negative
#[allow(clippy::cast_sign_loss)]
if let Some((start, ch)) = query.char_indices().nth(del_pos as usize) { if let Some((start, ch)) = query.char_indices().nth(del_pos as usize) {
let end = start + ch.len_utf8(); let end = start + ch.len_utf8();
query.replace_range(start..end, ""); query.replace_range(start..end, "");
@ -1094,7 +1089,10 @@ fn handle_key_press<T: Clone + 'static + Send>(
let search_text = ui.search_text.lock().unwrap(); let search_text = ui.search_text.lock().unwrap();
search_text.clone() search_text.clone()
}; };
let pos = ui.search.position(); let pos = ui.search.position();
// position never is negative here.
#[allow(clippy::cast_sign_loss)]
let byte_idx = query let byte_idx = query
.char_indices() .char_indices()
.nth(pos as usize) .nth(pos as usize)
@ -1502,7 +1500,6 @@ fn get_monitor_geometry(surface: Option<&gdk4::Surface>) -> Option<Rectangle> {
.map(|monitor| monitor.geometry()) .map(|monitor| monitor.geometry())
} }
#[allow(clippy::cast_possible_truncation)] // does not matter for calculating height
fn calculate_row_height<T: Clone + 'static>( fn calculate_row_height<T: Clone + 'static>(
ui: &UiElements<T>, ui: &UiElements<T>,
lines: i32, lines: i32,
@ -1523,8 +1520,12 @@ fn calculate_row_height<T: Clone + 'static>(
let factor = config.lines_size_factor(); let factor = config.lines_size_factor();
if config.allow_images() && baseline < i32::from(config.image_size()) { if config.allow_images() && baseline < i32::from(config.image_size()) {
// not relevant for height
#[allow(clippy::cast_possible_truncation)]
Some((f64::from(i32::from(config.image_size())) * factor) as i32) Some((f64::from(i32::from(config.image_size())) * factor) as i32)
} else { } else {
// not relevant for height
#[allow(clippy::cast_possible_truncation)]
Some((f64::from(baseline) * factor) as i32) Some((f64::from(baseline) * factor) as i32)
} }
} else { } else {
@ -1944,6 +1945,7 @@ pub fn filtered_query(search_ignored_words: Option<&Vec<Regex>>, query: &str) ->
} }
query query
} }
enum ChildPosition { enum ChildPosition {
Front, Front,
Back, Back,
@ -1992,13 +1994,13 @@ fn select_visible_child<T: Clone>(
} }
// allowed because truncating is fine, we do no need the precision // allowed because truncating is fine, we do no need the precision
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_precision_loss)]
fn percent_or_absolute(value: &str, base_value: i32) -> Option<i32> { fn percent_or_absolute(value: &str, base_value: i32) -> Option<i32> {
if value.contains('%') { if value.contains('%') {
let value = value.replace('%', "").trim().to_string(); let value = value.replace('%', "").trim().to_string();
match value.parse::<i32>() { match value.parse::<i32>() {
Ok(n) => Some(((n as f32 / 100.0) * base_value as f32) as i32), // okay to truncate the value for positioning.
#[allow(clippy::cast_possible_truncation)]
Ok(n) => Some(((f64::from(n) / 100.0) * f64::from(base_value)) as i32),
Err(_) => None, Err(_) => None,
} }
} else { } else {
@ -2007,14 +2009,12 @@ fn percent_or_absolute(value: &str, base_value: i32) -> Option<i32> {
} }
/// Sorts menu items in alphabetical order, while maintaining the initial score /// Sorts menu items in alphabetical order, while maintaining the initial score
// highly unlikely that we are dealing with > i64 items
#[allow(clippy::cast_possible_wrap)]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_precision_loss)]
pub fn apply_sort<T: Clone>(items: &mut [MenuItem<T>], order: &SortOrder) { pub fn apply_sort<T: Clone>(items: &mut [MenuItem<T>], order: &SortOrder) {
match order { match order {
SortOrder::Default => {} SortOrder::Default => {}
SortOrder::Alphabetical => { SortOrder::Alphabetical => {
// we won't deal w/ enough items that this matters
#[allow(clippy::cast_precision_loss)]
let special_score = items.len() as f64; let special_score = items.len() as f64;
let mut regular_score = 0.0; let mut regular_score = 0.0;
items.sort_by(|l, r| r.label.cmp(&l.label)); items.sort_by(|l, r| r.label.cmp(&l.label));

View file

@ -70,8 +70,6 @@ impl<T: Clone + Send + Sync> DRunProvider<T> {
} }
} }
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_precision_loss)]
fn load(&self) -> Vec<MenuItem<T>> { fn load(&self) -> Vec<MenuItem<T>> {
let locale_variants = get_locale_variants(); let locale_variants = get_locale_variants();
let default_icon = "application-x-executable".to_string(); let default_icon = "application-x-executable".to_string();
@ -117,6 +115,7 @@ impl<T: Clone + Send + Sync> DRunProvider<T> {
.map(|s| s.content.clone()) .map(|s| s.content.clone())
.or(Some(default_icon.clone())); .or(Some(default_icon.clone()));
#[allow(clippy::cast_precision_loss)] // we won't deal with enough values anyways
let sort_score = *self.cache.get(&name).unwrap_or(&0) as f64; let sort_score = *self.cache.get(&name).unwrap_or(&0) as f64;
let mut entry = MenuItem::new( let mut entry = MenuItem::new(

View file

@ -32,7 +32,6 @@ impl<T: Clone> MathProvider<T> {
} }
impl<T: Clone> ItemProvider<T> for MathProvider<T> { impl<T: Clone> ItemProvider<T> for MathProvider<T> {
#[allow(clippy::cast_possible_truncation)]
fn get_elements(&mut self, search: Option<&str>) -> ProviderData<T> { fn get_elements(&mut self, search: Option<&str>) -> ProviderData<T> {
if let Some(search_text) = search { if let Some(search_text) = search {
let result = calc(search_text); let result = calc(search_text);

View file

@ -55,8 +55,6 @@ impl RunProvider {
}) })
} }
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_precision_loss)]
fn load(&self) -> Vec<MenuItem<()>> { fn load(&self) -> Vec<MenuItem<()>> {
let path_var = env::var("PATH").unwrap_or_default(); let path_var = env::var("PATH").unwrap_or_default();
let paths = env::split_paths(&path_var); let paths = env::split_paths(&path_var);
@ -75,6 +73,8 @@ impl RunProvider {
} }
let label = path.file_name()?.to_str()?.to_string(); let label = path.file_name()?.to_str()?.to_string();
// acceptable, because we most likely have not enough items anyways
#[allow(clippy::cast_precision_loss)]
let sort_score = *self.cache.get(&label).unwrap_or(&0) as f64; let sort_score = *self.cache.get(&label).unwrap_or(&0) as f64;
Some(MenuItem::new( Some(MenuItem::new(