Fix clippy warnings (#2108)

* Fix clippy warnings

* review feedback.
This commit is contained in:
Lucas Kent 2022-01-01 13:00:11 +11:00 committed by GitHub
parent 438d286fd5
commit 0b39024133
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 105 additions and 127 deletions

View file

@ -43,7 +43,6 @@ fn main() {
..
} => {
*control_flow = ControlFlow::Exit;
return;
}
_ => (),
}

View file

@ -15,7 +15,7 @@ fn main() {
let mut num = String::new();
stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let num = num.trim().parse().expect("Please enter a number");
let fullscreen = Some(match num {
1 => Fullscreen::Exclusive(prompt_for_video_mode(&prompt_for_monitor(&event_loop))),
@ -85,7 +85,7 @@ fn prompt_for_monitor(event_loop: &EventLoop<()>) -> MonitorHandle {
let mut num = String::new();
stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let num = num.trim().parse().expect("Please enter a number");
let monitor = event_loop
.available_monitors()
.nth(num)
@ -106,7 +106,7 @@ fn prompt_for_video_mode(monitor: &MonitorHandle) -> VideoMode {
let mut num = String::new();
stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let num = num.trim().parse().expect("Please enter a number");
let video_mode = monitor
.video_modes()
.nth(num)

View file

@ -34,10 +34,10 @@ fn main() {
// We need to update our chosen video mode if the window
// was moved to an another monitor, so that the window
// appears on this monitor instead when we go fullscreen
let previous_video_mode = video_modes.iter().cloned().nth(video_mode_id);
let previous_video_mode = video_modes.get(video_mode_id).cloned();
video_modes = window.current_monitor().unwrap().video_modes().collect();
video_mode_id = video_mode_id.min(video_modes.len());
let video_mode = video_modes.iter().nth(video_mode_id);
let video_mode = video_modes.get(video_mode_id);
// Different monitors may support different video modes,
// and the index we chose previously may now point to a
@ -45,7 +45,7 @@ fn main() {
if video_mode != previous_video_mode.as_ref() {
println!(
"Window moved to another monitor, picked video mode: {}",
video_modes.iter().nth(video_mode_id).unwrap()
video_modes.get(video_mode_id).unwrap()
);
}
}
@ -77,16 +77,13 @@ fn main() {
Right => (video_modes.len() - 1).min(video_mode_id + 1),
_ => unreachable!(),
};
println!(
"Picking video mode: {}",
video_modes.iter().nth(video_mode_id).unwrap()
);
println!("Picking video mode: {}", video_modes[video_mode_id]);
}
F => window.set_fullscreen(match (state, modifiers.alt()) {
(true, false) => Some(Fullscreen::Borderless(None)),
(true, true) => Some(Fullscreen::Exclusive(
video_modes.iter().nth(video_mode_id).unwrap().clone(),
)),
(true, true) => {
Some(Fullscreen::Exclusive(video_modes[video_mode_id].clone()))
}
(false, _) => None,
}),
G => window.set_cursor_grab(state).unwrap(),
@ -173,7 +170,7 @@ fn main() {
}
}
},
_ => (),
_ => {}
}
})
}

View file

@ -41,7 +41,7 @@ fn main() {
},
..
} => {
let window = Window::new(&event_loop).unwrap();
let window = Window::new(event_loop).unwrap();
windows.insert(window.id(), window);
}
_ => (),

View file

@ -46,7 +46,6 @@ fn main() {
..
} => {
*control_flow = ControlFlow::Exit;
return;
}
_ => (),
}

View file

@ -118,9 +118,9 @@ impl fmt::Display for OsError {
#[cfg(feature = "x11")]
OsError::XError(ref e) => _f.pad(&e.description),
#[cfg(feature = "x11")]
OsError::XMisc(ref e) => _f.pad(e),
OsError::XMisc(e) => _f.pad(e),
#[cfg(feature = "wayland")]
OsError::WaylandMisc(ref e) => _f.pad(e),
OsError::WaylandMisc(e) => _f.pad(e),
}
}
}
@ -409,7 +409,7 @@ impl Window {
#[cfg(feature = "x11")]
Window::X(ref w) => w.set_always_on_top(_always_on_top),
#[cfg(feature = "wayland")]
_ => (),
Window::Wayland(_) => (),
}
}
@ -419,7 +419,7 @@ impl Window {
#[cfg(feature = "x11")]
Window::X(ref w) => w.set_window_icon(_window_icon),
#[cfg(feature = "wayland")]
_ => (),
Window::Wayland(_) => (),
}
}
@ -434,7 +434,7 @@ impl Window {
#[cfg(feature = "x11")]
Window::X(ref w) => w.focus_window(),
#[cfg(feature = "wayland")]
_ => (),
Window::Wayland(_) => (),
}
}
pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) {

View file

@ -536,12 +536,12 @@ impl<T: 'static> EventLoop<T> {
}
fn loop_dispatch<D: Into<Option<std::time::Duration>>>(&mut self, timeout: D) -> IOResult<()> {
let mut state = match &mut self.window_target.p {
let state = match &mut self.window_target.p {
PlatformEventLoopWindowTarget::Wayland(window_target) => window_target.state.get_mut(),
#[cfg(feature = "x11")]
_ => unreachable!(),
};
self.event_loop.dispatch(timeout, &mut state)
self.event_loop.dispatch(timeout, state)
}
}

View file

@ -45,7 +45,7 @@ impl<T: 'static> EventProcessor<T> {
let mut devices = self.devices.borrow_mut();
if let Some(info) = DeviceInfo::get(&wt.xconn, device) {
for info in info.iter() {
devices.insert(DeviceId(info.deviceid), Device::new(&self, info));
devices.insert(DeviceId(info.deviceid), Device::new(self, info));
}
}
}
@ -925,7 +925,7 @@ impl<T: 'static> EventProcessor<T> {
// Issue key press events for all pressed keys
Self::handle_pressed_keys(
&wt,
wt,
window_id,
ElementState::Pressed,
&self.mod_keymap,
@ -949,7 +949,7 @@ impl<T: 'static> EventProcessor<T> {
// Issue key release events for all pressed keys
Self::handle_pressed_keys(
&wt,
wt,
window_id,
ElementState::Released,
&self.mod_keymap,
@ -1220,11 +1220,8 @@ impl<T: 'static> EventProcessor<T> {
}
}
match self.ime_receiver.try_recv() {
Ok((window_id, x, y)) => {
wt.ime.borrow_mut().send_xim_spot(window_id, x, y);
}
Err(_) => (),
if let Ok((window_id, x, y)) = self.ime_receiver.try_recv() {
wt.ime.borrow_mut().send_xim_spot(window_id, x, y);
}
}

View file

@ -62,7 +62,7 @@ pub unsafe fn set_destroy_callback(
inner: &ImeInner,
) -> Result<(), XError> {
xim_set_callback(
&xconn,
xconn,
im,
ffi::XNDestroyCallback_0.as_ptr() as *const _,
&inner.destroy_callback as *const _ as *mut _,
@ -70,6 +70,7 @@ pub unsafe fn set_destroy_callback(
}
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum ReplaceImError {
MethodOpenFailed(PotentialInputMethods),
ContextCreationFailed(ImeContextCreationError),
@ -136,13 +137,17 @@ pub unsafe extern "C" fn xim_instantiate_callback(
let inner: *mut ImeInner = client_data as _;
if !inner.is_null() {
let xconn = &(*inner).xconn;
let result = replace_im(inner);
if result.is_ok() {
let _ = unset_instantiate_callback(xconn, client_data);
(*inner).is_fallback = false;
} else if result.is_err() && (*inner).is_destroyed {
// We have no usable input methods!
result.expect("Failed to reopen input method");
match replace_im(inner) {
Ok(()) => {
let _ = unset_instantiate_callback(xconn, client_data);
(*inner).is_fallback = false;
}
Err(err) => {
if (*inner).is_destroyed {
// We have no usable input methods!
panic!("Failed to reopen input method: {:?}", err);
}
}
}
}
}
@ -163,12 +168,12 @@ pub unsafe extern "C" fn xim_destroy_callback(
if !(*inner).is_fallback {
let _ = set_instantiate_callback(xconn, client_data);
// Attempt to open fallback input method.
let result = replace_im(inner);
if result.is_ok() {
(*inner).is_fallback = true;
} else {
// We have no usable input methods!
result.expect("Failed to open fallback input method");
match replace_im(inner) {
Ok(()) => (*inner).is_fallback = true,
Err(err) => {
// We have no usable input methods!
panic!("Failed to open fallback input method: {:?}", err);
}
}
}
}

View file

@ -58,7 +58,7 @@ impl ImeContext {
Ok(ImeContext {
ic,
ic_spot: ic_spot.unwrap_or_else(|| ffi::XPoint { x: 0, y: 0 }),
ic_spot: ic_spot.unwrap_or(ffi::XPoint { x: 0, y: 0 }),
})
}

View file

@ -58,10 +58,8 @@ impl ImeInner {
}
pub unsafe fn destroy_all_contexts_if_necessary(&self) -> Result<bool, XError> {
for context in self.contexts.values() {
if let &Some(ref context) = context {
self.destroy_ic_if_necessary(context.ic)?;
}
for context in self.contexts.values().flatten() {
self.destroy_ic_if_necessary(context.ic)?;
}
Ok(!self.is_destroyed)
}

View file

@ -63,11 +63,7 @@ pub enum InputMethodResult {
impl InputMethodResult {
pub fn is_fallback(&self) -> bool {
if let &InputMethodResult::Fallback(_) = self {
true
} else {
false
}
matches!(self, InputMethodResult::Fallback(_))
}
pub fn ok(self) -> Option<InputMethod> {
@ -249,7 +245,7 @@ impl PotentialInputMethods {
pub fn open_im(
&mut self,
xconn: &Arc<XConnection>,
callback: Option<&dyn Fn() -> ()>,
callback: Option<&dyn Fn()>,
) -> InputMethodResult {
use self::InputMethodResult::*;
@ -259,10 +255,8 @@ impl PotentialInputMethods {
let im = input_method.open_im(xconn);
if let Some(im) = im {
return XModifiers(im);
} else {
if let Some(ref callback) = callback {
callback();
}
} else if let Some(ref callback) = callback {
callback();
}
}

View file

@ -634,25 +634,22 @@ impl Device {
// Identify scroll axes
for class_ptr in Device::classes(info) {
let class = unsafe { &**class_ptr };
match class._type {
ffi::XIScrollClass => {
let info = unsafe {
mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIScrollClassInfo>(class)
};
scroll_axes.push((
info.number,
ScrollAxis {
increment: info.increment,
orientation: match info.scroll_type {
ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal,
ffi::XIScrollTypeVertical => ScrollOrientation::Vertical,
_ => unreachable!(),
},
position: 0.0,
if class._type == ffi::XIScrollClass {
let info = unsafe {
mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIScrollClassInfo>(class)
};
scroll_axes.push((
info.number,
ScrollAxis {
increment: info.increment,
orientation: match info.scroll_type {
ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal,
ffi::XIScrollTypeVertical => ScrollOrientation::Vertical,
_ => unreachable!(),
},
));
}
_ => {}
position: 0.0,
},
));
}
}
}
@ -670,20 +667,17 @@ impl Device {
if Device::physical_device(info) {
for class_ptr in Device::classes(info) {
let class = unsafe { &**class_ptr };
match class._type {
ffi::XIValuatorClass => {
let info = unsafe {
mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIValuatorClassInfo>(class)
};
if let Some(&mut (_, ref mut axis)) = self
.scroll_axes
.iter_mut()
.find(|&&mut (axis, _)| axis == info.number)
{
axis.position = info.value;
}
if class._type == ffi::XIValuatorClass {
let info = unsafe {
mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIValuatorClassInfo>(class)
};
if let Some(&mut (_, ref mut axis)) = self
.scroll_axes
.iter_mut()
.find(|&&mut (axis, _)| axis == info.number)
{
axis.position = info.value;
}
_ => {}
}
}
}

View file

@ -90,7 +90,7 @@ impl Eq for MonitorHandle {}
impl PartialOrd for MonitorHandle {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(&other))
Some(self.cmp(other))
}
}
@ -204,7 +204,7 @@ impl XConnection {
let overlapping_area = window_rect.get_overlapping_area(&monitor.rect);
if overlapping_area > largest_overlap {
largest_overlap = overlapping_area;
matched_monitor = &monitor;
matched_monitor = monitor;
}
}
@ -242,8 +242,11 @@ impl XConnection {
if is_active {
let is_primary = *(*crtc).outputs.offset(0) == primary;
has_primary |= is_primary;
MonitorHandle::new(self, resources, crtc_id, crtc, is_primary)
.map(|monitor_id| available.push(monitor_id));
if let Some(monitor_id) =
MonitorHandle::new(self, resources, crtc_id, crtc, is_primary)
{
available.push(monitor_id)
}
}
(self.xrandr.XRRFreeCrtcInfo)(crtc);
}

View file

@ -23,9 +23,9 @@ impl Format {
pub fn get_actual_size(&self) -> usize {
match self {
&Format::Char => mem::size_of::<c_char>(),
&Format::Short => mem::size_of::<c_short>(),
&Format::Long => mem::size_of::<c_long>(),
Format::Char => mem::size_of::<c_char>(),
Format::Short => mem::size_of::<c_short>(),
Format::Long => mem::size_of::<c_long>(),
}
}
}

View file

@ -248,7 +248,7 @@ impl XConnection {
);
// The list of children isn't used
if children != ptr::null_mut() {
if !children.is_null() {
(self.xlib.XFree)(children as *mut _);
}

View file

@ -27,7 +27,7 @@ impl Icon {
data.push(rgba_icon.height as Cardinal);
let pixels = rgba_icon.rgba.as_ptr() as *const Pixel;
for pixel_index in 0..pixel_count {
let pixel = unsafe { &*pixels.offset(pixel_index as isize) };
let pixel = unsafe { &*pixels.add(pixel_index) };
data.push(pixel.to_packed_argb());
}
data

View file

@ -36,7 +36,7 @@ impl Iterator for KeymapIter<'_> {
fn next(&mut self) -> Option<ffi::KeyCode> {
if self.item.is_none() {
while let Some((index, &item)) = self.iter.next() {
for (index, &item) in self.iter.by_ref() {
if item != 0 {
self.index = index;
self.item = Some(item);

View file

@ -151,7 +151,7 @@ impl ModifierKeyState {
pub fn key_release(&mut self, keycode: ffi::KeyCode) {
if let Some(modifier) = self.keys.remove(&keycode) {
if self.keys.values().find(|&&m| m == modifier).is_none() {
if !self.keys.values().any(|&m| m == modifier) {
set_modifier(&mut self.state, modifier, false);
}
}

View file

@ -39,15 +39,15 @@ impl XConnection {
pub unsafe fn get_xft_dpi(&self) -> Option<f64> {
(self.xlib.XrmInitialize)();
let resource_manager_str = (self.xlib.XResourceManagerString)(self.display);
if resource_manager_str == ptr::null_mut() {
if resource_manager_str.is_null() {
return None;
}
if let Ok(res) = ::std::ffi::CStr::from_ptr(resource_manager_str).to_str() {
let name: &str = "Xft.dpi:\t";
for pair in res.split("\n") {
for pair in res.split('\n') {
if pair.starts_with(&name) {
let res = &pair[name.len()..];
return f64::from_str(&res).ok();
return f64::from_str(res).ok();
}
}
}

View file

@ -97,7 +97,7 @@ impl XConnection {
quantity_returned,
new_data,
);*/
data.extend_from_slice(&new_data);
data.extend_from_slice(new_data);
// Fun fact: XGetWindowProperty allocates one extra byte at the end.
(self.xlib.XFree)(buf as _); // Don't try to access new_data after this.
} else {

View file

@ -62,11 +62,7 @@ impl XConnection {
let wm_check = result.ok().and_then(|wm_check| wm_check.get(0).cloned());
if let Some(wm_check) = wm_check {
wm_check
} else {
return None;
}
wm_check?
};
// Querying the same property on the child window we were given, we should get this child
@ -76,11 +72,7 @@ impl XConnection {
let wm_check = result.ok().and_then(|wm_check| wm_check.get(0).cloned());
if let Some(wm_check) = wm_check {
wm_check
} else {
return None;
}
wm_check?
};
// These values should be the same.

View file

@ -150,7 +150,7 @@ impl UnownedWindow {
let position = window_attrs
.position
.map(|position| position.to_physical::<i32>(scale_factor).into());
.map(|position| position.to_physical::<i32>(scale_factor));
let dimensions = {
// x11 only applies constraints when the window is actively resized
@ -184,7 +184,7 @@ impl UnownedWindow {
// creating
let (visual, depth, require_colormap) = match pl_attribs.visual_infos {
Some(vi) => (vi.visual, vi.depth, false),
None if window_attrs.transparent == true => {
None if window_attrs.transparent => {
// Find a suitable visual
let mut vinfo = MaybeUninit::uninit();
let vinfo_initialized = unsafe {
@ -341,7 +341,9 @@ impl UnownedWindow {
} //.queue();
}
window.set_pid().map(|flusher| flusher.queue());
if let Some(flusher) = window.set_pid() {
flusher.queue()
}
window.set_window_types(pl_attribs.x11_window_types).queue();
@ -430,8 +432,7 @@ impl UnownedWindow {
}
// Select XInput2 events
let mask = {
let mask = ffi::XI_MotionMask
let mask = ffi::XI_MotionMask
| ffi::XI_ButtonPressMask
| ffi::XI_ButtonReleaseMask
//| ffi::XI_KeyPressMask
@ -443,8 +444,6 @@ impl UnownedWindow {
| ffi::XI_TouchBeginMask
| ffi::XI_TouchUpdateMask
| ffi::XI_TouchEndMask;
mask
};
xconn
.select_xinput_events(window.xwindow, ffi::XIAllMasterDevices, mask)
.queue();
@ -467,9 +466,10 @@ impl UnownedWindow {
window.set_maximized_inner(window_attrs.maximized).queue();
}
if window_attrs.fullscreen.is_some() {
window
.set_fullscreen_inner(window_attrs.fullscreen.clone())
.map(|flusher| flusher.queue());
if let Some(flusher) = window.set_fullscreen_inner(window_attrs.fullscreen.clone())
{
flusher.queue()
}
if let Some(PhysicalPosition { x, y }) = position {
let shared_state = window.shared_state.get_mut();