Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Clippy happier #2975

Merged
merged 4 commits into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Copyright © SixtyFPS GmbH <info@slint.dev>
# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-1.0 OR LicenseRef-Slint-commercial

type-complexity-threshold = 2500
too-many-arguments-threshold = 10
2 changes: 1 addition & 1 deletion api/rs/macros/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ fn fill_token_vec(stream: impl Iterator<Item = TokenTree>, vec: &mut Vec<parser:
let f = s.chars().next().unwrap();
let kind = if f == '"' {
SyntaxKind::StringLiteral
} else if f.is_digit(10) {
} else if f.is_ascii_digit() {
if let Some(last) = vec.last_mut() {
if (last.kind == SyntaxKind::ColorLiteral && last.text.len() == 1)
|| (last.kind == SyntaxKind::Identifier
Expand Down
1 change: 1 addition & 0 deletions api/rs/slint/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ See the [documentation of the `Global` trait](Global) for an example.
#![deny(unsafe_code)]
#![doc(html_logo_url = "https://slint.dev/logo/slint-logo-square-light.svg")]
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::needless_doctest_main)] // We document how to write a main function

extern crate alloc;

Expand Down
1 change: 0 additions & 1 deletion examples/energy-monitor/src/controllers/weather.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,6 @@ fn display_forecast(window_weak: Weak<MainWindow>, forecast: Vec<(ForecastDay, S
absolute_min: min_temp.round() as i32,
unit: SharedString::from("°"),
icon: get_icon(&window, &forecast_day.day.condition),
..Default::default()
};

forecast_model.push(model);
Expand Down
2 changes: 1 addition & 1 deletion examples/slide_puzzle/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn shuffle() -> Vec<i8> {
inversions % 2 != blank_row % 2
}

let mut vec = ((-1)..15).into_iter().collect::<Vec<i8>>();
let mut vec = ((-1)..15).collect::<Vec<i8>>();
use rand::seq::SliceRandom;
let mut rng = rand::thread_rng();
vec.shuffle(&mut rng);
Expand Down
1 change: 0 additions & 1 deletion examples/virtual_keyboard/rust/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ mod virtual_keyboard {
pub fn init(app: &MainWindow) {
let weak = app.as_weak();
app.global::<VirtualKeyboardHandler>().on_key_pressed({
let weak = weak.clone();
move |key| {
weak.unwrap()
.window()
Expand Down
6 changes: 4 additions & 2 deletions helper_crates/vtable/macro/macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ pub fn vtable(_attr: TokenStream, item: TokenStream) -> TokenStream {

// Check if this is a constructor functions
if let ReturnType::Type(_, ret) = &f.output {
if match_generic_type(&**ret, "VBox", &vtable_name) {
if match_generic_type(ret, "VBox", &vtable_name) {
// Change VBox<VTable> to Self
sig.output = parse_str("-> Self").unwrap();
wrap_trait_call = Some(quote! {
Expand Down Expand Up @@ -561,7 +561,9 @@ pub fn vtable(_attr: TokenStream, item: TokenStream) -> TokenStream {
ReturnType::Default => quote!(),
// If the return type contains a implicit lifetime, it is safe to erase it while returning it
// because a sound implementation of the trait wouldn't allow unsound things here
ReturnType::Type(_, r) => quote!(core::mem::transmute::<#r, #r>),
ReturnType::Type(_, r) => {
quote!(#[allow(clippy::useless_transmute)] core::mem::transmute::<#r, #r>)
}
};
vtable_ctor.push(quote!(#ident: {
#sig_extern {
Expand Down
2 changes: 1 addition & 1 deletion helper_crates/vtable/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ impl<'a, T: ?Sized + VTableMeta> VRefMut<'a, T> {
/// Can create mutable reference to ptr, so no other code can create mutable reference of ptr
/// during the life time 'a.
pub unsafe fn from_raw(vtable: NonNull<T::VTable>, ptr: NonNull<u8>) -> Self {
Self { inner: Inner { vtable: vtable.cast(), ptr: ptr }, phantom: PhantomData }
Self { inner: Inner { vtable: vtable.cast(), ptr }, phantom: PhantomData }
}

/// Borrow this to obtain a VRef.
Expand Down
4 changes: 2 additions & 2 deletions helper_crates/vtable/src/vrc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ impl<VTable: VTableMetaDropInPlace, X> VRc<VTable, X> {
///
/// This is safe because we don't allow mutable reference to the inner
pub fn as_pin_ref(&self) -> Pin<&X> {
unsafe { Pin::new_unchecked(&*self) }
unsafe { Pin::new_unchecked(self) }
}

/// Gets a VRef pointing to this instance
Expand Down Expand Up @@ -393,7 +393,7 @@ impl<VTable: VTableMetaDropInPlace + 'static, MappedType: ?Sized> VRcMapped<VTab
///
/// This is safe because the map function returns a pinned reference.
pub fn as_pin_ref(&self) -> Pin<&MappedType> {
unsafe { Pin::new_unchecked(&*self) }
unsafe { Pin::new_unchecked(self) }
}

/// This function allows safely holding a reference to a field inside the `VRcMapped`. In order to accomplish
Expand Down
4 changes: 2 additions & 2 deletions internal/backends/qt/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ impl i_slint_core::platform::Platform for Backend {
ensure_initialized(true);
qApp->exec();
} }
return Ok(());
};
Ok(())
}
#[cfg(no_qt)]
Err("Qt platform requested but Slint is compiled without Qt support".into())
}
Expand Down
5 changes: 3 additions & 2 deletions internal/backends/qt/qt_accessible.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// cspell:ignore descendents qobject qwidget

use crate::accessible_generated::*;
use crate::qt_window::QtWindow;

use i_slint_core::accessibility::AccessibleStringProperty;
use i_slint_core::item_tree::{ItemRc, ItemWeak};
Expand All @@ -23,7 +24,7 @@ use std::pin::Pin;
const NAME: u32 = QAccessible_Text_Name;
const DESCRIPTION: u32 = QAccessible_Text_Description;
const VALUE: u32 = QAccessible_Text_Value;
const CHECKED: u32 = QAccessible_Text_UserText as u32;
const CHECKED: u32 = QAccessible_Text_UserText;
const VALUE_MINIMUM: u32 = CHECKED + 1;
const VALUE_MAXIMUM: u32 = VALUE_MINIMUM + 1;
const VALUE_STEP: u32 = VALUE_MAXIMUM + 1;
Expand Down Expand Up @@ -656,7 +657,7 @@ cpp! {{
~Slint_accessible_window()
{
rust!(Slint_accessible_window_dtor [m_rustWindow: *mut c_void as "void*"] {
alloc::rc::Weak::from_raw(m_rustWindow as _); // Consume the Weak we hold in our void*!
alloc::rc::Weak::from_raw(m_rustWindow as *const QtWindow); // Consume the Weak<QtWindow> we hold in our void*!
});
}

Expand Down
4 changes: 2 additions & 2 deletions internal/backends/qt/qt_widgets/groupbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ cpp! {{
}}

fn minimum_group_box_size(title: qttypes::QString) -> qttypes::QSize {
return cpp!(unsafe [title as "QString"] -> qttypes::QSize as "QSize" {
cpp!(unsafe [title as "QString"] -> qttypes::QSize as "QSize" {
ensure_initialized();

QStyleOptionGroupBox option = create_group_box_option(title);
Expand All @@ -58,7 +58,7 @@ fn minimum_group_box_size(title: qttypes::QString) -> qttypes::QSize {
int baseHeight = metrics.height();

return qApp->style()->sizeFromContents(QStyle::CT_GroupBox, &option, QSize(baseWidth, baseHeight), nullptr);
});
})
}

impl Item for NativeGroupBox {
Expand Down
4 changes: 2 additions & 2 deletions internal/backends/qt/qt_widgets/progress_indicator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl Item for NativeProgressIndicator {
orientation: Orientation,
_window_adapter: &Rc<dyn WindowAdapter>,
) -> LayoutInfo {
let indeterminate = self.indeterminate() as bool;
let indeterminate = self.indeterminate();
let progress =
if indeterminate { 0 } else { (self.progress().max(0.0).min(1.0) * 100.) as i32 };

Expand Down Expand Up @@ -102,7 +102,7 @@ impl Item for NativeProgressIndicator {
}

fn_render! { this dpr size painter widget initial_state =>
let indeterminate = this.indeterminate() as bool;
let indeterminate = this.indeterminate();
let progress = if indeterminate { -1 } else { (this.progress().max(0.0).min(1.0) * 100.) as i32 };

cpp!(unsafe [
Expand Down
1 change: 1 addition & 0 deletions internal/backends/qt/qt_widgets/slider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ impl Item for NativeSlider {
InputEventFilterResult::ForwardEvent
}

#[allow(clippy::unnecessary_cast)] // MouseEvent uses Coord
fn input_event(
self: Pin<&Self>,
event: MouseEvent,
Expand Down
2 changes: 1 addition & 1 deletion internal/backends/qt/qt_widgets/stylemetrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl NativeStyleMetrics {
return qApp->palette().color(QPalette::Window).rgba();
});
let window_background = Color::from_argb_encoded(window_background);
self.window_background.set(window_background.into());
self.window_background.set(window_background);
let default_text_color = cpp!(unsafe[] -> u32 as "QRgb" {
return qApp->palette().color(QPalette::WindowText).rgba();
});
Expand Down
7 changes: 3 additions & 4 deletions internal/backends/qt/qt_window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,6 @@ cpp! {{
text: preedit_string.to_string().into(),
preedit_selection_start: replacement_start as usize,
preedit_selection_end: replacement_start as usize + replacement_length as usize,
..Default::default()
};
runtime_window.process_key_input(event);

Expand Down Expand Up @@ -1111,7 +1110,7 @@ fn shared_image_buffer_to_pixmap(buffer: &SharedImageBuffer) -> Option<qttypes::
QImage img(buffer_ptr, width, height, bytes_per_line, format);
return QPixmap::fromImage(img);
} };
return Some(pixmap);
Some(pixmap)
}

pub(crate) fn image_to_pixmap(
Expand Down Expand Up @@ -1720,10 +1719,10 @@ impl WindowAdapterInternal for QtWindow {
self.tree_structure_changed.replace(true);
}

fn unregister_component<'a>(
fn unregister_component(
&self,
_component: ComponentRef,
_: &mut dyn Iterator<Item = Pin<ItemRef<'a>>>,
_: &mut dyn Iterator<Item = Pin<ItemRef<'_>>>,
) {
self.tree_structure_changed.replace(true);
}
Expand Down
4 changes: 2 additions & 2 deletions internal/backends/selector/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ cfg_if::cfg_if! {
let backend_config = std::env::var("SLINT_BACKEND").unwrap_or_default();

let backend_config = backend_config.to_lowercase();
let (event_loop, _renderer) = backend_config.split_once('-').unwrap_or_else(|| match backend_config.as_str() {
let (event_loop, _renderer) = backend_config.split_once('-').unwrap_or(match backend_config.as_str() {
hunger marked this conversation as resolved.
Show resolved Hide resolved
"qt" => ("qt", ""),
"gl" | "winit" => ("winit", ""),
"femtovg" => ("winit", "femtovg"),
Expand All @@ -51,7 +51,7 @@ cfg_if::cfg_if! {
#[cfg(all(feature = "i-slint-backend-qt", not(no_qt)))]
"qt" => return Ok(Box::new(i_slint_backend_qt::Backend::new())),
#[cfg(feature = "i-slint-backend-winit")]
"winit" => return Ok(Box::new(i_slint_backend_winit::Backend::new_with_renderer_by_name((!_renderer.is_empty()).then(|| _renderer)))),
"winit" => return Ok(Box::new(i_slint_backend_winit::Backend::new_with_renderer_by_name((!_renderer.is_empty()).then_some(_renderer)))),
_ => {},
}

Expand Down
6 changes: 3 additions & 3 deletions internal/backends/testing/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl RendererSealed for TestingWindow {
/// Must be called before any call that would otherwise initialize the rendering backend.
/// Calling it when the rendering backend is already initialized will have no effects
pub fn init() {
i_slint_core::platform::set_platform(Box::new(TestingBackend::default()))
i_slint_core::platform::set_platform(Box::<TestingBackend>::default())
hunger marked this conversation as resolved.
Show resolved Hide resolved
.expect("platform already initialized");
}

Expand Down Expand Up @@ -242,11 +242,11 @@ pub fn access_testing_window<R>(
window: &i_slint_core::api::Window,
callback: impl FnOnce(&TestingWindow) -> R,
) -> R {
i_slint_core::window::WindowInner::from_pub(&window)
i_slint_core::window::WindowInner::from_pub(window)
.window_adapter()
.internal(i_slint_core::InternalToken)
.and_then(|wa| wa.as_any().downcast_ref::<TestingWindow>())
.map(|adapter| callback(adapter))
.map(callback)
.expect("access_testing_window called without testing backend/adapter")
}

Expand Down
34 changes: 14 additions & 20 deletions internal/backends/winit/accesskit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ impl AccessKitAdapter {
send_wrapper::SendWrapper::new(window_adapter_weak.clone());
Self {
inner: accesskit_winit::Adapter::with_action_handler(
&winit_window,
move || Self::build_initial_tree(wrapped_window_adapter_weak.clone()),
winit_window,
move || Self::build_initial_tree(wrapped_window_adapter_weak),
Box::new(ActionForwarder::new(&window_adapter_weak)),
),
window_adapter_weak: window_adapter_weak.clone(),
Expand Down Expand Up @@ -118,17 +118,14 @@ impl AccessKitAdapter {

fn handle_request(&self, request: ActionRequest) {
let Some(window_adapter) = self.window_adapter_weak.upgrade() else { return };
match request.action {
Action::Focus => {
if let Some(item) = self.item_rc_for_node_id(request.target) {
WindowInner::from_pub(window_adapter.window()).set_focus_item(&item);
}
if request.action == Action::Focus {
if let Some(item) = self.item_rc_for_node_id(request.target) {
WindowInner::from_pub(window_adapter.window()).set_focus_item(&item);
}
_ => {}
}
}

pub fn register_component<'a>(&self) {
pub fn register_component(&self) {
let win = self.window_adapter_weak.clone();
i_slint_core::timers::Timer::single_shot(Default::default(), move || {
if let Some(window_adapter) = win.upgrade() {
Expand All @@ -138,7 +135,7 @@ impl AccessKitAdapter {
});
}

pub fn unregister_component<'a>(&self, component: ComponentRef) {
pub fn unregister_component(&self, component: ComponentRef) {
let component_ptr = ComponentRef::as_ptr(component);
if let Some(component_id) = self.component_ids.borrow_mut().remove(&component_ptr) {
self.components_by_id.borrow_mut().remove(&component_id);
Expand Down Expand Up @@ -217,10 +214,7 @@ impl AccessKitAdapter {
})?
});

let update =
TreeUpdate { nodes: nodes.collect(), tree: None, focus: self.focus_node() };

update
TreeUpdate { nodes: nodes.collect(), tree: None, focus: self.focus_node() }
})
})
}
Expand Down Expand Up @@ -280,8 +274,7 @@ impl AccessKitAdapter {
)
});

let update = TreeUpdate { nodes, tree: Some(Tree::new(root_id)), focus: self.focus_node() };
update
TreeUpdate { nodes, tree: Some(Tree::new(root_id)), focus: self.focus_node() }
}

fn build_initial_tree(
Expand All @@ -296,8 +289,7 @@ impl AccessKitAdapter {
}

let update_from_main_thread = Arc::new((Mutex::new(None), Condvar::new()));

if let Err(_) = i_slint_core::api::invoke_from_event_loop({
let update_result = i_slint_core::api::invoke_from_event_loop({
let update_from_main_thread = update_from_main_thread.clone();
move || {
let (lock, wait_condition) = &*update_from_main_thread;
Expand All @@ -307,7 +299,9 @@ impl AccessKitAdapter {

wait_condition.notify_one();
}
}) {
});

if update_result.is_err() {
return Default::default();
}

Expand All @@ -317,7 +311,7 @@ impl AccessKitAdapter {
update = wait_condition.wait(update).unwrap();
}

return update.take().unwrap();
update.take().unwrap()
}

fn build_node_without_children(&self, item: &ItemRc, scale_factor: ScaleFactor) -> NodeBuilder {
Expand Down
5 changes: 2 additions & 3 deletions internal/backends/winit/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub(crate) trait EventLoopInterface {

impl EventLoopInterface for NotRunningEventLoop {
fn event_loop_target(&self) -> &winit::event_loop::EventLoopWindowTarget<SlintUserEvent> {
&*self.instance
&self.instance
}

fn event_loop_proxy(&self) -> &winit::event_loop::EventLoopProxy<SlintUserEvent> {
Expand Down Expand Up @@ -322,7 +322,7 @@ fn process_window_event(
winit::event::VirtualKeyCode::LWin => winit::event::VirtualKeyCode::LControl,
#[cfg(target_os = "macos")]
winit::event::VirtualKeyCode::RWin => winit::event::VirtualKeyCode::RControl,
code @ _ => code,
code => code,
});
window.currently_pressed_key_code().set(match input.state {
winit::event::ElementState::Pressed => key_code,
Expand All @@ -347,7 +347,6 @@ fn process_window_event(
text: string.into(),
preedit_selection_start: preedit_selection.0,
preedit_selection_end: preedit_selection.1,
..Default::default()
};
runtime_window.process_key_input(event);
}
Expand Down
4 changes: 2 additions & 2 deletions internal/backends/winit/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ fn window_factory_fn<R: WinitCompatibleRenderer + 'static>(
cfg_if::cfg_if! {
if #[cfg(feature = "renderer-winit-femtovg")] {
type DefaultRenderer = renderer::femtovg::GlutinFemtoVGRenderer;
const DEFAULT_RENDERER_NAME: &'static str = "FemtoVG";
const DEFAULT_RENDERER_NAME: &str = "FemtoVG";
} else if #[cfg(enable_skia_renderer)] {
type DefaultRenderer = renderer::skia::SkiaRenderer;
const DEFAULT_RENDERER_NAME: &'static str = "Skia";
Expand Down Expand Up @@ -307,7 +307,7 @@ impl private::WinitWindowAccessorSealed for i_slint_core::api::Window {}
fn winit_window_rc_for_window(
window: &i_slint_core::api::Window,
) -> Option<Rc<winit::window::Window>> {
i_slint_core::window::WindowInner::from_pub(&window)
i_slint_core::window::WindowInner::from_pub(window)
.window_adapter()
.internal(i_slint_core::InternalToken)
.and_then(|wa| wa.as_any().downcast_ref::<WinitWindowAdapter>())
Expand Down