chore: Fix several style lints (#17488)

It's not comprehensive enough to start linting on `style` group, but
hey, it's a start.

Release Notes:

- N/A
This commit is contained in:
Piotr Osiewicz 2024-09-06 11:58:39 +02:00 committed by GitHub
parent 93249fc82b
commit e6c1c51b37
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
361 changed files with 3530 additions and 3587 deletions

View file

@ -81,9 +81,12 @@ mod macos {
fn generate_shader_bindings() -> PathBuf {
let output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("scene.h");
let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut config = Config::default();
config.include_guard = Some("SCENE_H".into());
config.language = cbindgen::Language::C;
let mut config = Config {
include_guard: Some("SCENE_H".into()),
language: cbindgen::Language::C,
no_includes: true,
..Default::default()
};
config.export.include.extend([
"Bounds".into(),
"Corners".into(),
@ -178,7 +181,7 @@ mod macos {
"-c",
shader_path,
"-include",
&header_path.to_str().unwrap(),
(header_path.to_str().unwrap()),
"-o",
])
.arg(&air_output_path)

View file

@ -9,7 +9,7 @@ impl AssetSource for Assets {
std::fs::read(path)
.map(Into::into)
.map_err(Into::into)
.map(|result| Some(result))
.map(Some)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
@ -23,7 +23,7 @@ impl AssetSource for Assets {
}
}
const ARROW_CIRCLE_SVG: &'static str = concat!(
const ARROW_CIRCLE_SVG: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/image/arrow_circle.svg"
);

View file

@ -298,9 +298,7 @@ impl ViewInputHandler for TextInput {
bounds: Bounds<Pixels>,
_cx: &mut ViewContext<Self>,
) -> Option<Bounds<Pixels>> {
let Some(last_layout) = self.last_layout.as_ref() else {
return None;
};
let last_layout = self.last_layout.as_ref()?;
let range = self.range_from_utf16(&range_utf16);
Some(Bounds::from_corners(
point(

View file

@ -66,8 +66,6 @@ impl HelloWorld {
break;
}
}
()
}));
}
}

View file

@ -514,7 +514,7 @@ impl AppContext {
}
Err(e) => {
cx.windows.remove(id);
return Err(e);
Err(e)
}
}
})

View file

@ -666,7 +666,7 @@ impl LeakDetector {
let handles = self.entity_handles.entry(entity_id).or_default();
handles.insert(
handle_id,
LEAK_BACKTRACE.then(|| backtrace::Backtrace::new_unresolved()),
LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
);
handle_id
}
@ -679,7 +679,7 @@ impl LeakDetector {
pub fn assert_released(&mut self, entity_id: EntityId) {
let handles = self.entity_handles.entry(entity_id).or_default();
if !handles.is_empty() {
for (_, backtrace) in handles {
for backtrace in handles.values_mut() {
if let Some(mut backtrace) = backtrace.take() {
backtrace.resolve();
eprintln!("Leaked handle: {:#?}", backtrace);

View file

@ -52,11 +52,9 @@ where
// the surface area the least. This attempts to keep the tree balanced
// in terms of surface area. If there is an intersection with the other child,
// add its keys to the intersections vector.
let left_cost = new_bounds
.union(&self.nodes[left].bounds())
.half_perimeter();
let left_cost = new_bounds.union(self.nodes[left].bounds()).half_perimeter();
let right_cost = new_bounds
.union(&self.nodes[right].bounds())
.union(self.nodes[right].bounds())
.half_perimeter();
if left_cost < right_cost {
max_intersecting_ordering =

View file

@ -119,13 +119,13 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {
done = true;
delta = 1.0;
} else {
delta = delta % 1.0;
delta %= 1.0;
}
}
let delta = (self.animation.easing)(delta);
debug_assert!(
delta >= 0.0 && delta <= 1.0,
(0.0..=1.0).contains(&delta),
"delta should always be between 0 and 1"
);

View file

@ -110,6 +110,6 @@ impl DefaultColor {
/// Returns the HSLA color for the given color type.
pub fn hsla(&self, colors: &DefaultColors) -> Hsla {
self.color(&colors).into()
self.color(colors).into()
}
}

View file

@ -1314,16 +1314,14 @@ impl Interactivity {
// If there's an explicit focus handle we're tracking, use that. Otherwise
// create a new handle and store it in the element state, which lives for as
// as frames contain an element with this id.
if self.focusable {
if self.tracked_focus_handle.is_none() {
if let Some(element_state) = element_state.as_mut() {
self.tracked_focus_handle = Some(
element_state
.focus_handle
.get_or_insert_with(|| cx.focus_handle())
.clone(),
);
}
if self.focusable && self.tracked_focus_handle.is_none() {
if let Some(element_state) = element_state.as_mut() {
self.tracked_focus_handle = Some(
element_state
.focus_handle
.get_or_insert_with(|| cx.focus_handle())
.clone(),
);
}
}
@ -1336,7 +1334,7 @@ impl Interactivity {
self.scroll_offset = Some(
element_state
.scroll_offset
.get_or_insert_with(|| Rc::default())
.get_or_insert_with(Rc::default)
.clone(),
);
}
@ -1360,7 +1358,7 @@ impl Interactivity {
) -> R {
self.content_size = content_size;
if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
cx.set_focus_handle(&focus_handle);
cx.set_focus_handle(focus_handle);
}
cx.with_optional_element_state::<InteractiveElementState, _>(
global_id,
@ -1949,10 +1947,10 @@ impl Interactivity {
let tooltip_is_hovered =
tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(cx));
if !tooltip_is_hoverable || !tooltip_is_hovered {
if active_tooltip.borrow_mut().take().is_some() {
cx.refresh();
}
if (!tooltip_is_hoverable || !tooltip_is_hovered)
&& active_tooltip.borrow_mut().take().is_some()
{
cx.refresh();
}
}
});
@ -1963,10 +1961,10 @@ impl Interactivity {
move |_: &ScrollWheelEvent, _, cx| {
let tooltip_is_hovered =
tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(cx));
if !tooltip_is_hoverable || !tooltip_is_hovered {
if active_tooltip.borrow_mut().take().is_some() {
cx.refresh();
}
if (!tooltip_is_hoverable || !tooltip_is_hovered)
&& active_tooltip.borrow_mut().take().is_some()
{
cx.refresh();
}
}
})

View file

@ -5,7 +5,6 @@ use crate::{
SvgSize, UriOrPath, WindowContext,
};
use futures::{AsyncReadExt, Future};
use http_client;
use image::{
codecs::gif::GifDecoder, AnimationDecoder, Frame, ImageBuffer, ImageError, ImageFormat,
};
@ -47,7 +46,7 @@ impl From<SharedUri> for ImageSource {
impl From<&'static str> for ImageSource {
fn from(s: &'static str) -> Self {
if is_uri(&s) {
if is_uri(s) {
Self::Uri(s.into())
} else {
Self::Embedded(s.into())
@ -187,18 +186,17 @@ impl Element for Img {
}
let image_size = data.size(frame_index);
match (style.size.width, style.size.height) {
(Length::Auto, Length::Auto) => {
style.size = Size {
width: Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(px(image_size.width.0 as f32)),
)),
height: Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(px(image_size.height.0 as f32)),
)),
}
if let (Length::Auto, Length::Auto) = (style.size.width, style.size.height)
{
style.size = Size {
width: Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(px(image_size.width.0 as f32)),
)),
height: Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(px(image_size.height.0 as f32)),
)),
}
_ => {}
}
if global_id.is_some() && data.frame_count() > 1 {

View file

@ -71,7 +71,6 @@ impl Element for Surface {
_request_layout: &mut Self::RequestLayoutState,
_cx: &mut WindowContext,
) -> Self::PrepaintState {
()
}
fn paint(

View file

@ -604,7 +604,7 @@ impl Element for InteractiveText {
let mut interactive_state = interactive_state.unwrap_or_default();
if let Some(click_listener) = self.click_listener.take() {
let mouse_position = cx.mouse_position();
if let Some(ix) = text_layout.index_for_position(mouse_position).ok() {
if let Ok(ix) = text_layout.index_for_position(mouse_position) {
if self
.clickable_ranges
.iter()
@ -621,8 +621,8 @@ impl Element for InteractiveText {
let clickable_ranges = mem::take(&mut self.clickable_ranges);
cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
if let Some(mouse_up_index) =
text_layout.index_for_position(event.position).ok()
if let Ok(mouse_up_index) =
text_layout.index_for_position(event.position)
{
click_listener(
&clickable_ranges,
@ -642,8 +642,8 @@ impl Element for InteractiveText {
let hitbox = hitbox.clone();
cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
if let Some(mouse_down_index) =
text_layout.index_for_position(event.position).ok()
if let Ok(mouse_down_index) =
text_layout.index_for_position(event.position)
{
mouse_down.set(Some(mouse_down_index));
cx.refresh();

View file

@ -210,10 +210,10 @@ impl BackgroundExecutor {
Poll::Pending => {
let timeout =
deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
if !self.dispatcher.park(timeout) {
if deadline.is_some_and(|deadline| deadline < Instant::now()) {
return Err(future);
}
if !self.dispatcher.park(timeout)
&& deadline.is_some_and(|deadline| deadline < Instant::now())
{
return Err(future);
}
}
}

View file

@ -2146,7 +2146,7 @@ pub struct Percentage(pub f32);
/// Generate a `Radian` from a percentage of a full circle.
pub fn percentage(value: f32) -> Percentage {
debug_assert!(
value >= 0.0 && value <= 1.0,
(0.0..=1.0).contains(&value),
"Percentage must be between 0 and 1"
);
Percentage(value)
@ -3133,12 +3133,12 @@ mod tests {
};
// Test Case 1: Intersecting bounds
assert_eq!(bounds1.intersects(&bounds2), true);
assert!(bounds1.intersects(&bounds2));
// Test Case 2: Non-Intersecting bounds
assert_eq!(bounds1.intersects(&bounds3), false);
assert!(!bounds1.intersects(&bounds3));
// Test Case 3: Bounds intersecting with themselves
assert_eq!(bounds1.intersects(&bounds1), true);
assert!(bounds1.intersects(&bounds1));
}
}

View file

@ -402,7 +402,7 @@ impl DispatchTree {
keymap
.bindings_for_action(action)
.filter(|binding| {
let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, &context_stack);
let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, context_stack);
bindings
.iter()
.next()
@ -424,7 +424,7 @@ impl DispatchTree {
self.keymap
.borrow()
.bindings_for_input(&input, &context_stack)
.bindings_for_input(input, &context_stack)
}
/// dispatch_key processes the keystroke
@ -463,7 +463,7 @@ impl DispatchTree {
let mut result = self.dispatch_key(suffix, keystroke, dispatch_path);
to_replay.extend(result.to_replay);
result.to_replay = to_replay;
return result;
result
}
/// If the user types a matching prefix of a binding and then waits for a timeout
@ -475,7 +475,7 @@ impl DispatchTree {
) -> SmallVec<[Replay; 1]> {
let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
if suffix.len() > 0 {
if !suffix.is_empty() {
to_replay.extend(self.flush_dispatch(suffix, dispatch_path))
}

View file

@ -130,7 +130,7 @@ impl Keymap {
})
.collect();
return (bindings, is_pending.unwrap_or_default());
(bindings, is_pending.unwrap_or_default())
}
/// Check if the given binding is enabled, given a certain key context.

View file

@ -57,7 +57,7 @@ impl KeyBinding {
}
}
return Some(self.keystrokes.len() > typed.len());
Some(self.keystrokes.len() > typed.len())
}
/// Get the keystrokes associated with this binding

View file

@ -593,9 +593,7 @@ impl PlatformInputHandler {
}
pub fn selected_bounds(&mut self, cx: &mut WindowContext) -> Option<Bounds<Pixels>> {
let Some(selection) = self.handler.selected_text_range(true, cx) else {
return None;
};
let selection = self.handler.selected_text_range(true, cx)?;
self.handler.bounds_for_range(
if selection.reversed {
selection.range.start..selection.range.start

View file

@ -22,7 +22,8 @@ use std::{mem, sync::Arc};
const MAX_FRAME_TIME_MS: u32 = 10000;
#[cfg(target_os = "macos")]
pub type Context = ();
#[derive(Clone, Default)]
pub struct Context {}
#[cfg(target_os = "macos")]
pub type Renderer = BladeRenderer;

View file

@ -161,13 +161,39 @@ impl Keystroke {
}
fn is_printable_key(key: &str) -> bool {
match key {
"f1" | "f2" | "f3" | "f4" | "f5" | "f6" | "f7" | "f8" | "f9" | "f10" | "f11" | "f12"
| "f13" | "f14" | "f15" | "f16" | "f17" | "f18" | "f19" | "backspace" | "delete"
| "left" | "right" | "up" | "down" | "pageup" | "pagedown" | "insert" | "home" | "end"
| "escape" => false,
_ => true,
}
!matches!(
key,
"f1" | "f2"
| "f3"
| "f4"
| "f5"
| "f6"
| "f7"
| "f8"
| "f9"
| "f10"
| "f11"
| "f12"
| "f13"
| "f14"
| "f15"
| "f16"
| "f17"
| "f18"
| "f19"
| "backspace"
| "delete"
| "left"
| "right"
| "up"
| "down"
| "pageup"
| "pagedown"
| "insert"
| "home"
| "end"
| "escape"
)
}
impl std::fmt::Display for Keystroke {
@ -250,12 +276,12 @@ impl Modifiers {
pub fn secondary(&self) -> bool {
#[cfg(target_os = "macos")]
{
return self.platform;
self.platform
}
#[cfg(not(target_os = "macos"))]
{
return self.control;
self.control
}
}

View file

@ -76,7 +76,7 @@ fn generate_feature_array(features: &FontFeatures) -> CFMutableArrayRef {
for (tag, value) in features.tag_value_list() {
let keys = [kCTFontOpenTypeFeatureTag, kCTFontOpenTypeFeatureValue];
let values = [
CFString::new(&tag).as_CFTypeRef(),
CFString::new(tag).as_CFTypeRef(),
CFNumber::from(*value as i32).as_CFTypeRef(),
];
let dict = CFDictionaryCreate(

View file

@ -540,8 +540,6 @@ impl Platform for MacPlatform {
handle: AnyWindowHandle,
options: WindowParams,
) -> Result<Box<dyn PlatformWindow>> {
// Clippy thinks that this evaluates to `()`, for some reason.
#[allow(clippy::unit_arg, clippy::clone_on_copy)]
let renderer_context = self.0.lock().renderer_context.clone();
Ok(Box::new(MacWindow::open(
handle,

View file

@ -449,7 +449,7 @@ impl MacWindowState {
window_frame.origin.y =
screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
let bounds = Bounds::new(
Bounds::new(
point(
px((window_frame.origin.x - screen_frame.origin.x) as f32),
px((window_frame.origin.y + screen_frame.origin.y) as f32),
@ -458,8 +458,7 @@ impl MacWindowState {
px(window_frame.size.width as f32),
px(window_frame.size.height as f32),
),
);
bounds
)
}
fn content_size(&self) -> Size<Pixels> {
@ -537,7 +536,7 @@ impl MacWindow {
let display = display_id
.and_then(MacDisplay::find_by_id)
.unwrap_or_else(|| MacDisplay::primary());
.unwrap_or_else(MacDisplay::primary);
let mut target_screen = nil;
let mut screen_frame = None;
@ -1981,13 +1980,10 @@ fn send_to_input_handler(window: &Object, ime: ImeInput) {
}
window_state.lock().input_handler = Some(input_handler);
} else {
match ime {
ImeInput::InsertText(text, range) => {
if let Some(ime_input) = lock.last_ime_inputs.as_mut() {
ime_input.push((text, range));
}
if let ImeInput::InsertText(text, range) = ime {
if let Some(ime_input) = lock.last_ime_inputs.as_mut() {
ime_input.push((text, range));
}
_ => {}
}
}
}

View file

@ -145,7 +145,7 @@ impl TestPlatform {
}
pub(crate) fn did_prompt_for_new_path(&self) -> bool {
self.prompts.borrow().new_path.len() > 0
!self.prompts.borrow().new_path.is_empty()
}
}

View file

@ -592,9 +592,9 @@ impl TransformationMatrix {
pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
let input = [point.x.0, point.y.0];
let mut output = self.translation;
for i in 0..2 {
for k in 0..2 {
output[i] += self.rotation_scale[i][k] * input[k];
for (i, output_cell) in output.iter_mut().enumerate() {
for (k, input_cell) in input.iter().enumerate() {
*output_cell += self.rotation_scale[i][k] * *input_cell;
}
}
Point::new(output[0].into(), output[1].into())

View file

@ -52,7 +52,7 @@ impl ObjectFit {
let image_ratio = image_size.width / image_size.height;
let bounds_ratio = bounds.size.width / bounds.size.height;
let result_bounds = match self {
match self {
ObjectFit::Fill => bounds,
ObjectFit::Contain => {
let new_size = if bounds_ratio > image_ratio {
@ -136,9 +136,7 @@ impl ObjectFit {
origin: bounds.origin,
size: image_size,
},
};
result_bounds
}
}
}

View file

@ -46,7 +46,7 @@ impl SvgRenderer {
}
pub fn render_pixmap(&self, bytes: &[u8], size: SvgSize) -> Result<Pixmap, usvg::Error> {
let tree = usvg::Tree::from_data(&bytes, &usvg::Options::default())?;
let tree = usvg::Tree::from_data(bytes, &usvg::Options::default())?;
let size = match size {
SvgSize::Size(size) => size,

View file

@ -69,7 +69,7 @@ impl TaffyLayoutEngine {
.expect(EXPECT_MESSAGE)
.into();
self.children_to_parents
.extend(children.into_iter().map(|child_id| (*child_id, parent_id)));
.extend(children.iter().map(|child_id| (*child_id, parent_id)));
parent_id
};
self.styles.insert(layout_id, style);

View file

@ -11,7 +11,7 @@ pub struct FontFallbacks(pub Arc<Vec<String>>);
impl FontFallbacks {
/// Get the fallback fonts family names
pub fn fallback_list(&self) -> &[String] {
&self.0.as_slice()
self.0.as_slice()
}
/// Create a font fallback from a list of strings

View file

@ -10,7 +10,7 @@ impl FontFeatures {
/// Get the tag name list of the font OpenType features
/// only enabled or disabled features are returned
pub fn tag_value_list(&self) -> &[(String, u32)] {
&self.0.as_slice()
self.0.as_slice()
}
/// Returns whether the `calt` feature is enabled.
@ -134,11 +134,14 @@ impl schemars::JsonSchema for FontFeatures {
InstanceType::Object,
)));
{
let mut property = SchemaObject::default();
property.instance_type = Some(schemars::schema::SingleOrVec::Vec(vec![
InstanceType::Boolean,
InstanceType::Integer,
]));
let mut property = SchemaObject {
instance_type: Some(schemars::schema::SingleOrVec::Vec(vec![
InstanceType::Boolean,
InstanceType::Integer,
])),
..Default::default()
};
{
let mut number_constraints = property.number();
number_constraints.multiple_of = Some(1.0);

View file

@ -74,7 +74,7 @@ impl<'a> std::fmt::Debug for CwdBacktrace<'a> {
if frame
.symbols()
.iter()
.any(|s| s.filename().map_or(false, |f| f.starts_with(&cwd)))
.any(|s| s.filename().map_or(false, |f| f.starts_with(cwd)))
{
formatted_frame.backtrace_frame(frame)?;
}

View file

@ -3262,24 +3262,23 @@ impl<'a> WindowContext<'a> {
&& self.window.pending_modifier.modifiers.number_of_modifiers() == 1
&& !self.window.pending_modifier.saw_keystroke
{
if event.modifiers.number_of_modifiers() == 0 {
let key = match self.window.pending_modifier.modifiers {
modifiers if modifiers.shift => Some("shift"),
modifiers if modifiers.control => Some("control"),
modifiers if modifiers.alt => Some("alt"),
modifiers if modifiers.platform => Some("platform"),
modifiers if modifiers.function => Some("function"),
_ => None,
};
if let Some(key) = key {
keystroke = Some(Keystroke {
key: key.to_string(),
ime_key: None,
modifiers: Modifiers::default(),
});
}
let key = match self.window.pending_modifier.modifiers {
modifiers if modifiers.shift => Some("shift"),
modifiers if modifiers.control => Some("control"),
modifiers if modifiers.alt => Some("alt"),
modifiers if modifiers.platform => Some("platform"),
modifiers if modifiers.function => Some("function"),
_ => None,
};
if let Some(key) = key {
keystroke = Some(Keystroke {
key: key.to_string(),
ime_key: None,
modifiers: Modifiers::default(),
});
}
}
if self.window.pending_modifier.modifiers.number_of_modifiers() == 0
&& event.modifiers.number_of_modifiers() == 1
{

View file

@ -41,7 +41,7 @@ impl PromptHandle {
sender.send(e.0).ok();
cx.window.prompt.take();
if let Some(previous_focus) = &previous_focus {
cx.focus(&previous_focus);
cx.focus(previous_focus);
}
}
})