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 - name: Check Formatting
run: cargo +stable fmt --all -- --check run: cargo +stable fmt --all -- --check
Tests: tests:
name: Tests
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@ -62,6 +63,7 @@ jobs:
with: with:
rust-version: ${{ matrix.rust_version }}${{ matrix.platform.host }} rust-version: ${{ matrix.rust_version }}${{ matrix.platform.host }}
targets: ${{ matrix.platform.target }} targets: ${{ matrix.platform.target }}
components: clippy
- name: Install Linux dependencies - name: Install Linux dependencies
if: (matrix.platform.os == 'ubuntu-latest') if: (matrix.platform.os == 'ubuntu-latest')
@ -93,6 +95,10 @@ jobs:
!contains(matrix.platform.target, 'wasm32')) !contains(matrix.platform.target, 'wasm32'))
run: cargo $CMD test --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES 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 - name: Build with serde enabled
shell: bash 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. - **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`. - 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. - **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) # 0.26.1 (2022-01-05)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,3 +1,5 @@
#![allow(clippy::single_match)]
// Limit this example to only compatible platforms. // Limit this example to only compatible platforms.
#[cfg(any( #[cfg(any(
target_os = "windows", 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. /// will fall back on X11. If this variable is set with any other value, winit will panic.
#[inline] #[inline]
pub fn build(&mut self) -> EventLoop<T> { pub fn build(&mut self) -> EventLoop<T> {
// Certain platforms accept a mutable reference in their API.
#[allow(clippy::unnecessary_mut_passed)]
EventLoop { EventLoop {
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific), event_loop: platform_impl::EventLoop::new(&mut self.platform_specific),
_marker: PhantomData, _marker: PhantomData,
@ -221,6 +223,12 @@ impl EventLoop<()> {
} }
} }
impl Default for EventLoop<()> {
fn default() -> Self {
Self::new()
}
}
impl<T> EventLoop<T> { impl<T> EventLoop<T> {
#[deprecated = "Use `EventLoopBuilder::<T>::with_user_event().build()` instead."] #[deprecated = "Use `EventLoopBuilder::<T>::with_user_event().build()` instead."]
pub fn with_user_event() -> EventLoop<T> { pub fn with_user_event() -> EventLoop<T> {

View file

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

View file

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

View file

@ -53,11 +53,7 @@ enum UserCallbackTransitionResult<'a> {
impl Event<'static, Never> { impl Event<'static, Never> {
fn is_redraw(&self) -> bool { fn is_redraw(&self) -> bool {
if let Event::RedrawRequested(_) = self { matches!(self, Event::RedrawRequested(_))
true
} else {
false
}
} }
} }
@ -120,7 +116,7 @@ impl Drop for AppState {
} => { } => {
for &mut window in queued_windows { for &mut window in queued_windows {
unsafe { unsafe {
let () = msg_send![window, release]; let _: () = msg_send![window, release];
} }
} }
} }
@ -201,10 +197,10 @@ impl AppState {
} }
fn has_launched(&self) -> bool { fn has_launched(&self) -> bool {
match self.state() { !matches!(
&AppStateImpl::NotLaunched { .. } | &AppStateImpl::Launching { .. } => false, self.state(),
_ => true, AppStateImpl::NotLaunched { .. } | AppStateImpl::Launching { .. }
} )
} }
fn will_launch_transition(&mut self, queued_event_handler: Box<dyn EventHandler>) { 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 { | &mut AppStateImpl::InUserCallback {
ref mut queued_gpu_redraws, ref mut queued_gpu_redraws,
.. ..
} => drop(queued_gpu_redraws.insert(window)), } => {
let _ = queued_gpu_redraws.insert(window);
}
s @ &mut AppStateImpl::ProcessingRedraws { .. } s @ &mut AppStateImpl::ProcessingRedraws { .. }
| s @ &mut AppStateImpl::Waiting { .. } | s @ &mut AppStateImpl::Waiting { .. }
| s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), | 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") panic!("Attempt to create a `Window` after the app has terminated")
} }
} }
drop(this); drop(this);
} }
@ -549,7 +548,7 @@ pub unsafe fn will_launch(queued_event_handler: Box<dyn EventHandler>) {
pub unsafe fn did_finish_launching() { pub unsafe fn did_finish_launching() {
let mut this = AppState::get_mut(); let mut this = AppState::get_mut();
let windows = match this.state_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), s => bug!("unexpected state {:?}", s),
}; };
@ -579,15 +578,15 @@ pub unsafe fn did_finish_launching() {
// ``` // ```
let screen: id = msg_send![window, screen]; let screen: id = msg_send![window, screen];
let _: id = msg_send![screen, retain]; let _: id = msg_send![screen, retain];
let () = msg_send![window, setScreen:0 as id]; let _: () = msg_send![window, setScreen:0 as id];
let () = msg_send![window, setScreen: screen]; let _: () = msg_send![window, setScreen: screen];
let () = msg_send![screen, release]; let _: () = msg_send![screen, release];
let controller: id = msg_send![window, rootViewController]; let controller: id = msg_send![window, rootViewController];
let () = msg_send![window, setRootViewController:ptr::null::<()>()]; let _: () = msg_send![window, setRootViewController:ptr::null::<()>()];
let () = msg_send![window, setRootViewController: controller]; let _: () = msg_send![window, setRootViewController: controller];
let () = msg_send![window, makeKeyAndVisible]; 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(); 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]; let count: NSUInteger = msg_send![window, retainCount];
// make sure the window is still referenced // make sure the window is still referenced
if count > 1 { 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 { &mut AppStateImpl::InUserCallback {
ref mut queued_events, ref mut queued_events,
queued_gpu_redraws: _, queued_gpu_redraws: _,
} => mem::replace(queued_events, Vec::new()), } => mem::take(queued_events),
s => bug!("unexpected state {:?}", s), s => bug!("unexpected state {:?}", s),
}; };
if queued_events.is_empty() { if queued_events.is_empty() {
@ -752,7 +751,7 @@ unsafe fn handle_user_events() {
&mut AppStateImpl::InUserCallback { &mut AppStateImpl::InUserCallback {
ref mut queued_events, ref mut queued_events,
queued_gpu_redraws: _, queued_gpu_redraws: _,
} => mem::replace(queued_events, Vec::new()), } => mem::take(queued_events),
s => bug!("unexpected state {:?}", s), s => bug!("unexpected state {:?}", s),
}; };
if queued_events.is_empty() { if queued_events.is_empty() {
@ -876,7 +875,7 @@ fn handle_hidpi_proxy(
let size = CGSize::new(logical_size); let size = CGSize::new(logical_size);
let new_frame: CGRect = CGRect::new(screen_frame.origin, size); let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
unsafe { 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>, window_target: RootEventLoopWindowTarget<T>,
} }
#[derive(Default, Debug, Copy, Clone, PartialEq, Hash)] #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes {} pub(crate) struct PlatformSpecificEventLoopAttributes {}
impl<T: 'static> EventLoop<T> { impl<T: 'static> EventLoop<T> {

View file

@ -88,7 +88,7 @@ pub enum UITouchPhase {
Cancelled, Cancelled,
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq, Eq)]
#[allow(dead_code)] #[allow(dead_code)]
#[repr(isize)] #[repr(isize)]
pub enum UIForceTouchCapability { pub enum UIForceTouchCapability {
@ -97,7 +97,7 @@ pub enum UIForceTouchCapability {
Available, Available,
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq, Eq)]
#[allow(dead_code)] #[allow(dead_code)]
#[repr(isize)] #[repr(isize)]
pub enum UITouchType { pub enum UITouchType {
@ -144,10 +144,9 @@ impl From<Idiom> for UIUserInterfaceIdiom {
} }
} }
} }
impl From<UIUserInterfaceIdiom> for Idiom {
impl Into<Idiom> for UIUserInterfaceIdiom { fn from(ui_idiom: UIUserInterfaceIdiom) -> Idiom {
fn into(self) -> Idiom { match ui_idiom {
match self {
UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified, UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified,
UIUserInterfaceIdiom::Phone => Idiom::Phone, UIUserInterfaceIdiom::Phone => Idiom::Phone,
UIUserInterfaceIdiom::Pad => Idiom::Pad, UIUserInterfaceIdiom::Pad => Idiom::Pad,
@ -230,9 +229,9 @@ impl From<ScreenEdge> for UIRectEdge {
} }
} }
impl Into<ScreenEdge> for UIRectEdge { impl From<UIRectEdge> for ScreenEdge {
fn into(self) -> ScreenEdge { fn from(ui_rect_edge: UIRectEdge) -> ScreenEdge {
let bits: u8 = self.0.try_into().expect("invalid `UIRectEdge`"); let bits: u8 = ui_rect_edge.0.try_into().expect("invalid `UIRectEdge`");
ScreenEdge::from_bits(bits).expect("invalid `ScreenEdge`") 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. //! Also note that app may not receive the LoopDestroyed event if suspended; it might be SIGKILL'ed.
#![cfg(target_os = "ios")] #![cfg(target_os = "ios")]
#![allow(clippy::let_unit_value)]
// TODO: (mtak-) UIKit requires main thread for virtually all function/method calls. This could be // 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 // 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 {} pub enum OsError {}
impl fmt::Display for OsError { impl fmt::Display for OsError {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { write!(f, "os error")
_ => unreachable!(),
}
} }
} }

View file

@ -30,7 +30,7 @@ unsafe impl Send for NativeDisplayMode {}
impl Drop for NativeDisplayMode { impl Drop for NativeDisplayMode {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
let () = msg_send![self.0, release]; let _: () = msg_send![self.0, release];
} }
} }
} }
@ -115,7 +115,7 @@ pub struct Inner {
impl Drop for Inner { impl Drop for Inner {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { 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 { pub fn retained_new(uiscreen: id) -> MonitorHandle {
unsafe { unsafe {
assert_main_thread!("`MonitorHandle` can only be cloned on the main thread on iOS"); 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 { MonitorHandle {
inner: Inner { uiscreen }, 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 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) { extern "C" fn layout_subviews(object: &Object, _: Sel) {
unsafe { unsafe {
let superclass: &'static Class = msg_send![object, superclass]; 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]; let window: id = msg_send![object, window];
assert!(!window.is_null()); 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, width: screen_frame.size.width as f64,
height: screen_frame.size.height 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. // 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 // 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. // window bounds to the view frame to make it consistent.
let view_frame: CGRect = msg_send![object, frame]; let view_frame: CGRect = msg_send![object, frame];
if view_frame != window_bounds { 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 { 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 { unsafe {
let superclass: &'static Class = msg_send![object, superclass]; let superclass: &'static Class = msg_send![object, superclass];
let () = msg_send![ let _: () = msg_send![
super(object, superclass), super(object, superclass),
setContentScaleFactor: untrusted_scale_factor setContentScaleFactor: untrusted_scale_factor
]; ];
@ -180,7 +180,7 @@ unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class {
&& scale_factor > 0.0, && scale_factor > 0.0,
"invalid scale_factor set on UIView", "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 bounds: CGRect = msg_send![object, bounds];
let screen: id = msg_send![window, screen]; let screen: id = msg_send![window, screen];
let screen_space: id = msg_send![screen, coordinateSpace]; 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, prefers_status_bar_hidden: BOOL,
setPrefersStatusBarHidden: |object| { setPrefersStatusBarHidden: |object| {
unsafe { unsafe {
let () = msg_send![object, setNeedsStatusBarAppearanceUpdate]; let _: () = msg_send![object, setNeedsStatusBarAppearanceUpdate];
} }
}, },
prefersStatusBarHidden, prefersStatusBarHidden,
@ -353,7 +353,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
OSCapabilities::home_indicator_hidden_err_msg; OSCapabilities::home_indicator_hidden_err_msg;
|object| { |object| {
unsafe { unsafe {
let () = msg_send![object, setNeedsUpdateOfHomeIndicatorAutoHidden]; let _: () = msg_send![object, setNeedsUpdateOfHomeIndicatorAutoHidden];
} }
}, },
prefersHomeIndicatorAutoHidden, prefersHomeIndicatorAutoHidden,
@ -363,7 +363,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
supported_orientations: UIInterfaceOrientationMask, supported_orientations: UIInterfaceOrientationMask,
setSupportedInterfaceOrientations: |object| { setSupportedInterfaceOrientations: |object| {
unsafe { unsafe {
let () = msg_send![class!(UIViewController), attemptRotationToDeviceOrientation]; let _: () = msg_send![class!(UIViewController), attemptRotationToDeviceOrientation];
} }
}, },
supportedInterfaceOrientations, supportedInterfaceOrientations,
@ -376,7 +376,7 @@ unsafe fn get_view_controller_class() -> &'static Class {
OSCapabilities::defer_system_gestures_err_msg; OSCapabilities::defer_system_gestures_err_msg;
|object| { |object| {
unsafe { unsafe {
let () = msg_send![object, setNeedsUpdateOfScreenEdgesDeferringSystemGestures]; let _: () = msg_send![object, setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
} }
}, },
preferredScreenEdgesDeferringSystemGestures, preferredScreenEdgesDeferringSystemGestures,
@ -398,7 +398,7 @@ unsafe fn get_window_class() -> &'static Class {
window_id: RootWindowId(object.into()), window_id: RootWindowId(object.into()),
event: WindowEvent::Focused(true), 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()), window_id: RootWindowId(object.into()),
event: WindowEvent::Focused(false), 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"); assert!(!view.is_null(), "Failed to create `UIView` instance");
let view: id = msg_send![view, initWithFrame: frame]; let view: id = msg_send![view, initWithFrame: frame];
assert!(!view.is_null(), "Failed to initialize `UIView` instance"); 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 { 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 view
@ -484,23 +484,23 @@ pub unsafe fn create_view_controller(
let edges: UIRectEdge = platform_attributes let edges: UIRectEdge = platform_attributes
.preferred_screen_edges_deferring_system_gestures .preferred_screen_edges_deferring_system_gestures
.into(); .into();
let () = msg_send![ let _: () = msg_send![
view_controller, view_controller,
setPrefersStatusBarHidden: status_bar_hidden setPrefersStatusBarHidden: status_bar_hidden
]; ];
let () = msg_send![ let _: () = msg_send![
view_controller, view_controller,
setSupportedInterfaceOrientations: supported_orientations setSupportedInterfaceOrientations: supported_orientations
]; ];
let () = msg_send![ let _: () = msg_send![
view_controller, view_controller,
setPrefersHomeIndicatorAutoHidden: prefers_home_indicator_hidden setPrefersHomeIndicatorAutoHidden: prefers_home_indicator_hidden
]; ];
let () = msg_send![ let _: () = msg_send![
view_controller, view_controller,
setPreferredScreenEdgesDeferringSystemGestures: edges setPreferredScreenEdgesDeferringSystemGestures: edges
]; ];
let () = msg_send![view_controller, setView: view]; let _: () = msg_send![view_controller, setView: view];
view_controller view_controller
} }
@ -520,11 +520,11 @@ pub unsafe fn create_window(
!window.is_null(), !window.is_null(),
"Failed to initialize `UIWindow` instance" "Failed to initialize `UIWindow` instance"
); );
let () = msg_send![window, setRootViewController: view_controller]; let _: () = msg_send![window, setRootViewController: view_controller];
match window_attributes.fullscreen { match window_attributes.fullscreen {
Some(Fullscreen::Exclusive(ref video_mode)) => { Some(Fullscreen::Exclusive(ref video_mode)) => {
let uiscreen = video_mode.monitor().ui_screen() as id; 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()] msg_send![window, setScreen:video_mode.monitor().ui_screen()]
} }
Some(Fullscreen::Borderless(ref monitor)) => { Some(Fullscreen::Borderless(ref monitor)) => {

View file

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

View file

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

View file

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

View file

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

View file

@ -243,7 +243,7 @@ pub(super) fn init_relative_pointer(
relative_pointer_manager: &ZwpRelativePointerManagerV1, relative_pointer_manager: &ZwpRelativePointerManagerV1,
pointer: &WlPointer, pointer: &WlPointer,
) -> ZwpRelativePointerV1 { ) -> 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| { relative_pointer.quick_assign(move |_, event, mut dispatch_data| {
let winit_state = dispatch_data.get::<WinitState>().unwrap(); let winit_state = dispatch_data.get::<WinitState>().unwrap();
handlers::handle_relative_pointer(event, winit_state); 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. // Process the rest of the events.
for (window_id, window_handle) in window_map.iter_mut() { for (window_id, window_handle) in window_map.iter_mut() {
let mut requests = window_handle.pending_window_requests.lock().unwrap(); 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 { match request {
WindowRequest::Fullscreen(fullscreen) => { WindowRequest::Fullscreen(fullscreen) => {
window_handle.window.set_fullscreen(fullscreen.as_ref()); 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. // resizing by dragging across monitors *without* dropping the window.
let (width, height) = shared_state_lock let (width, height) = shared_state_lock
.dpi_adjusted .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 last_scale_factor = shared_state_lock.last_monitor.scale_factor;
let new_scale_factor = { let new_scale_factor = {
@ -1258,8 +1258,12 @@ impl<T: 'static> EventProcessor<T> {
} }
} }
match self.ime_event_receiver.try_recv() { let (window, event) = match self.ime_event_receiver.try_recv() {
Ok((window, event)) => match event { Ok((window, event)) => (window, event),
Err(_) => return,
};
match event {
ImeEvent::Enabled => { ImeEvent::Enabled => {
callback(Event::WindowEvent { callback(Event::WindowEvent {
window_id: mkwid(window), window_id: mkwid(window),
@ -1296,8 +1300,6 @@ impl<T: 'static> EventProcessor<T> {
event: WindowEvent::Ime(Ime::Disabled), 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"); .expect("failed to send preedit end event");
} }
fn calc_byte_position(text: &Vec<char>, pos: usize) -> usize { fn calc_byte_position(text: &[char], pos: usize) -> usize {
let mut byte_pos = 0; text.iter()
for i in 0..pos { .take(pos)
byte_pos += text[i].len_utf8(); .fold(0, |byte_pos, text| byte_pos + text.len_utf8())
}
byte_pos
} }
/// Preedit text information to be drawn inline by the client. /// 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() { if self.first.is_some() {
return true; return true;
} }
match self.recv.try_recv() { match self.recv.try_recv() {
Ok(v) => { Ok(v) => {
self.first = Some(v); self.first = Some(v);
return true; true
} }
Err(TryRecvError::Empty) => return false, Err(TryRecvError::Empty) => false,
Err(TryRecvError::Disconnected) => { Err(TryRecvError::Disconnected) => {
warn!("Channel was disconnected when checking incoming"); warn!("Channel was disconnected when checking incoming");
return false; false
} }
} }
} }
@ -416,11 +417,12 @@ impl<T: 'static> EventLoop<T> {
deadline = Some(*wait_deadline); deadline = Some(*wait_deadline);
} }
} }
return IterationResult {
IterationResult {
wait_start: start, wait_start: start,
deadline, deadline,
timeout, timeout,
}; }
} }
let mut control_flow = ControlFlow::default(); let mut control_flow = ControlFlow::default();
@ -670,10 +672,7 @@ struct GenericEventCookie<'a> {
} }
impl<'a> GenericEventCookie<'a> { impl<'a> GenericEventCookie<'a> {
fn from_event<'b>( fn from_event(xconn: &XConnection, event: ffi::XEvent) -> Option<GenericEventCookie<'_>> {
xconn: &'b XConnection,
event: ffi::XEvent,
) -> Option<GenericEventCookie<'b>> {
unsafe { unsafe {
let mut cookie: ffi::XGenericEventCookie = From::from(event); let mut cookie: ffi::XGenericEventCookie = From::from(event);
if (xconn.xlib.XGetEventData)(xconn.display, &mut cookie) == ffi::True { 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."); 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 mut has_primary = false;
let primary = (self.xrandr.XRRGetOutputPrimary)(self.display, root); 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 { for crtc_index in 0..(*resources).ncrtc {
let crtc_id = *((*resources).crtcs.offset(crtc_index as isize)); let crtc_id = *((*resources).crtcs.offset(crtc_index as isize));
let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id); let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id);

View file

@ -98,7 +98,7 @@ pub struct LogicalFrameExtents {
pub bottom: f64, pub bottom: f64,
} }
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameExtentsHeuristicPath { pub enum FrameExtentsHeuristicPath {
Supported, Supported,
UnsupportedNested, UnsupportedNested,
@ -370,8 +370,12 @@ impl XConnection {
let top = offset_y; let top = offset_y;
let bottom = diff_y.saturating_sub(offset_y); let bottom = diff_y.saturating_sub(offset_y);
let frame_extents = let frame_extents = FrameExtents::new(
FrameExtents::new(left.into(), right.into(), top.into(), bottom.into()); left as c_ulong,
right as c_ulong,
top as c_ulong,
bottom as c_ulong,
);
FrameExtentsHeuristic { FrameExtentsHeuristic {
frame_extents, frame_extents,
heuristic_path: UnsupportedNested, heuristic_path: UnsupportedNested,
@ -379,7 +383,7 @@ impl XConnection {
} else { } else {
// This is the case for xmonad and dwm, AKA the only WMs tested that supplied a // 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. // 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 { FrameExtentsHeuristic {
frame_extents, frame_extents,
heuristic_path: UnsupportedBordered, heuristic_path: UnsupportedBordered,

View file

@ -173,6 +173,12 @@ impl MotifHints {
} }
} }
impl Default for MotifHints {
fn default() -> Self {
Self::new()
}
}
impl MwmHints { impl MwmHints {
fn as_slice(&self) -> &[c_ulong] { fn as_slice(&self) -> &[c_ulong] {
unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) }
@ -317,7 +323,7 @@ impl XConnection {
let mut hints = MotifHints::new(); let mut hints = MotifHints::new();
if let Ok(props) = self.get_property::<c_ulong>(window, motif_hints, motif_hints) { 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.functions = props.get(1).cloned().unwrap_or(0);
hints.hints.decorations = props.get(2).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; 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 super::*;
use crate::icon::{Icon, Pixel, PIXEL_SIZE}; use crate::icon::{Icon, Pixel, PIXEL_SIZE};

View file

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

View file

@ -60,7 +60,7 @@ impl XConnection {
let root_window_wm_check = { let root_window_wm_check = {
let result = self.get_property(root, check_atom, ffi::XA_WINDOW); 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? wm_check?
}; };
@ -70,7 +70,7 @@ impl XConnection {
let child_window_wm_check = { let child_window_wm_check = {
let result = self.get_property(root_window_wm_check, check_atom, ffi::XA_WINDOW); 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? wm_check?
}; };

View file

@ -401,7 +401,7 @@ impl AppState {
let app: id = NSApp(); let app: id = NSApp();
autoreleasepool(|| { 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. // To stop event loop immediately, we need to post some event here.
post_dummy_event(app); post_dummy_event(app);
}); });

View file

@ -120,7 +120,7 @@ pub struct EventLoop<T: 'static> {
_callback: Option<Rc<Callback<T>>>, _callback: Option<Rc<Callback<T>>>,
} }
#[derive(Debug, Copy, Clone, PartialEq, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct PlatformSpecificEventLoopAttributes { pub(crate) struct PlatformSpecificEventLoopAttributes {
pub(crate) activation_policy: ActivationPolicy, pub(crate) activation_policy: ActivationPolicy,
pub(crate) default_menu: bool, pub(crate) default_menu: bool,
@ -213,7 +213,7 @@ impl<T> EventLoop<T> {
mem::drop(callback); mem::drop(callback);
AppState::set_callback(weak_cb, Rc::clone(&self.window_target)); 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() { if let Some(panic) = self.panic_info.take() {
drop(self._callback.take()); drop(self._callback.take());
@ -246,7 +246,7 @@ pub unsafe fn post_dummy_event(target: id) {
data1: 0 as NSInteger data1: 0 as NSInteger
data2: 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 /// 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 { unsafe {
let app_class = class!(NSApplication); let app_class = class!(NSApplication);
let app: id = msg_send![app_class, sharedApplication]; 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. // 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 // See: https://stackoverflow.com/questions/48041279/stopping-the-nsapplication-main-event-loop/48064752#48064752

View file

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

View file

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

View file

@ -33,7 +33,7 @@ pub const EMPTY_RANGE: ffi::NSRange = ffi::NSRange {
length: 0, length: 0,
}; };
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq, Eq)]
pub struct IdRef(id); pub struct IdRef(id);
impl IdRef { impl IdRef {
@ -61,7 +61,7 @@ impl Drop for IdRef {
fn drop(&mut self) { fn drop(&mut self) {
if self.0 != nil { if self.0 != nil {
unsafe { 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)] #[allow(dead_code)]
pub unsafe fn open_emoji_picker() { 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) { 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 { fn get_scale_factor(&self) -> f64 {
(unsafe { NSWindow::backingScaleFactor(self.ns_window) }) as f64 (unsafe { NSWindow::backingScaleFactor(self.ns_window) }) as f64
} }
fn is_ime_enabled(&self) -> bool { fn is_ime_enabled(&self) -> bool {
match self.ime_state { !matches!(self.ime_state, ImeState::Disabled)
ImeState::Disabled => false,
_ => true,
}
} }
} }
@ -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))); AppState::handle_redraw(WindowId(get_window_id(state.ns_window)));
let superclass = util::superclass(this); 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; state.forward_key_to_app = true;
let has_marked_text: BOOL = msg_send![this, hasMarkedText]; let has_marked_text: BOOL = msg_send![this, hasMarkedText];
if has_marked_text == NO { if has_marked_text == NO && state.ime_state == ImeState::Preedit {
if state.ime_state == ImeState::Preedit {
// Leave preedit so that we also report the keyup for this key // Leave preedit so that we also report the keyup for this key
state.ime_state = ImeState::Enabled; state.ime_state = ImeState::Enabled;
} }
} }
} }
}
fn get_characters(event: id, ignore_modifiers: bool) -> String { fn get_characters(event: id, ignore_modifiers: bool) -> String {
unsafe { 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 first_responder: id = msg_send![window, firstResponder];
let this_ptr = this as *const _ as *mut _; let this_ptr = this as *const _ as *mut _;
if first_responder == this_ptr { 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 first_responder: id = msg_send![window, firstResponder];
let this_ptr = this as *const _ as *mut _; let this_ptr = this as *const _ as *mut _;
if first_responder == this_ptr { 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; use cocoa::foundation::NSArray;
// register for drag and drop operations. // register for drag and drop operations.
let () = msg_send![ let _: () = msg_send![
*ns_window, *ns_window,
registerForDraggedTypes: registerForDraggedTypes:
NSArray::arrayWithObject(nil, appkit::NSFilenamesPboardType) NSArray::arrayWithObject(nil, appkit::NSFilenamesPboardType)
@ -951,7 +951,7 @@ impl UnownedWindow {
| NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar;
app.setPresentationOptions_(presentation_options); 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 })), &Some(Fullscreen::Exclusive(RootVideoMode { ref video_mode })),
@ -969,7 +969,7 @@ impl UnownedWindow {
// Restore the normal window level following the Borderless fullscreen // Restore the normal window level following the Borderless fullscreen
// `CGShieldingWindowLevel() + 1` hack. // `CGShieldingWindowLevel() + 1` hack.
let () = msg_send![ let _: () = msg_send![
*self.ns_window, *self.ns_window,
setLevel: ffi::NSWindowLevel::NSNormalWindowLevel 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 { if this != nil {
(*this).set_ivar("winitState", state); (*this).set_ivar("winitState", state);
with_state(&*this, |state| { with_state(&*this, |state| {
let () = msg_send![*state.ns_window, setDelegate: this]; let _: () = msg_send![*state.ns_window, setDelegate: this];
}); });
} }
this this
@ -267,7 +267,7 @@ extern "C" fn window_will_close(this: &Object, _: Sel, _: id) {
autoreleasepool(|| { autoreleasepool(|| {
// Since El Capitan, we need to be careful that delegate methods can't // Since El Capitan, we need to be careful that delegate methods can't
// be called after the window closes. // 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); state.emit_event(WindowEvent::Destroyed);
}); });
@ -416,7 +416,8 @@ extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
state.with_window(|window| { state.with_window(|window| {
let mut shared_state = window.lock_shared_state("window_will_enter_fullscreen"); let mut shared_state = window.lock_shared_state("window_will_enter_fullscreen");
shared_state.maximized = window.is_zoomed(); 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 // Exclusive mode sets the state in `set_fullscreen` as the user
// can't enter exclusive mode by other means (like the // can't enter exclusive mode by other means (like the
// fullscreen button on the window decorations) // 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; shared_state.target_fullscreen = None;
}); });
if state.initial_fullscreen { if state.initial_fullscreen {
let _: () = unsafe { unsafe {
msg_send![*state.ns_window, let _: () = msg_send![*state.ns_window,
performSelector:sel!(toggleFullScreen:) performSelector:sel!(toggleFullScreen:)
withObject:nil withObject:nil
afterDelay: 0.5 afterDelay: 0.5
] ];
}; };
} else { } else {
state.with_window(|window| window.restore_state_from_fullscreen()); state.with_window(|window| window.restore_state_from_fullscreen());

View file

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

View file

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

View file

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

View file

@ -44,11 +44,11 @@ impl Canvas {
Some(canvas) => canvas, Some(canvas) => canvas,
None => { None => {
let window = web_sys::window() 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 let document = window
.document() .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 document
.create_element("canvas") .create_element("canvas")
@ -94,10 +94,10 @@ impl Canvas {
self.raw().request_pointer_lock(); self.raw().request_pointer_lock();
} else { } else {
let window = web_sys::window() 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 let document = window
.document() .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(); document.exit_pointer_lock();
} }
Ok(()) Ok(())
@ -107,7 +107,7 @@ impl Canvas {
self.common self.common
.raw .raw
.set_attribute(attribute, value) .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> { pub fn position(&self) -> LogicalPosition<f64> {
@ -339,9 +339,7 @@ impl Common {
handler(event); handler(event);
}) as Box<dyn FnMut(E)>); }) as Box<dyn FnMut(E)>);
let listener = EventListenerHandle::new(&self.raw, event_name, closure); EventListenerHandle::new(&self.raw, event_name, closure)
listener
} }
// The difference between add_event and add_user_event is that the latter has a special meaning // 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}; use web_sys::{EventTarget, MouseEvent};
type MouseLeaveHandler = Rc<RefCell<Option<Box<dyn FnMut(i32)>>>>;
#[allow(dead_code)] #[allow(dead_code)]
pub(super) struct MouseHandler { pub(super) struct MouseHandler {
on_mouse_leave: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>, 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_move: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
on_mouse_press: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>, on_mouse_press: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>,
on_mouse_release: 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>>, mouse_capture_state: Rc<RefCell<MouseCaptureState>>,
} }
@ -175,8 +177,8 @@ impl MouseHandler {
.map_or(false, |target| target == EventTarget::from(canvas.clone())); .map_or(false, |target| target == EventTarget::from(canvas.clone()));
match &*mouse_capture_state { match &*mouse_capture_state {
// Don't handle hover events outside of canvas. // Don't handle hover events outside of canvas.
MouseCaptureState::NotCaptured if !is_over_canvas => return, MouseCaptureState::NotCaptured | MouseCaptureState::OtherElement
MouseCaptureState::OtherElement if !is_over_canvas => return, if !is_over_canvas => {}
// If hovering over the canvas, just send the cursor move event. // If hovering over the canvas, just send the cursor move event.
MouseCaptureState::NotCaptured MouseCaptureState::NotCaptured
| MouseCaptureState::OtherElement | MouseCaptureState::OtherElement

View file

@ -17,7 +17,7 @@ impl MediaQueryListHandle {
.ok() .ok()
.flatten() .flatten()
.and_then(|mql| { .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) .map(|_| mql)
.ok() .ok()
}); });

View file

@ -98,7 +98,7 @@ pub fn set_canvas_style_property(raw: &HtmlCanvasElement, property: &str, value:
let style = raw.style(); let style = raw.style();
style style
.set_property(property, value) .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 { pub fn is_fullscreen(canvas: &HtmlCanvasElement) -> bool {

View file

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

View file

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

View file

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

View file

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

View file

@ -80,19 +80,18 @@ impl ImeContext {
let data = self.get_composition_data(gcs_mode)?; let data = self.get_composition_data(gcs_mode)?;
let (prefix, shorts, suffix) = data.align_to::<u16>(); let (prefix, shorts, suffix) = data.align_to::<u16>();
if prefix.is_empty() && suffix.is_empty() { if prefix.is_empty() && suffix.is_empty() {
OsString::from_wide(&shorts).into_string().ok() OsString::from_wide(shorts).into_string().ok()
} else { } else {
None None
} }
} }
unsafe fn get_composition_data(&self, gcs_mode: u32) -> Option<Vec<u8>> { unsafe fn get_composition_data(&self, gcs_mode: u32) -> Option<Vec<u8>> {
let size = ImmGetCompositionStringW(self.himc, gcs_mode, null_mut(), 0); let size = match ImmGetCompositionStringW(self.himc, gcs_mode, null_mut(), 0) {
if size < 0 { 0 => return Some(Vec::new()),
return None; size if size < 0 => return None,
} else if size == 0 { size => size,
return Some(Vec::new()); };
}
let mut buf = Vec::<u8>::with_capacity(size as _); let mut buf = Vec::<u8>::with_capacity(size as _);
let size = ImmGetCompositionStringW( let size = ImmGetCompositionStringW(
@ -139,7 +138,7 @@ impl ImeContext {
} }
unsafe fn system_has_ime() -> bool { 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. /// Fullscreen modes.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fullscreen { pub enum Fullscreen {
Exclusive(VideoMode), Exclusive(VideoMode),
@ -1134,7 +1134,7 @@ pub enum Fullscreen {
Borderless(Option<MonitorHandle>), Borderless(Option<MonitorHandle>),
} }
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Theme { pub enum Theme {
Light, Light,
Dark, Dark,
@ -1143,7 +1143,7 @@ pub enum Theme {
/// ## Platform-specific /// ## Platform-specific
/// ///
/// - **X11:** Sets the WM's `XUrgencyHint`. No distinction between `Critical` and `Informational`. /// - **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 { pub enum UserAttentionType {
/// ## Platform-specific /// ## Platform-specific
/// - **macOS:** Bounces the dock icon until the application is in focus. /// - **macOS:** Bounces the dock icon until the application is in focus.