Run clippy on CI

Fixes #1402.
This commit is contained in:
Kirill Chibisov 2022-06-10 13:43:33 +03:00 committed by GitHub
parent 57981b533d
commit 10419ff441
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
72 changed files with 377 additions and 312 deletions

View file

@ -17,7 +17,8 @@ jobs:
- name: Check Formatting
run: cargo +stable fmt --all -- --check
Tests:
tests:
name: Tests
strategy:
fail-fast: false
matrix:
@ -62,6 +63,7 @@ jobs:
with:
rust-version: ${{ matrix.rust_version }}${{ matrix.platform.host }}
targets: ${{ matrix.platform.target }}
components: clippy
- name: Install Linux dependencies
if: (matrix.platform.os == 'ubuntu-latest')
@ -93,6 +95,10 @@ jobs:
!contains(matrix.platform.target, 'wasm32'))
run: cargo $CMD test --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
- name: Lint with clippy
shell: bash
if: (matrix.rust_version != 'nightly') && !contains(matrix.platform.options, '--no-default-features')
run: cargo clippy --all-targets --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES -- -Dwarnings
- name: Build with serde enabled
shell: bash

View file

@ -53,6 +53,8 @@ And please only add new entries to the top of this list, right below the `# Unre
- **Breaking:** IME input on desktop platforms won't be received unless it's explicitly allowed via `Window::set_ime_allowed` and new `WindowEvent::Ime` events are handled.
- On macOS, `WindowEvent::Resized` is now emitted in `frameDidChange` instead of `windowDidResize`.
- **Breaking:** On X11, device events are now ignored for unfocused windows by default, use `EventLoopWindowTarget::set_device_event_filter` to set the filter level.
- Implemented `Default` on `EventLoop<()>`.
- Implemented `Eq` for `Fullscreen`, `Theme`, and `UserAttentionType`.
# 0.26.1 (2022-01-05)

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use std::{thread, time};
use simple_logger::SimpleLogger;

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{ElementState, Event, KeyboardInput, WindowEvent},

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{DeviceEvent, ElementState, Event, KeyboardInput, ModifiersState, WindowEvent},

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
#[cfg(not(target_arch = "wasm32"))]
fn main() {
use simple_logger::SimpleLogger;

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use std::io::{stdin, stdout, Write};
use simple_logger::SimpleLogger;

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{Event, KeyboardInput, WindowEvent},

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use log::LevelFilter;
use simple_logger::SimpleLogger;
use winit::{

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
dpi::LogicalSize,

View file

@ -1,4 +1,4 @@
extern crate winit;
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::event::{Event, VirtualKeyCode, WindowEvent};

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{event_loop::EventLoop, window::WindowBuilder};

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
#[cfg(not(target_arch = "wasm32"))]
fn main() {
use std::{collections::HashMap, sync::mpsc, thread, time::Duration};

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use std::collections::HashMap;
use simple_logger::SimpleLogger;

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{ElementState, Event, WindowEvent},

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
#[cfg(not(target_arch = "wasm32"))]
fn main() {
use std::{thread, time};
@ -28,10 +30,10 @@ fn main() {
control_flow.set_wait();
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => control_flow.set_exit(),
_ => (),
},
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => control_flow.set_exit(),
Event::RedrawRequested(_) => {
println!("\nredrawing!\n");
}

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
dpi::LogicalSize,

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use instant::Instant;
use std::time::Duration;

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::event_loop::EventLoop;

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use winit::{
event::{Event, WindowEvent},
event_loop::EventLoop,
@ -43,6 +45,7 @@ mod wasm {
pub fn run() {
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
#[allow(clippy::main_recursion)]
super::main();
}

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
// This example is used by developers to test various window functions.
use simple_logger::SimpleLogger;
@ -58,13 +60,17 @@ fn main() {
_ => (),
},
Event::WindowEvent {
event: WindowEvent::KeyboardInput { input, .. },
..
} => match input {
event:
WindowEvent::KeyboardInput {
input:
KeyboardInput {
virtual_keycode: Some(key),
state: ElementState::Pressed,
..
},
..
},
..
} => match key {
VirtualKeyCode::E => {
fn area(size: PhysicalSize<u32>) -> u32 {
@ -113,8 +119,6 @@ fn main() {
}
_ => (),
},
_ => (),
},
Event::WindowEvent {
event: WindowEvent::CloseRequested,
window_id,

View file

@ -1,4 +1,5 @@
extern crate image;
#![allow(clippy::single_match)]
use std::path::Path;
use simple_logger::SimpleLogger;

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
// Limit this example to only compatible platforms.
#[cfg(any(
target_os = "windows",

View file

@ -94,6 +94,8 @@ impl<T> EventLoopBuilder<T> {
/// will fall back on X11. If this variable is set with any other value, winit will panic.
#[inline]
pub fn build(&mut self) -> EventLoop<T> {
// Certain platforms accept a mutable reference in their API.
#[allow(clippy::unnecessary_mut_passed)]
EventLoop {
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific),
_marker: PhantomData,
@ -221,6 +223,12 @@ impl EventLoop<()> {
}
}
impl Default for EventLoop<()> {
fn default() -> Self {
Self::new()
}
}
impl<T> EventLoop<T> {
#[deprecated = "Use `EventLoopBuilder::<T>::with_user_event().build()` instead."]
pub fn with_user_event() -> EventLoop<T> {

View file

@ -132,6 +132,9 @@
#![deny(rust_2018_idioms)]
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(clippy::all)]
#![cfg_attr(feature = "cargo-clippy", deny(warnings))]
#![allow(clippy::missing_safety_doc)]
#[allow(unused_imports)]
#[macro_use]

View file

@ -240,7 +240,7 @@ pub struct EventLoop<T: 'static> {
running: bool,
}
#[derive(Default, Debug, Copy, Clone, PartialEq, Hash)]
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes {}
macro_rules! call_event_handler {
@ -846,18 +846,16 @@ impl MonitorHandle {
pub fn video_modes(&self) -> impl Iterator<Item = monitor::VideoMode> {
let size = self.size().into();
let mut v = Vec::new();
// FIXME this is not the real refresh rate
// (it is guarunteed to support 32 bit color though)
v.push(monitor::VideoMode {
// (it is guaranteed to support 32 bit color though)
std::iter::once(monitor::VideoMode {
video_mode: VideoMode {
size,
bit_depth: 32,
refresh_rate: 60,
monitor: self.clone(),
},
});
v.into_iter()
})
}
}

View file

@ -53,11 +53,7 @@ enum UserCallbackTransitionResult<'a> {
impl Event<'static, Never> {
fn is_redraw(&self) -> bool {
if let Event::RedrawRequested(_) = self {
true
} else {
false
}
matches!(self, Event::RedrawRequested(_))
}
}
@ -120,7 +116,7 @@ impl Drop for AppState {
} => {
for &mut window in queued_windows {
unsafe {
let () = msg_send![window, release];
let _: () = msg_send![window, release];
}
}
}
@ -201,10 +197,10 @@ impl AppState {
}
fn has_launched(&self) -> bool {
match self.state() {
&AppStateImpl::NotLaunched { .. } | &AppStateImpl::Launching { .. } => false,
_ => true,
}
!matches!(
self.state(),
AppStateImpl::NotLaunched { .. } | AppStateImpl::Launching { .. }
)
}
fn will_launch_transition(&mut self, queued_event_handler: Box<dyn EventHandler>) {
@ -529,7 +525,9 @@ pub unsafe fn queue_gl_or_metal_redraw(window: id) {
| &mut AppStateImpl::InUserCallback {
ref mut queued_gpu_redraws,
..
} => drop(queued_gpu_redraws.insert(window)),
} => {
let _ = queued_gpu_redraws.insert(window);
}
s @ &mut AppStateImpl::ProcessingRedraws { .. }
| s @ &mut AppStateImpl::Waiting { .. }
| s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s),
@ -537,6 +535,7 @@ pub unsafe fn queue_gl_or_metal_redraw(window: id) {
panic!("Attempt to create a `Window` after the app has terminated")
}
}
drop(this);
}
@ -549,7 +548,7 @@ pub unsafe fn will_launch(queued_event_handler: Box<dyn EventHandler>) {
pub unsafe fn did_finish_launching() {
let mut this = AppState::get_mut();
let windows = match this.state_mut() {
AppStateImpl::Launching { queued_windows, .. } => mem::replace(queued_windows, Vec::new()),
AppStateImpl::Launching { queued_windows, .. } => mem::take(queued_windows),
s => bug!("unexpected state {:?}", s),
};
@ -579,15 +578,15 @@ pub unsafe fn did_finish_launching() {
// ```
let screen: id = msg_send![window, screen];
let _: id = msg_send![screen, retain];
let () = msg_send![window, setScreen:0 as id];
let () = msg_send![window, setScreen: screen];
let () = msg_send![screen, release];
let _: () = msg_send![window, setScreen:0 as id];
let _: () = msg_send![window, setScreen: screen];
let _: () = msg_send![screen, release];
let controller: id = msg_send![window, rootViewController];
let () = msg_send![window, setRootViewController:ptr::null::<()>()];
let () = msg_send![window, setRootViewController: controller];
let () = msg_send![window, makeKeyAndVisible];
let _: () = msg_send![window, setRootViewController:ptr::null::<()>()];
let _: () = msg_send![window, setRootViewController: controller];
let _: () = msg_send![window, makeKeyAndVisible];
}
let () = msg_send![window, release];
let _: () = msg_send![window, release];
}
let (windows, events) = AppState::get_mut().did_finish_launching_transition();
@ -604,9 +603,9 @@ pub unsafe fn did_finish_launching() {
let count: NSUInteger = msg_send![window, retainCount];
// make sure the window is still referenced
if count > 1 {
let () = msg_send![window, makeKeyAndVisible];
let _: () = msg_send![window, makeKeyAndVisible];
}
let () = msg_send![window, release];
let _: () = msg_send![window, release];
}
}
@ -671,7 +670,7 @@ pub unsafe fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(events
&mut AppStateImpl::InUserCallback {
ref mut queued_events,
queued_gpu_redraws: _,
} => mem::replace(queued_events, Vec::new()),
} => mem::take(queued_events),
s => bug!("unexpected state {:?}", s),
};
if queued_events.is_empty() {
@ -752,7 +751,7 @@ unsafe fn handle_user_events() {
&mut AppStateImpl::InUserCallback {
ref mut queued_events,
queued_gpu_redraws: _,
} => mem::replace(queued_events, Vec::new()),
} => mem::take(queued_events),
s => bug!("unexpected state {:?}", s),
};
if queued_events.is_empty() {
@ -876,7 +875,7 @@ fn handle_hidpi_proxy(
let size = CGSize::new(logical_size);
let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
unsafe {
let () = msg_send![view, setFrame: new_frame];
let _: () = msg_send![view, setFrame: new_frame];
}
}

View file

@ -69,7 +69,7 @@ pub struct EventLoop<T: 'static> {
window_target: RootEventLoopWindowTarget<T>,
}
#[derive(Default, Debug, Copy, Clone, PartialEq, Hash)]
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes {}
impl<T: 'static> EventLoop<T> {

View file

@ -88,7 +88,7 @@ pub enum UITouchPhase {
Cancelled,
}
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq)]
#[allow(dead_code)]
#[repr(isize)]
pub enum UIForceTouchCapability {
@ -97,7 +97,7 @@ pub enum UIForceTouchCapability {
Available,
}
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq)]
#[allow(dead_code)]
#[repr(isize)]
pub enum UITouchType {
@ -144,10 +144,9 @@ impl From<Idiom> for UIUserInterfaceIdiom {
}
}
}
impl Into<Idiom> for UIUserInterfaceIdiom {
fn into(self) -> Idiom {
match self {
impl From<UIUserInterfaceIdiom> for Idiom {
fn from(ui_idiom: UIUserInterfaceIdiom) -> Idiom {
match ui_idiom {
UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified,
UIUserInterfaceIdiom::Phone => Idiom::Phone,
UIUserInterfaceIdiom::Pad => Idiom::Pad,
@ -230,9 +229,9 @@ impl From<ScreenEdge> for UIRectEdge {
}
}
impl Into<ScreenEdge> for UIRectEdge {
fn into(self) -> ScreenEdge {
let bits: u8 = self.0.try_into().expect("invalid `UIRectEdge`");
impl From<UIRectEdge> for ScreenEdge {
fn from(ui_rect_edge: UIRectEdge) -> ScreenEdge {
let bits: u8 = ui_rect_edge.0.try_into().expect("invalid `UIRectEdge`");
ScreenEdge::from_bits(bits).expect("invalid `ScreenEdge`")
}
}

View file

@ -56,6 +56,7 @@
//! Also note that app may not receive the LoopDestroyed event if suspended; it might be SIGKILL'ed.
#![cfg(target_os = "ios")]
#![allow(clippy::let_unit_value)]
// TODO: (mtak-) UIKit requires main thread for virtually all function/method calls. This could be
// worked around in the future by using GCD (grand central dispatch) and/or caching of values like
@ -108,9 +109,7 @@ unsafe impl Sync for DeviceId {}
pub enum OsError {}
impl fmt::Display for OsError {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
_ => unreachable!(),
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "os error")
}
}

View file

@ -30,7 +30,7 @@ unsafe impl Send for NativeDisplayMode {}
impl Drop for NativeDisplayMode {
fn drop(&mut self) {
unsafe {
let () = msg_send![self.0, release];
let _: () = msg_send![self.0, release];
}
}
}
@ -115,7 +115,7 @@ pub struct Inner {
impl Drop for Inner {
fn drop(&mut self) {
unsafe {
let () = msg_send![self.uiscreen, release];
let _: () = msg_send![self.uiscreen, release];
}
}
}
@ -193,7 +193,7 @@ impl MonitorHandle {
pub fn retained_new(uiscreen: id) -> MonitorHandle {
unsafe {
assert_main_thread!("`MonitorHandle` can only be cloned on the main thread on iOS");
let () = msg_send![uiscreen, retain];
let _: () = msg_send![uiscreen, retain];
}
MonitorHandle {
inner: Inner { uiscreen },

View file

@ -112,14 +112,14 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
))),
);
let superclass: &'static Class = msg_send![object, superclass];
let () = msg_send![super(object, superclass), drawRect: rect];
let _: () = msg_send![super(object, superclass), drawRect: rect];
}
}
extern "C" fn layout_subviews(object: &Object, _: Sel) {
unsafe {
let superclass: &'static Class = msg_send![object, superclass];
let () = msg_send![super(object, superclass), layoutSubviews];
let _: () = msg_send![super(object, superclass), layoutSubviews];
let window: id = msg_send![object, window];
assert!(!window.is_null());
@ -133,14 +133,14 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
width: screen_frame.size.width as f64,
height: screen_frame.size.height as f64,
}
.to_physical(scale_factor.into());
.to_physical(scale_factor as f64);
// If the app is started in landscape, the view frame and window bounds can be mismatched.
// The view frame will be in portrait and the window bounds in landscape. So apply the
// window bounds to the view frame to make it consistent.
let view_frame: CGRect = msg_send![object, frame];
if view_frame != window_bounds {
let () = msg_send![object, setFrame: window_bounds];
let _: () = msg_send![object, setFrame: window_bounds];
}
app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent {
@ -157,7 +157,7 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
) {
unsafe {
let superclass: &'static Class = msg_send![object, superclass];
let () = msg_send![
let _: () = msg_send![
super(object, superclass),
setContentScaleFactor: untrusted_scale_factor
];
@ -180,7 +180,7 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
&& scale_factor > 0.0,
"invalid scale_factor set on UIView",
);
let scale_factor: f64 = scale_factor.into();
let scale_factor = scale_factor as f64;
let bounds: CGRect = msg_send![object, bounds];
let screen: id = msg_send![window, screen];
let screen_space: id = msg_send![screen, coordinateSpace];
@ -340,7 +340,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
prefers_status_bar_hidden: BOOL,
setPrefersStatusBarHidden: |object| {
unsafe {
let () = msg_send![object, setNeedsStatusBarAppearanceUpdate];
let _: () = msg_send![object, setNeedsStatusBarAppearanceUpdate];
}
},
prefersStatusBarHidden,
@ -353,7 +353,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
OSCapabilities::home_indicator_hidden_err_msg;
|object| {
unsafe {
let () = msg_send![object, setNeedsUpdateOfHomeIndicatorAutoHidden];
let _: () = msg_send![object, setNeedsUpdateOfHomeIndicatorAutoHidden];
}
},
prefersHomeIndicatorAutoHidden,
@ -363,7 +363,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
supported_orientations: UIInterfaceOrientationMask,
setSupportedInterfaceOrientations: |object| {
unsafe {
let () = msg_send![class!(UIViewController), attemptRotationToDeviceOrientation];
let _: () = msg_send![class!(UIViewController), attemptRotationToDeviceOrientation];
}
},
supportedInterfaceOrientations,
@ -376,7 +376,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
OSCapabilities::defer_system_gestures_err_msg;
|object| {
unsafe {
let () = msg_send![object, setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
let _: () = msg_send![object, setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
}
},
preferredScreenEdgesDeferringSystemGestures,
@ -398,7 +398,7 @@ unsafe fn get_window_class() -> &'static Class {
window_id: RootWindowId(object.into()),
event: WindowEvent::Focused(true),
}));
let () = msg_send![super(object, class!(UIWindow)), becomeKeyWindow];
let _: () = msg_send![super(object, class!(UIWindow)), becomeKeyWindow];
}
}
@ -408,7 +408,7 @@ unsafe fn get_window_class() -> &'static Class {
window_id: RootWindowId(object.into()),
event: WindowEvent::Focused(false),
}));
let () = msg_send![super(object, class!(UIWindow)), resignKeyWindow];
let _: () = msg_send![super(object, class!(UIWindow)), resignKeyWindow];
}
}
@ -440,9 +440,9 @@ pub unsafe fn create_view(
assert!(!view.is_null(), "Failed to create `UIView` instance");
let view: id = msg_send![view, initWithFrame: frame];
assert!(!view.is_null(), "Failed to initialize `UIView` instance");
let () = msg_send![view, setMultipleTouchEnabled: YES];
let _: () = msg_send![view, setMultipleTouchEnabled: YES];
if let Some(scale_factor) = platform_attributes.scale_factor {
let () = msg_send![view, setContentScaleFactor: scale_factor as CGFloat];
let _: () = msg_send![view, setContentScaleFactor: scale_factor as CGFloat];
}
view
@ -484,23 +484,23 @@ pub unsafe fn create_view_controller(
let edges: UIRectEdge = platform_attributes
.preferred_screen_edges_deferring_system_gestures
.into();
let () = msg_send![
let _: () = msg_send![
view_controller,
setPrefersStatusBarHidden: status_bar_hidden
];
let () = msg_send![
let _: () = msg_send![
view_controller,
setSupportedInterfaceOrientations: supported_orientations
];
let () = msg_send![
let _: () = msg_send![
view_controller,
setPrefersHomeIndicatorAutoHidden: prefers_home_indicator_hidden
];
let () = msg_send![
let _: () = msg_send![
view_controller,
setPreferredScreenEdgesDeferringSystemGestures: edges
];
let () = msg_send![view_controller, setView: view];
let _: () = msg_send![view_controller, setView: view];
view_controller
}
@ -520,11 +520,11 @@ pub unsafe fn create_window(
!window.is_null(),
"Failed to initialize `UIWindow` instance"
);
let () = msg_send![window, setRootViewController: view_controller];
let _: () = msg_send![window, setRootViewController: view_controller];
match window_attributes.fullscreen {
Some(Fullscreen::Exclusive(ref video_mode)) => {
let uiscreen = video_mode.monitor().ui_screen() as id;
let () = msg_send![uiscreen, setCurrentMode: video_mode.video_mode.screen_mode.0];
let _: () = msg_send![uiscreen, setCurrentMode: video_mode.video_mode.screen_mode.0];
msg_send![window, setScreen:video_mode.monitor().ui_screen()]
}
Some(Fullscreen::Borderless(ref monitor)) => {

View file

@ -37,9 +37,9 @@ pub struct Inner {
impl Drop for Inner {
fn drop(&mut self) {
unsafe {
let () = msg_send![self.view, release];
let () = msg_send![self.view_controller, release];
let () = msg_send![self.window, release];
let _: () = msg_send![self.view, release];
let _: () = msg_send![self.view_controller, release];
let _: () = msg_send![self.window, release];
}
}
}
@ -52,10 +52,10 @@ impl Inner {
pub fn set_visible(&self, visible: bool) {
match visible {
true => unsafe {
let () = msg_send![self.window, setHidden: NO];
let _: () = msg_send![self.window, setHidden: NO];
},
false => unsafe {
let () = msg_send![self.window, setHidden: YES];
let _: () = msg_send![self.window, setHidden: YES];
},
}
}
@ -78,7 +78,7 @@ impl Inner {
// https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay?language=objc
app_state::queue_gl_or_metal_redraw(self.window);
} else {
let () = msg_send![self.view, setNeedsDisplay];
let _: () = msg_send![self.view, setNeedsDisplay];
}
}
}
@ -119,8 +119,8 @@ impl Inner {
},
size: screen_frame.size,
};
let bounds = self.from_screen_space(new_screen_frame);
let () = msg_send![self.window, setBounds: bounds];
let bounds = self.rect_from_screen_space(new_screen_frame);
let _: () = msg_send![self.window, setBounds: bounds];
}
}
@ -218,7 +218,7 @@ impl Inner {
let uiscreen = match monitor {
Some(Fullscreen::Exclusive(video_mode)) => {
let uiscreen = video_mode.video_mode.monitor.ui_screen() as id;
let () =
let _: () =
msg_send![uiscreen, setCurrentMode: video_mode.video_mode.screen_mode.0];
uiscreen
}
@ -234,16 +234,16 @@ impl Inner {
// this is pretty slow on iOS, so avoid doing it if we can
let current: id = msg_send![self.window, screen];
if uiscreen != current {
let () = msg_send![self.window, setScreen: uiscreen];
let _: () = msg_send![self.window, setScreen: uiscreen];
}
let bounds: CGRect = msg_send![uiscreen, bounds];
let () = msg_send![self.window, setFrame: bounds];
let _: () = msg_send![self.window, setFrame: bounds];
// For external displays, we must disable overscan compensation or
// the displayed image will have giant black bars surrounding it on
// each side
let () = msg_send![
let _: () = msg_send![
uiscreen,
setOverscanCompensation: UIScreenOverscanCompensation::None
];
@ -380,10 +380,10 @@ impl Window {
window_attributes: WindowAttributes,
platform_attributes: PlatformSpecificWindowBuilderAttributes,
) -> Result<Window, RootOsError> {
if let Some(_) = window_attributes.min_inner_size {
if window_attributes.min_inner_size.is_some() {
warn!("`WindowAttributes::min_inner_size` is ignored on iOS");
}
if let Some(_) = window_attributes.max_inner_size {
if window_attributes.max_inner_size.is_some() {
warn!("`WindowAttributes::max_inner_size` is ignored on iOS");
}
if window_attributes.always_on_top {
@ -419,7 +419,7 @@ impl Window {
None => screen_bounds,
};
let view = view::create_view(&window_attributes, &platform_attributes, frame.clone());
let view = view::create_view(&window_attributes, &platform_attributes, frame);
let gl_or_metal_backed = {
let view_class: id = msg_send![view, class];
@ -452,7 +452,7 @@ impl Window {
// Like the Windows and macOS backends, we send a `ScaleFactorChanged` and `Resized`
// event on window creation if the DPI factor != 1.0
let scale_factor: CGFloat = msg_send![view, contentScaleFactor];
let scale_factor: f64 = scale_factor.into();
let scale_factor = scale_factor as f64;
if scale_factor != 1.0 {
let bounds: CGRect = msg_send![view, bounds];
let screen: id = msg_send![window, screen];
@ -502,7 +502,7 @@ impl Inner {
"`WindowExtIOS::set_scale_factor` received an invalid hidpi factor"
);
let scale_factor = scale_factor as CGFloat;
let () = msg_send![self.view, setContentScaleFactor: scale_factor];
let _: () = msg_send![self.view, setContentScaleFactor: scale_factor];
}
}
@ -523,7 +523,7 @@ impl Inner {
pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) {
unsafe {
let prefers_home_indicator_hidden = if hidden { YES } else { NO };
let () = msg_send![
let _: () = msg_send![
self.view_controller,
setPrefersHomeIndicatorAutoHidden: prefers_home_indicator_hidden
];
@ -533,7 +533,7 @@ impl Inner {
pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) {
let edges: UIRectEdge = edges.into();
unsafe {
let () = msg_send![
let _: () = msg_send![
self.view_controller,
setPreferredScreenEdgesDeferringSystemGestures: edges
];
@ -543,7 +543,7 @@ impl Inner {
pub fn set_prefers_status_bar_hidden(&self, hidden: bool) {
unsafe {
let status_bar_hidden = if hidden { YES } else { NO };
let () = msg_send![
let _: () = msg_send![
self.view_controller,
setPrefersStatusBarHidden: status_bar_hidden
];
@ -554,11 +554,11 @@ impl Inner {
impl Inner {
// requires main thread
unsafe fn screen_frame(&self) -> CGRect {
self.to_screen_space(msg_send![self.window, bounds])
self.rect_to_screen_space(msg_send![self.window, bounds])
}
// requires main thread
unsafe fn to_screen_space(&self, rect: CGRect) -> CGRect {
unsafe fn rect_to_screen_space(&self, rect: CGRect) -> CGRect {
let screen: id = msg_send![self.window, screen];
if !screen.is_null() {
let screen_space: id = msg_send![screen, coordinateSpace];
@ -569,7 +569,7 @@ impl Inner {
}
// requires main thread
unsafe fn from_screen_space(&self, rect: CGRect) -> CGRect {
unsafe fn rect_from_screen_space(&self, rect: CGRect) -> CGRect {
let screen: id = msg_send![self.window, screen];
if !screen.is_null() {
let screen_space: id = msg_send![screen, coordinateSpace];
@ -594,9 +594,9 @@ impl Inner {
height: bounds.size.height - safe_area.top - safe_area.bottom,
},
};
self.to_screen_space(safe_bounds)
self.rect_to_screen_space(safe_bounds)
} else {
let screen_frame = self.to_screen_space(bounds);
let screen_frame = self.rect_to_screen_space(bounds);
let status_bar_frame: CGRect = {
let app: id = msg_send![class!(UIApplication), sharedApplication];
assert!(

View file

@ -56,7 +56,7 @@ pub mod x11;
/// If this variable is set with any other value, winit will panic.
const BACKEND_PREFERENCE_ENV_VAR: &str = "WINIT_UNIX_BACKEND";
#[derive(Debug, Copy, Clone, PartialEq, Hash)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Backend {
#[cfg(feature = "x11")]
X,
@ -64,22 +64,13 @@ pub(crate) enum Backend {
Wayland,
}
#[derive(Debug, Copy, Clone, PartialEq, Hash)]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes {
pub(crate) forced_backend: Option<Backend>,
pub(crate) any_thread: bool,
}
impl Default for PlatformSpecificEventLoopAttributes {
fn default() -> Self {
Self {
forced_backend: None,
any_thread: false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApplicationName {
pub general: String,
pub instance: String,

View file

@ -175,7 +175,7 @@ impl MonitorHandle {
#[inline]
pub fn video_modes(&self) -> impl Iterator<Item = RootVideoMode> {
let modes = sctk::output::with_output_info(&self.proxy, |info| info.modes.clone())
.unwrap_or_else(Vec::new);
.unwrap_or_default();
let monitor = self.clone();

View file

@ -300,17 +300,17 @@ pub(super) fn handle_pointer(
#[inline]
pub(super) fn handle_relative_pointer(event: RelativePointerEvent, winit_state: &mut WinitState) {
match event {
RelativePointerEvent::RelativeMotion {
if let RelativePointerEvent::RelativeMotion {
dx_unaccel,
dy_unaccel,
..
} => winit_state.event_sink.push_device_event(
} = event
{
winit_state.event_sink.push_device_event(
DeviceEvent::MouseMotion {
delta: (dx_unaccel, dy_unaccel),
},
DeviceId,
),
_ => (),
)
}
}

View file

@ -243,7 +243,7 @@ pub(super) fn init_relative_pointer(
relative_pointer_manager: &ZwpRelativePointerManagerV1,
pointer: &WlPointer,
) -> ZwpRelativePointerV1 {
let relative_pointer = relative_pointer_manager.get_relative_pointer(&*pointer);
let relative_pointer = relative_pointer_manager.get_relative_pointer(pointer);
relative_pointer.quick_assign(move |_, event, mut dispatch_data| {
let winit_state = dispatch_data.get::<WinitState>().unwrap();
handlers::handle_relative_pointer(event, winit_state);

View file

@ -406,7 +406,8 @@ pub fn handle_window_requests(winit_state: &mut WinitState) {
// Process the rest of the events.
for (window_id, window_handle) in window_map.iter_mut() {
let mut requests = window_handle.pending_window_requests.lock().unwrap();
for request in requests.drain(..) {
let requests = requests.drain(..);
for request in requests {
match request {
WindowRequest::Fullscreen(fullscreen) => {
window_handle.window.set_fullscreen(fullscreen.as_ref());

View file

@ -414,7 +414,7 @@ impl<T: 'static> EventProcessor<T> {
// resizing by dragging across monitors *without* dropping the window.
let (width, height) = shared_state_lock
.dpi_adjusted
.unwrap_or_else(|| (xev.width as u32, xev.height as u32));
.unwrap_or((xev.width as u32, xev.height as u32));
let last_scale_factor = shared_state_lock.last_monitor.scale_factor;
let new_scale_factor = {
@ -1258,8 +1258,12 @@ impl<T: 'static> EventProcessor<T> {
}
}
match self.ime_event_receiver.try_recv() {
Ok((window, event)) => match event {
let (window, event) = match self.ime_event_receiver.try_recv() {
Ok((window, event)) => (window, event),
Err(_) => return,
};
match event {
ImeEvent::Enabled => {
callback(Event::WindowEvent {
window_id: mkwid(window),
@ -1296,8 +1300,6 @@ impl<T: 'static> EventProcessor<T> {
event: WindowEvent::Ime(Ime::Disabled),
});
}
},
Err(_) => (),
}
}

View file

@ -65,12 +65,10 @@ extern "C" fn preedit_done_callback(
.expect("failed to send preedit end event");
}
fn calc_byte_position(text: &Vec<char>, pos: usize) -> usize {
let mut byte_pos = 0;
for i in 0..pos {
byte_pos += text[i].len_utf8();
}
byte_pos
fn calc_byte_position(text: &[char], pos: usize) -> usize {
text.iter()
.take(pos)
.fold(0, |byte_pos, text| byte_pos + text.len_utf8())
}
/// Preedit text information to be drawn inline by the client.

View file

@ -78,15 +78,16 @@ impl<T> PeekableReceiver<T> {
if self.first.is_some() {
return true;
}
match self.recv.try_recv() {
Ok(v) => {
self.first = Some(v);
return true;
true
}
Err(TryRecvError::Empty) => return false,
Err(TryRecvError::Empty) => false,
Err(TryRecvError::Disconnected) => {
warn!("Channel was disconnected when checking incoming");
return false;
false
}
}
}
@ -416,11 +417,12 @@ impl<T: 'static> EventLoop<T> {
deadline = Some(*wait_deadline);
}
}
return IterationResult {
IterationResult {
wait_start: start,
deadline,
timeout,
};
}
}
let mut control_flow = ControlFlow::default();
@ -670,10 +672,7 @@ struct GenericEventCookie<'a> {
}
impl<'a> GenericEventCookie<'a> {
fn from_event<'b>(
xconn: &'b XConnection,
event: ffi::XEvent,
) -> Option<GenericEventCookie<'b>> {
fn from_event(xconn: &XConnection, event: ffi::XEvent) -> Option<GenericEventCookie<'_>> {
unsafe {
let mut cookie: ffi::XGenericEventCookie = From::from(event);
if (xconn.xlib.XGetEventData)(xconn.display, &mut cookie) == ffi::True {

View file

@ -229,11 +229,11 @@ impl XConnection {
panic!("[winit] `XRRGetScreenResources` returned NULL. That should only happen if the root window doesn't exist.");
}
let mut available;
let mut has_primary = false;
let primary = (self.xrandr.XRRGetOutputPrimary)(self.display, root);
available = Vec::with_capacity((*resources).ncrtc as usize);
let mut available = Vec::with_capacity((*resources).ncrtc as usize);
for crtc_index in 0..(*resources).ncrtc {
let crtc_id = *((*resources).crtcs.offset(crtc_index as isize));
let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id);

View file

@ -98,7 +98,7 @@ pub struct LogicalFrameExtents {
pub bottom: f64,
}
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameExtentsHeuristicPath {
Supported,
UnsupportedNested,
@ -370,8 +370,12 @@ impl XConnection {
let top = offset_y;
let bottom = diff_y.saturating_sub(offset_y);
let frame_extents =
FrameExtents::new(left.into(), right.into(), top.into(), bottom.into());
let frame_extents = FrameExtents::new(
left as c_ulong,
right as c_ulong,
top as c_ulong,
bottom as c_ulong,
);
FrameExtentsHeuristic {
frame_extents,
heuristic_path: UnsupportedNested,
@ -379,7 +383,7 @@ impl XConnection {
} else {
// This is the case for xmonad and dwm, AKA the only WMs tested that supplied a
// border value. This is convenient, since we can use it to get an accurate frame.
let frame_extents = FrameExtents::from_border(border.into());
let frame_extents = FrameExtents::from_border(border as c_ulong);
FrameExtentsHeuristic {
frame_extents,
heuristic_path: UnsupportedBordered,

View file

@ -173,6 +173,12 @@ impl MotifHints {
}
}
impl Default for MotifHints {
fn default() -> Self {
Self::new()
}
}
impl MwmHints {
fn as_slice(&self) -> &[c_ulong] {
unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) }
@ -317,7 +323,7 @@ impl XConnection {
let mut hints = MotifHints::new();
if let Ok(props) = self.get_property::<c_ulong>(window, motif_hints, motif_hints) {
hints.hints.flags = props.get(0).cloned().unwrap_or(0);
hints.hints.flags = props.first().cloned().unwrap_or(0);
hints.hints.functions = props.get(1).cloned().unwrap_or(0);
hints.hints.decorations = props.get(2).cloned().unwrap_or(0);
hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long;

View file

@ -1,3 +1,5 @@
#![allow(clippy::assertions_on_constants)]
use super::*;
use crate::icon::{Icon, Pixel, PIXEL_SIZE};

View file

@ -164,7 +164,9 @@ impl XConnection {
(self.xrandr.XRRFreeOutputInfo)(output_info);
Some((name, scale_factor, modes))
}
pub fn set_crtc_config(&self, crtc_id: RRCrtc, mode_id: RRMode) -> Result<(), ()> {
#[must_use]
pub fn set_crtc_config(&self, crtc_id: RRCrtc, mode_id: RRMode) -> Option<()> {
unsafe {
let mut major = 0;
let mut minor = 0;
@ -195,12 +197,13 @@ impl XConnection {
(self.xrandr.XRRFreeScreenResources)(resources);
if status == Success as i32 {
Ok(())
Some(())
} else {
Err(())
None
}
}
}
pub fn get_crtc_mode(&self, crtc_id: RRCrtc) -> RRMode {
unsafe {
let mut major = 0;

View file

@ -60,7 +60,7 @@ impl XConnection {
let root_window_wm_check = {
let result = self.get_property(root, check_atom, ffi::XA_WINDOW);
let wm_check = result.ok().and_then(|wm_check| wm_check.get(0).cloned());
let wm_check = result.ok().and_then(|wm_check| wm_check.first().cloned());
wm_check?
};
@ -70,7 +70,7 @@ impl XConnection {
let child_window_wm_check = {
let result = self.get_property(root_window_wm_check, check_atom, ffi::XA_WINDOW);
let wm_check = result.ok().and_then(|wm_check| wm_check.get(0).cloned());
let wm_check = result.ok().and_then(|wm_check| wm_check.first().cloned());
wm_check?
};

View file

@ -401,7 +401,7 @@ impl AppState {
let app: id = NSApp();
autoreleasepool(|| {
let () = msg_send![app, stop: nil];
let _: () = msg_send![app, stop: nil];
// To stop event loop immediately, we need to post some event here.
post_dummy_event(app);
});

View file

@ -120,7 +120,7 @@ pub struct EventLoop<T: 'static> {
_callback: Option<Rc<Callback<T>>>,
}
#[derive(Debug, Copy, Clone, PartialEq, Hash)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes {
pub(crate) activation_policy: ActivationPolicy,
pub(crate) default_menu: bool,
@ -213,7 +213,7 @@ impl<T> EventLoop<T> {
mem::drop(callback);
AppState::set_callback(weak_cb, Rc::clone(&self.window_target));
let () = msg_send![app, run];
let _: () = msg_send![app, run];
if let Some(panic) = self.panic_info.take() {
drop(self._callback.take());
@ -246,7 +246,7 @@ pub unsafe fn post_dummy_event(target: id) {
data1: 0 as NSInteger
data2: 0 as NSInteger
];
let () = msg_send![target, postEvent: dummy_event atStart: YES];
let _: () = msg_send![target, postEvent: dummy_event atStart: YES];
}
/// Catches panics that happen inside `f` and when a panic
@ -270,7 +270,7 @@ pub fn stop_app_on_panic<F: FnOnce() -> R + UnwindSafe, R>(
unsafe {
let app_class = class!(NSApplication);
let app: id = msg_send![app_class, sharedApplication];
let () = msg_send![app, stop: nil];
let _: () = msg_send![app, stop: nil];
// Posting a dummy event to get `stop` to take effect immediately.
// See: https://stackoverflow.com/questions/48041279/stopping-the-nsapplication-main-event-loop/48064752#48064752

View file

@ -1,4 +1,5 @@
#![cfg(target_os = "macos")]
#![allow(clippy::let_unit_value)]
#[macro_use]
mod util;

View file

@ -167,11 +167,15 @@ pub unsafe fn set_maximized_async(
shared_state_lock.maximized = maximized;
let curr_mask = ns_window.styleMask();
if shared_state_lock.fullscreen.is_some() {
// Handle it in window_did_exit_fullscreen
return;
} else if curr_mask.contains(NSWindowStyleMask::NSResizableWindowMask) {
}
if ns_window
.styleMask()
.contains(NSWindowStyleMask::NSResizableWindowMask)
{
// Just use the native zoom if resizable
ns_window.zoom_(nil);
} else {

View file

@ -33,7 +33,7 @@ pub const EMPTY_RANGE: ffi::NSRange = ffi::NSRange {
length: 0,
};
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq)]
pub struct IdRef(id);
impl IdRef {
@ -61,7 +61,7 @@ impl Drop for IdRef {
fn drop(&mut self) {
if self.0 != nil {
unsafe {
let () = msg_send![self.0, release];
let _: () = msg_send![self.0, release];
};
}
}
@ -150,7 +150,7 @@ pub unsafe fn superclass(this: &Object) -> &Class {
#[allow(dead_code)]
pub unsafe fn open_emoji_picker() {
let () = msg_send![NSApp(), orderFrontCharacterPalette: nil];
let _: () = msg_send![NSApp(), orderFrontCharacterPalette: nil];
}
pub unsafe fn toggle_style_mask(window: id, view: id, mask: NSWindowStyleMask, on: bool) {

View file

@ -84,11 +84,9 @@ impl ViewState {
fn get_scale_factor(&self) -> f64 {
(unsafe { NSWindow::backingScaleFactor(self.ns_window) }) as f64
}
fn is_ime_enabled(&self) -> bool {
match self.ime_state {
ImeState::Disabled => false,
_ => true,
}
!matches!(self.ime_state, ImeState::Disabled)
}
}
@ -422,7 +420,7 @@ extern "C" fn draw_rect(this: &Object, _sel: Sel, rect: NSRect) {
AppState::handle_redraw(WindowId(get_window_id(state.ns_window)));
let superclass = util::superclass(this);
let () = msg_send![super(this, superclass), drawRect: rect];
let _: () = msg_send![super(this, superclass), drawRect: rect];
}
}
@ -648,14 +646,12 @@ extern "C" fn do_command_by_selector(this: &Object, _sel: Sel, _command: Sel) {
state.forward_key_to_app = true;
let has_marked_text: BOOL = msg_send![this, hasMarkedText];
if has_marked_text == NO {
if state.ime_state == ImeState::Preedit {
if has_marked_text == NO && state.ime_state == ImeState::Preedit {
// Leave preedit so that we also report the keyup for this key
state.ime_state = ImeState::Enabled;
}
}
}
}
fn get_characters(event: id, ignore_modifiers: bool) -> String {
unsafe {
@ -900,7 +896,7 @@ extern "C" fn insert_tab(this: &Object, _sel: Sel, _sender: id) {
let first_responder: id = msg_send![window, firstResponder];
let this_ptr = this as *const _ as *mut _;
if first_responder == this_ptr {
let (): _ = msg_send![window, selectNextKeyView: this];
let _: () = msg_send![window, selectNextKeyView: this];
}
}
}
@ -912,7 +908,7 @@ extern "C" fn insert_back_tab(this: &Object, _sel: Sel, _sender: id) {
let first_responder: id = msg_send![window, firstResponder];
let this_ptr = this as *const _ as *mut _;
if first_responder == this_ptr {
let (): _ = msg_send![window, selectPreviousKeyView: this];
let _: () = msg_send![window, selectPreviousKeyView: this];
}
}
}

View file

@ -414,7 +414,7 @@ impl UnownedWindow {
use cocoa::foundation::NSArray;
// register for drag and drop operations.
let () = msg_send![
let _: () = msg_send![
*ns_window,
registerForDraggedTypes:
NSArray::arrayWithObject(nil, appkit::NSFilenamesPboardType)
@ -951,7 +951,7 @@ impl UnownedWindow {
| NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar;
app.setPresentationOptions_(presentation_options);
let () = msg_send![*self.ns_window, setLevel: ffi::CGShieldingWindowLevel() + 1];
let _: () = msg_send![*self.ns_window, setLevel: ffi::CGShieldingWindowLevel() + 1];
},
(
&Some(Fullscreen::Exclusive(RootVideoMode { ref video_mode })),
@ -969,7 +969,7 @@ impl UnownedWindow {
// Restore the normal window level following the Borderless fullscreen
// `CGShieldingWindowLevel() + 1` hack.
let () = msg_send![
let _: () = msg_send![
*self.ns_window,
setLevel: ffi::NSWindowLevel::NSNormalWindowLevel
];

View file

@ -247,7 +247,7 @@ extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> i
if this != nil {
(*this).set_ivar("winitState", state);
with_state(&*this, |state| {
let () = msg_send![*state.ns_window, setDelegate: this];
let _: () = msg_send![*state.ns_window, setDelegate: this];
});
}
this
@ -267,7 +267,7 @@ extern "C" fn window_will_close(this: &Object, _: Sel, _: id) {
autoreleasepool(|| {
// Since El Capitan, we need to be careful that delegate methods can't
// be called after the window closes.
let () = msg_send![*state.ns_window, setDelegate: nil];
let _: () = msg_send![*state.ns_window, setDelegate: nil];
});
state.emit_event(WindowEvent::Destroyed);
});
@ -416,7 +416,8 @@ extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
state.with_window(|window| {
let mut shared_state = window.lock_shared_state("window_will_enter_fullscreen");
shared_state.maximized = window.is_zoomed();
match shared_state.fullscreen {
let fullscreen = shared_state.fullscreen.as_ref();
match fullscreen {
// Exclusive mode sets the state in `set_fullscreen` as the user
// can't enter exclusive mode by other means (like the
// fullscreen button on the window decorations)
@ -541,12 +542,12 @@ extern "C" fn window_did_fail_to_enter_fullscreen(this: &Object, _: Sel, _: id)
shared_state.target_fullscreen = None;
});
if state.initial_fullscreen {
let _: () = unsafe {
msg_send![*state.ns_window,
unsafe {
let _: () = msg_send![*state.ns_window,
performSelector:sel!(toggleFullScreen:)
withObject:nil
afterDelay: 0.5
]
];
};
} else {
state.with_window(|window| window.restore_state_from_fullscreen());

View file

@ -16,7 +16,7 @@ pub struct EventLoop<T: 'static> {
elw: RootEventLoopWindowTarget<T>,
}
#[derive(Default, Debug, Copy, Clone, PartialEq, Hash)]
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes {}
impl<T> EventLoop<T> {

View file

@ -456,12 +456,9 @@ impl<T: 'static> Shared<T> {
ControlFlow::ExitWithCode(_) => State::Exit,
};
match *self.0.runner.borrow_mut() {
RunnerEnum::Running(ref mut runner) => {
if let RunnerEnum::Running(ref mut runner) = *self.0.runner.borrow_mut() {
runner.state = new_state;
}
_ => (),
}
}
fn handle_loop_destroyed(&self, control: &mut ControlFlow) {

View file

@ -22,10 +22,7 @@ pub enum State {
impl State {
pub fn is_exit(&self) -> bool {
match self {
State::Exit => true,
_ => false,
}
matches!(self, State::Exit)
}
pub fn control_flow(&self) -> ControlFlow {

View file

@ -44,11 +44,11 @@ impl Canvas {
Some(canvas) => canvas,
None => {
let window = web_sys::window()
.ok_or(os_error!(OsError("Failed to obtain window".to_owned())))?;
.ok_or_else(|| os_error!(OsError("Failed to obtain window".to_owned())))?;
let document = window
.document()
.ok_or(os_error!(OsError("Failed to obtain document".to_owned())))?;
.ok_or_else(|| os_error!(OsError("Failed to obtain document".to_owned())))?;
document
.create_element("canvas")
@ -94,10 +94,10 @@ impl Canvas {
self.raw().request_pointer_lock();
} else {
let window = web_sys::window()
.ok_or(os_error!(OsError("Failed to obtain window".to_owned())))?;
.ok_or_else(|| os_error!(OsError("Failed to obtain window".to_owned())))?;
let document = window
.document()
.ok_or(os_error!(OsError("Failed to obtain document".to_owned())))?;
.ok_or_else(|| os_error!(OsError("Failed to obtain document".to_owned())))?;
document.exit_pointer_lock();
}
Ok(())
@ -107,7 +107,7 @@ impl Canvas {
self.common
.raw
.set_attribute(attribute, value)
.expect(&format!("Set attribute: {}", attribute));
.unwrap_or_else(|err| panic!("error: {:?}\nSet attribute: {}", err, attribute))
}
pub fn position(&self) -> LogicalPosition<f64> {
@ -339,9 +339,7 @@ impl Common {
handler(event);
}) as Box<dyn FnMut(E)>);
let listener = EventListenerHandle::new(&self.raw, event_name, closure);
listener
EventListenerHandle::new(&self.raw, event_name, closure)
}
// The difference between add_event and add_user_event is that the latter has a special meaning

View file

@ -8,6 +8,8 @@ use std::rc::Rc;
use web_sys::{EventTarget, MouseEvent};
type MouseLeaveHandler = Rc<RefCell<Option<Box<dyn FnMut(i32)>>>>;
#[allow(dead_code)]
pub(super) struct MouseHandler {
on_mouse_leave: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
@ -15,7 +17,7 @@ pub(super) struct MouseHandler {
on_mouse_move: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
on_mouse_press: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
on_mouse_release: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
on_mouse_leave_handler: Rc<RefCell<Option<Box<dyn FnMut(i32)>>>>,
on_mouse_leave_handler: MouseLeaveHandler,
mouse_capture_state: Rc<RefCell<MouseCaptureState>>,
}
@ -175,8 +177,8 @@ impl MouseHandler {
.map_or(false, |target| target == EventTarget::from(canvas.clone()));
match &*mouse_capture_state {
// Don't handle hover events outside of canvas.
MouseCaptureState::NotCaptured if !is_over_canvas => return,
MouseCaptureState::OtherElement if !is_over_canvas => return,
MouseCaptureState::NotCaptured | MouseCaptureState::OtherElement
if !is_over_canvas => {}
// If hovering over the canvas, just send the cursor move event.
MouseCaptureState::NotCaptured
| MouseCaptureState::OtherElement

View file

@ -17,7 +17,7 @@ impl MediaQueryListHandle {
.ok()
.flatten()
.and_then(|mql| {
mql.add_listener_with_opt_callback(Some(&listener.as_ref().unchecked_ref()))
mql.add_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref()))
.map(|_| mql)
.ok()
});

View file

@ -98,7 +98,7 @@ pub fn set_canvas_style_property(raw: &HtmlCanvasElement, property: &str, value:
let style = raw.style();
style
.set_property(property, value)
.expect(&format!("Failed to set {}", property));
.unwrap_or_else(|err| panic!("error: {:?}\nFailed to set {}", err, property))
}
pub fn is_fullscreen(canvas: &HtmlCanvasElement) -> bool {

View file

@ -65,13 +65,13 @@ impl ScaleChangeDetectorInternal {
);
let mql = MediaQueryListHandle::new(&media_query, closure);
if let Some(mql) = &mql {
assert_eq!(mql.mql().matches(), true);
assert!(mql.mql().matches());
}
mql
}
fn handler(&mut self, event: MediaQueryListEvent) {
assert_eq!(event.matches(), false);
assert!(!event.matches());
let mql = self
.mql
.take()

View file

@ -21,7 +21,7 @@ impl Timeout {
let handle = window
.set_timeout_with_callback_and_timeout_and_arguments_0(
&closure.as_ref().unchecked_ref(),
closure.as_ref().unchecked_ref(),
duration.as_millis() as i32,
)
.expect("Failed to set timeout");
@ -64,7 +64,7 @@ impl AnimationFrameRequest {
}) as Box<dyn FnMut()>);
let handle = window
.request_animation_frame(&closure.as_ref().unchecked_ref())
.request_animation_frame(closure.as_ref().unchecked_ref())
.expect("Failed to request animation frame");
AnimationFrameRequest {

View file

@ -36,11 +36,11 @@ impl Window {
let id = target.generate_id();
let canvas = backend::Canvas::create(platform_attr)?;
let mut canvas = Rc::new(RefCell::new(canvas));
let canvas = Rc::new(RefCell::new(canvas));
let register_redraw_request = Box::new(move || runner.request_redraw(RootWI(id)));
target.register(&mut canvas, id);
target.register(&canvas, id);
let runner = target.runner.clone();
let resize_notify_fn = Box::new(move |new_size| {
@ -77,7 +77,7 @@ impl Window {
Ok(window)
}
pub fn canvas<'a>(&'a self) -> Ref<'a, backend::Canvas> {
pub fn canvas(&self) -> Ref<'_, backend::Canvas> {
self.canvas.borrow()
}
@ -220,7 +220,7 @@ impl Window {
self.canvas
.borrow()
.set_cursor_grab(grab)
.map_err(|e| ExternalError::Os(e))
.map_err(ExternalError::Os)
}
#[inline]
@ -344,7 +344,7 @@ impl Window {
#[inline]
pub fn id(&self) -> WindowId {
return self.id;
self.id
}
#[inline]

View file

@ -1976,7 +1976,7 @@ unsafe fn public_window_callback_inner<T: 'static>(
false => old_physical_inner_size,
};
let _ = userdata.send_event(Event::WindowEvent {
userdata.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: ScaleFactorChanged {
scale_factor: new_scale_factor,

View file

@ -80,19 +80,18 @@ impl ImeContext {
let data = self.get_composition_data(gcs_mode)?;
let (prefix, shorts, suffix) = data.align_to::<u16>();
if prefix.is_empty() && suffix.is_empty() {
OsString::from_wide(&shorts).into_string().ok()
OsString::from_wide(shorts).into_string().ok()
} else {
None
}
}
unsafe fn get_composition_data(&self, gcs_mode: u32) -> Option<Vec<u8>> {
let size = ImmGetCompositionStringW(self.himc, gcs_mode, null_mut(), 0);
if size < 0 {
return None;
} else if size == 0 {
return Some(Vec::new());
}
let size = match ImmGetCompositionStringW(self.himc, gcs_mode, null_mut(), 0) {
0 => return Some(Vec::new()),
size if size < 0 => return None,
size => size,
};
let mut buf = Vec::<u8>::with_capacity(size as _);
let size = ImmGetCompositionStringW(
@ -139,7 +138,7 @@ impl ImeContext {
}
unsafe fn system_has_ime() -> bool {
return GetSystemMetrics(SM_IMMENABLED) != 0;
GetSystemMetrics(SM_IMMENABLED) != 0
}
}

View file

@ -1126,7 +1126,7 @@ impl Default for CursorIcon {
}
/// Fullscreen modes.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fullscreen {
Exclusive(VideoMode),
@ -1134,7 +1134,7 @@ pub enum Fullscreen {
Borderless(Option<MonitorHandle>),
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Theme {
Light,
Dark,
@ -1143,7 +1143,7 @@ pub enum Theme {
/// ## Platform-specific
///
/// - **X11:** Sets the WM's `XUrgencyHint`. No distinction between `Critical` and `Informational`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UserAttentionType {
/// ## Platform-specific
/// - **macOS:** Bounces the dock icon until the application is in focus.