From 7b0c7b6cb2c62767ca0c73c857b299883f55a883 Mon Sep 17 00:00:00 2001 From: Kirill Chibisov Date: Fri, 26 Apr 2024 19:11:44 +0400 Subject: [PATCH] chore(rustfmt): use nightly (#2325) Stable rustfmt lacks a lot of features resulting in worse formatted code, thus use nightly formatter. --- .github/workflows/ci.yml | 2 +- dpi/src/lib.rs | 135 +--- examples/child_window.rs | 40 +- examples/control_flow.rs | 25 +- examples/pump_events.rs | 14 +- examples/run_on_demand.rs | 15 +- examples/util/fill.rs | 22 +- examples/util/tracing.rs | 4 +- examples/window.rs | 151 ++-- examples/x11_embed.rs | 7 +- rustfmt.toml | 22 +- src/application.rs | 30 +- src/changelog/mod.rs | 1 - src/cursor.rs | 87 +-- src/error.rs | 11 +- src/event.rs | 273 +++----- src/event_loop.rs | 82 +-- src/icon.rs | 46 +- src/keyboard.rs | 71 +- src/lib.rs | 46 +- src/monitor.rs | 14 +- src/platform/android.rs | 21 +- src/platform/ios.rs | 39 +- src/platform/macos.rs | 45 +- src/platform/mod.rs | 8 +- src/platform/modifier_supplement.rs | 5 +- src/platform/pump_events.rs | 9 +- src/platform/run_on_demand.rs | 20 +- src/platform/scancode.rs | 6 +- src/platform/wayland.rs | 14 +- src/platform/web.rs | 35 +- src/platform/windows.rs | 63 +- src/platform/x11.rs | 35 +- src/platform_impl/android/keycodes.rs | 25 +- src/platform_impl/android/mod.rs | 257 ++++--- src/platform_impl/ios/app_delegate.rs | 6 +- src/platform_impl/ios/app_state.rs | 300 +++----- src/platform_impl/ios/event_loop.rs | 81 +-- src/platform_impl/ios/mod.rs | 17 +- src/platform_impl/ios/monitor.rs | 43 +- .../ios/uikit/gesture_recognizer.rs | 6 +- src/platform_impl/ios/uikit/view.rs | 15 +- src/platform_impl/ios/view.rs | 14 +- src/platform_impl/ios/view_controller.rs | 41 +- src/platform_impl/ios/window.rs | 140 ++-- src/platform_impl/linux/common/xkb/compose.rs | 5 +- src/platform_impl/linux/common/xkb/keymap.rs | 14 +- src/platform_impl/linux/common/xkb/mod.rs | 87 +-- src/platform_impl/linux/mod.rs | 82 +-- .../linux/wayland/event_loop/mod.rs | 114 ++-- .../linux/wayland/event_loop/proxy.rs | 8 +- .../linux/wayland/event_loop/sink.rs | 5 +- src/platform_impl/linux/wayland/output.rs | 14 +- .../linux/wayland/seat/keyboard/mod.rs | 82 +-- src/platform_impl/linux/wayland/seat/mod.rs | 25 +- .../linux/wayland/seat/pointer/mod.rs | 78 +-- .../wayland/seat/pointer/relative_pointer.rs | 32 +- .../linux/wayland/seat/text_input/mod.rs | 45 +- .../linux/wayland/seat/touch/mod.rs | 8 +- src/platform_impl/linux/wayland/state.rs | 34 +- .../linux/wayland/types/kwin_blur.rs | 8 +- .../wayland/types/wp_fractional_scaling.rs | 15 +- .../linux/wayland/types/wp_viewporter.rs | 6 +- .../linux/wayland/types/xdg_activation.rs | 11 +- src/platform_impl/linux/wayland/window/mod.rs | 85 +-- .../linux/wayland/window/state.rs | 108 +-- src/platform_impl/linux/x11/activation.rs | 18 +- src/platform_impl/linux/x11/dnd.rs | 58 +- .../linux/x11/event_processor.rs | 413 ++++------- src/platform_impl/linux/x11/ffi.rs | 6 +- src/platform_impl/linux/x11/ime/callbacks.rs | 31 +- src/platform_impl/linux/x11/ime/context.rs | 28 +- src/platform_impl/linux/x11/ime/inner.rs | 10 +- .../linux/x11/ime/input_method.rs | 58 +- src/platform_impl/linux/x11/ime/mod.rs | 37 +- src/platform_impl/linux/x11/mod.rs | 190 ++---- src/platform_impl/linux/x11/monitor.rs | 44 +- src/platform_impl/linux/x11/util/cursor.rs | 26 +- src/platform_impl/linux/x11/util/geometry.rs | 116 +--- src/platform_impl/linux/x11/util/hint.rs | 8 +- src/platform_impl/linux/x11/util/input.rs | 17 +- src/platform_impl/linux/x11/util/keys.rs | 11 +- src/platform_impl/linux/x11/util/mod.rs | 32 +- src/platform_impl/linux/x11/util/mouse.rs | 5 +- src/platform_impl/linux/x11/util/randr.rs | 46 +- .../linux/x11/util/window_property.rs | 5 +- src/platform_impl/linux/x11/util/wm.rs | 28 +- src/platform_impl/linux/x11/window.rs | 384 ++++------- src/platform_impl/linux/x11/xdisplay.rs | 47 +- src/platform_impl/linux/x11/xsettings.rs | 50 +- src/platform_impl/macos/app.rs | 20 +- src/platform_impl/macos/app_delegate.rs | 70 +- src/platform_impl/macos/cursor.rs | 21 +- src/platform_impl/macos/event.rs | 119 ++-- src/platform_impl/macos/event_handler.rs | 21 +- src/platform_impl/macos/event_loop.rs | 100 ++- src/platform_impl/macos/ffi.rs | 16 +- src/platform_impl/macos/menu.rs | 26 +- src/platform_impl/macos/mod.rs | 16 +- src/platform_impl/macos/monitor.rs | 18 +- src/platform_impl/macos/observer.rs | 44 +- src/platform_impl/macos/util.rs | 16 +- src/platform_impl/macos/view.rs | 32 +- src/platform_impl/macos/window.rs | 7 +- src/platform_impl/macos/window_delegate.rs | 141 ++-- src/platform_impl/mod.rs | 7 +- src/platform_impl/orbital/event_loop.rs | 188 ++--- src/platform_impl/orbital/mod.rs | 40 +- src/platform_impl/orbital/window.rs | 90 +-- src/platform_impl/web/async/abortable.rs | 10 +- src/platform_impl/web/async/channel.rs | 27 +- .../web/async/concurrent_queue.rs | 5 +- src/platform_impl/web/async/dispatcher.rs | 32 +- src/platform_impl/web/async/notifier.rs | 16 +- src/platform_impl/web/async/waker.rs | 3 +- src/platform_impl/web/async/wrapper.rs | 17 +- src/platform_impl/web/cursor.rs | 165 ++--- src/platform_impl/web/event_loop/mod.rs | 21 +- src/platform_impl/web/event_loop/proxy.rs | 9 +- src/platform_impl/web/event_loop/runner.rs | 134 ++-- src/platform_impl/web/event_loop/state.rs | 14 +- .../web/event_loop/window_target.rs | 75 +- src/platform_impl/web/mod.rs | 7 +- .../web/web_sys/animation_frame.rs | 18 +- src/platform_impl/web/web_sys/canvas.rs | 41 +- src/platform_impl/web/web_sys/event.rs | 52 +- src/platform_impl/web/web_sys/event_handle.rs | 9 +- src/platform_impl/web/web_sys/fullscreen.rs | 2 +- .../web/web_sys/intersection_handle.rs | 8 +- .../web/web_sys/media_query_handle.rs | 10 +- src/platform_impl/web/web_sys/mod.rs | 14 +- src/platform_impl/web/web_sys/pointer.rs | 59 +- .../web/web_sys/resize_scaling.rs | 15 +- src/platform_impl/web/web_sys/schedule.rs | 23 +- src/platform_impl/web/window.rs | 44 +- src/platform_impl/windows/dark_mode.rs | 34 +- src/platform_impl/windows/definitions.rs | 20 +- src/platform_impl/windows/dpi.rs | 20 +- src/platform_impl/windows/drop_handler.rs | 59 +- src/platform_impl/windows/event_loop.rs | 644 +++++++----------- .../windows/event_loop/runner.rs | 92 +-- src/platform_impl/windows/icon.rs | 33 +- src/platform_impl/windows/ime.rs | 46 +- src/platform_impl/windows/keyboard.rs | 568 +++++++-------- src/platform_impl/windows/keyboard_layout.rs | 138 ++-- src/platform_impl/windows/mod.rs | 28 +- src/platform_impl/windows/monitor.rs | 56 +- src/platform_impl/windows/raw_input.rs | 95 +-- src/platform_impl/windows/util.rs | 65 +- src/platform_impl/windows/window.rs | 356 ++++------ src/platform_impl/windows/window_state.rs | 119 ++-- src/utils.rs | 6 +- src/window.rs | 256 ++++--- tests/serde_objects.rs | 10 +- 154 files changed, 3446 insertions(+), 5898 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28c1f75c61..ecf78fcf25 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@nightly with: components: rustfmt - name: Check Formatting diff --git a/dpi/src/lib.rs b/dpi/src/lib.rs index 06dcdd06fa..942d40a5cf 100644 --- a/dpi/src/lib.rs +++ b/dpi/src/lib.rs @@ -35,9 +35,9 @@ //! //! ### Position and Size types //! -//! The [`PhysicalPosition`] / [`PhysicalSize`] / [`PhysicalUnit`] types correspond with the actual pixels on the -//! device, and the [`LogicalPosition`] / [`LogicalSize`] / [`LogicalUnit`] types correspond to the physical pixels -//! divided by the scale factor. +//! The [`PhysicalPosition`] / [`PhysicalSize`] / [`PhysicalUnit`] types correspond with the actual +//! pixels on the device, and the [`LogicalPosition`] / [`LogicalSize`] / [`LogicalUnit`] types +//! correspond to the physical pixels divided by the scale factor. //! //! The position and size types are generic over their exact pixel type, `P`, to allow the //! API to have integer precision where appropriate (e.g. most window manipulation functions) and @@ -52,19 +52,14 @@ //! //! This crate provides the following Cargo features: //! -//! * `serde`: Enables serialization/deserialization of certain types with -//! [Serde](https://crates.io/crates/serde). +//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde). //! * `mint`: Enables mint (math interoperability standard types) conversions. //! //! //! [points]: https://en.wikipedia.org/wiki/Point_(typography) //! [picas]: https://en.wikipedia.org/wiki/Pica_(typography) -#![cfg_attr( - docsrs, - feature(doc_auto_cfg, doc_cfg_hide), - doc(cfg_hide(doc, docsrs)) -)] +#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))] #![forbid(unsafe_code)] #[cfg(feature = "serde")] @@ -120,9 +115,9 @@ impl Pixel for f64 { /// Checks that the scale factor is a normal positive `f64`. /// -/// All functions that take a scale factor assert that this will return `true`. If you're sourcing scale factors from -/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit; -/// otherwise, you risk panics. +/// All functions that take a scale factor assert that this will return `true`. If you're sourcing +/// scale factors from anywhere other than winit, it's recommended to validate them using this +/// function before passing them to winit; otherwise, you risk panics. #[inline] pub fn validate_scale_factor(scale_factor: f64) -> bool { scale_factor.is_sign_positive() && scale_factor.is_normal() @@ -134,12 +129,12 @@ pub fn validate_scale_factor(scale_factor: f64) -> bool { pub struct LogicalUnit

(pub P); impl

LogicalUnit

{ + /// Represents a maximum logical unit that is equal to [`f64::MAX`]. + pub const MAX: LogicalUnit = LogicalUnit::new(f64::MAX); /// Represents a minimum logical unit of [`f64::MAX`]. pub const MIN: LogicalUnit = LogicalUnit::new(f64::MIN); /// Represents a logical unit of `0_f64`. pub const ZERO: LogicalUnit = LogicalUnit::new(0.0); - /// Represents a maximum logical unit that is equal to [`f64::MAX`]. - pub const MAX: LogicalUnit = LogicalUnit::new(f64::MAX); #[inline] pub const fn new(v: P) -> Self { @@ -228,12 +223,12 @@ impl From> for f64 { pub struct PhysicalUnit

(pub P); impl

PhysicalUnit

{ + /// Represents a maximum physical unit that is equal to [`f64::MAX`]. + pub const MAX: LogicalUnit = LogicalUnit::new(f64::MAX); /// Represents a minimum physical unit of [`f64::MAX`]. pub const MIN: LogicalUnit = LogicalUnit::new(f64::MIN); /// Represents a physical unit of `0_f64`. pub const ZERO: LogicalUnit = LogicalUnit::new(0.0); - /// Represents a maximum physical unit that is equal to [`f64::MAX`]. - pub const MAX: LogicalUnit = LogicalUnit::new(f64::MAX); #[inline] pub const fn new(v: P) -> Self { @@ -322,12 +317,12 @@ pub enum PixelUnit { } impl PixelUnit { + /// Represents a maximum logical unit that is equal to [`f64::MAX`]. + pub const MAX: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MAX)); /// Represents a minimum logical unit of [`f64::MAX`]. pub const MIN: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MIN)); /// Represents a logical unit of `0_f64`. pub const ZERO: PixelUnit = PixelUnit::Logical(LogicalUnit::new(0.0)); - /// Represents a maximum logical unit that is equal to [`f64::MAX`]. - pub const MAX: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MAX)); pub fn new>(unit: S) -> PixelUnit { unit.into() @@ -400,10 +395,7 @@ impl LogicalPosition

{ #[inline] pub fn cast(&self) -> LogicalPosition { - LogicalPosition { - x: self.x.cast(), - y: self.y.cast(), - } + LogicalPosition { x: self.x.cast(), y: self.y.cast() } } } @@ -479,10 +471,7 @@ impl PhysicalPosition

{ #[inline] pub fn cast(&self) -> PhysicalPosition { - PhysicalPosition { - x: self.x.cast(), - y: self.y.cast(), - } + PhysicalPosition { x: self.x.cast(), y: self.y.cast() } } } @@ -558,10 +547,7 @@ impl LogicalSize

{ #[inline] pub fn cast(&self) -> LogicalSize { - LogicalSize { - width: self.width.cast(), - height: self.height.cast(), - } + LogicalSize { width: self.width.cast(), height: self.height.cast() } } } @@ -599,10 +585,7 @@ impl From> for LogicalSize

{ #[cfg(feature = "mint")] impl From> for mint::Vector2

{ fn from(s: LogicalSize

) -> Self { - mint::Vector2 { - x: s.width, - y: s.height, - } + mint::Vector2 { x: s.width, y: s.height } } } @@ -637,10 +620,7 @@ impl PhysicalSize

{ #[inline] pub fn cast(&self) -> PhysicalSize { - PhysicalSize { - width: self.width.cast(), - height: self.height.cast(), - } + PhysicalSize { width: self.width.cast(), height: self.height.cast() } } } @@ -678,10 +658,7 @@ impl From> for PhysicalSize

{ #[cfg(feature = "mint")] impl From> for mint::Vector2

{ fn from(s: PhysicalSize

) -> Self { - mint::Vector2 { - x: s.width, - y: s.height, - } + mint::Vector2 { x: s.width, y: s.height } } } @@ -846,12 +823,7 @@ mod tests { macro_rules! assert_approx_eq { ($a:expr, $b:expr $(,)?) => { - assert!( - ($a - $b).abs() < 0.001, - "{} is not approximately equal to {}", - $a, - $b - ); + assert!(($a - $b).abs() < 0.001, "{} is not approximately equal to {}", $a, $b); }; } @@ -970,14 +942,8 @@ mod tests { assert_eq!(log_unit.to_physical::(1.0), PhysicalUnit::new(1)); assert_eq!(log_unit.to_physical::(2.0), PhysicalUnit::new(2)); assert_eq!(log_unit.cast::(), LogicalUnit::new(1)); - assert_eq!( - log_unit, - LogicalUnit::from_physical(PhysicalUnit::new(1.0), 1.0) - ); - assert_eq!( - log_unit, - LogicalUnit::from_physical(PhysicalUnit::new(2.0), 2.0) - ); + assert_eq!(log_unit, LogicalUnit::from_physical(PhysicalUnit::new(1.0), 1.0)); + assert_eq!(log_unit, LogicalUnit::from_physical(PhysicalUnit::new(2.0), 2.0)); assert_eq!(LogicalUnit::from(2.0), LogicalUnit::new(2.0)); let x: f64 = log_unit.into(); @@ -986,14 +952,8 @@ mod tests { #[test] fn test_physical_unit() { - assert_eq!( - PhysicalUnit::from_logical(LogicalUnit::new(1.0), 1.0), - PhysicalUnit::new(1) - ); - assert_eq!( - PhysicalUnit::from_logical(LogicalUnit::new(2.0), 0.5), - PhysicalUnit::new(1) - ); + assert_eq!(PhysicalUnit::from_logical(LogicalUnit::new(1.0), 1.0), PhysicalUnit::new(1)); + assert_eq!(PhysicalUnit::from_logical(LogicalUnit::new(2.0), 0.5), PhysicalUnit::new(1)); assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0,)); assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0)); @@ -1007,22 +967,10 @@ mod tests { assert_eq!(log_pos.to_physical::(1.0), PhysicalPosition::new(1, 2)); assert_eq!(log_pos.to_physical::(2.0), PhysicalPosition::new(2, 4)); assert_eq!(log_pos.cast::(), LogicalPosition::new(1, 2)); - assert_eq!( - log_pos, - LogicalPosition::from_physical(PhysicalPosition::new(1.0, 2.0), 1.0) - ); - assert_eq!( - log_pos, - LogicalPosition::from_physical(PhysicalPosition::new(2.0, 4.0), 2.0) - ); - assert_eq!( - LogicalPosition::from((2.0, 2.0)), - LogicalPosition::new(2.0, 2.0) - ); - assert_eq!( - LogicalPosition::from([2.0, 3.0]), - LogicalPosition::new(2.0, 3.0) - ); + assert_eq!(log_pos, LogicalPosition::from_physical(PhysicalPosition::new(1.0, 2.0), 1.0)); + assert_eq!(log_pos, LogicalPosition::from_physical(PhysicalPosition::new(2.0, 4.0), 2.0)); + assert_eq!(LogicalPosition::from((2.0, 2.0)), LogicalPosition::new(2.0, 2.0)); + assert_eq!(LogicalPosition::from([2.0, 3.0]), LogicalPosition::new(2.0, 3.0)); let x: (f64, f64) = log_pos.into(); assert_eq!(x, (1.0, 2.0)); @@ -1040,14 +988,8 @@ mod tests { PhysicalPosition::from_logical(LogicalPosition::new(2.0, 4.0), 0.5), PhysicalPosition::new(1, 2) ); - assert_eq!( - PhysicalPosition::from((2.0, 2.0)), - PhysicalPosition::new(2.0, 2.0) - ); - assert_eq!( - PhysicalPosition::from([2.0, 3.0]), - PhysicalPosition::new(2.0, 3.0) - ); + assert_eq!(PhysicalPosition::from((2.0, 2.0)), PhysicalPosition::new(2.0, 2.0)); + assert_eq!(PhysicalPosition::from([2.0, 3.0]), PhysicalPosition::new(2.0, 3.0)); let x: (f64, f64) = PhysicalPosition::new(1, 2).into(); assert_eq!(x, (1.0, 2.0)); @@ -1061,14 +1003,8 @@ mod tests { assert_eq!(log_size.to_physical::(1.0), PhysicalSize::new(1, 2)); assert_eq!(log_size.to_physical::(2.0), PhysicalSize::new(2, 4)); assert_eq!(log_size.cast::(), LogicalSize::new(1, 2)); - assert_eq!( - log_size, - LogicalSize::from_physical(PhysicalSize::new(1.0, 2.0), 1.0) - ); - assert_eq!( - log_size, - LogicalSize::from_physical(PhysicalSize::new(2.0, 4.0), 2.0) - ); + assert_eq!(log_size, LogicalSize::from_physical(PhysicalSize::new(1.0, 2.0), 1.0)); + assert_eq!(log_size, LogicalSize::from_physical(PhysicalSize::new(2.0, 4.0), 2.0)); assert_eq!(LogicalSize::from((2.0, 2.0)), LogicalSize::new(2.0, 2.0)); assert_eq!(LogicalSize::from([2.0, 3.0]), LogicalSize::new(2.0, 3.0)); @@ -1099,10 +1035,7 @@ mod tests { #[test] fn test_size() { - assert_eq!( - Size::new(PhysicalSize::new(1, 2)), - Size::Physical(PhysicalSize::new(1, 2)) - ); + assert_eq!(Size::new(PhysicalSize::new(1, 2)), Size::Physical(PhysicalSize::new(1, 2))); assert_eq!( Size::new(LogicalSize::new(1.0, 2.0)), Size::Logical(LogicalSize::new(1.0, 2.0)) diff --git a/examples/child_window.rs b/examples/child_window.rs index f3ff496c9d..715996eb60 100644 --- a/examples/child_window.rs +++ b/examples/child_window.rs @@ -1,7 +1,4 @@ -#[cfg(all( - feature = "rwh_06", - any(x11_platform, macos_platform, windows_platform) -))] +#[cfg(all(feature = "rwh_06", any(x11_platform, macos_platform, windows_platform)))] #[allow(deprecated)] fn main() -> Result<(), impl std::error::Error> { use std::collections::HashMap; @@ -46,25 +43,22 @@ fn main() -> Result<(), impl std::error::Error> { println!("Parent window id: {parent_window_id:?})"); windows.insert(window.id(), window); - } + }, Event::WindowEvent { window_id, event } => match event { WindowEvent::CloseRequested => { windows.clear(); event_loop.exit(); - } + }, WindowEvent::CursorEntered { device_id: _ } => { - // On x11, println when the cursor entered in a window even if the child window is created - // by some key inputs. - // the child windows are always placed at (0, 0) with size (200, 200) in the parent window, - // so we also can see this log when we move the cursor around (200, 200) in parent window. + // On x11, println when the cursor entered in a window even if the child window + // is created by some key inputs. + // the child windows are always placed at (0, 0) with size (200, 200) in the + // parent window, so we also can see this log when we move + // the cursor around (200, 200) in parent window. println!("cursor entered in the window {window_id:?}"); - } + }, WindowEvent::KeyboardInput { - event: - KeyEvent { - state: ElementState::Pressed, - .. - }, + event: KeyEvent { state: ElementState::Pressed, .. }, .. } => { let parent_window = windows.get(&parent_window_id.unwrap()).unwrap(); @@ -72,12 +66,12 @@ fn main() -> Result<(), impl std::error::Error> { let child_id = child_window.id(); println!("Child window created with id: {child_id:?}"); windows.insert(child_id, child_window); - } + }, WindowEvent::RedrawRequested => { if let Some(window) = windows.get(&window_id) { fill::fill_window(window); } - } + }, _ => (), }, _ => (), @@ -85,10 +79,10 @@ fn main() -> Result<(), impl std::error::Error> { }) } -#[cfg(all( - feature = "rwh_06", - not(any(x11_platform, macos_platform, windows_platform)) -))] +#[cfg(all(feature = "rwh_06", not(any(x11_platform, macos_platform, windows_platform))))] fn main() { - panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled."); + panic!( + "This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \ + enabled." + ); } diff --git a/examples/control_flow.rs b/examples/control_flow.rs index 76032db251..13cc94771c 100644 --- a/examples/control_flow.rs +++ b/examples/control_flow.rs @@ -85,14 +85,9 @@ impl ApplicationHandler for ControlFlowDemo { match event { WindowEvent::CloseRequested => { self.close_requested = true; - } + }, WindowEvent::KeyboardInput { - event: - KeyEvent { - logical_key: key, - state: ElementState::Pressed, - .. - }, + event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. }, .. } => match key.as_ref() { // WARNING: Consider using `key_without_modifiers()` if available on your platform. @@ -100,29 +95,29 @@ impl ApplicationHandler for ControlFlowDemo { Key::Character("1") => { self.mode = Mode::Wait; warn!("mode: {:?}", self.mode); - } + }, Key::Character("2") => { self.mode = Mode::WaitUntil; warn!("mode: {:?}", self.mode); - } + }, Key::Character("3") => { self.mode = Mode::Poll; warn!("mode: {:?}", self.mode); - } + }, Key::Character("r") => { self.request_redraw = !self.request_redraw; warn!("request_redraw: {}", self.request_redraw); - } + }, Key::Named(NamedKey::Escape) => { self.close_requested = true; - } + }, _ => (), }, WindowEvent::RedrawRequested => { let window = self.window.as_ref().unwrap(); window.pre_present_notify(); fill::fill_window(window); - } + }, _ => (), } } @@ -139,11 +134,11 @@ impl ApplicationHandler for ControlFlowDemo { event_loop .set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME)); } - } + }, Mode::Poll => { thread::sleep(POLL_SLEEP_TIME); event_loop.set_control_flow(ControlFlow::Poll); - } + }, }; if self.close_requested { diff --git a/examples/pump_events.rs b/examples/pump_events.rs index c7c64990cc..ad198cfafe 100644 --- a/examples/pump_events.rs +++ b/examples/pump_events.rs @@ -1,15 +1,11 @@ #![allow(clippy::single_match)] // Limit this example to only compatible platforms. -#[cfg(any( - windows_platform, - macos_platform, - x11_platform, - wayland_platform, - android_platform, -))] +#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, android_platform,))] fn main() -> std::process::ExitCode { - use std::{process::ExitCode, thread::sleep, time::Duration}; + use std::process::ExitCode; + use std::thread::sleep; + use std::time::Duration; use winit::application::ApplicationHandler; use winit::event::WindowEvent; @@ -49,7 +45,7 @@ fn main() -> std::process::ExitCode { WindowEvent::RedrawRequested => { fill::fill_window(window); window.request_redraw(); - } + }, _ => (), } } diff --git a/examples/run_on_demand.rs b/examples/run_on_demand.rs index 33488c1f9e..5a277de1b0 100644 --- a/examples/run_on_demand.rs +++ b/examples/run_on_demand.rs @@ -60,13 +60,17 @@ fn main() -> Result<(), Box> { match event { WindowEvent::CloseRequested => { - println!("--------------------------------------------------------- Window {} CloseRequested", self.idx); + println!( + "--------------------------------------------------------- Window {} \ + CloseRequested", + self.idx + ); fill::cleanup_window(window); self.window = None; - } + }, WindowEvent::RedrawRequested => { fill::fill_window(window); - } + }, _ => (), } } @@ -76,10 +80,7 @@ fn main() -> Result<(), Box> { let mut event_loop = EventLoop::new().unwrap(); - let mut app = App { - idx: 1, - ..Default::default() - }; + let mut app = App { idx: 1, ..Default::default() }; event_loop.run_app_on_demand(&mut app)?; println!("--------------------------------------------------------- Finished first loop"); diff --git a/examples/util/fill.rs b/examples/util/fill.rs index 5b5d9b4693..31540c0290 100644 --- a/examples/util/fill.rs +++ b/examples/util/fill.rs @@ -20,8 +20,7 @@ mod platform { use std::num::NonZeroU32; use softbuffer::{Context, Surface}; - use winit::window::Window; - use winit::window::WindowId; + use winit::window::{Window, WindowId}; thread_local! { // NOTE: You should never do things like that, create context and drop it before @@ -80,24 +79,17 @@ mod platform { // Either get the last context used or create a new one. let mut gc = gc.borrow_mut(); - let surface = gc - .get_or_insert_with(|| GraphicsContext::new(window)) - .create_surface(window); + let surface = + gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window); // Fill a buffer with a solid color. - const DARK_GRAY: u32 = 0xFF181818; + const DARK_GRAY: u32 = 0xff181818; - surface - .resize(width, height) - .expect("Failed to resize the softbuffer surface"); + surface.resize(width, height).expect("Failed to resize the softbuffer surface"); - let mut buffer = surface - .buffer_mut() - .expect("Failed to get the softbuffer buffer"); + let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer"); buffer.fill(DARK_GRAY); - buffer - .present() - .expect("Failed to present the softbuffer buffer"); + buffer.present().expect("Failed to present the softbuffer buffer"); }) } diff --git a/examples/util/tracing.rs b/examples/util/tracing.rs index f5c8f3742d..bab7ced71a 100644 --- a/examples/util/tracing.rs +++ b/examples/util/tracing.rs @@ -4,9 +4,7 @@ pub fn init() { tracing_subscriber::fmt() .with_env_filter( - EnvFilter::builder() - .with_default_directive(LevelFilter::INFO.into()) - .from_env_lossy(), + EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy(), ) .init(); } diff --git a/examples/window.rs b/examples/window.rs index 437d90ec81..83a31e1346 100644 --- a/examples/window.rs +++ b/examples/window.rs @@ -2,12 +2,11 @@ use std::collections::HashMap; use std::error::Error; -use std::fmt; use std::fmt::Debug; -use std::mem; #[cfg(not(any(android_platform, ios_platform)))] use std::num::NonZeroU32; use std::sync::Arc; +use std::{fmt, mem}; use ::tracing::{error, info}; use cursor_icon::CursorIcon; @@ -18,15 +17,13 @@ use softbuffer::{Context, Surface}; use winit::application::ApplicationHandler; use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize}; -use winit::event::{DeviceEvent, DeviceId, Ime, WindowEvent}; -use winit::event::{MouseButton, MouseScrollDelta}; +use winit::event::{DeviceEvent, DeviceId, Ime, MouseButton, MouseScrollDelta, WindowEvent}; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::keyboard::{Key, ModifiersState}; use winit::window::{ Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, Fullscreen, Icon, ResizeDirection, - Theme, + Theme, Window, WindowId, }; -use winit::window::{Window, WindowId}; #[cfg(macos_platform)] use winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS}; @@ -100,10 +97,11 @@ impl Application { .unwrap(), ); - // You'll have to choose an icon size at your own discretion. On X11, the desired size varies - // by WM, and on Windows, you still have to account for screen scaling. Here we use 32px, - // since it seems to work well enough in most cases. Be careful about going too high, or - // you'll be bitten by the low-quality downscaling built into the WM. + // You'll have to choose an icon size at your own discretion. On X11, the desired size + // varies by WM, and on Windows, you still have to account for screen scaling. Here + // we use 32px, since it seems to work well enough in most cases. Be careful about + // going too high, or you'll be bitten by the low-quality downscaling built into the + // WM. let icon = load_icon(include_bytes!("data/icon.png")); info!("Loading cursor assets"); @@ -177,7 +175,7 @@ impl Application { match action { Action::CloseWindow => { let _ = self.windows.remove(&window_id); - } + }, Action::CreateNewWindow => { #[cfg(any(x11_platform, wayland_platform))] if let Err(err) = window.window.request_activation_token() { @@ -189,7 +187,7 @@ impl Application { if let Err(err) = self.create_window(event_loop, None) { error!("Error creating new window: {err}"); } - } + }, Action::ToggleResizeIncrements => window.toggle_resize_increments(), Action::ToggleCursorVisibility => window.toggle_cursor_visibility(), Action::ToggleResizable => window.toggle_resizable(), @@ -205,7 +203,7 @@ impl Application { #[cfg(web_platform)] Action::AnimationCustomCursor => { window.animation_custom_cursor(event_loop, &self.custom_cursors) - } + }, Action::CycleCursorGrab => window.cycle_cursor_grab(), Action::DragWindow => window.drag_window(), Action::DragResizeWindow => window.drag_resize_window(), @@ -219,7 +217,7 @@ impl Application { if let Err(err) = self.create_window(event_loop, Some(tab_id)) { error!("Error creating new window: {err}"); } - } + }, Action::RequestResize => window.swap_dimensions(), } } @@ -260,31 +258,23 @@ impl Application { let PhysicalSize { width, height } = mode.size(); let bits = mode.bit_depth(); let m_hz = mode.refresh_rate_millihertz(); - info!( - " {width}x{height}x{bits} @ {}.{} Hz", - m_hz / 1000, - m_hz % 1000 - ); + info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000); } } } /// Process the key binding. fn process_key_binding(key: &str, mods: &ModifiersState) -> Option { - KEY_BINDINGS.iter().find_map(|binding| { - binding - .is_triggered_by(&key, mods) - .then_some(binding.action) - }) + KEY_BINDINGS + .iter() + .find_map(|binding| binding.is_triggered_by(&key, mods).then_some(binding.action)) } /// Process mouse binding. fn process_mouse_binding(button: MouseButton, mods: &ModifiersState) -> Option { - MOUSE_BINDINGS.iter().find_map(|binding| { - binding - .is_triggered_by(&button, mods) - .then_some(binding.action) - }) + MOUSE_BINDINGS + .iter() + .find_map(|binding| binding.is_triggered_by(&button, mods).then_some(binding.action)) } fn print_help(&self) { @@ -330,50 +320,46 @@ impl ApplicationHandler for Application { match event { WindowEvent::Resized(size) => { window.resize(size); - } + }, WindowEvent::Focused(focused) => { if focused { info!("Window={window_id:?} focused"); } else { info!("Window={window_id:?} unfocused"); } - } + }, WindowEvent::ScaleFactorChanged { scale_factor, .. } => { info!("Window={window_id:?} changed scale to {scale_factor}"); - } + }, WindowEvent::ThemeChanged(theme) => { info!("Theme changed to {theme:?}"); window.set_theme(theme); - } + }, WindowEvent::RedrawRequested => { if let Err(err) = window.draw() { error!("Error drawing window: {err}"); } - } + }, WindowEvent::Occluded(occluded) => { window.set_occluded(occluded); - } + }, WindowEvent::CloseRequested => { info!("Closing Window={window_id:?}"); self.windows.remove(&window_id); - } + }, WindowEvent::ModifiersChanged(modifiers) => { window.modifiers = modifiers.state(); info!("Modifiers changed to {:?}", window.modifiers); - } + }, WindowEvent::MouseWheel { delta, .. } => match delta { MouseScrollDelta::LineDelta(x, y) => { info!("Mouse wheel Line Delta: ({x},{y})"); - } + }, MouseScrollDelta::PixelDelta(px) => { info!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y); - } + }, }, - WindowEvent::KeyboardInput { - event, - is_synthetic: false, - .. - } => { + WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => { let mods = window.modifiers; // Dispatch actions only on press. @@ -388,25 +374,23 @@ impl ApplicationHandler for Application { self.handle_action(event_loop, window_id, action); } } - } + }, WindowEvent::MouseInput { button, state, .. } => { let mods = window.modifiers; - if let Some(action) = state - .is_pressed() - .then(|| Self::process_mouse_binding(button, &mods)) - .flatten() + if let Some(action) = + state.is_pressed().then(|| Self::process_mouse_binding(button, &mods)).flatten() { self.handle_action(event_loop, window_id, action); } - } + }, WindowEvent::CursorLeft { .. } => { info!("Cursor left Window={window_id:?}"); window.cursor_left(); - } + }, WindowEvent::CursorMoved { position, .. } => { info!("Moved cursor to {position:?}"); window.cursor_moved(position); - } + }, WindowEvent::ActivationTokenDone { token: _token, .. } => { #[cfg(any(x11_platform, wayland_platform))] { @@ -415,15 +399,15 @@ impl ApplicationHandler for Application { error!("Error creating new window: {err}"); } } - } + }, WindowEvent::Ime(event) => match event { Ime::Enabled => info!("IME enabled for Window={window_id:?}"), Ime::Preedit(text, caret_pos) => { info!("Preedit: {}, with caret at {:?}", text, caret_pos); - } + }, Ime::Commit(text) => { info!("Committed: {}", text); - } + }, Ime::Disabled => info!("IME disabled for Window={window_id:?}"), }, WindowEvent::PinchGesture { delta, .. } => { @@ -434,7 +418,7 @@ impl ApplicationHandler for Application { } else { info!("Zoomed out {delta:.5} (now: {zoom:.5})"); } - } + }, WindowEvent::RotationGesture { delta, .. } => { window.rotated += delta; let rotated = window.rotated; @@ -443,10 +427,10 @@ impl ApplicationHandler for Application { } else { info!("Rotated clockwise {delta:.5} (now: {rotated:.5})"); } - } + }, WindowEvent::DoubleTapGesture { .. } => { info!("Smart zoom"); - } + }, WindowEvent::TouchpadPressure { .. } | WindowEvent::HoveredFileCancelled | WindowEvent::KeyboardInput { .. } @@ -474,8 +458,7 @@ impl ApplicationHandler for Application { self.dump_monitors(event_loop); // Create initial window. - self.create_window(event_loop, None) - .expect("failed to create initial window"); + self.create_window(event_loop, None).expect("failed to create initial window"); self.print_help(); } @@ -575,8 +558,7 @@ impl WindowState { self.ime = !self.ime; self.window.set_ime_allowed(self.ime); if let Some(position) = self.ime.then_some(self.cursor_position).flatten() { - self.window - .set_ime_cursor_area(position, PhysicalSize::new(20, 20)); + self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20)); } } @@ -587,8 +569,7 @@ impl WindowState { pub fn cursor_moved(&mut self, position: PhysicalPosition) { self.cursor_position = Some(position); if self.ime { - self.window - .set_ime_cursor_area(position, PhysicalSize::new(20, 20)); + self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20)); } } @@ -689,8 +670,7 @@ impl WindowState { fn next_cursor(&mut self) { self.named_idx = (self.named_idx + 1) % CURSORS.len(); info!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]); - self.window - .set_cursor(Cursor::Icon(CURSORS[self.named_idx])); + self.window.set_cursor(Cursor::Icon(CURSORS[self.named_idx])); } /// Pick the next custom cursor. @@ -739,9 +719,7 @@ impl WindowState { (Some(width), Some(height)) => (width, height), _ => return, }; - self.surface - .resize(width, height) - .expect("failed to resize inner buffer"); + self.surface.resize(width, height).expect("failed to resize inner buffer"); } self.window.request_redraw(); } @@ -775,7 +753,7 @@ impl WindowState { None => { info!("Drag-resize requires cursor to be inside the window"); return; - } + }, }; let win_size = self.window.inner_size(); @@ -834,8 +812,8 @@ impl WindowState { return Ok(()); } - const WHITE: u32 = 0xFFFFFFFF; - const DARK_GRAY: u32 = 0xFF181818; + const WHITE: u32 = 0xffffffff; + const DARK_GRAY: u32 = 0xff181818; let color = match self.theme { Theme::Light => WHITE, @@ -864,11 +842,7 @@ struct Binding { impl Binding { const fn new(trigger: T, mods: ModifiersState, action: Action) -> Self { - Self { - trigger, - mods, - action, - } + Self { trigger, mods, action } } fn is_triggered_by(&self, trigger: &T, mods: &ModifiersState) -> bool { @@ -962,10 +936,7 @@ fn url_custom_cursor() -> CustomCursorSource { static URL_COUNTER: AtomicU64 = AtomicU64::new(0); CustomCursor::from_url( - format!( - "https://picsum.photos/128?random={}", - URL_COUNTER.fetch_add(1, Ordering::Relaxed) - ), + format!("https://picsum.photos/128?random={}", URL_COUNTER.fetch_add(1, Ordering::Relaxed)), 64, 64, ) @@ -1086,19 +1057,7 @@ const KEY_BINDINGS: &[Binding<&'static str>] = &[ ]; const MOUSE_BINDINGS: &[Binding] = &[ - Binding::new( - MouseButton::Left, - ModifiersState::ALT, - Action::DragResizeWindow, - ), - Binding::new( - MouseButton::Left, - ModifiersState::CONTROL, - Action::DragWindow, - ), - Binding::new( - MouseButton::Right, - ModifiersState::CONTROL, - Action::ShowWindowMenu, - ), + Binding::new(MouseButton::Left, ModifiersState::ALT, Action::DragResizeWindow), + Binding::new(MouseButton::Left, ModifiersState::CONTROL, Action::DragWindow), + Binding::new(MouseButton::Right, ModifiersState::CONTROL, Action::ShowWindowMenu), ]; diff --git a/examples/x11_embed.rs b/examples/x11_embed.rs index 9e77694c3b..9db55e5cd2 100644 --- a/examples/x11_embed.rs +++ b/examples/x11_embed.rs @@ -39,7 +39,7 @@ fn main() -> Result<(), Box> { WindowEvent::RedrawRequested => { window.pre_present_notify(); fill::fill_window(window); - } + }, _ => (), } } @@ -58,10 +58,7 @@ fn main() -> Result<(), Box> { tracing_subscriber::fmt::init(); let event_loop = EventLoop::new()?; - let mut app = XEmbedDemo { - parent_window_id, - window: None, - }; + let mut app = XEmbedDemo { parent_window_id, window: None }; event_loop.run_app(&mut app).map_err(Into::into) } diff --git a/rustfmt.toml b/rustfmt.toml index a069b434e3..e10d6b0027 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,3 +1,19 @@ -force_explicit_abi=true -use_field_init_shorthand=true -# merge_imports=true +format_code_in_doc_comments = true +match_block_trailing_comma = true +condense_wildcard_suffixes = true +use_field_init_shorthand = true +normalize_doc_attributes = true +overflow_delimited_expr = true +imports_granularity = "Module" +use_small_heuristics = "Max" +format_macro_matchers = true +error_on_unformatted = true +format_macro_bodies = true +hex_literal_case = "Lower" +normalize_comments = true +# Some macros break with this. +reorder_impl_items = false +newline_style = "Unix" +format_strings = true +wrap_comments = true +comment_width = 100 diff --git a/src/application.rs b/src/application.rs index 024c0e033e..1d318d2167 100644 --- a/src/application.rs +++ b/src/application.rs @@ -20,8 +20,8 @@ pub trait ApplicationHandler { /// /// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a /// formal suspend/resume lifecycle. For systems without a formal suspend/resume lifecycle - /// the `Resumed` event is always emitted after the [`NewEvents(StartCause::Init)`][StartCause::Init] - /// event. + /// the `Resumed` event is always emitted after the + /// [`NewEvents(StartCause::Init)`][StartCause::Init] event. /// /// # Portability /// @@ -33,15 +33,16 @@ pub trait ApplicationHandler { /// Considering that the implementation of [`Suspended`] and `Resumed` events may be internally /// driven by multiple platform-specific events, and that there may be subtle differences across /// platforms with how these internal events are delivered, it's recommended that applications - /// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed` events. + /// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed` + /// events. /// /// Also see [`Suspended`] notes. /// /// ## Android /// /// On Android, the `Resumed` event is sent when a new [`SurfaceView`] has been created. This is - /// expected to closely correlate with the [`onResume`] lifecycle event but there may technically - /// be a discrepancy. + /// expected to closely correlate with the [`onResume`] lifecycle event but there may + /// technically be a discrepancy. /// /// [`onResume`]: https://developer.android.com/reference/android/app/Activity#onResume() /// @@ -109,7 +110,8 @@ pub trait ApplicationHandler { /// Emitted when the event loop is about to block and wait for new events. /// /// Most applications shouldn't need to hook into this event since there is no real relationship - /// between how often the event loop needs to wake up and the dispatching of any specific events. + /// between how often the event loop needs to wake up and the dispatching of any specific + /// events. /// /// High frequency event sources, such as input devices could potentially lead to lots of wake /// ups and also lots of corresponding `AboutToWait` events. @@ -133,7 +135,8 @@ pub trait ApplicationHandler { /// Considering that the implementation of `Suspended` and [`Resumed`] events may be internally /// driven by multiple platform-specific events, and that there may be subtle differences across /// platforms with how these internal events are delivered, it's recommended that applications - /// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`] events. + /// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`] + /// events. /// /// Also see [`Resumed`] notes. /// @@ -150,7 +153,8 @@ pub trait ApplicationHandler { /// created outside of Winit (such as an `EGLSurface`, [`VkSurfaceKHR`] or [`wgpu::Surface`]). /// /// After being `Suspended` on Android applications must drop all render surfaces before - /// the event callback completes, which may be re-created when the application is next [`Resumed`]. + /// the event callback completes, which may be re-created when the application is next + /// [`Resumed`]. /// /// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView /// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle @@ -197,17 +201,17 @@ pub trait ApplicationHandler { /// /// ### Android /// - /// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The application - /// must [release memory] or risk being killed. + /// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The + /// application must [release memory] or risk being killed. /// /// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory() /// [release memory]: https://developer.android.com/topic/performance/memory#release /// /// ### iOS /// - /// On iOS, the `MemoryWarning` event is emitted in response to an [`applicationDidReceiveMemoryWarning`] - /// callback. The application must free as much memory as possible or risk being terminated, see - /// [how to respond to memory warnings]. + /// On iOS, the `MemoryWarning` event is emitted in response to an + /// [`applicationDidReceiveMemoryWarning`] callback. The application must free as much + /// memory as possible or risk being terminated, see [how to respond to memory warnings]. /// /// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni /// [how to respond to memory warnings]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle/responding_to_memory_warnings diff --git a/src/changelog/mod.rs b/src/changelog/mod.rs index cdd001a55b..ee86b84a11 100644 --- a/src/changelog/mod.rs +++ b/src/changelog/mod.rs @@ -2,7 +2,6 @@ //! //! All notable changes to this project will be documented in this module, //! along with migration instructions for larger changes. -//! // Put the current entry at the top of this page, for discoverability. // See `.cargo/config.toml` for details about `unreleased_changelogs`. #![cfg_attr(unreleased_changelogs, doc = include_str!("unreleased.md"))] diff --git a/src/cursor.rs b/src/cursor.rs index b36eadd174..7bcac54d76 100644 --- a/src/cursor.rs +++ b/src/cursor.rs @@ -1,7 +1,7 @@ use core::fmt; -use std::hash::Hasher; +use std::error::Error; +use std::hash::{Hash, Hasher}; use std::sync::Arc; -use std::{error::Error, hash::Hash}; use cursor_icon::CursorIcon; @@ -88,14 +88,9 @@ impl CustomCursor { hotspot_x: u16, hotspot_y: u16, ) -> Result { - let _span = tracing::debug_span!( - "winit::Cursor::from_rgba", - width, - height, - hotspot_x, - hotspot_y - ) - .entered(); + let _span = + tracing::debug_span!("winit::Cursor::from_rgba", width, height, hotspot_x, hotspot_y) + .entered(); Ok(CustomCursorSource { inner: PlatformCustomCursorSource::from_rgba( @@ -129,45 +124,36 @@ pub enum BadImage { ByteCountNotDivisibleBy4 { byte_count: usize }, /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. /// At least one of your arguments is incorrect. - DimensionsVsPixelCount { - width: u16, - height: u16, - width_x_height: u64, - pixel_count: u64, - }, + DimensionsVsPixelCount { width: u16, height: u16, width_x_height: u64, pixel_count: u64 }, /// Produced when the hotspot is outside the image bounds - HotspotOutOfBounds { - width: u16, - height: u16, - hotspot_x: u16, - hotspot_y: u16, - }, + HotspotOutOfBounds { width: u16, height: u16, hotspot_x: u16, hotspot_y: u16 }, } impl fmt::Display for BadImage { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - BadImage::TooLarge { width, height } => write!(f, - "The specified dimensions ({width:?}x{height:?}) are too large. The maximum is {MAX_CURSOR_SIZE:?}x{MAX_CURSOR_SIZE:?}.", + BadImage::TooLarge { width, height } => write!( + f, + "The specified dimensions ({width:?}x{height:?}) are too large. The maximum is \ + {MAX_CURSOR_SIZE:?}x{MAX_CURSOR_SIZE:?}.", ), - BadImage::ByteCountNotDivisibleBy4 { byte_count } => write!(f, - "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.", - ), - BadImage::DimensionsVsPixelCount { - width, - height, - width_x_height, - pixel_count, - } => write!(f, - "The specified dimensions ({width:?}x{height:?}) don't match the number of pixels supplied by the `rgba` argument ({pixel_count:?}). For those dimensions, the expected pixel count is {width_x_height:?}.", + BadImage::ByteCountNotDivisibleBy4 { byte_count } => write!( + f, + "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \ + it impossible to interpret as 32bpp RGBA pixels.", ), - BadImage::HotspotOutOfBounds { - width, - height, - hotspot_x, - hotspot_y, - } => write!(f, - "The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds ({width:?}x{height:?}).", + BadImage::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => { + write!( + f, + "The specified dimensions ({width:?}x{height:?}) don't match the number of \ + pixels supplied by the `rgba` argument ({pixel_count:?}). For those \ + dimensions, the expected pixel count is {width_x_height:?}.", + ) + }, + BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y } => write!( + f, + "The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds \ + ({width:?}x{height:?}).", ), } } @@ -236,9 +222,7 @@ impl CursorImage { } if rgba.len() % PIXEL_SIZE != 0 { - return Err(BadImage::ByteCountNotDivisibleBy4 { - byte_count: rgba.len(), - }); + return Err(BadImage::ByteCountNotDivisibleBy4 { byte_count: rgba.len() }); } let pixel_count = (rgba.len() / PIXEL_SIZE) as u64; @@ -253,21 +237,10 @@ impl CursorImage { } if hotspot_x >= width || hotspot_y >= height { - return Err(BadImage::HotspotOutOfBounds { - width, - height, - hotspot_x, - hotspot_y, - }); + return Err(BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y }); } - Ok(CursorImage { - rgba, - width, - height, - hotspot_x, - hotspot_y, - }) + Ok(CursorImage { rgba, width, height, hotspot_x, hotspot_y }) } } diff --git a/src/error.rs b/src/error.rs index fdeb3c507b..d15bb9e7b2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -71,10 +71,7 @@ macro_rules! os_error { impl fmt::Display for OsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - f.pad(&format!( - "os error at {}:{}: {}", - self.file, self.line, self.error - )) + f.pad(&format!("os error at {}:{}: {}", self.file, self.line, self.error)) } } @@ -124,11 +121,7 @@ mod tests { // Eat attributes for testing #[test] fn ensure_fmt_does_not_panic() { - let _ = format!( - "{:?}, {}", - NotSupportedError::new(), - NotSupportedError::new().clone() - ); + let _ = format!("{:?}, {}", NotSupportedError::new(), NotSupportedError::new().clone()); let _ = format!( "{:?}, {}", ExternalError::NotSupported(NotSupportedError::new()), diff --git a/src/event.rs b/src/event.rs index e1975c657a..bc7c18a52c 100644 --- a/src/event.rs +++ b/src/event.rs @@ -1,7 +1,8 @@ //! The [`Event`] enum and assorted supporting types. //! //! These are sent to the closure given to [`EventLoop::run_app(...)`], where they get -//! processed and used to modify the program state. For more details, see the root-level documentation. +//! processed and used to modify the program state. For more details, see the root-level +//! documentation. //! //! Some of these events represent different "parts" of a traditional event-handling loop. You could //! approximate the basic ordering loop of [`EventLoop::run_app(...)`] like this: @@ -44,16 +45,14 @@ use smol_str::SmolStr; #[cfg(web_platform)] use web_time::Instant; +use crate::dpi::{PhysicalPosition, PhysicalSize}; use crate::error::ExternalError; +use crate::event_loop::AsyncRequestSerial; +use crate::keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState}; +use crate::platform_impl; #[cfg(doc)] use crate::window::Window; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize}, - event_loop::AsyncRequestSerial, - keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState}, - platform_impl, - window::{ActivationToken, Theme, WindowId}, -}; +use crate::window::{ActivationToken, Theme, WindowId}; /// Describes a generic event. /// @@ -68,18 +67,12 @@ pub enum Event { /// See [`ApplicationHandler::window_event`] for details. /// /// [`ApplicationHandler::window_event`]: crate::application::ApplicationHandler::window_event - WindowEvent { - window_id: WindowId, - event: WindowEvent, - }, + WindowEvent { window_id: WindowId, event: WindowEvent }, /// See [`ApplicationHandler::device_event`] for details. /// /// [`ApplicationHandler::device_event`]: crate::application::ApplicationHandler::device_event - DeviceEvent { - device_id: DeviceId, - event: DeviceEvent, - }, + DeviceEvent { device_id: DeviceId, event: DeviceEvent }, /// See [`ApplicationHandler::user_event`] for details. /// @@ -138,17 +131,11 @@ pub enum StartCause { /// guaranteed to be equal to or after the requested resume time. /// /// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil - ResumeTimeReached { - start: Instant, - requested_resume: Instant, - }, + ResumeTimeReached { start: Instant, requested_resume: Instant }, /// Sent if the OS has new events to send to the window, after a wait was requested. Contains /// the moment the wait was requested and the resume time, if requested. - WaitCancelled { - start: Instant, - requested_resume: Option, - }, + WaitCancelled { start: Instant, requested_resume: Option }, /// Sent if the event loop is being resumed after the loop's control flow was set to /// [`ControlFlow::Poll`]. @@ -164,18 +151,11 @@ pub enum StartCause { #[derive(Debug, Clone, PartialEq)] pub enum WindowEvent { /// The activation token was delivered back and now could be used. - /// - #[cfg_attr( - not(any(x11_platform, wayland_platform)), - allow(rustdoc::broken_intra_doc_links) - )] + #[cfg_attr(not(any(x11_platform, wayland_platform)), allow(rustdoc::broken_intra_doc_links))] /// Delivered in response to [`request_activation_token`]. /// /// [`request_activation_token`]: crate::platform::startup_notify::WindowExtStartupNotify::request_activation_token - ActivationTokenDone { - serial: AsyncRequestSerial, - token: ActivationToken, - }, + ActivationTokenDone { serial: AsyncRequestSerial, token: ActivationToken }, /// The size of the window has changed. Contains the client area's new dimensions. Resized(PhysicalSize), @@ -229,10 +209,10 @@ pub enum WindowEvent { /// If `true`, the event was generated synthetically by winit /// in one of the following circumstances: /// - /// * Synthetic key press events are generated for all keys pressed - /// when a window gains focus. Likewise, synthetic key release events - /// are generated for all keys pressed when a window goes out of focus. - /// ***Currently, this is only functional on X11 and Windows*** + /// * Synthetic key press events are generated for all keys pressed when a window gains + /// focus. Likewise, synthetic key release events are generated for all keys pressed when + /// a window goes out of focus. ***Currently, this is only functional on X11 and + /// Windows*** /// /// Otherwise, this value is always `false`. is_synthetic: bool, @@ -262,9 +242,10 @@ pub enum WindowEvent { CursorMoved { device_id: DeviceId, - /// (x,y) coords in pixels relative to the top-left corner of the window. Because the range of this data is - /// limited by the display area and it may have been transformed by the OS to implement effects such as cursor - /// acceleration, it should not be used to implement non-cursor-like interactions such as 3D camera control. + /// (x,y) coords in pixels relative to the top-left corner of the window. Because the range + /// of this data is limited by the display area and it may have been transformed by + /// the OS to implement effects such as cursor acceleration, it should not be used + /// to implement non-cursor-like interactions such as 3D camera control. position: PhysicalPosition, }, @@ -291,18 +272,10 @@ pub enum WindowEvent { CursorLeft { device_id: DeviceId }, /// A mouse wheel movement or touchpad scroll occurred. - MouseWheel { - device_id: DeviceId, - delta: MouseScrollDelta, - phase: TouchPhase, - }, + MouseWheel { device_id: DeviceId, delta: MouseScrollDelta, phase: TouchPhase }, /// An mouse button press has been received. - MouseInput { - device_id: DeviceId, - state: ElementState, - button: MouseButton, - }, + MouseInput { device_id: DeviceId, state: ElementState, button: MouseButton }, /// Two-finger pinch gesture, often used for magnification. /// @@ -349,29 +322,17 @@ pub enum WindowEvent { /// /// - Only available on **macOS** and **iOS**. /// - On iOS, not recognized by default. It must be enabled when needed. - RotationGesture { - device_id: DeviceId, - delta: f32, - phase: TouchPhase, - }, + RotationGesture { device_id: DeviceId, delta: f32, phase: TouchPhase }, /// Touchpad pressure event. /// /// At the moment, only supported on Apple forcetouch-capable macbooks. - /// The parameters are: pressure level (value between 0 and 1 representing how hard the touchpad - /// is being pressed) and stage (integer representing the click level). - TouchpadPressure { - device_id: DeviceId, - pressure: f32, - stage: i64, - }, + /// The parameters are: pressure level (value between 0 and 1 representing how hard the + /// touchpad is being pressed) and stage (integer representing the click level). + TouchpadPressure { device_id: DeviceId, pressure: f32, stage: i64 }, /// Motion on some analog axis. May report data redundant to other, more specific events. - AxisMotion { - device_id: DeviceId, - axis: AxisId, - value: f64, - }, + AxisMotion { device_id: DeviceId, axis: AxisId, value: f64 }, /// Touch event has been received /// @@ -393,8 +354,8 @@ pub enum WindowEvent { /// * Changing the display's scale factor (e.g. in Control Panel on Windows). /// * Moving the window to a display with a different scale factor. /// - /// To update the window size, use the provided [`InnerSizeWriter`] handle. By default, the window is - /// resized to the value suggested by the OS, but it can be changed to any value. + /// To update the window size, use the provided [`InnerSizeWriter`] handle. By default, the + /// window is resized to the value suggested by the OS, but it can be changed to any value. /// /// For more information about DPI in general, see the [`dpi`] crate. ScaleFactorChanged { @@ -424,10 +385,11 @@ pub enum WindowEvent { /// /// ### iOS /// - /// On iOS, the `Occluded(false)` event is emitted in response to an [`applicationWillEnterForeground`] - /// callback which means the application should start preparing its data. The `Occluded(true)` event is - /// emitted in response to an [`applicationDidEnterBackground`] callback which means the application - /// should free resources (according to the [iOS application lifecycle]). + /// On iOS, the `Occluded(false)` event is emitted in response to an + /// [`applicationWillEnterForeground`] callback which means the application should start + /// preparing its data. The `Occluded(true)` event is emitted in response to an + /// [`applicationDidEnterBackground`] callback which means the application should free + /// resources (according to the [iOS application lifecycle]). /// /// [`applicationWillEnterForeground`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623076-applicationwillenterforeground /// [`applicationDidEnterBackground`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622997-applicationdidenterbackground @@ -457,9 +419,10 @@ pub enum WindowEvent { /// Identifier of an input device. /// -/// Whenever you receive an event arising from a particular input device, this event contains a `DeviceId` which -/// identifies its origin. Note that devices may be virtual (representing an on-screen cursor and keyboard focus) or -/// physical. Virtual devices typically aggregate inputs from multiple physical devices. +/// Whenever you receive an event arising from a particular input device, this event contains a +/// `DeviceId` which identifies its origin. Note that devices may be virtual (representing an +/// on-screen cursor and keyboard focus) or physical. Virtual devices typically aggregate inputs +/// from multiple physical devices. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DeviceId(pub(crate) platform_impl::DeviceId); @@ -481,10 +444,10 @@ impl DeviceId { /// Represents raw hardware events that are not associated with any particular window. /// -/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera or first-person -/// game controls. Many physical actions, such as mouse movement, can produce both device and window events. Because -/// window events typically arise from virtual devices (corresponding to GUI cursors and keyboard focus) the device IDs -/// may not match. +/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera +/// or first-person game controls. Many physical actions, such as mouse movement, can produce both +/// device and window events. Because window events typically arise from virtual devices +/// (corresponding to GUI cursors and keyboard focus) the device IDs may not match. /// /// Note that these events are delivered regardless of input focus. #[derive(Clone, Debug, PartialEq)] @@ -494,7 +457,8 @@ pub enum DeviceEvent { /// Change in physical position of a pointing device. /// - /// This represents raw, unfiltered physical motion. Not to be confused with [`WindowEvent::CursorMoved`]. + /// This represents raw, unfiltered physical motion. Not to be confused with + /// [`WindowEvent::CursorMoved`]. MouseMotion { /// (x, y) change in position in unspecified units. /// @@ -615,13 +579,13 @@ pub struct KeyEvent { /// Contains the location of this key on the keyboard. /// - /// Certain keys on the keyboard may appear in more than once place. For example, the "Shift" key - /// appears on the left side of the QWERTY keyboard as well as the right side. However, both keys - /// have the same symbolic value. Another example of this phenomenon is the "1" key, which appears - /// both above the "Q" key and as the "Keypad 1" key. + /// Certain keys on the keyboard may appear in more than once place. For example, the "Shift" + /// key appears on the left side of the QWERTY keyboard as well as the right side. However, + /// both keys have the same symbolic value. Another example of this phenomenon is the "1" + /// key, which appears both above the "Q" key and as the "Keypad 1" key. /// - /// This field allows the user to differentiate between keys like this that have the same symbolic - /// value but different locations on the keyboard. + /// This field allows the user to differentiate between keys like this that have the same + /// symbolic value but different locations on the keyboard. /// /// See the [`KeyLocation`] type for more details. /// @@ -636,8 +600,8 @@ pub struct KeyEvent { /// Whether or not this key is a key repeat event. /// /// On some systems, holding down a key for some period of time causes that key to be repeated - /// as though it were being pressed and released repeatedly. This field is `true` if and only if - /// this event is the result of one of those repeats. + /// as though it were being pressed and released repeatedly. This field is `true` if and only + /// if this event is the result of one of those repeats. /// /// # Example /// @@ -645,30 +609,31 @@ pub struct KeyEvent { /// done by ignoring events where this property is set. /// /// ``` - /// use winit::event::{WindowEvent, KeyEvent, ElementState}; + /// use winit::event::{ElementState, KeyEvent, WindowEvent}; /// use winit::keyboard::{KeyCode, PhysicalKey}; /// # let window_event = WindowEvent::RedrawRequested; // To make the example compile /// match window_event { /// WindowEvent::KeyboardInput { - /// event: KeyEvent { - /// physical_key: PhysicalKey::Code(KeyCode::KeyW), - /// state: ElementState::Pressed, - /// repeat: false, - /// .. - /// }, + /// event: + /// KeyEvent { + /// physical_key: PhysicalKey::Code(KeyCode::KeyW), + /// state: ElementState::Pressed, + /// repeat: false, + /// .. + /// }, /// .. /// } => { - /// // The physical key `W` was pressed, and it was not a repeat - /// } - /// _ => {} // Handle other events + /// // The physical key `W` was pressed, and it was not a repeat + /// }, + /// _ => {}, // Handle other events /// } /// ``` pub repeat: bool, /// Platform-specific key event information. /// - /// On Windows, Linux and macOS, this type contains the key without modifiers and the text with all - /// modifiers applied. + /// On Windows, Linux and macOS, this type contains the key without modifiers and the text with + /// all modifiers applied. /// /// On Android, iOS, Redox and Web, this type is a no-op. pub(crate) platform_specific: platform_impl::KeyEventExtra, @@ -742,10 +707,7 @@ impl Modifiers { impl From for Modifiers { fn from(value: ModifiersState) -> Self { - Self { - state: value, - pressed_mods: Default::default(), - } + Self { state: value, pressed_mods: Default::default() } } } @@ -753,12 +715,15 @@ impl From for Modifiers { /// /// This is also called a "composition event". /// -/// Most keypresses using a latin-like keyboard layout simply generate a [`WindowEvent::KeyboardInput`]. -/// However, one couldn't possibly have a key for every single unicode character that the user might want to type -/// - so the solution operating systems employ is to allow the user to type these using _a sequence of keypresses_ instead. +/// Most keypresses using a latin-like keyboard layout simply generate a +/// [`WindowEvent::KeyboardInput`]. However, one couldn't possibly have a key for every single +/// unicode character that the user might want to type +/// - so the solution operating systems employ is to allow the user to type these using _a sequence +/// of keypresses_ instead. /// -/// A prominent example of this is accents - many keyboard layouts allow you to first click the "accent key", and then -/// the character you want to apply the accent to. In this case, some platforms will generate the following event sequence: +/// A prominent example of this is accents - many keyboard layouts allow you to first click the +/// "accent key", and then the character you want to apply the accent to. In this case, some +/// platforms will generate the following event sequence: ```ignore /// ```ignore /// // Press "`" key /// Ime::Preedit("`", Some((0, 0))) @@ -766,12 +731,12 @@ impl From for Modifiers { /// Ime::Preedit("", None) // Synthetic event generated by winit to clear preedit. /// Ime::Commit("é") /// ``` +/// Additionally, certain input devices are configured to display a candidate box that allow the +/// user to select the desired character interactively. (To properly position this box, you must use +/// [`Window::set_ime_cursor_area`].) /// -/// Additionally, certain input devices are configured to display a candidate box that allow the user to select the -/// desired character interactively. (To properly position this box, you must use [`Window::set_ime_cursor_area`].) -/// -/// An example of a keyboard layout which uses candidate boxes is pinyin. On a latin keyboard the following event -/// sequence could be obtained: +/// An example of a keyboard layout which uses candidate boxes is pinyin. On a latin keyboard the +/// following event sequence could be obtained: /// ```ignore /// // Press "A" key /// Ime::Preedit("a", Some((1, 1))) @@ -813,8 +778,8 @@ pub enum Ime { /// /// After receiving this event you won't get any more [`Preedit`][Self::Preedit] or /// [`Commit`][Self::Commit] events until the next [`Enabled`][Self::Enabled] event. You should - /// also stop issuing IME related requests like [`Window::set_ime_cursor_area`] and clear pending - /// preedit text. + /// also stop issuing IME related requests like [`Window::set_ime_cursor_area`] and clear + /// pending preedit text. Disabled, } @@ -913,17 +878,13 @@ impl Force { /// consistent across devices. pub fn normalized(&self) -> f64 { match self { - Force::Calibrated { - force, - max_possible_force, - altitude_angle, - } => { + Force::Calibrated { force, max_possible_force, altitude_angle } => { let force = match altitude_angle { Some(altitude_angle) => force / altitude_angle.sin(), None => *force, }; force / max_possible_force - } + }, Force::Normalized(force) => *force, } } @@ -1040,7 +1001,9 @@ mod tests { #[allow(deprecated)] { - use crate::event::{Event::*, Ime::Enabled, WindowEvent::*}; + use crate::event::Event::*; + use crate::event::Ime::Enabled; + use crate::event::WindowEvent::*; use crate::window::WindowId; // Mainline events. @@ -1053,12 +1016,7 @@ mod tests { x(Resumed); // Window events. - let with_window_event = |wev| { - x(WindowEvent { - window_id: wid, - event: wev, - }) - }; + let with_window_event = |wev| x(WindowEvent { window_id: wid, event: wev }); with_window_event(CloseRequested); with_window_event(Destroyed); @@ -1069,10 +1027,7 @@ mod tests { with_window_event(HoveredFile("x.txt".into())); with_window_event(HoveredFileCancelled); with_window_event(Ime(Enabled)); - with_window_event(CursorMoved { - device_id: did, - position: (0, 0).into(), - }); + with_window_event(CursorMoved { device_id: did, position: (0, 0).into() }); with_window_event(ModifiersChanged(event::Modifiers::default())); with_window_event(CursorEntered { device_id: did }); with_window_event(CursorLeft { device_id: did }); @@ -1097,16 +1052,8 @@ mod tests { delta: 0.0, phase: event::TouchPhase::Started, }); - with_window_event(TouchpadPressure { - device_id: did, - pressure: 0.0, - stage: 0, - }); - with_window_event(AxisMotion { - device_id: did, - axis: 0, - value: 0.0, - }); + with_window_event(TouchpadPressure { device_id: did, pressure: 0.0, stage: 0 }); + with_window_event(AxisMotion { device_id: did, axis: 0, value: 0.0 }); with_window_event(Touch(event::Touch { device_id: did, phase: event::TouchPhase::Started, @@ -1122,29 +1069,17 @@ mod tests { { use event::DeviceEvent::*; - let with_device_event = |dev_ev| { - x(event::Event::DeviceEvent { - device_id: did, - event: dev_ev, - }) - }; + let with_device_event = + |dev_ev| x(event::Event::DeviceEvent { device_id: did, event: dev_ev }); with_device_event(Added); with_device_event(Removed); - with_device_event(MouseMotion { - delta: (0.0, 0.0).into(), - }); + with_device_event(MouseMotion { delta: (0.0, 0.0).into() }); with_device_event(MouseWheel { delta: event::MouseScrollDelta::LineDelta(0.0, 0.0), }); - with_device_event(Motion { - axis: 0, - value: 0.0, - }); - with_device_event(Button { - button: 0, - state: event::ElementState::Pressed, - }); + with_device_event(Motion { axis: 0, value: 0.0 }); + with_device_event(Button { button: 0, state: event::ElementState::Pressed }); } }}; } @@ -1176,11 +1111,8 @@ mod tests { let force = event::Force::Normalized(0.0); assert_eq!(force.normalized(), 0.0); - let force2 = event::Force::Calibrated { - force: 5.0, - max_possible_force: 2.5, - altitude_angle: None, - }; + let force2 = + event::Force::Calibrated { force: 5.0, max_possible_force: 2.5, altitude_angle: None }; assert_eq!(force2.normalized(), 2.0); let force3 = event::Force::Calibrated { @@ -1219,11 +1151,8 @@ mod tests { force: Some(event::Force::Normalized(0.0)), } .clone(); - let _ = event::Force::Calibrated { - force: 0.0, - max_possible_force: 0.0, - altitude_angle: None, - } - .clone(); + let _ = + event::Force::Calibrated { force: 0.0, max_possible_force: 0.0, altitude_angle: None } + .clone(); } } diff --git a/src/event_loop.rs b/src/event_loop.rs index 48455e3062..c0f64d9e4b 100644 --- a/src/event_loop.rs +++ b/src/event_loop.rs @@ -20,8 +20,10 @@ use web_time::{Duration, Instant}; use crate::application::ApplicationHandler; use crate::error::{EventLoopError, OsError}; +use crate::event::Event; +use crate::monitor::MonitorHandle; +use crate::platform_impl; use crate::window::{CustomCursor, CustomCursorSource, Window, WindowAttributes}; -use crate::{event::Event, monitor::MonitorHandle, platform_impl}; /// Provides a way to retrieve events from the system and from the windows that were registered to /// the events loop. @@ -33,8 +35,8 @@ use crate::{event::Event, monitor::MonitorHandle, platform_impl}; /// To wake up an `EventLoop` from a another thread, see the [`EventLoopProxy`] docs. /// /// Note that this cannot be shared across threads (due to platform-dependant logic -/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access, the -/// [`Window`] created from this _can_ be sent to an other thread, and the +/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access, +/// the [`Window`] created from this _can_ be sent to an other thread, and the /// [`EventLoopProxy`] allows you to wake up an `EventLoop` from another thread. /// /// [`Window`]: crate::window::Window @@ -94,20 +96,18 @@ impl EventLoopBuilder { /// /// ## Platform-specific /// - /// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY` - /// or `DISPLAY` respectively when building the event loop. + /// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY` or + /// `DISPLAY` respectively when building the event loop. /// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling - /// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic. + /// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic. /// /// [`platform`]: crate::platform #[cfg_attr( android, - doc = "[`.with_android_app(app)`]: crate::platform::android::EventLoopBuilderExtAndroid::with_android_app" - )] - #[cfg_attr( - not(android), - doc = "[`.with_android_app(app)`]: #only-available-on-android" + doc = "[`.with_android_app(app)`]: \ + crate::platform::android::EventLoopBuilderExtAndroid::with_android_app" )] + #[cfg_attr(not(android), doc = "[`.with_android_app(app)`]: #only-available-on-android")] #[inline] pub fn build(&mut self) -> Result, EventLoopError> { let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered(); @@ -162,9 +162,9 @@ pub enum ControlFlow { /// When the current loop iteration finishes, suspend the thread until either another event /// arrives or the given time is reached. /// - /// Useful for implementing efficient timers. Applications which want to render at the display's - /// native refresh rate should instead use [`Poll`] and the VSync functionality of a graphics API - /// to reduce odds of missed frames. + /// Useful for implementing efficient timers. Applications which want to render at the + /// display's native refresh rate should instead use [`Poll`] and the VSync functionality + /// of a graphics API to reduce odds of missed frames. /// /// [`Poll`]: Self::Poll WaitUntil(Instant), @@ -210,10 +210,7 @@ impl EventLoop { /// Start building a new event loop, with the given type as the user event /// type. pub fn with_user_event() -> EventLoopBuilder { - EventLoopBuilder { - platform_specific: Default::default(), - _p: PhantomData, - } + EventLoopBuilder { platform_specific: Default::default(), _p: PhantomData } } /// See [`run_app`]. @@ -239,9 +236,9 @@ impl EventLoop { /// /// - **iOS:** Will never return to the caller and so values not passed to this function will /// *not* be dropped before the process exits. - /// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript exception - /// (that Rust doesn't see) that will also mean that the rest of the function is never executed - /// and any values not passed to this function will *not* be dropped. + /// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript + /// exception (that Rust doesn't see) that will also mean that the rest of the function is + /// never executed and any values not passed to this function will *not* be dropped. /// /// Web applications are recommended to use #[cfg_attr( @@ -262,25 +259,20 @@ impl EventLoop { #[inline] #[cfg(not(all(web_platform, target_feature = "exception-handling")))] pub fn run_app>(self, app: &mut A) -> Result<(), EventLoopError> { - self.event_loop - .run(|event, event_loop| dispatch_event_for_app(app, event_loop, event)) + self.event_loop.run(|event, event_loop| dispatch_event_for_app(app, event_loop, event)) } /// Creates an [`EventLoopProxy`] that can be used to dispatch user events /// to the main event loop, possibly from another thread. pub fn create_proxy(&self) -> EventLoopProxy { - EventLoopProxy { - event_loop_proxy: self.event_loop.create_proxy(), - } + EventLoopProxy { event_loop_proxy: self.event_loop.create_proxy() } } /// Gets a persistent reference to the underlying platform display. /// /// See the [`OwnedDisplayHandle`] type for more information. pub fn owned_display_handle(&self) -> OwnedDisplayHandle { - OwnedDisplayHandle { - platform: self.event_loop.window_target().p.owned_display_handle(), - } + OwnedDisplayHandle { platform: self.event_loop.window_target().p.owned_display_handle() } } /// Change if or when [`DeviceEvent`]s are captured. @@ -295,18 +287,12 @@ impl EventLoop { ) .entered(); - self.event_loop - .window_target() - .p - .listen_device_events(allowed); + self.event_loop.window_target().p.listen_device_events(allowed); } /// Sets the [`ControlFlow`]. pub fn set_control_flow(&self, control_flow: ControlFlow) { - self.event_loop - .window_target() - .p - .set_control_flow(control_flow) + self.event_loop.window_target().p.set_control_flow(control_flow) } /// Create a window. @@ -329,10 +315,7 @@ impl EventLoop { /// Create custom cursor. pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor { - self.event_loop - .window_target() - .p - .create_custom_cursor(custom_cursor) + self.event_loop.window_target().p.create_custom_cursor(custom_cursor) } } @@ -413,10 +396,7 @@ impl ActiveEventLoop { let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered(); #[allow(clippy::useless_conversion)] // false positive on some platforms - self.p - .available_monitors() - .into_iter() - .map(|inner| MonitorHandle { inner }) + self.p.available_monitors().into_iter().map(|inner| MonitorHandle { inner }) } /// Returns the primary monitor of the system. @@ -430,9 +410,7 @@ impl ActiveEventLoop { pub fn primary_monitor(&self) -> Option { let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered(); - self.p - .primary_monitor() - .map(|inner| MonitorHandle { inner }) + self.p.primary_monitor().map(|inner| MonitorHandle { inner }) } /// Change if or when [`DeviceEvent`]s are captured. @@ -486,9 +464,7 @@ impl ActiveEventLoop { /// /// See the [`OwnedDisplayHandle`] type for more information. pub fn owned_display_handle(&self) -> OwnedDisplayHandle { - OwnedDisplayHandle { - platform: self.p.owned_display_handle(), - } + OwnedDisplayHandle { platform: self.p.owned_display_handle() } } } @@ -562,9 +538,7 @@ pub struct EventLoopProxy { impl Clone for EventLoopProxy { fn clone(&self) -> Self { - Self { - event_loop_proxy: self.event_loop_proxy.clone(), - } + Self { event_loop_proxy: self.event_loop_proxy.clone() } } } diff --git a/src/icon.rs b/src/icon.rs index d01098d0fa..b013d2f049 100644 --- a/src/icon.rs +++ b/src/icon.rs @@ -1,5 +1,6 @@ use crate::platform_impl::PlatformIcon; -use std::{error::Error, fmt, io, mem}; +use std::error::Error; +use std::{fmt, io, mem}; #[repr(C)] #[derive(Debug)] @@ -20,12 +21,7 @@ pub enum BadIcon { ByteCountNotDivisibleBy4 { byte_count: usize }, /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. /// At least one of your arguments is incorrect. - DimensionsVsPixelCount { - width: u32, - height: u32, - width_x_height: usize, - pixel_count: usize, - }, + DimensionsVsPixelCount { width: u32, height: u32, width_x_height: usize, pixel_count: usize }, /// Produced when underlying OS functionality failed to create the icon OsError(io::Error), } @@ -33,17 +29,19 @@ pub enum BadIcon { impl fmt::Display for BadIcon { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f, - "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.", - ), - BadIcon::DimensionsVsPixelCount { - width, - height, - width_x_height, - pixel_count, - } => write!(f, - "The specified dimensions ({width:?}x{height:?}) don't match the number of pixels supplied by the `rgba` argument ({pixel_count:?}). For those dimensions, the expected pixel count is {width_x_height:?}.", + BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!( + f, + "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \ + it impossible to interpret as 32bpp RGBA pixels.", ), + BadIcon::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => { + write!( + f, + "The specified dimensions ({width:?}x{height:?}) don't match the number of \ + pixels supplied by the `rgba` argument ({pixel_count:?}). For those \ + dimensions, the expected pixel count is {width_x_height:?}.", + ) + }, BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"), } } @@ -69,9 +67,7 @@ mod constructors { impl RgbaIcon { pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { if rgba.len() % PIXEL_SIZE != 0 { - return Err(BadIcon::ByteCountNotDivisibleBy4 { - byte_count: rgba.len(), - }); + return Err(BadIcon::ByteCountNotDivisibleBy4 { byte_count: rgba.len() }); } let pixel_count = rgba.len() / PIXEL_SIZE; if pixel_count != (width * height) as usize { @@ -82,11 +78,7 @@ mod constructors { pixel_count, }) } else { - Ok(RgbaIcon { - rgba, - width, - height, - }) + Ok(RgbaIcon { rgba, width, height }) } } } @@ -120,8 +112,6 @@ impl Icon { pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered(); - Ok(Icon { - inner: PlatformIcon::from_rgba(rgba, width, height)?, - }) + Ok(Icon { inner: PlatformIcon::from_rgba(rgba, width, height)? }) } } diff --git a/src/keyboard.rs b/src/keyboard.rs index 94f6863a5c..49d55c1e1f 100644 --- a/src/keyboard.rs +++ b/src/keyboard.rs @@ -106,23 +106,23 @@ impl std::fmt::Debug for NativeKeyCode { match self { Unidentified => { debug_tuple = f.debug_tuple("Unidentified"); - } + }, Android(code) => { debug_tuple = f.debug_tuple("Android"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, MacOS(code) => { debug_tuple = f.debug_tuple("MacOS"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, Windows(code) => { debug_tuple = f.debug_tuple("Windows"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, Xkb(code) => { debug_tuple = f.debug_tuple("Xkb"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, } debug_tuple.finish() } @@ -162,27 +162,27 @@ impl std::fmt::Debug for NativeKey { match self { Unidentified => { debug_tuple = f.debug_tuple("Unidentified"); - } + }, Android(code) => { debug_tuple = f.debug_tuple("Android"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, MacOS(code) => { debug_tuple = f.debug_tuple("MacOS"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, Windows(code) => { debug_tuple = f.debug_tuple("Windows"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, Xkb(code) => { debug_tuple = f.debug_tuple("Xkb"); debug_tuple.field(&format_args!("0x{code:04X}")); - } + }, Web(code) => { debug_tuple = f.debug_tuple("Web"); debug_tuple.field(code); - } + }, } debug_tuple.finish() } @@ -442,7 +442,8 @@ pub enum KeyCode { Tab, /// Japanese: (henkan) Convert, - /// Japanese: カタカナ/ひらがな/ローマ字 (katakana/hiragana/romaji) + /// Japanese: カタカナ/ひらがな/ローマ字 + /// (katakana/hiragana/romaji) KanaMode, /// Korean: HangulMode 한/영 (han/yeong) /// @@ -490,7 +491,8 @@ pub enum KeyCode { NumLock, /// 0 Ins on a keyboard. 0 on a phone or remote control Numpad0, - /// 1 End on a keyboard. 1 or 1 QZ on a phone or remote control + /// 1 End on a keyboard. 1 or 1 QZ on a phone or remote + /// control Numpad1, /// 2 ↓ on a keyboard. 2 ABC on a phone or remote control Numpad2, @@ -794,13 +796,14 @@ pub enum NamedKey { // Legacy modifier key. Hyper, /// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard - /// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘` key. + /// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘` + /// key. /// /// Note: In some contexts (e.g. the Web) this is referred to as the "Meta" key. Super, - /// The `Enter` or `↵` key. Used to activate current selection or accept current input. This key - /// value is also used for the `Return` (Macintosh numpad) key. This key value is also used for - /// the Android `KEYCODE_DPAD_CENTER`. + /// The `Enter` or `↵` key. Used to activate current selection or accept current input. This + /// key value is also used for the `Return` (Macintosh numpad) key. This key value is also + /// used for the Android `KEYCODE_DPAD_CENTER`. Enter, /// The Horizontal Tabulation `Tab` key. Tab, @@ -836,8 +839,8 @@ pub enum NamedKey { CrSel, /// Cut the current selection. (`APPCOMMAND_CUT`) Cut, - /// Used to delete the character to the right of the cursor. This key value is also used for the - /// key labeled `Delete` on MacOS keyboards when `Fn` is active. + /// Used to delete the character to the right of the cursor. This key value is also used for + /// the key labeled `Delete` on MacOS keyboards when `Fn` is active. Delete, /// The Erase to End of Field key. This key deletes all characters from the current cursor /// position to the end of the current field. @@ -921,8 +924,8 @@ pub enum NamedKey { /// their code points. CodeInput, /// The Compose key, also known as "Multi_key" on the X Window System. This key acts in a - /// manner similar to a dead key, triggering a mode where subsequent key presses are combined to - /// produce a different character. + /// manner similar to a dead key, triggering a mode where subsequent key presses are combined + /// to produce a different character. Compose, /// Convert the current input method sequence. Convert, @@ -961,9 +964,9 @@ pub enum NamedKey { /// The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from /// romaji mode). KanaMode, - /// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key is - /// typically used to switch to a hiragana keyboard for the purpose of converting input into - /// kanji. (`KEYCODE_KANA`) + /// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key + /// is typically used to switch to a hiragana keyboard for the purpose of converting input + /// into kanji. (`KEYCODE_KANA`) KanjiMode, /// The Katakana (Japanese Kana characters) key. Katakana, @@ -1588,7 +1591,7 @@ impl Key { /// # Examples /// /// ``` - /// use winit::keyboard::{NamedKey, Key}; + /// use winit::keyboard::{Key, NamedKey}; /// /// assert_eq!(Key::Character("a".into()).to_text(), Some("a")); /// assert_eq!(Key::Named(NamedKey::Enter).to_text(), Some("\r")); @@ -1610,7 +1613,8 @@ impl Key { /// keys can be above the letters or on the numpad. This enum allows the user to differentiate /// them. /// -/// See the documentation for the [`location`] field on the [`KeyEvent`] struct for more information. +/// See the documentation for the [`location`] field on the [`KeyEvent`] struct for more +/// information. /// /// [`location`]: ../event/struct.KeyEvent.html#structfield.location /// [`KeyEvent`]: crate::event::KeyEvent @@ -1619,8 +1623,8 @@ impl Key { pub enum KeyLocation { /// The key is in its "normal" location on the keyboard. /// - /// For instance, the "1" key above the "Q" key on a QWERTY keyboard will use this location. This - /// invariant is also returned when the location of the key cannot be identified. + /// For instance, the "1" key above the "Q" key on a QWERTY keyboard will use this location. + /// This invariant is also returned when the location of the key cannot be identified. /// /// ![Standard 1 key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_standard_1_key.svg) /// @@ -1703,14 +1707,17 @@ impl ModifiersState { pub fn shift_key(&self) -> bool { self.intersects(Self::SHIFT) } + /// Returns `true` if the control key is pressed. pub fn control_key(&self) -> bool { self.intersects(Self::CONTROL) } + /// Returns `true` if the alt key is pressed. pub fn alt_key(&self) -> bool { self.intersects(Self::ALT) } + /// Returns `true` if the super key is pressed. pub fn super_key(&self) -> bool { self.intersects(Self::SUPER) @@ -1784,12 +1791,8 @@ mod modifiers_serde { where D: Deserializer<'de>, { - let ModifiersStateSerialize { - shift_key, - control_key, - alt_key, - super_key, - } = ModifiersStateSerialize::deserialize(deserializer)?; + let ModifiersStateSerialize { shift_key, control_key, alt_key, super_key } = + ModifiersStateSerialize::deserialize(deserializer)?; let mut m = ModifiersState::empty(); m.set(ModifiersState::SHIFT, shift_key); m.set(ModifiersState::CONTROL, control_key); diff --git a/src/lib.rs b/src/lib.rs index 7880121769..cef9106e21 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,33 +19,22 @@ //! window or a key getting pressed while the window is focused. Devices can generate //! [`DeviceEvent`]s, which contain unfiltered event data that isn't specific to a certain window. //! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a -//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if desired. +//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if +//! desired. //! //! You can retrieve events by calling [`EventLoop::run_app()`]. This function will //! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and //! will run until [`exit()`] is used, at which point [`Event::LoopExiting`]. //! //! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator`-based event loop -//! model, since that can't be implemented properly on some platforms (e.g web, iOS) and works poorly on -//! most other platforms. However, this model can be re-implemented to an extent with +//! model, since that can't be implemented properly on some platforms (e.g web, iOS) and works +//! poorly on most other platforms. However, this model can be re-implemented to an extent with #![cfg_attr( - any( - windows_platform, - macos_platform, - android_platform, - x11_platform, - wayland_platform - ), + any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform), doc = "[`EventLoopExtPumpEvents::pump_app_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_app_events()]" )] #![cfg_attr( - not(any( - windows_platform, - macos_platform, - android_platform, - x11_platform, - wayland_platform - )), + not(any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform)), doc = "`EventLoopExtPumpEvents::pump_app_events()`" )] //! [^1]. See that method's documentation for more reasons about why @@ -116,16 +105,16 @@ //! //! # Drawing on the window //! -//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you to -//! retrieve the raw handle of the window and display (see the [`platform`] module and/or the +//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you +//! to retrieve the raw handle of the window and display (see the [`platform`] module and/or the //! [`raw_window_handle`] and [`raw_display_handle`] methods), which in turn allows //! you to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics. //! //! Note that many platforms will display garbage data in the window's client area if the //! application doesn't render anything to the window by the time the desktop compositor is ready to //! display the window to the user. If you notice this happening, you should create the window with -//! [`visible` set to `false`][crate::window::WindowAttributes::with_visible] and explicitly make the -//! window visible only once you're ready to render into it. +//! [`visible` set to `false`][crate::window::WindowAttributes::with_visible] and explicitly make +//! the window visible only once you're ready to render into it. //! //! # UI scaling //! @@ -151,13 +140,11 @@ //! Winit provides the following Cargo features: //! //! * `x11` (enabled by default): On Unix platforms, enables the X11 backend. -//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland -//! backend. +//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland backend. //! * `rwh_04`: Implement `raw-window-handle v0.4` traits. //! * `rwh_05`: Implement `raw-window-handle v0.5` traits. //! * `rwh_06`: Implement `raw-window-handle v0.6` traits. -//! * `serde`: Enables serialization/deserialization of certain types with -//! [Serde](https://crates.io/crates/serde). +//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde). //! * `mint`: Enables mint (math interoperability standard types) conversions. //! //! See the [`platform`] module for documentation on platform-specific cargo @@ -186,12 +173,9 @@ #![deny(clippy::all)] #![deny(unsafe_op_in_unsafe_fn)] #![cfg_attr(clippy, deny(warnings))] -// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly doc -#![cfg_attr( - docsrs, - feature(doc_auto_cfg, doc_cfg_hide), - doc(cfg_hide(doc, docsrs)) -)] +// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly +// doc +#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))] #![allow(clippy::missing_safety_doc)] #[cfg(feature = "rwh_06")] diff --git a/src/monitor.rs b/src/monitor.rs index 5c522b104b..ed987e25d1 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -5,10 +5,8 @@ //! methods, which return an iterator of [`MonitorHandle`]: //! - [`ActiveEventLoop::available_monitors`][crate::event_loop::ActiveEventLoop::available_monitors]. //! - [`Window::available_monitors`][crate::window::Window::available_monitors]. -use crate::{ - dpi::{PhysicalPosition, PhysicalSize}, - platform_impl, -}; +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::platform_impl; /// Deprecated! Use `VideoModeHandle` instead. #[deprecated = "Renamed to `VideoModeHandle`"] @@ -79,9 +77,7 @@ impl VideoModeHandle { /// a separate set of valid video modes. #[inline] pub fn monitor(&self) -> MonitorHandle { - MonitorHandle { - inner: self.video_mode.monitor(), - } + MonitorHandle { inner: self.video_mode.monitor() } } } @@ -166,8 +162,6 @@ impl MonitorHandle { /// - **Web:** Always returns an empty iterator #[inline] pub fn video_modes(&self) -> impl Iterator { - self.inner - .video_modes() - .map(|video_mode| VideoModeHandle { video_mode }) + self.inner.video_modes().map(|video_mode| VideoModeHandle { video_mode }) } } diff --git a/src/platform/android.rs b/src/platform/android.rs index 1d0a9d9365..5d13364b6f 100644 --- a/src/platform/android.rs +++ b/src/platform/android.rs @@ -58,16 +58,19 @@ //! //! ## Converting from `ndk-glue` to `android-activity` //! -//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk`, then the minimal changes would be: +//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building +//! with `cargo apk`, then the minimal changes would be: //! 1. Remove `ndk-glue` from your `Cargo.toml` -//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.15", features = [ "android-native-activity" ] }` -//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above). -//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above). +//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.15", +//! features = [ "android-native-activity" ] }` +//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc +//! macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize +//! logging as above). +//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your +//! event loop (as shown above). -use crate::{ - event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder}, - window::{Window, WindowAttributes}, -}; +use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder}; +use crate::window::{Window, WindowAttributes}; use self::activity::{AndroidApp, ConfigurationRef, Rect}; @@ -146,7 +149,7 @@ impl EventLoopBuilderExtAndroid for EventLoopBuilder { /// For compatibility applications should then import the `AndroidApp` type for /// their `android_main(app: AndroidApp)` function like: /// ```rust -/// #[cfg(target_os="android")] +/// #[cfg(target_os = "android")] /// use winit::platform::android::activity::AndroidApp; /// ``` pub mod activity { diff --git a/src/platform/ios.rs b/src/platform/ios.rs index 2e8d4548f7..500cf3db19 100644 --- a/src/platform/ios.rs +++ b/src/platform/ios.rs @@ -66,11 +66,9 @@ use std::os::raw::c_void; -use crate::{ - event_loop::EventLoop, - monitor::{MonitorHandle, VideoModeHandle}, - window::{Window, WindowAttributes}, -}; +use crate::event_loop::EventLoop; +use crate::monitor::{MonitorHandle, VideoModeHandle}; +use crate::window::{Window, WindowAttributes}; /// Additional methods on [`EventLoop`] that are specific to iOS. pub trait EventLoopExtIOS { @@ -171,20 +169,17 @@ pub trait WindowExtIOS { impl WindowExtIOS for Window { #[inline] fn set_scale_factor(&self, scale_factor: f64) { - self.window - .maybe_queue_on_main(move |w| w.set_scale_factor(scale_factor)) + self.window.maybe_queue_on_main(move |w| w.set_scale_factor(scale_factor)) } #[inline] fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { - self.window - .maybe_queue_on_main(move |w| w.set_valid_orientations(valid_orientations)) + self.window.maybe_queue_on_main(move |w| w.set_valid_orientations(valid_orientations)) } #[inline] fn set_prefers_home_indicator_hidden(&self, hidden: bool) { - self.window - .maybe_queue_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden)) + self.window.maybe_queue_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden)) } #[inline] @@ -196,32 +191,27 @@ impl WindowExtIOS for Window { #[inline] fn set_prefers_status_bar_hidden(&self, hidden: bool) { - self.window - .maybe_queue_on_main(move |w| w.set_prefers_status_bar_hidden(hidden)) + self.window.maybe_queue_on_main(move |w| w.set_prefers_status_bar_hidden(hidden)) } #[inline] fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) { - self.window - .maybe_queue_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style)) + self.window.maybe_queue_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style)) } #[inline] fn recognize_pinch_gesture(&self, should_recognize: bool) { - self.window - .maybe_queue_on_main(move |w| w.recognize_pinch_gesture(should_recognize)); + self.window.maybe_queue_on_main(move |w| w.recognize_pinch_gesture(should_recognize)); } #[inline] fn recognize_doubletap_gesture(&self, should_recognize: bool) { - self.window - .maybe_queue_on_main(move |w| w.recognize_doubletap_gesture(should_recognize)); + self.window.maybe_queue_on_main(move |w| w.recognize_doubletap_gesture(should_recognize)); } #[inline] fn recognize_rotation_gesture(&self, should_recognize: bool) { - self.window - .maybe_queue_on_main(move |w| w.recognize_rotation_gesture(should_recognize)); + self.window.maybe_queue_on_main(move |w| w.recognize_rotation_gesture(should_recognize)); } } @@ -301,8 +291,7 @@ impl WindowAttributesExtIOS for WindowAttributes { #[inline] fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self { - self.platform_specific - .preferred_screen_edges_deferring_system_gestures = edges; + self.platform_specific.preferred_screen_edges_deferring_system_gestures = edges; self } @@ -342,9 +331,7 @@ impl MonitorHandleExtIOS for MonitorHandle { #[inline] fn preferred_video_mode(&self) -> VideoModeHandle { - VideoModeHandle { - video_mode: self.inner.preferred_video_mode(), - } + VideoModeHandle { video_mode: self.inner.preferred_video_mode() } } } diff --git a/src/platform/macos.rs b/src/platform/macos.rs index dafbd59b09..74d400f327 100644 --- a/src/platform/macos.rs +++ b/src/platform/macos.rs @@ -19,11 +19,9 @@ use std::os::raw::c_void; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -use crate::{ - event_loop::{ActiveEventLoop, EventLoopBuilder}, - monitor::MonitorHandle, - window::{Window, WindowAttributes}, -}; +use crate::event_loop::{ActiveEventLoop, EventLoopBuilder}; +use crate::monitor::MonitorHandle; +use crate::window::{Window, WindowAttributes}; /// Additional methods on [`Window`] that are specific to MacOS. pub trait WindowExtMacOS { @@ -106,8 +104,7 @@ impl WindowExtMacOS for Window { #[inline] fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { - self.window - .maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen)) + self.window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen)) } #[inline] @@ -117,14 +114,12 @@ impl WindowExtMacOS for Window { #[inline] fn set_has_shadow(&self, has_shadow: bool) { - self.window - .maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow)) + self.window.maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow)) } #[inline] fn set_tabbing_identifier(&self, identifier: &str) { - self.window - .maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier)) + self.window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier)) } #[inline] @@ -144,8 +139,7 @@ impl WindowExtMacOS for Window { #[inline] fn select_tab_at_index(&self, index: usize) { - self.window - .maybe_queue_on_main(move |w| w.select_tab_at_index(index)) + self.window.maybe_queue_on_main(move |w| w.select_tab_at_index(index)) } #[inline] @@ -160,14 +154,12 @@ impl WindowExtMacOS for Window { #[inline] fn set_document_edited(&self, edited: bool) { - self.window - .maybe_queue_on_main(move |w| w.set_document_edited(edited)) + self.window.maybe_queue_on_main(move |w| w.set_document_edited(edited)) } #[inline] fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) { - self.window - .maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt)) + self.window.maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt)) } #[inline] @@ -192,7 +184,8 @@ pub enum ActivationPolicy { /// Additional methods on [`WindowAttributes`] that are specific to MacOS. /// -/// **Note:** Properties dealing with the titlebar will be overwritten by the [`WindowAttributes::with_decorations`] method: +/// **Note:** Properties dealing with the titlebar will be overwritten by the +/// [`WindowAttributes::with_decorations`] method: /// - `with_titlebar_transparent` /// - `with_title_hidden` /// - `with_titlebar_hidden` @@ -282,9 +275,7 @@ impl WindowAttributesExtMacOS for WindowAttributes { #[inline] fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self { - self.platform_specific - .tabbing_identifier - .replace(tabbing_identifier.to_string()); + self.platform_specific.tabbing_identifier.replace(tabbing_identifier.to_string()); self } @@ -307,7 +298,7 @@ pub trait EventLoopBuilderExtMacOS { /// ``` /// use winit::event_loop::EventLoopBuilder; /// #[cfg(target_os = "macos")] - /// use winit::platform::macos::{EventLoopBuilderExtMacOS, ActivationPolicy}; + /// use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS}; /// /// let mut builder = EventLoopBuilder::new(); /// #[cfg(target_os = "macos")] @@ -384,17 +375,17 @@ impl MonitorHandleExtMacOS for MonitorHandle { fn ns_screen(&self) -> Option<*mut c_void> { // SAFETY: We only use the marker to get a pointer let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() }; - self.inner - .ns_screen(mtm) - .map(|s| objc2::rc::Id::as_ptr(&s) as _) + self.inner.ns_screen(mtm).map(|s| objc2::rc::Id::as_ptr(&s) as _) } } /// Additional methods on [`ActiveEventLoop`] that are specific to macOS. pub trait ActiveEventLoopExtMacOS { - /// Hide the entire application. In most applications this is typically triggered with Command-H. + /// Hide the entire application. In most applications this is typically triggered with + /// Command-H. fn hide_application(&self); - /// Hide the other applications. In most applications this is typically triggered with Command+Option-H. + /// Hide the other applications. In most applications this is typically triggered with + /// Command+Option-H. fn hide_other_applications(&self); /// Set whether the system can automatically organize windows into tabs. /// diff --git a/src/platform/mod.rs b/src/platform/mod.rs index da6c7aa871..4f59303ed9 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -51,11 +51,5 @@ pub mod pump_events; ))] pub mod modifier_supplement; -#[cfg(any( - windows_platform, - macos_platform, - x11_platform, - wayland_platform, - docsrs -))] +#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, docsrs))] pub mod scancode; diff --git a/src/platform/modifier_supplement.rs b/src/platform/modifier_supplement.rs index 651ba7f3aa..b1db7345d5 100644 --- a/src/platform/modifier_supplement.rs +++ b/src/platform/modifier_supplement.rs @@ -25,10 +25,7 @@ pub trait KeyEventExtModifierSupplement { impl KeyEventExtModifierSupplement for KeyEvent { #[inline] fn text_with_all_modifiers(&self) -> Option<&str> { - self.platform_specific - .text_with_all_modifiers - .as_ref() - .map(|s| s.as_str()) + self.platform_specific.text_with_all_modifiers.as_ref().map(|s| s.as_str()) } #[inline] diff --git a/src/platform/pump_events.rs b/src/platform/pump_events.rs index 37a31ea615..7eedda2816 100644 --- a/src/platform/pump_events.rs +++ b/src/platform/pump_events.rs @@ -84,12 +84,11 @@ pub trait EventLoopExtPumpEvents { /// /// ## Platform-specific /// - /// - **Windows**: The implementation will use `PeekMessage` when checking for - /// window messages to avoid blocking your external event loop. + /// - **Windows**: The implementation will use `PeekMessage` when checking for window messages + /// to avoid blocking your external event loop. /// - /// - **MacOS**: The implementation works in terms of stopping the global application - /// whenever the application `RunLoop` indicates that it is preparing to block - /// and wait for new events. + /// - **MacOS**: The implementation works in terms of stopping the global application whenever + /// the application `RunLoop` indicates that it is preparing to block and wait for new events. /// /// This is very different to the polling APIs that are available on other /// platforms (the lower level polling primitives on MacOS are private diff --git a/src/platform/run_on_demand.rs b/src/platform/run_on_demand.rs index 886ff49df1..ecb22395a7 100644 --- a/src/platform/run_on_demand.rs +++ b/src/platform/run_on_demand.rs @@ -21,8 +21,8 @@ pub trait EventLoopExtRunOnDemand { /// Run the application with the event loop on the calling thread. /// - /// Unlike [`EventLoop::run_app`], this function accepts non-`'static` (i.e. non-`move`) closures - /// and it is possible to return control back to the caller without + /// Unlike [`EventLoop::run_app`], this function accepts non-`'static` (i.e. non-`move`) + /// closures and it is possible to return control back to the caller without /// consuming the `EventLoop` (by using [`exit()`]) and /// so the event loop can be re-run after it has exit. /// @@ -55,17 +55,13 @@ pub trait EventLoopExtRunOnDemand { /// - Android /// /// # Unsupported Platforms - /// - **Web:** This API is fundamentally incompatible with the event-based way in which - /// Web browsers work because it's not possible to have a long-running external - /// loop that would block the browser and there is nothing that can be - /// polled to ask for new events. Events are delivered via callbacks based - /// on an event loop that is internal to the browser itself. + /// - **Web:** This API is fundamentally incompatible with the event-based way in which Web + /// browsers work because it's not possible to have a long-running external loop that would + /// block the browser and there is nothing that can be polled to ask for new events. Events + /// are delivered via callbacks based on an event loop that is internal to the browser itself. /// - **iOS:** It's not possible to stop and start an `UIApplication` repeatedly on iOS. - /// - #[cfg_attr( - not(web_platform), - doc = "[^1]: `spawn()` is only available on `wasm` platforms." - )] + #[cfg_attr(not(web_platform), doc = "[^1]: `spawn()` is only available on `wasm` platforms.")] + #[rustfmt::skip] /// /// [`exit()`]: ActiveEventLoop::exit() /// [`set_control_flow()`]: ActiveEventLoop::set_control_flow() diff --git a/src/platform/scancode.rs b/src/platform/scancode.rs index c175e5b8bf..0d783135f2 100644 --- a/src/platform/scancode.rs +++ b/src/platform/scancode.rs @@ -2,8 +2,8 @@ use crate::keyboard::{KeyCode, PhysicalKey}; // TODO: Describe what this value contains for each platform -/// Additional methods for the [`PhysicalKey`] type that allow the user to access the platform-specific -/// scancode. +/// Additional methods for the [`PhysicalKey`] type that allow the user to access the +/// platform-specific scancode. /// /// [`PhysicalKey`]: crate::keyboard::PhysicalKey pub trait PhysicalKeyExtScancode { @@ -23,7 +23,7 @@ pub trait PhysicalKeyExtScancode { /// /// ## Platform-specific /// - **Wayland/X11**: A 32-bit linux scancode. When building from X11/Wayland keycode subtract - /// `8` to get the value you wanted. + /// `8` to get the value you wanted. fn from_scancode(scancode: u32) -> PhysicalKey; } diff --git a/src/platform/wayland.rs b/src/platform/wayland.rs index 24301ee085..683621923c 100644 --- a/src/platform/wayland.rs +++ b/src/platform/wayland.rs @@ -13,11 +13,9 @@ //! * `wayland-csd-adwaita` (default). //! * `wayland-csd-adwaita-crossfont`. //! * `wayland-csd-adwaita-notitle`. -use crate::{ - event_loop::{ActiveEventLoop, EventLoopBuilder}, - monitor::MonitorHandle, - window::{Window, WindowAttributes}, -}; +use crate::event_loop::{ActiveEventLoop, EventLoopBuilder}; +use crate::monitor::MonitorHandle; +use crate::window::{Window, WindowAttributes}; pub use crate::window::Theme; @@ -80,10 +78,8 @@ pub trait WindowAttributesExtWayland { impl WindowAttributesExtWayland for WindowAttributes { #[inline] fn with_name(mut self, general: impl Into, instance: impl Into) -> Self { - self.platform_specific.name = Some(crate::platform_impl::ApplicationName::new( - general.into(), - instance.into(), - )); + self.platform_specific.name = + Some(crate::platform_impl::ApplicationName::new(general.into(), instance.into())); self } } diff --git a/src/platform/web.rs b/src/platform/web.rs index 1209b50c6e..25765ae8e3 100644 --- a/src/platform/web.rs +++ b/src/platform/web.rs @@ -30,8 +30,8 @@ //! The following APIs can't take them into account and will therefore provide inaccurate results: //! - [`WindowEvent::Resized`] and [`Window::(set_)inner_size()`] //! - [`WindowEvent::Occluded`] -//! - [`WindowEvent::CursorMoved`], [`WindowEvent::CursorEntered`], [`WindowEvent::CursorLeft`], -//! and [`WindowEvent::Touch`]. +//! - [`WindowEvent::CursorMoved`], [`WindowEvent::CursorEntered`], [`WindowEvent::CursorLeft`], and +//! [`WindowEvent::Touch`]. //! - [`Window::set_outer_position()`] //! //! [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized @@ -109,11 +109,7 @@ pub trait WindowAttributesExtWebSys { /// In any case, the canvas won't be automatically inserted into the web page. /// /// [`None`] by default. - #[cfg_attr( - not(web_platform), - doc = "", - doc = "[`HtmlCanvasElement`]: #only-available-on-wasm" - )] + #[cfg_attr(not(web_platform), doc = "", doc = "[`HtmlCanvasElement`]: #only-available-on-wasm")] fn with_canvas(self, canvas: Option) -> Self; /// Sets whether `event.preventDefault()` should be called on events on the @@ -166,10 +162,7 @@ pub trait EventLoopExtWebSys { /// Initializes the winit event loop. /// /// Unlike - #[cfg_attr( - all(web_platform, target_feature = "exception-handling"), - doc = "`run_app()`" - )] + #[cfg_attr(all(web_platform, target_feature = "exception-handling"), doc = "`run_app()`")] #[cfg_attr( not(all(web_platform, target_feature = "exception-handling")), doc = "[`run_app()`]" @@ -181,6 +174,7 @@ pub trait EventLoopExtWebSys { /// by calling this function again. This can be useful if you want to recreate the event loop /// while the WebAssembly module is still loaded. For example, this can be used to recreate the /// event loop when switching between tabs on a single page application. + #[rustfmt::skip] /// #[cfg_attr( not(all(web_platform, target_feature = "exception-handling")), @@ -303,13 +297,7 @@ impl CustomCursorExtWebSys for CustomCursor { } fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource { - CustomCursorSource { - inner: PlatformCustomCursorSource::Url { - url, - hotspot_x, - hotspot_y, - }, - } + CustomCursorSource { inner: PlatformCustomCursorSource::Url { url, hotspot_x, hotspot_y } } } fn from_animation( @@ -360,9 +348,7 @@ impl Future for CustomCursorFuture { type Output = Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - Pin::new(&mut self.0) - .poll(cx) - .map_ok(|cursor| CustomCursor { inner: cursor }) + Pin::new(&mut self.0).poll(cx).map_ok(|cursor| CustomCursor { inner: cursor }) } } @@ -378,10 +364,9 @@ impl Display for CustomCursorError { match self { Self::Blob => write!(f, "failed to create `Blob`"), Self::Decode(error) => write!(f, "failed to decode image: {error}"), - Self::Animation => write!( - f, - "found `CustomCursor` that is an animation when building an animation" - ), + Self::Animation => { + write!(f, "found `CustomCursor` that is an animation when building an animation") + }, } } } diff --git a/src/platform/windows.rs b/src/platform/windows.rs index 9857e9e9bd..16ff8eab9b 100644 --- a/src/platform/windows.rs +++ b/src/platform/windows.rs @@ -2,15 +2,14 @@ //! //! The supported OS version is Windows 7 or higher, though Windows 10 is //! tested regularly. -use std::{ffi::c_void, path::Path}; +use std::ffi::c_void; +use std::path::Path; -use crate::{ - dpi::PhysicalSize, - event::DeviceId, - event_loop::EventLoopBuilder, - monitor::MonitorHandle, - window::{BadIcon, Icon, Window, WindowAttributes}, -}; +use crate::dpi::PhysicalSize; +use crate::event::DeviceId; +use crate::event_loop::EventLoopBuilder; +use crate::monitor::MonitorHandle; +use crate::window::{BadIcon, Icon, Window, WindowAttributes}; /// Window Handle type used by Win32 API pub type HWND = isize; @@ -57,11 +56,11 @@ pub enum BackdropType { pub struct Color(u32); impl Color { + // Special constant only valid for the window border and therefore modeled using Option + // for user facing code + const NONE: Color = Color(0xfffffffe); /// Use the system's default color - pub const SYSTEM_DEFAULT: Color = Color(0xFFFFFFFF); - - //Special constant only valid for the window border and therefore modeled using Option for user facing code - const NONE: Color = Color(0xFFFFFFFE); + pub const SYSTEM_DEFAULT: Color = Color(0xffffffff); /// Create a new color from the given RGB values pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self { @@ -202,8 +201,8 @@ pub trait WindowExtWindows { /// /// A window must be enabled before it can be activated. /// If an application has create a modal dialog box by disabling its owner window - /// (as described in [`WindowAttributesExtWindows::with_owner_window`]), the application must enable - /// the owner window before destroying the dialog box. + /// (as described in [`WindowAttributesExtWindows::with_owner_window`]), the application must + /// enable the owner window before destroying the dialog box. /// Otherwise, another window will receive the keyboard focus and be activated. /// /// If a child window is disabled, it is ignored when the system tries to determine which @@ -283,10 +282,10 @@ impl WindowExtWindows for Window { #[inline] fn set_title_background_color(&self, color: Option) { - // The windows docs don't mention NONE as a valid options but it works in practice and is useful - // to circumvent the Windows option "Show accent color on title bars and window borders" - self.window - .set_title_background_color(color.unwrap_or(Color::NONE)) + // The windows docs don't mention NONE as a valid options but it works in practice and is + // useful to circumvent the Windows option "Show accent color on title bars and + // window borders" + self.window.set_title_background_color(color.unwrap_or(Color::NONE)) } #[inline] @@ -305,8 +304,9 @@ impl WindowExtWindows for Window { pub trait WindowAttributesExtWindows { /// Set an owner to the window to be created. Can be used to create a dialog box, for example. /// This only works when [`WindowAttributes::with_parent_window`] isn't called or set to `None`. - /// Can be used in combination with [`WindowExtWindows::set_enable(false)`][WindowExtWindows::set_enable] - /// on the owner window to create a modal dialog box. + /// Can be used in combination with + /// [`WindowExtWindows::set_enable(false)`][WindowExtWindows::set_enable] on the owner + /// window to create a modal dialog box. /// /// From MSDN: /// - An owned window is always above its owner in the z-order. @@ -322,17 +322,14 @@ pub trait WindowAttributesExtWindows { /// /// The menu must have been manually created beforehand with [`CreateMenu`] or similar. /// - /// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how the menus look. - /// If you use this, it is recommended that you combine it with `with_theme(Some(Theme::Light))` to avoid a jarring effect. - /// + /// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how + /// the menus look. If you use this, it is recommended that you combine it with + /// `with_theme(Some(Theme::Light))` to avoid a jarring effect. #[cfg_attr( platform_windows, doc = "[`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu" )] - #[cfg_attr( - not(platform_windows), - doc = "[`CreateMenu`]: #only-available-on-windows" - )] + #[cfg_attr(not(platform_windows), doc = "[`CreateMenu`]: #only-available-on-windows")] fn with_menu(self, menu: HMENU) -> Self; /// This sets `ICON_BIG`. A good ceiling here is 256x256. @@ -341,12 +338,12 @@ pub trait WindowAttributesExtWindows { /// This sets `WS_EX_NOREDIRECTIONBITMAP`. fn with_no_redirection_bitmap(self, flag: bool) -> Self; - /// Enables or disables drag and drop support (enabled by default). Will interfere with other crates - /// that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` instead of - /// `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still attempt to initialize - /// COM API regardless of this option. Currently only fullscreen mode does that, but there may be more in the future. - /// If you need COM API with `COINIT_MULTITHREADED` you must initialize it before calling any winit functions. - /// See for more information. + /// Enables or disables drag and drop support (enabled by default). Will interfere with other + /// crates that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` + /// instead of `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still + /// attempt to initialize COM API regardless of this option. Currently only fullscreen mode + /// does that, but there may be more in the future. If you need COM API with + /// `COINIT_MULTITHREADED` you must initialize it before calling any winit functions. See for more information. fn with_drag_and_drop(self, flag: bool) -> Self; /// Whether show or hide the window icon in the taskbar. diff --git a/src/platform/x11.rs b/src/platform/x11.rs index 1b0f661c9e..80262fe8b4 100644 --- a/src/platform/x11.rs +++ b/src/platform/x11.rs @@ -2,11 +2,9 @@ #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -use crate::{ - event_loop::{ActiveEventLoop, EventLoopBuilder}, - monitor::MonitorHandle, - window::{Window, WindowAttributes}, -}; +use crate::event_loop::{ActiveEventLoop, EventLoopBuilder}; +use crate::monitor::MonitorHandle; +use crate::window::{Window, WindowAttributes}; use crate::dpi::Size; @@ -15,11 +13,12 @@ use crate::dpi::Size; #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WindowType { - /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the - /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying - /// root window clicks. + /// A desktop feature. This can include a single window containing desktop icons with the same + /// dimensions as the screen, allowing the desktop environment to have full control of the + /// desktop, without the need for proxying root window clicks. Desktop, - /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows. + /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all + /// other windows. Dock, /// Toolbar windows. "Torn off" from the main application. Toolbar, @@ -37,8 +36,8 @@ pub enum WindowType { /// A popup menu that usually appears when the user right clicks on an object. /// This property is typically used on override-redirect windows. PopupMenu, - /// A tooltip window. Usually used to show additional information when hovering over an object with the cursor. - /// This property is typically used on override-redirect windows. + /// A tooltip window. Usually used to show additional information when hovering over an object + /// with the cursor. This property is typically used on override-redirect windows. Tooltip, /// The window is a notification. /// This property is typically used on override-redirect windows. @@ -83,10 +82,7 @@ pub type XWindow = u32; pub fn register_xlib_error_hook(hook: XlibErrorHook) { // Append new hook. unsafe { - crate::platform_impl::XLIB_ERROR_HOOKS - .lock() - .unwrap() - .push(hook); + crate::platform_impl::XLIB_ERROR_HOOKS.lock().unwrap().push(hook); } } @@ -144,7 +140,8 @@ pub trait WindowAttributesExtX11 { /// Build window with the given `general` and `instance` names. /// /// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the - /// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance", "general"`. + /// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance", + /// "general"`. /// /// For details about application ID conventions, see the /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) @@ -202,10 +199,8 @@ impl WindowAttributesExtX11 for WindowAttributes { #[inline] fn with_name(mut self, general: impl Into, instance: impl Into) -> Self { - self.platform_specific.name = Some(crate::platform_impl::ApplicationName::new( - general.into(), - instance.into(), - )); + self.platform_specific.name = + Some(crate::platform_impl::ApplicationName::new(general.into(), instance.into())); self } diff --git a/src/platform_impl/android/keycodes.rs b/src/platform_impl/android/keycodes.rs index a1cbf4ce90..207d549f3d 100644 --- a/src/platform_impl/android/keycodes.rs +++ b/src/platform_impl/android/keycodes.rs @@ -1,7 +1,5 @@ -use android_activity::{ - input::{KeyAction, KeyEvent, KeyMapChar, Keycode}, - AndroidApp, -}; +use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode}; +use android_activity::AndroidApp; use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey}; @@ -105,7 +103,7 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey { Keycode::VolumeUp => KeyCode::AudioVolumeUp, Keycode::VolumeDown => KeyCode::AudioVolumeDown, Keycode::VolumeMute => KeyCode::AudioVolumeMute, - //Keycode::Mute => None, // Microphone mute + // Keycode::Mute => None, // Microphone mute Keycode::MediaPlayPause => KeyCode::MediaPlayPause, Keycode::MediaStop => KeyCode::MediaStop, Keycode::MediaNext => KeyCode::MediaTrackNext, @@ -176,7 +174,7 @@ pub fn character_map_and_combine_key( Err(err) => { tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}"); return None; - } + }, }; match key_map.get(key_event.key_code(), key_event.meta_state()) { @@ -188,9 +186,12 @@ pub fn character_map_and_combine_key( Ok(Some(key)) => Some(key), Ok(None) => None, Err(err) => { - tracing::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}"); + tracing::warn!( + "KeyEvent: Failed to combine 'dead key' accent '{accent}' with \ + '{unicode}': {err:?}" + ); None - } + }, } } else { Some(unicode) @@ -200,23 +201,23 @@ pub fn character_map_and_combine_key( } else { Some(KeyMapChar::Unicode(unicode)) } - } + }, Ok(KeyMapChar::CombiningAccent(accent)) => { if key_event.action() == KeyAction::Down { *combining_accent = Some(accent); } Some(KeyMapChar::CombiningAccent(accent)) - } + }, Ok(KeyMapChar::None) => { // Leave any combining_accent state in tact (seems to match how other // Android apps work) None - } + }, Err(err) => { tracing::warn!("KeyEvent: Failed to get key map character: {err:?}"); *combining_accent = None; None - } + }, } } diff --git a/src/platform_impl/android/mod.rs b/src/platform_impl/android/mod.rs index f10016d9d6..31285b63f9 100644 --- a/src/platform_impl/android/mod.rs +++ b/src/platform_impl/android/mod.rs @@ -1,16 +1,12 @@ #![cfg(android_platform)] -use std::{ - cell::Cell, - collections::VecDeque, - hash::Hash, - marker::PhantomData, - sync::{ - atomic::{AtomicBool, Ordering}, - mpsc, Arc, Mutex, - }, - time::{Duration, Instant}, -}; +use std::cell::Cell; +use std::collections::VecDeque; +use std::hash::Hash; +use std::marker::PhantomData; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::{Duration, Instant}; use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction}; use android_activity::{ @@ -18,24 +14,24 @@ use android_activity::{ }; use tracing::{debug, trace, warn}; -use crate::{ - cursor::Cursor, - dpi::{PhysicalPosition, PhysicalSize, Position, Size}, - error, - event::{self, Force, InnerSizeWriter, StartCause}, - event_loop::{self, ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents}, - platform::pump_events::PumpStatus, - window::{ - self, CursorGrabMode, CustomCursor, CustomCursorSource, ImePurpose, ResizeDirection, Theme, - WindowButtons, WindowLevel, - }, +use crate::cursor::Cursor; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error; +use crate::error::EventLoopError; +use crate::event::{self, Force, InnerSizeWriter, StartCause}; +use crate::event_loop::{self, ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents}; +use crate::platform::pump_events::PumpStatus; +use crate::platform_impl::Fullscreen; +use crate::window::{ + self, CursorGrabMode, CustomCursor, CustomCursorSource, ImePurpose, ResizeDirection, Theme, + WindowButtons, WindowLevel, }; -use crate::{error::EventLoopError, platform_impl::Fullscreen}; mod keycodes; -pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursor; -pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursorSource; +pub(crate) use crate::cursor::{ + NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource, +}; pub(crate) use crate::icon::NoIcon as PlatformIcon; static HAS_FOCUS: AtomicBool = AtomicBool::new(true); @@ -44,9 +40,7 @@ static HAS_FOCUS: AtomicBool = AtomicBool::new(true); /// equates to an infinite timeout, not a zero timeout (so can't just use /// `Option::min`) fn min_timeout(a: Option, b: Option) -> Option { - a.map_or(b, |a_timeout| { - b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))) - }) + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) } struct PeekableReceiver { @@ -58,6 +52,7 @@ impl PeekableReceiver { pub fn from_recv(recv: mpsc::Receiver) -> Self { Self { recv, first: None } } + pub fn has_incoming(&mut self) -> bool { if self.first.is_some() { return true; @@ -66,14 +61,15 @@ impl PeekableReceiver { Ok(v) => { self.first = Some(v); true - } + }, Err(mpsc::TryRecvError::Empty) => false, Err(mpsc::TryRecvError::Disconnected) => { warn!("Channel was disconnected when checking incoming"); false - } + }, } } + pub fn try_recv(&mut self) -> Result { if let Some(first) = self.first.take() { return Ok(first); @@ -88,9 +84,7 @@ struct SharedFlagSetter { } impl SharedFlagSetter { pub fn set(&self) -> bool { - self.flag - .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) - .is_ok() + self.flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed).is_ok() } } @@ -104,15 +98,13 @@ struct SharedFlag { // was queued and be able to read and clear the state atomically) impl SharedFlag { pub fn new() -> Self { - Self { - flag: Arc::new(AtomicBool::new(false)), - } + Self { flag: Arc::new(AtomicBool::new(false)) } } + pub fn setter(&self) -> SharedFlagSetter { - SharedFlagSetter { - flag: self.flag.clone(), - } + SharedFlagSetter { flag: self.flag.clone() } } + pub fn get_and_reset(&self) -> bool { self.flag.swap(false, std::sync::atomic::Ordering::AcqRel) } @@ -126,11 +118,9 @@ pub struct RedrawRequester { impl RedrawRequester { fn new(flag: &SharedFlag, waker: AndroidAppWaker) -> Self { - RedrawRequester { - flag: flag.setter(), - waker, - } + RedrawRequester { flag: flag.setter(), waker } } + pub fn request_redraw(&self) { if self.flag.set() { // Only explicitly try to wake up the main loop when the flag @@ -148,7 +138,7 @@ pub struct EventLoop { window_target: event_loop::ActiveEventLoop, redraw_flag: SharedFlag, user_events_sender: mpsc::Sender, - user_events_receiver: PeekableReceiver, //must wake looper whenever something gets sent + user_events_receiver: PeekableReceiver, // must wake looper whenever something gets sent loop_running: bool, // Dispatched `NewEvents` running: bool, pending_redraw: bool, @@ -165,10 +155,7 @@ pub(crate) struct PlatformSpecificEventLoopAttributes { impl Default for PlatformSpecificEventLoopAttributes { fn default() -> Self { - Self { - android_app: Default::default(), - ignore_volume_keys: true, - } + Self { android_app: Default::default(), ignore_volume_keys: true } } } @@ -178,7 +165,10 @@ impl EventLoop { ) -> Result { let (user_events_sender, user_events_receiver) = mpsc::channel(); - let android_app = attributes.android_app.as_ref().expect("An `AndroidApp` as passed to android_main() is required to create an `EventLoop` on Android"); + let android_app = attributes.android_app.as_ref().expect( + "An `AndroidApp` as passed to android_main() is required to create an `EventLoop` on \ + Android", + ); let redraw_flag = SharedFlag::new(); Ok(Self { @@ -225,15 +215,15 @@ impl EventLoop { match event { MainEvent::InitWindow { .. } => { callback(event::Event::Resumed, self.window_target()); - } + }, MainEvent::TerminateWindow { .. } => { callback(event::Event::Suspended, self.window_target()); - } + }, MainEvent::WindowResized { .. } => resized = true, MainEvent::RedrawNeeded { .. } => pending_redraw = true, MainEvent::ContentRectChanged { .. } => { warn!("TODO: find a way to notify application of content rect change"); - } + }, MainEvent::GainedFocus => { HAS_FOCUS.store(true, Ordering::Relaxed); callback( @@ -243,7 +233,7 @@ impl EventLoop { }, self.window_target(), ); - } + }, MainEvent::LostFocus => { HAS_FOCUS.store(false, Ordering::Relaxed); callback( @@ -253,7 +243,7 @@ impl EventLoop { }, self.window_target(), ); - } + }, MainEvent::ConfigChanged { .. } => { let monitor = MonitorHandle::new(self.android_app.clone()); let old_scale_factor = monitor.scale_factor(); @@ -273,43 +263,43 @@ impl EventLoop { }; callback(event, self.window_target()); } - } + }, MainEvent::LowMemory => { callback(event::Event::MemoryWarning, self.window_target()); - } + }, MainEvent::Start => { // XXX: how to forward this state to applications? warn!("TODO: forward onStart notification to application"); - } + }, MainEvent::Resume { .. } => { debug!("App Resumed - is running"); self.running = true; - } + }, MainEvent::SaveState { .. } => { // XXX: how to forward this state to applications? // XXX: also how do we expose state restoration to apps? warn!("TODO: forward saveState notification to application"); - } + }, MainEvent::Pause => { debug!("App Paused - stopped running"); self.running = false; - } + }, MainEvent::Stop => { // XXX: how to forward this state to applications? warn!("TODO: forward onStop notification to application"); - } + }, MainEvent::Destroy => { // XXX: maybe exit mainloop to drop things before being // killed by the OS? warn!("TODO: forward onDestroy notification to application"); - } + }, MainEvent::InsetsChanged { .. } => { // XXX: how to forward this state to applications? warn!("TODO: handle Android InsetsChanged notification"); - } + }, unknown => { trace!("Unknown MainEvent {unknown:?} (ignored)"); - } + }, } } else { trace!("No main event to handle"); @@ -331,7 +321,7 @@ impl EventLoop { }, Err(err) => { tracing::warn!("Failed to get input events iterator: {err:?}"); - } + }, } // Empty the user event buffer @@ -392,13 +382,13 @@ impl EventLoop { let phase = match motion_event.action() { MotionAction::Down | MotionAction::PointerDown => { Some(event::TouchPhase::Started) - } + }, MotionAction::Up | MotionAction::PointerUp => Some(event::TouchPhase::Ended), MotionAction::Move => Some(event::TouchPhase::Moved), MotionAction::Cancel => Some(event::TouchPhase::Cancelled), _ => { None // TODO mouse events - } + }, }; if let Some(phase) = phase { let pointers: Box>> = @@ -407,18 +397,19 @@ impl EventLoop { Box::new(std::iter::once( motion_event.pointer_at_index(motion_event.pointer_index()), )) - } + }, event::TouchPhase::Moved | event::TouchPhase::Cancelled => { Box::new(motion_event.pointers()) - } + }, }; for pointer in pointers { - let location = PhysicalPosition { - x: pointer.x() as _, - y: pointer.y() as _, - }; - trace!("Input event {device_id:?}, {phase:?}, loc={location:?}, pointer={pointer:?}"); + let location = + PhysicalPosition { x: pointer.x() as _, y: pointer.y() as _ }; + trace!( + "Input event {device_id:?}, {phase:?}, loc={location:?}, \ + pointer={pointer:?}" + ); let event = event::Event::WindowEvent { window_id, event: event::WindowEvent::Touch(event::Touch { @@ -432,17 +423,18 @@ impl EventLoop { callback(event, self.window_target()); } } - } + }, InputEvent::KeyEvent(key) => { match key.key_code() { - // Flag keys related to volume as unhandled. While winit does not have a way for applications - // to configure what keys to flag as handled, this appears to be a good default until winit + // Flag keys related to volume as unhandled. While winit does not have a way for + // applications to configure what keys to flag as handled, + // this appears to be a good default until winit // can be configured. Keycode::VolumeUp | Keycode::VolumeDown | Keycode::VolumeMute if self.ignore_volume_keys => { input_status = InputStatus::Unhandled - } + }, keycode => { let state = match key.action() { KeyAction::Down => event::ElementState::Pressed, @@ -473,12 +465,12 @@ impl EventLoop { }, }; callback(event, self.window_target()); - } + }, } - } + }, _ => { warn!("Unknown android_activity input event {event:?}") - } + }, } input_status @@ -499,13 +491,13 @@ impl EventLoop { match self.pump_events(None, &mut event_handler) { PumpStatus::Exit(0) => { break Ok(()); - } + }, PumpStatus::Exit(code) => { break Err(EventLoopError::ExitFailure(code)); - } + }, _ => { continue; - } + }, } } } @@ -561,7 +553,7 @@ impl EventLoop { ControlFlow::Poll => Some(Duration::ZERO), ControlFlow::WaitUntil(wait_deadline) => { Some(wait_deadline.saturating_duration_since(start)) - } + }, }; min_timeout(control_flow_timeout, timeout) @@ -574,8 +566,9 @@ impl EventLoop { match poll_event { android_activity::PollEvent::Wake => { // In the X11 backend it's noted that too many false-positive wake ups - // would cause the event loop to run continuously. They handle this by re-checking - // for pending events (assuming they cover all valid reasons for a wake up). + // would cause the event loop to run continuously. They handle this by + // re-checking for pending events (assuming they cover all + // valid reasons for a wake up). // // For now, user_events and redraw_requests are the only reasons to expect // a wake up here so we can ignore the wake up if there are no events/requests. @@ -586,35 +579,26 @@ impl EventLoop { { return; } - } - android_activity::PollEvent::Timeout => {} + }, + android_activity::PollEvent::Timeout => {}, android_activity::PollEvent::Main(event) => { main_event = Some(event); - } + }, unknown_event => { warn!("Unknown poll event {unknown_event:?} (ignored)"); - } + }, } self.cause = match self.control_flow() { ControlFlow::Poll => StartCause::Poll, - ControlFlow::Wait => StartCause::WaitCancelled { - start, - requested_resume: None, - }, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, ControlFlow::WaitUntil(deadline) => { if Instant::now() < deadline { - StartCause::WaitCancelled { - start, - requested_resume: Some(deadline), - } + StartCause::WaitCancelled { start, requested_resume: Some(deadline) } } else { - StartCause::ResumeTimeReached { - start, - requested_resume: deadline, - } + StartCause::ResumeTimeReached { start, requested_resume: deadline } } - } + }, }; self.single_iteration(main_event, &mut callback); @@ -657,9 +641,7 @@ impl Clone for EventLoopProxy { impl EventLoopProxy { pub fn send_event(&self, event: T) -> Result<(), event_loop::EventLoopClosed> { - self.user_events_sender - .send(event) - .map_err(|err| event_loop::EventLoopClosed(err.0))?; + self.user_events_sender.send(event).map_err(|err| event_loop::EventLoopClosed(err.0))?; self.waker.wake(); Ok(()) } @@ -679,9 +661,7 @@ impl ActiveEventLoop { pub fn create_custom_cursor(&self, source: CustomCursorSource) -> CustomCursor { let _ = source.inner; - CustomCursor { - inner: PlatformCustomCursor, - } + CustomCursor { inner: PlatformCustomCursor } } pub fn available_monitors(&self) -> VecDeque { @@ -704,9 +684,7 @@ impl ActiveEventLoop { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Android( - rwh_06::AndroidDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Android(rwh_06::AndroidDisplayHandle::new())) } pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { @@ -798,10 +776,7 @@ impl Window { ) -> Result { // FIXME this ignores requested window attributes - Ok(Self { - app: el.app.clone(), - redraw_requester: el.redraw_requester.clone(), - }) + Ok(Self { app: el.app.clone(), redraw_requester: el.redraw_requester.clone() }) } pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Self) + Send + 'static) { @@ -941,41 +916,31 @@ impl Window { pub fn set_cursor(&self, _: Cursor) {} pub fn set_cursor_position(&self, _: Position) -> Result<(), error::ExternalError> { - Err(error::ExternalError::NotSupported( - error::NotSupportedError::new(), - )) + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) } pub fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), error::ExternalError> { - Err(error::ExternalError::NotSupported( - error::NotSupportedError::new(), - )) + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) } pub fn set_cursor_visible(&self, _: bool) {} pub fn drag_window(&self) -> Result<(), error::ExternalError> { - Err(error::ExternalError::NotSupported( - error::NotSupportedError::new(), - )) + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) } pub fn drag_resize_window( &self, _direction: ResizeDirection, ) -> Result<(), error::ExternalError> { - Err(error::ExternalError::NotSupported( - error::NotSupportedError::new(), - )) + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) } #[inline] pub fn show_window_menu(&self, _position: Position) {} pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), error::ExternalError> { - Err(error::ExternalError::NotSupported( - error::NotSupportedError::new(), - )) + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) } #[cfg(feature = "rwh_04")] @@ -985,7 +950,11 @@ impl Window { if let Some(native_window) = self.app.native_window().as_ref() { native_window.raw_window_handle() } else { - panic!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events."); + panic!( + "Cannot get the native window, it's null and will always be null before \ + Event::Resumed and after Event::Suspended. Make sure you only call this function \ + between those events." + ); } } @@ -996,7 +965,11 @@ impl Window { if let Some(native_window) = self.app.native_window().as_ref() { native_window.raw_window_handle() } else { - panic!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events."); + panic!( + "Cannot get the native window, it's null and will always be null before \ + Event::Resumed and after Event::Suspended. Make sure you only call this function \ + between those events." + ); } } @@ -1014,7 +987,11 @@ impl Window { if let Some(native_window) = self.app.native_window().as_ref() { native_window.raw_window_handle() } else { - tracing::error!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events."); + tracing::error!( + "Cannot get the native window, it's null and will always be null before \ + Event::Resumed and after Event::Suspended. Make sure you only call this function \ + between those events." + ); Err(rwh_06::HandleError::Unavailable) } } @@ -1023,9 +1000,7 @@ impl Window { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Android( - rwh_06::AndroidDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Android(rwh_06::AndroidDisplayHandle::new())) } pub fn config(&self) -> ConfigurationRef { @@ -1102,11 +1077,7 @@ impl MonitorHandle { } pub fn scale_factor(&self) -> f64 { - self.app - .config() - .density() - .map(|dpi| dpi as f64 / 160.0) - .unwrap_or(1.0) + self.app.config().density().map(|dpi| dpi as f64 / 160.0).unwrap_or(1.0) } pub fn refresh_rate_millihertz(&self) -> Option { diff --git a/src/platform_impl/ios/app_delegate.rs b/src/platform_impl/ios/app_delegate.rs index ecc02553e5..99ddf1e384 100644 --- a/src/platform_impl/ios/app_delegate.rs +++ b/src/platform_impl/ios/app_delegate.rs @@ -4,10 +4,8 @@ use objc2_foundation::{MainThreadMarker, NSObject, NSObjectProtocol}; use super::app_state::{self, EventWrapper}; use super::uikit::{UIApplication, UIWindow}; use super::window::WinitUIWindow; -use crate::{ - event::{Event, WindowEvent}, - window::WindowId as RootWindowId, -}; +use crate::event::{Event, WindowEvent}; +use crate::window::WindowId as RootWindowId; declare_class!( pub struct AppDelegate; diff --git a/src/platform_impl/ios/app_state.rs b/src/platform_impl/ios/app_state.rs index 4ab33685be..15dd25f377 100644 --- a/src/platform_impl/ios/app_state.rs +++ b/src/platform_impl/ios/app_state.rs @@ -1,14 +1,11 @@ #![deny(unused_results)] -use std::{ - cell::{RefCell, RefMut}, - collections::HashSet, - fmt, mem, - os::raw::c_void, - ptr, - sync::{Arc, Mutex, OnceLock}, - time::Instant, -}; +use std::cell::{RefCell, RefMut}; +use std::collections::HashSet; +use std::os::raw::c_void; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Instant; +use std::{fmt, mem, ptr}; use core_foundation::base::CFRelease; use core_foundation::date::CFAbsoluteTimeGetCurrent; @@ -25,12 +22,10 @@ use objc2_foundation::{ use super::uikit::UIView; use super::window::WinitUIWindow; -use crate::{ - dpi::PhysicalSize, - event::{Event, InnerSizeWriter, StartCause, WindowEvent}, - event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow}, - window::WindowId as RootWindowId, -}; +use crate::dpi::PhysicalSize; +use crate::event::{Event, InnerSizeWriter, StartCause, WindowEvent}; +use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow}; +use crate::window::WindowId as RootWindowId; macro_rules! bug { ($($msg:tt)*) => { @@ -94,13 +89,7 @@ enum UserCallbackTransitionResult<'a> { impl Event { fn is_redraw(&self) -> bool { - matches!( - self, - Event::WindowEvent { - event: WindowEvent::RedrawRequested, - .. - } - ) + matches!(self, Event::WindowEvent { event: WindowEvent::RedrawRequested, .. }) } } @@ -216,10 +205,7 @@ impl AppState { } fn has_launched(&self) -> bool { - !matches!( - self.state(), - AppStateImpl::NotLaunched { .. } | AppStateImpl::Launching { .. } - ) + !matches!(self.state(), AppStateImpl::NotLaunched { .. } | AppStateImpl::Launching { .. }) } fn has_terminated(&self) -> bool { @@ -228,11 +214,9 @@ impl AppState { fn will_launch_transition(&mut self, queued_handler: EventLoopHandler) { let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() { - AppStateImpl::NotLaunched { - queued_windows, - queued_events, - queued_gpu_redraws, - } => (queued_windows, queued_events, queued_gpu_redraws), + AppStateImpl::NotLaunched { queued_windows, queued_events, queued_gpu_redraws } => { + (queued_windows, queued_events, queued_gpu_redraws) + }, s => bug!("unexpected state {:?}", s), }; self.set_state(AppStateImpl::Launching { @@ -250,12 +234,7 @@ impl AppState { queued_events, queued_handler, queued_gpu_redraws, - } => ( - queued_windows, - queued_events, - queued_handler, - queued_gpu_redraws, - ), + } => (queued_windows, queued_events, queued_handler, queued_gpu_redraws), s => bug!("unexpected state {:?}", s), }; self.set_state(AppStateImpl::ProcessingEvents { @@ -274,17 +253,10 @@ impl AppState { } let (handler, event) = match (self.control_flow, self.take_state()) { - (ControlFlow::Poll, AppStateImpl::PollFinished { waiting_handler }) => ( - waiting_handler, - EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll)), - ), - ( - ControlFlow::Wait, - AppStateImpl::Waiting { - waiting_handler, - start, - }, - ) => ( + (ControlFlow::Poll, AppStateImpl::PollFinished { waiting_handler }) => { + (waiting_handler, EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll))) + }, + (ControlFlow::Wait, AppStateImpl::Waiting { waiting_handler, start }) => ( waiting_handler, EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled { start, @@ -293,10 +265,7 @@ impl AppState { ), ( ControlFlow::WaitUntil(requested_resume), - AppStateImpl::Waiting { - waiting_handler, - start, - }, + AppStateImpl::Waiting { waiting_handler, start }, ) => { let event = if Instant::now() >= requested_resume { EventWrapper::StaticEvent(Event::NewEvents(StartCause::ResumeTimeReached { @@ -310,7 +279,7 @@ impl AppState { })) }; (waiting_handler, event) - } + }, s => bug!("`EventHandler` unexpectedly woke up {:?}", s), }; @@ -326,18 +295,9 @@ impl AppState { // If we're not able to process an event due to recursion or `Init` not having been sent out // yet, then queue the events up. match self.state_mut() { - &mut AppStateImpl::Launching { - ref mut queued_events, - .. - } - | &mut AppStateImpl::NotLaunched { - ref mut queued_events, - .. - } - | &mut AppStateImpl::InUserCallback { - ref mut queued_events, - .. - } => { + &mut AppStateImpl::Launching { ref mut queued_events, .. } + | &mut AppStateImpl::NotLaunched { ref mut queued_events, .. } + | &mut AppStateImpl::InUserCallback { ref mut queued_events, .. } => { // A lifetime cast: early returns are not currently handled well with NLL, but // polonius handles them well. This transmute is a safe workaround. return unsafe { @@ -348,60 +308,49 @@ impl AppState { queued_events, }) }; - } + }, &mut AppStateImpl::ProcessingEvents { .. } - | &mut AppStateImpl::ProcessingRedraws { .. } => {} + | &mut AppStateImpl::ProcessingRedraws { .. } => {}, s @ &mut AppStateImpl::PollFinished { .. } | s @ &mut AppStateImpl::Waiting { .. } | s @ &mut AppStateImpl::Terminated => { bug!("unexpected attempted to process an event {:?}", s) - } + }, } - let (handler, queued_gpu_redraws, active_control_flow, processing_redraws) = - match self.take_state() { - AppStateImpl::Launching { .. } - | AppStateImpl::NotLaunched { .. } - | AppStateImpl::InUserCallback { .. } => unreachable!(), - AppStateImpl::ProcessingEvents { - handler, - queued_gpu_redraws, - active_control_flow, - } => (handler, queued_gpu_redraws, active_control_flow, false), - AppStateImpl::ProcessingRedraws { - handler, - active_control_flow, - } => (handler, Default::default(), active_control_flow, true), - AppStateImpl::PollFinished { .. } - | AppStateImpl::Waiting { .. } - | AppStateImpl::Terminated => unreachable!(), - }; + let (handler, queued_gpu_redraws, active_control_flow, processing_redraws) = match self + .take_state() + { + AppStateImpl::Launching { .. } + | AppStateImpl::NotLaunched { .. } + | AppStateImpl::InUserCallback { .. } => unreachable!(), + AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } => { + (handler, queued_gpu_redraws, active_control_flow, false) + }, + AppStateImpl::ProcessingRedraws { handler, active_control_flow } => { + (handler, Default::default(), active_control_flow, true) + }, + AppStateImpl::PollFinished { .. } + | AppStateImpl::Waiting { .. } + | AppStateImpl::Terminated => unreachable!(), + }; self.set_state(AppStateImpl::InUserCallback { queued_events: Vec::new(), queued_gpu_redraws, }); - UserCallbackTransitionResult::Success { - handler, - active_control_flow, - processing_redraws, - } + UserCallbackTransitionResult::Success { handler, active_control_flow, processing_redraws } } fn main_events_cleared_transition(&mut self) -> HashSet> { let (handler, queued_gpu_redraws, active_control_flow) = match self.take_state() { - AppStateImpl::ProcessingEvents { - handler, - queued_gpu_redraws, - active_control_flow, - } => (handler, queued_gpu_redraws, active_control_flow), + AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } => { + (handler, queued_gpu_redraws, active_control_flow) + }, s => bug!("unexpected state {:?}", s), }; - self.set_state(AppStateImpl::ProcessingRedraws { - handler, - active_control_flow, - }); + self.set_state(AppStateImpl::ProcessingRedraws { handler, active_control_flow }); queued_gpu_redraws } @@ -410,10 +359,9 @@ impl AppState { return; } let (waiting_handler, old) = match self.take_state() { - AppStateImpl::ProcessingRedraws { - handler, - active_control_flow, - } => (handler, active_control_flow), + AppStateImpl::ProcessingRedraws { handler, active_control_flow } => { + (handler, active_control_flow) + }, s => bug!("unexpected state {:?}", s), }; @@ -421,41 +369,29 @@ impl AppState { match (old, new) { (ControlFlow::Wait, ControlFlow::Wait) => { let start = Instant::now(); - self.set_state(AppStateImpl::Waiting { - waiting_handler, - start, - }); - } + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); + }, (ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant)) if old_instant == new_instant => { let start = Instant::now(); - self.set_state(AppStateImpl::Waiting { - waiting_handler, - start, - }); - } + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); + }, (_, ControlFlow::Wait) => { let start = Instant::now(); - self.set_state(AppStateImpl::Waiting { - waiting_handler, - start, - }); + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); self.waker.stop() - } + }, (_, ControlFlow::WaitUntil(new_instant)) => { let start = Instant::now(); - self.set_state(AppStateImpl::Waiting { - waiting_handler, - start, - }); + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); self.waker.start_at(new_instant) - } + }, // Unlike on macOS, handle Poll to Poll transition here to call the waker (_, ControlFlow::Poll) => { self.set_state(AppStateImpl::PollFinished { waiting_handler }); self.waker.start() - } + }, } } @@ -478,19 +414,18 @@ impl AppState { pub(crate) fn set_key_window(mtm: MainThreadMarker, window: &Id) { let mut this = AppState::get_mut(mtm); match this.state_mut() { - &mut AppStateImpl::NotLaunched { - ref mut queued_windows, - .. - } => return queued_windows.push(window.clone()), + &mut AppStateImpl::NotLaunched { ref mut queued_windows, .. } => { + return queued_windows.push(window.clone()) + }, &mut AppStateImpl::ProcessingEvents { .. } | &mut AppStateImpl::InUserCallback { .. } - | &mut AppStateImpl::ProcessingRedraws { .. } => {} + | &mut AppStateImpl::ProcessingRedraws { .. } => {}, s @ &mut AppStateImpl::Launching { .. } | s @ &mut AppStateImpl::Waiting { .. } | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), &mut AppStateImpl::Terminated => { panic!("Attempt to create a `Window` after the app has terminated") - } + }, } drop(this); window.makeKeyAndVisible(); @@ -499,30 +434,18 @@ pub(crate) fn set_key_window(mtm: MainThreadMarker, window: &Id) pub(crate) fn queue_gl_or_metal_redraw(mtm: MainThreadMarker, window: Id) { let mut this = AppState::get_mut(mtm); match this.state_mut() { - &mut AppStateImpl::NotLaunched { - ref mut queued_gpu_redraws, - .. - } - | &mut AppStateImpl::Launching { - ref mut queued_gpu_redraws, - .. - } - | &mut AppStateImpl::ProcessingEvents { - ref mut queued_gpu_redraws, - .. - } - | &mut AppStateImpl::InUserCallback { - ref mut queued_gpu_redraws, - .. - } => { + &mut AppStateImpl::NotLaunched { ref mut queued_gpu_redraws, .. } + | &mut AppStateImpl::Launching { ref mut queued_gpu_redraws, .. } + | &mut AppStateImpl::ProcessingEvents { ref mut queued_gpu_redraws, .. } + | &mut AppStateImpl::InUserCallback { ref mut queued_gpu_redraws, .. } => { let _ = queued_gpu_redraws.insert(window); - } + }, s @ &mut AppStateImpl::ProcessingRedraws { .. } | s @ &mut AppStateImpl::Waiting { .. } | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), &mut AppStateImpl::Terminated => { panic!("Attempt to create a `Window` after the app has terminated") - } + }, } } @@ -566,10 +489,8 @@ pub fn did_finish_launching(mtm: MainThreadMarker) { let (windows, events) = AppState::get_mut(mtm).did_finish_launching_transition(); - let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents( - StartCause::Init, - ))) - .chain(events); + let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents(StartCause::Init))) + .chain(events); handle_nonuser_events(mtm, events); // the above window dance hack, could possibly trigger new windows to be created. @@ -609,7 +530,7 @@ pub(crate) fn handle_nonuser_events>( UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => { queued_events.extend(events); return; - } + }, UserCallbackTransitionResult::Success { handler, active_control_flow, @@ -630,7 +551,7 @@ pub(crate) fn handle_nonuser_events>( ); } handler.handle_event(event) - } + }, EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event), } } @@ -638,18 +559,16 @@ pub(crate) fn handle_nonuser_events>( loop { let mut this = AppState::get_mut(mtm); let queued_events = match this.state_mut() { - &mut AppStateImpl::InUserCallback { - ref mut queued_events, - queued_gpu_redraws: _, - } => mem::take(queued_events), + &mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _ } => { + mem::take(queued_events) + }, s => bug!("unexpected state {:?}", s), }; if queued_events.is_empty() { let queued_gpu_redraws = match this.take_state() { - AppStateImpl::InUserCallback { - queued_events: _, - queued_gpu_redraws, - } => queued_gpu_redraws, + AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws } => { + queued_gpu_redraws + }, _ => unreachable!(), }; this.app_state = Some(if processing_redraws { @@ -657,16 +576,9 @@ pub(crate) fn handle_nonuser_events>( queued_gpu_redraws.is_empty(), "redraw queued while processing redraws" ); - AppStateImpl::ProcessingRedraws { - handler, - active_control_flow, - } + AppStateImpl::ProcessingRedraws { handler, active_control_flow } } else { - AppStateImpl::ProcessingEvents { - handler, - queued_gpu_redraws, - active_control_flow, - } + AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } }); break; } @@ -679,12 +591,13 @@ pub(crate) fn handle_nonuser_events>( tracing::info!("processing `RedrawRequested` during the main event loop"); } else if processing_redraws && !event.is_redraw() { tracing::warn!( - "processing non-`RedrawRequested` event after the main event loop: {:#?}", + "processing non-`RedrawRequested` event after the main event loop: \ + {:#?}", event ); } handler.handle_event(event) - } + }, EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event), } } @@ -697,7 +610,7 @@ fn handle_user_events(mtm: MainThreadMarker) { match this.try_user_callback_transition() { UserCallbackTransitionResult::ReentrancyPrevented { .. } => { bug!("unexpected attempted to process an event") - } + }, UserCallbackTransitionResult::Success { handler, active_control_flow, @@ -714,18 +627,16 @@ fn handle_user_events(mtm: MainThreadMarker) { loop { let mut this = AppState::get_mut(mtm); let queued_events = match this.state_mut() { - &mut AppStateImpl::InUserCallback { - ref mut queued_events, - queued_gpu_redraws: _, - } => mem::take(queued_events), + &mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _ } => { + mem::take(queued_events) + }, s => bug!("unexpected state {:?}", s), }; if queued_events.is_empty() { let queued_gpu_redraws = match this.take_state() { - AppStateImpl::InUserCallback { - queued_events: _, - queued_gpu_redraws, - } => queued_gpu_redraws, + AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws } => { + queued_gpu_redraws + }, _ => unreachable!(), }; this.app_state = Some(AppStateImpl::ProcessingEvents { @@ -754,7 +665,7 @@ pub fn handle_main_events_cleared(mtm: MainThreadMarker) { return; } match this.state_mut() { - AppStateImpl::ProcessingEvents { .. } => {} + AppStateImpl::ProcessingEvents { .. } => {}, _ => bug!("`ProcessingRedraws` happened unexpectedly"), }; drop(this); @@ -791,11 +702,7 @@ pub fn terminated(mtm: MainThreadMarker) { } fn handle_hidpi_proxy(handler: &mut EventLoopHandler, event: ScaleFactorChanged) { - let ScaleFactorChanged { - suggested_size, - scale_factor, - window, - } = event; + let ScaleFactorChanged { suggested_size, scale_factor, window } = event; let new_inner_size = Arc::new(Mutex::new(suggested_size)); let event = Event::WindowEvent { window_id: RootWindowId(window.id()), @@ -956,11 +863,12 @@ fn get_version() -> NSOperatingSystemVersion { &process_info, respondsToSelector: sel!(operatingSystemVersion) ]; - // winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions. - // Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support - // debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS - // simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7 - // has been tested to not even run on macOS 10.15 - Xcode 8 might? + // winit requires atleast iOS 8 because no one has put the time into supporting earlier os + // versions. Older iOS versions are increasingly difficult to test. For example, + // Xcode 11 does not support debugging on devices with an iOS version of less than + // 8. Another example, in order to use an iOS simulator older than iOS 8, you must + // download an older version of Xcode (<9), and at least Xcode 7 has been tested to + // not even run on macOS 10.15 - Xcode 8 might? // // The minimum required iOS version is likely to grow in the future. assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater"); @@ -971,7 +879,5 @@ fn get_version() -> NSOperatingSystemVersion { pub fn os_capabilities() -> OSCapabilities { // Cache the version lookup for efficiency static OS_CAPABILITIES: OnceLock = OnceLock::new(); - OS_CAPABILITIES - .get_or_init(|| OSCapabilities::from_os_version(get_version())) - .clone() + OS_CAPABILITIES.get_or_init(|| OSCapabilities::from_os_version(get_version())).clone() } diff --git a/src/platform_impl/ios/event_loop.rs b/src/platform_impl/ios/event_loop.rs index 3064a0869f..40293d9f79 100644 --- a/src/platform_impl/ios/event_loop.rs +++ b/src/platform_impl/ios/event_loop.rs @@ -1,10 +1,8 @@ -use std::{ - collections::VecDeque, - ffi::c_void, - marker::PhantomData, - ptr, - sync::mpsc::{self, Receiver, Sender}, -}; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::marker::PhantomData; +use std::ptr; +use std::sync::mpsc::{self, Receiver, Sender}; use core_foundation::base::{CFIndex, CFRelease}; use core_foundation::runloop::{ @@ -16,23 +14,19 @@ use core_foundation::runloop::{ use objc2::ClassType; use objc2_foundation::{MainThreadMarker, NSString}; -use crate::{ - error::EventLoopError, - event::Event, - event_loop::{ - ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents, EventLoopClosed, - }, - platform::ios::Idiom, - platform_impl::platform::app_state::{EventLoopHandler, HandlePendingUserEvents}, - window::{CustomCursor, CustomCursorSource}, +use crate::error::EventLoopError; +use crate::event::Event; +use crate::event_loop::{ + ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents, EventLoopClosed, }; +use crate::platform::ios::Idiom; +use crate::platform_impl::platform::app_state::{EventLoopHandler, HandlePendingUserEvents}; +use crate::window::{CustomCursor, CustomCursorSource}; -use super::{app_delegate::AppDelegate, uikit::UIUserInterfaceIdiom}; +use super::app_delegate::AppDelegate; +use super::app_state::AppState; +use super::uikit::{UIApplication, UIApplicationMain, UIDevice, UIScreen, UIUserInterfaceIdiom}; use super::{app_state, monitor, MonitorHandle}; -use super::{ - app_state::AppState, - uikit::{UIApplication, UIApplicationMain, UIDevice, UIScreen}, -}; #[derive(Debug)] pub struct ActiveEventLoop { @@ -42,9 +36,7 @@ pub struct ActiveEventLoop { impl ActiveEventLoop { pub fn create_custom_cursor(&self, source: CustomCursorSource) -> CustomCursor { let _ = source.inner; - CustomCursor { - inner: super::PlatformCustomCursor, - } + CustomCursor { inner: super::PlatformCustomCursor } } pub fn available_monitors(&self) -> VecDeque { @@ -69,9 +61,7 @@ impl ActiveEventLoop { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::UiKit( - rwh_06::UiKitDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new())) } pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { @@ -126,7 +116,7 @@ fn map_user_event( for event in receiver.try_iter() { (handler)(Event::UserEvent(event), window_target); } - } + }, } } @@ -151,8 +141,7 @@ impl EventLoop { unsafe { assert!( !SINGLETON_INIT, - "Only one `EventLoop` is supported on iOS. \ - `EventLoopProxy` might be helpful" + "Only one `EventLoop` is supported on iOS. `EventLoopProxy` might be helpful" ); SINGLETON_INIT = true; } @@ -166,10 +155,7 @@ impl EventLoop { mtm, sender, receiver, - window_target: RootActiveEventLoop { - p: ActiveEventLoop { mtm }, - _marker: PhantomData, - }, + window_target: RootActiveEventLoop { p: ActiveEventLoop { mtm }, _marker: PhantomData }, }) } @@ -181,8 +167,8 @@ impl EventLoop { assert!( application.is_none(), "\ - `EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\n\ - Note: `EventLoop::run_app` calls `UIApplicationMain` on iOS", + `EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\nNote: \ + `EventLoop::run_app` calls `UIApplicationMain` on iOS", ); let handler = map_user_event(handler, self.receiver); @@ -194,10 +180,7 @@ impl EventLoop { >(Box::new(handler)) }; - let handler = EventLoopHandler { - handler, - event_loop: self.window_target, - }; + let handler = EventLoopHandler { handler, event_loop: self.window_target }; app_state::will_launch(self.mtm, handler); @@ -205,12 +188,7 @@ impl EventLoop { let _ = AppDelegate::class(); unsafe { - UIApplicationMain( - 0, - ptr::null(), - None, - Some(&NSString::from_str(AppDelegate::NAME)), - ) + UIApplicationMain(0, ptr::null(), None, Some(&NSString::from_str(AppDelegate::NAME))) }; unreachable!() } @@ -292,9 +270,7 @@ impl EventLoopProxy { } pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { - self.sender - .send(event) - .map_err(|::std::sync::mpsc::SendError(x)| EventLoopClosed(x))?; + self.sender.send(event).map_err(|::std::sync::mpsc::SendError(x)| EventLoopClosed(x))?; unsafe { // let the main thread know there's a new event CFRunLoopSourceSignal(self.source); @@ -307,7 +283,8 @@ impl EventLoopProxy { fn setup_control_flow_observers() { unsafe { - // begin is queued with the highest priority to ensure it is processed before other observers + // begin is queued with the highest priority to ensure it is processed before other + // observers extern "C" fn control_flow_begin_handler( _: CFRunLoopObserverRef, activity: CFRunLoopActivity, @@ -341,7 +318,7 @@ fn setup_control_flow_observers() { #[allow(non_upper_case_globals)] match activity { kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(mtm), - kCFRunLoopExit => {} // may happen when running on macOS + kCFRunLoopExit => {}, // may happen when running on macOS _ => unreachable!(), } } @@ -356,7 +333,7 @@ fn setup_control_flow_observers() { #[allow(non_upper_case_globals)] match activity { kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(mtm), - kCFRunLoopExit => {} // may happen when running on macOS + kCFRunLoopExit => {}, // may happen when running on macOS _ => unreachable!(), } } diff --git a/src/platform_impl/ios/mod.rs b/src/platform_impl/ios/mod.rs index a6f30e67a8..c90a21c5fd 100644 --- a/src/platform_impl/ios/mod.rs +++ b/src/platform_impl/ios/mod.rs @@ -14,16 +14,15 @@ use std::fmt; use crate::event::DeviceId as RootDeviceId; -pub(crate) use self::{ - event_loop::{ - ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, - PlatformSpecificEventLoopAttributes, - }, - monitor::{MonitorHandle, VideoModeHandle}, - window::{PlatformSpecificWindowAttributes, Window, WindowId}, +pub(crate) use self::event_loop::{ + ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, + PlatformSpecificEventLoopAttributes, +}; +pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle}; +pub(crate) use self::window::{PlatformSpecificWindowAttributes, Window, WindowId}; +pub(crate) use crate::cursor::{ + NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource, }; -pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursor; -pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursorSource; pub(crate) use crate::icon::NoIcon as PlatformIcon; pub(crate) use crate::platform_impl::Fullscreen; diff --git a/src/platform_impl/ios/monitor.rs b/src/platform_impl/ios/monitor.rs index d109401bfb..d85fe20e63 100644 --- a/src/platform_impl/ios/monitor.rs +++ b/src/platform_impl/ios/monitor.rs @@ -1,9 +1,7 @@ #![allow(clippy::unnecessary_cast)] -use std::{ - collections::{BTreeSet, VecDeque}, - fmt, hash, ptr, -}; +use std::collections::{BTreeSet, VecDeque}; +use std::{fmt, hash, ptr}; use objc2::mutability::IsRetainable; use objc2::rc::Id; @@ -11,11 +9,9 @@ use objc2::Message; use objc2_foundation::{run_on_main, MainThreadBound, MainThreadMarker, NSInteger}; use super::uikit::{UIScreen, UIScreenMode}; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize}, - monitor::VideoModeHandle as RootVideoModeHandle, - platform_impl::platform::app_state, -}; +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::monitor::VideoModeHandle as RootVideoModeHandle; +use crate::platform_impl::platform::app_state; // Workaround for `MainThreadBound` implementing almost no traits #[derive(Debug)] @@ -23,9 +19,7 @@ struct MainThreadBoundDelegateImpls(MainThreadBound>); impl Clone for MainThreadBoundDelegateImpls { fn clone(&self) -> Self { - Self(run_on_main(|mtm| { - MainThreadBound::new(Id::clone(self.0.get(mtm)), mtm) - })) + Self(run_on_main(|mtm| MainThreadBound::new(Id::clone(self.0.get(mtm)), mtm))) } } @@ -149,9 +143,7 @@ impl MonitorHandle { pub(crate) fn new(ui_screen: Id) -> Self { // Holding `Id` implies we're on the main thread. let mtm = MainThreadMarker::new().unwrap(); - Self { - ui_screen: MainThreadBound::new(ui_screen, mtm), - } + Self { ui_screen: MainThreadBound::new(ui_screen, mtm) } } pub fn name(&self) -> Option { @@ -171,29 +163,21 @@ impl MonitorHandle { } pub fn size(&self) -> PhysicalSize { - let bounds = self - .ui_screen - .get_on_main(|ui_screen| ui_screen.nativeBounds()); + let bounds = self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeBounds()); PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32) } pub fn position(&self) -> PhysicalPosition { - let bounds = self - .ui_screen - .get_on_main(|ui_screen| ui_screen.nativeBounds()); + let bounds = self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeBounds()); (bounds.origin.x as f64, bounds.origin.y as f64).into() } pub fn scale_factor(&self) -> f64 { - self.ui_screen - .get_on_main(|ui_screen| ui_screen.nativeScale()) as f64 + self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeScale()) as f64 } pub fn refresh_rate_millihertz(&self) -> Option { - Some( - self.ui_screen - .get_on_main(|ui_screen| refresh_rate_millihertz(ui_screen)), - ) + Some(self.ui_screen.get_on_main(|ui_screen| refresh_rate_millihertz(ui_screen))) } pub fn video_modes(&self) -> impl Iterator { @@ -253,8 +237,5 @@ fn refresh_rate_millihertz(uiscreen: &UIScreen) -> u32 { } pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque { - UIScreen::screens(mtm) - .into_iter() - .map(MonitorHandle::new) - .collect() + UIScreen::screens(mtm).into_iter().map(MonitorHandle::new).collect() } diff --git a/src/platform_impl/ios/uikit/gesture_recognizer.rs b/src/platform_impl/ios/uikit/gesture_recognizer.rs index 7afe759fff..9092471a3c 100644 --- a/src/platform_impl/ios/uikit/gesture_recognizer.rs +++ b/src/platform_impl/ios/uikit/gesture_recognizer.rs @@ -1,7 +1,5 @@ -use objc2::{ - encode::{Encode, Encoding}, - extern_class, extern_methods, mutability, ClassType, -}; +use objc2::encode::{Encode, Encoding}; +use objc2::{extern_class, extern_methods, mutability, ClassType}; use objc2_foundation::{CGFloat, NSInteger, NSObject, NSUInteger}; // https://developer.apple.com/documentation/uikit/uigesturerecognizer diff --git a/src/platform_impl/ios/uikit/view.rs b/src/platform_impl/ios/uikit/view.rs index 719b7c4d6d..abd9bc5341 100644 --- a/src/platform_impl/ios/uikit/view.rs +++ b/src/platform_impl/ios/uikit/view.rs @@ -84,13 +84,10 @@ pub struct UIEdgeInsets { } unsafe impl Encode for UIEdgeInsets { - const ENCODING: Encoding = Encoding::Struct( - "UIEdgeInsets", - &[ - CGFloat::ENCODING, - CGFloat::ENCODING, - CGFloat::ENCODING, - CGFloat::ENCODING, - ], - ); + const ENCODING: Encoding = Encoding::Struct("UIEdgeInsets", &[ + CGFloat::ENCODING, + CGFloat::ENCODING, + CGFloat::ENCODING, + CGFloat::ENCODING, + ]); } diff --git a/src/platform_impl/ios/view.rs b/src/platform_impl/ios/view.rs index 79a1eb9546..8531a60d14 100644 --- a/src/platform_impl/ios/view.rs +++ b/src/platform_impl/ios/view.rs @@ -15,12 +15,10 @@ use super::uikit::{ UITouchType, UITraitCollection, UIView, }; use super::window::WinitUIWindow; -use crate::{ - dpi::PhysicalPosition, - event::{Event, Force, Touch, TouchPhase, WindowEvent}, - platform_impl::platform::DEVICE_ID, - window::{WindowAttributes, WindowId as RootWindowId}, -}; +use crate::dpi::PhysicalPosition; +use crate::event::{Event, Force, Touch, TouchPhase, WindowEvent}; +use crate::platform_impl::platform::DEVICE_ID; +use crate::window::{WindowAttributes, WindowId as RootWindowId}; pub struct WinitViewState { pinch_gesture_recognizer: RefCell>>, @@ -314,9 +312,7 @@ impl WinitView { msg_send_id![UIRotationGestureRecognizer::alloc(), initWithTarget: self, action: sel!(rotationGesture:)] }; self.addGestureRecognizer(&rotation); - self.ivars() - .rotation_gesture_recognizer - .replace(Some(rotation)); + self.ivars().rotation_gesture_recognizer.replace(Some(rotation)); } } else if let Some(recognizer) = self.ivars().rotation_gesture_recognizer.take() { self.removeGestureRecognizer(&recognizer); diff --git a/src/platform_impl/ios/view_controller.rs b/src/platform_impl/ios/view_controller.rs index 8e2cf12b05..e0872859d0 100644 --- a/src/platform_impl/ios/view_controller.rs +++ b/src/platform_impl/ios/view_controller.rs @@ -9,8 +9,8 @@ use super::uikit::{ UIDevice, UIInterfaceOrientationMask, UIRectEdge, UIResponder, UIStatusBarStyle, UIUserInterfaceIdiom, UIView, UIViewController, }; -use crate::platform::ios::{ScreenEdge, StatusBarStyle}; -use crate::{platform::ios::ValidOrientations, window::WindowAttributes}; +use crate::platform::ios::{ScreenEdge, StatusBarStyle, ValidOrientations}; +use crate::window::WindowAttributes; pub struct ViewControllerState { prefers_status_bar_hidden: Cell, @@ -97,16 +97,10 @@ impl WinitViewController { pub(crate) fn set_preferred_screen_edges_deferring_system_gestures(&self, val: ScreenEdge) { let val = { - assert_eq!( - val.bits() & !ScreenEdge::ALL.bits(), - 0, - "invalid `ScreenEdge`" - ); + assert_eq!(val.bits() & !ScreenEdge::ALL.bits(), 0, "invalid `ScreenEdge`"); UIRectEdge(val.bits().into()) }; - self.ivars() - .preferred_screen_edges_deferring_system_gestures - .set(val); + self.ivars().preferred_screen_edges_deferring_system_gestures.set(val); let os_capabilities = app_state::os_capabilities(); if os_capabilities.defer_system_gestures { self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures(); @@ -120,22 +114,19 @@ impl WinitViewController { mtm: MainThreadMarker, valid_orientations: ValidOrientations, ) { - let mask = match ( - valid_orientations, - UIDevice::current(mtm).userInterfaceIdiom(), - ) { + let mask = match (valid_orientations, UIDevice::current(mtm).userInterfaceIdiom()) { (ValidOrientations::LandscapeAndPortrait, UIUserInterfaceIdiom::Phone) => { UIInterfaceOrientationMask::AllButUpsideDown - } + }, (ValidOrientations::LandscapeAndPortrait, _) => UIInterfaceOrientationMask::All, (ValidOrientations::Landscape, _) => UIInterfaceOrientationMask::Landscape, (ValidOrientations::Portrait, UIUserInterfaceIdiom::Phone) => { UIInterfaceOrientationMask::Portrait - } + }, (ValidOrientations::Portrait, _) => { UIInterfaceOrientationMask::Portrait | UIInterfaceOrientationMask::PortraitUpsideDown - } + }, }; self.ivars().supported_orientations.set(mask); UIViewController::attemptRotationToDeviceOrientation(); @@ -157,15 +148,11 @@ impl WinitViewController { let this: Id = unsafe { msg_send_id![super(this), init] }; this.set_prefers_status_bar_hidden( - window_attributes - .platform_specific - .prefers_status_bar_hidden, + window_attributes.platform_specific.prefers_status_bar_hidden, ); this.set_preferred_status_bar_style( - window_attributes - .platform_specific - .preferred_status_bar_style, + window_attributes.platform_specific.preferred_status_bar_style, ); this.set_supported_interface_orientations( @@ -174,15 +161,11 @@ impl WinitViewController { ); this.set_prefers_home_indicator_auto_hidden( - window_attributes - .platform_specific - .prefers_home_indicator_hidden, + window_attributes.platform_specific.prefers_home_indicator_hidden, ); this.set_preferred_screen_edges_deferring_system_gestures( - window_attributes - .platform_specific - .preferred_screen_edges_deferring_system_gestures, + window_attributes.platform_specific.preferred_screen_edges_deferring_system_gestures, ); this.setView(Some(view)); diff --git a/src/platform_impl/ios/window.rs b/src/platform_impl/ios/window.rs index 7fd5b6a428..1d9310daaa 100644 --- a/src/platform_impl/ios/window.rs +++ b/src/platform_impl/ios/window.rs @@ -14,18 +14,18 @@ use super::uikit::{ }; use super::view::WinitView; use super::view_controller::WinitViewController; -use crate::{ - cursor::Cursor, - dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}, - error::{ExternalError, NotSupportedError, OsError as RootOsError}, - event::{Event, WindowEvent}, - icon::Icon, - platform::ios::{ScreenEdge, StatusBarStyle, ValidOrientations}, - platform_impl::platform::{app_state, monitor, ActiveEventLoop, Fullscreen, MonitorHandle}, - window::{ - CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, - WindowButtons, WindowId as RootWindowId, WindowLevel, - }, +use crate::cursor::Cursor; +use crate::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event::{Event, WindowEvent}; +use crate::icon::Icon; +use crate::platform::ios::{ScreenEdge, StatusBarStyle, ValidOrientations}; +use crate::platform_impl::platform::{ + app_state, monitor, ActiveEventLoop, Fullscreen, MonitorHandle, +}; +use crate::window::{ + CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, + WindowButtons, WindowId as RootWindowId, WindowLevel, }; declare_class!( @@ -87,11 +87,11 @@ impl WinitUIWindow { let screen = monitor.ui_screen(mtm); screen.setCurrentMode(Some(video_mode.screen_mode(mtm))); this.setScreen(screen); - } + }, Some(Fullscreen::Borderless(Some(ref monitor))) => { let screen = monitor.ui_screen(mtm); this.setScreen(screen); - } + }, _ => (), } @@ -135,12 +135,13 @@ impl Inner { pub fn request_redraw(&self) { if self.gl_or_metal_backed { let mtm = MainThreadMarker::new().unwrap(); - // `setNeedsDisplay` does nothing on UIViews which are directly backed by CAEAGLLayer or CAMetalLayer. - // Ordinarily the OS sets up a bunch of UIKit state before calling drawRect: on a UIView, but when using - // raw or gl/metal for drawing this work is completely avoided. + // `setNeedsDisplay` does nothing on UIViews which are directly backed by CAEAGLLayer or + // CAMetalLayer. Ordinarily the OS sets up a bunch of UIKit state before + // calling drawRect: on a UIView, but when using raw or gl/metal for drawing + // this work is completely avoided. // - // The docs for `setNeedsDisplay` don't mention `CAMetalLayer`; however, this has been confirmed via - // testing. + // The docs for `setNeedsDisplay` don't mention `CAMetalLayer`; however, this has been + // confirmed via testing. // // https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay?language=objc app_state::queue_gl_or_metal_redraw(mtm, self.window.clone()); @@ -153,20 +154,16 @@ impl Inner { pub fn inner_position(&self) -> Result, NotSupportedError> { let safe_area = self.safe_area_screen_space(); - let position = LogicalPosition { - x: safe_area.origin.x as f64, - y: safe_area.origin.y as f64, - }; + let position = + LogicalPosition { x: safe_area.origin.x as f64, y: safe_area.origin.y as f64 }; let scale_factor = self.scale_factor(); Ok(position.to_physical(scale_factor)) } pub fn outer_position(&self) -> Result, NotSupportedError> { let screen_frame = self.screen_frame(); - let position = LogicalPosition { - x: screen_frame.origin.x as f64, - y: screen_frame.origin.y as f64, - }; + let position = + LogicalPosition { x: screen_frame.origin.x as f64, y: screen_frame.origin.y as f64 }; let scale_factor = self.scale_factor(); Ok(position.to_physical(scale_factor)) } @@ -176,10 +173,7 @@ impl Inner { let position = physical_position.to_logical::(scale_factor); let screen_frame = self.screen_frame(); let new_screen_frame = CGRect { - origin: CGPoint { - x: position.x as _, - y: position.y as _, - }, + origin: CGPoint { x: position.x as _, y: position.y as _ }, size: screen_frame.size, }; let bounds = self.rect_from_screen_space(new_screen_frame); @@ -307,15 +301,15 @@ impl Inner { let uiscreen = video_mode.monitor.ui_screen(mtm); uiscreen.setCurrentMode(Some(video_mode.screen_mode(mtm))); uiscreen.clone() - } + }, Some(Fullscreen::Borderless(Some(monitor))) => monitor.ui_screen(mtm).clone(), Some(Fullscreen::Borderless(None)) => { self.current_monitor_inner().ui_screen(mtm).clone() - } + }, None => { warn!("`Window::set_fullscreen(None)` ignored on iOS"); return; - } + }, }; // this is pretty slow on iOS, so avoid doing it if we can @@ -400,9 +394,7 @@ impl Inner { } pub fn primary_monitor(&self) -> Option { - Some(MonitorHandle::new(UIScreen::main( - MainThreadMarker::new().unwrap(), - ))) + Some(MonitorHandle::new(UIScreen::main(MainThreadMarker::new().unwrap()))) } pub fn id(&self) -> WindowId { @@ -505,12 +497,9 @@ impl Window { let size = dim.to_logical::(scale_factor as f64); CGRect { origin: screen_bounds.origin, - size: CGSize { - width: size.width as _, - height: size.height as _, - }, + size: CGSize { width: size.width as _, height: size.height as _ }, } - } + }, None => screen_bounds, }; @@ -544,13 +533,11 @@ impl Window { let window_id = RootWindowId(window.id()); app_state::handle_nonuser_events( mtm, - std::iter::once(EventWrapper::ScaleFactorChanged( - app_state::ScaleFactorChanged { - window: window.clone(), - scale_factor, - suggested_size: size.to_physical(scale_factor), - }, - )) + std::iter::once(EventWrapper::ScaleFactorChanged(app_state::ScaleFactorChanged { + window: window.clone(), + scale_factor, + suggested_size: size.to_physical(scale_factor), + })) .chain(std::iter::once(EventWrapper::StaticEvent( Event::WindowEvent { window_id, @@ -560,15 +547,8 @@ impl Window { ); } - let inner = Inner { - window, - view_controller, - view, - gl_or_metal_backed, - }; - Ok(Window { - inner: MainThreadBound::new(inner, mtm), - }) + let inner = Inner { window, view_controller, view, gl_or_metal_backed }; + Ok(Window { inner: MainThreadBound::new(inner, mtm) }) } pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Inner) + Send + 'static) { @@ -597,9 +577,7 @@ impl Window { pub(crate) fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::UiKit( - rwh_06::UiKitDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new())) } } @@ -622,13 +600,11 @@ impl Inner { } pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) { - self.view_controller - .set_prefers_home_indicator_auto_hidden(hidden); + self.view_controller.set_prefers_home_indicator_auto_hidden(hidden); } pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { - self.view_controller - .set_preferred_screen_edges_deferring_system_gestures(edges); + self.view_controller.set_preferred_screen_edges_deferring_system_gestures(edges); } pub fn set_prefers_status_bar_hidden(&self, hidden: bool) { @@ -636,8 +612,7 @@ impl Inner { } pub fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) { - self.view_controller - .set_preferred_status_bar_style(status_bar_style); + self.view_controller.set_preferred_status_bar_style(status_bar_style); } pub fn recognize_pinch_gesture(&self, should_recognize: bool) { @@ -660,14 +635,12 @@ impl Inner { fn rect_to_screen_space(&self, rect: CGRect) -> CGRect { let screen_space = self.window.screen().coordinateSpace(); - self.window - .convertRect_toCoordinateSpace(rect, &screen_space) + self.window.convertRect_toCoordinateSpace(rect, &screen_space) } fn rect_from_screen_space(&self, rect: CGRect) -> CGRect { let screen_space = self.window.screen().coordinateSpace(); - self.window - .convertRect_fromCoordinateSpace(rect, &screen_space) + self.window.convertRect_fromCoordinateSpace(rect, &screen_space) } fn safe_area_screen_space(&self) -> CGRect { @@ -689,7 +662,8 @@ impl Inner { let screen_frame = self.rect_to_screen_space(bounds); let status_bar_frame = { let app = UIApplication::shared(MainThreadMarker::new().unwrap()).expect( - "`Window::get_inner_position` cannot be called before `EventLoop::run_app` on iOS", + "`Window::get_inner_position` cannot be called before `EventLoop::run_app` on \ + iOS", ); app.statusBarFrame() }; @@ -702,14 +676,8 @@ impl Inner { (y, height) }; CGRect { - origin: CGPoint { - x: screen_frame.origin.x, - y, - }, - size: CGSize { - width: screen_frame.size.width, - height, - }, + origin: CGPoint { x: screen_frame.origin.x, y }, + size: CGSize { width: screen_frame.size.width, height }, } } } @@ -722,9 +690,7 @@ pub struct WindowId { impl WindowId { pub const unsafe fn dummy() -> Self { - WindowId { - window: std::ptr::null_mut(), - } + WindowId { window: std::ptr::null_mut() } } } @@ -736,9 +702,7 @@ impl From for u64 { impl From for WindowId { fn from(raw_id: u64) -> Self { - Self { - window: raw_id as _, - } + Self { window: raw_id as _ } } } @@ -747,9 +711,7 @@ unsafe impl Sync for WindowId {} impl From<&AnyObject> for WindowId { fn from(window: &AnyObject) -> WindowId { - WindowId { - window: window as *const _ as _, - } + WindowId { window: window as *const _ as _ } } } diff --git a/src/platform_impl/linux/common/xkb/compose.rs b/src/platform_impl/linux/common/xkb/compose.rs index 65b6514ba9..9d4f590aec 100644 --- a/src/platform_impl/linux/common/xkb/compose.rs +++ b/src/platform_impl/linux/common/xkb/compose.rs @@ -6,8 +6,7 @@ use std::ops::Deref; use std::os::unix::ffi::OsStringExt; use std::ptr::NonNull; -use super::XkbContext; -use super::XKBCH; +use super::{XkbContext, XKBCH}; use smol_str::SmolStr; use xkbcommon_dl::{ xkb_compose_compile_flags, xkb_compose_feed_result, xkb_compose_state, xkb_compose_state_flags, @@ -91,7 +90,7 @@ impl XkbComposeState { xkb_compose_feed_result::XKB_COMPOSE_FEED_IGNORED => ComposeStatus::Ignored, xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED => { ComposeStatus::Accepted(self.status()) - } + }, } } diff --git a/src/platform_impl/linux/common/xkb/keymap.rs b/src/platform_impl/linux/common/xkb/keymap.rs index f47643f390..67aac5c19a 100644 --- a/src/platform_impl/linux/common/xkb/keymap.rs +++ b/src/platform_impl/linux/common/xkb/keymap.rs @@ -296,7 +296,7 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option { NativeKeyCode::Xkb(raw) => Some(raw), _ => None, }; - } + }, }; match code { @@ -627,7 +627,6 @@ pub fn keysym_to_key(keysym: u32) -> Key { // keysyms::ISO_First_Group_Lock => NamedKey::GroupFirstLock, keysyms::ISO_Last_Group => NamedKey::GroupLast, // keysyms::ISO_Last_Group_Lock => NamedKey::GroupLastLock, - // keysyms::ISO_Left_Tab => NamedKey::Tab, // keysyms::ISO_Move_Line_Up => NamedKey::IsoMoveLineUp, // keysyms::ISO_Move_Line_Down => NamedKey::IsoMoveLineDown, @@ -809,18 +808,15 @@ pub fn keysym_to_key(keysym: u32) -> Key { keysyms::XF86_Music => NamedKey::LaunchMusicPlayer, // XF86_Battery..XF86_UWB - // keysyms::XF86_AudioForward => NamedKey::MediaFastForward, // XF86_AudioRepeat keysyms::XF86_AudioRandomPlay => NamedKey::RandomToggle, keysyms::XF86_Subtitle => NamedKey::Subtitle, keysyms::XF86_AudioCycleTrack => NamedKey::MediaAudioTrack, // XF86_CycleAngle..XF86_Blue - // keysyms::XF86_Suspend => NamedKey::Standby, keysyms::XF86_Hibernate => NamedKey::Hibernate, // XF86_TouchpadToggle..XF86_TouchpadOff - // keysyms::XF86_AudioMute => NamedKey::AudioVolumeMute, // XF86_Switch_VT_1..XF86_Switch_VT_12 @@ -853,7 +849,6 @@ pub fn keysym_to_key(keysym: u32) -> Key { keysyms::SUN_VideoLowerBrightness => NamedKey::BrightnessDown, keysyms::SUN_VideoRaiseBrightness => NamedKey::BrightnessUp, // SunPowerSwitchShift - // 0 => return Key::Unidentified(NativeKey::Unidentified), _ => return Key::Unidentified(NativeKey::Xkb(keysym)), }) @@ -968,11 +963,7 @@ impl XkbKeymap { mod5: mod_index_for_name(keymap, b"Mod5\0"), }; - Self { - keymap, - _mods_indices: mods_indices, - _core_keyboard_id, - } + Self { keymap, _mods_indices: mods_indices, _core_keyboard_id } } #[cfg(x11_platform)] @@ -1020,6 +1011,7 @@ impl Drop for XkbKeymap { impl Deref for XkbKeymap { type Target = NonNull; + fn deref(&self) -> &Self::Target { &self.keymap } diff --git a/src/platform_impl/linux/common/xkb/mod.rs b/src/platform_impl/linux/common/xkb/mod.rs index 572f7c8299..0b951b666c 100644 --- a/src/platform_impl/linux/common/xkb/mod.rs +++ b/src/platform_impl/linux/common/xkb/mod.rs @@ -15,8 +15,7 @@ use xkbcommon_dl::{ #[cfg(x11_platform)] use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle}; -use crate::event::ElementState; -use crate::event::KeyEvent; +use crate::event::{ElementState, KeyEvent}; use crate::keyboard::{Key, KeyLocation}; use crate::platform_impl::KeyEventExtra; @@ -143,9 +142,7 @@ impl Context { #[cfg(x11_platform)] pub fn set_keymap_from_x11(&mut self, xcb: *mut xcb_connection_t) { let keymap = XkbKeymap::from_x11_keymap(&self.context, xcb, self.core_keyboard_id); - let state = keymap - .as_ref() - .and_then(|keymap| XkbState::new_x11(xcb, keymap)); + let state = keymap.as_ref().and_then(|keymap| XkbState::new_x11(xcb, keymap)); if keymap.is_none() || state.is_none() { warn!("failed to update xkb keymap"); } @@ -160,13 +157,7 @@ impl Context { let compose_state1 = self.compose_state1.as_mut(); let compose_state2 = self.compose_state2.as_mut(); let scratch_buffer = &mut self.scratch_buffer; - Some(KeyContext { - state, - keymap, - compose_state1, - compose_state2, - scratch_buffer, - }) + Some(KeyContext { state, keymap, compose_state1, compose_state2, scratch_buffer }) } /// Key builder context with the user provided xkb state. @@ -181,13 +172,7 @@ impl Context { let compose_state1 = self.compose_state1.as_mut(); let compose_state2 = self.compose_state2.as_mut(); let scratch_buffer = &mut self.scratch_buffer; - Some(KeyContext { - state, - keymap, - compose_state1, - compose_state2, - scratch_buffer, - }) + Some(KeyContext { state, keymap, compose_state1, compose_state2, scratch_buffer }) } } @@ -214,20 +199,9 @@ impl<'a> KeyContext<'a> { let (key_without_modifiers, _) = event.key_without_modifiers(); let text_with_all_modifiers = event.text_with_all_modifiers(); - let platform_specific = KeyEventExtra { - text_with_all_modifiers, - key_without_modifiers, - }; + let platform_specific = KeyEventExtra { text_with_all_modifiers, key_without_modifiers }; - KeyEvent { - physical_key, - logical_key, - text, - location, - state, - repeat, - platform_specific, - } + KeyEvent { physical_key, logical_key, text, location, state, repeat, platform_specific } } fn keysym_to_utf8_raw(&mut self, keysym: u32) -> Option { @@ -246,10 +220,7 @@ impl<'a> KeyContext<'a> { } else if bytes_written == -1 { self.scratch_buffer.reserve(8); } else { - unsafe { - self.scratch_buffer - .set_len(bytes_written.try_into().unwrap()) - }; + unsafe { self.scratch_buffer.set_len(bytes_written.try_into().unwrap()) }; break; } } @@ -281,12 +252,7 @@ impl<'a, 'b> KeyEventResults<'a, 'b> { ComposeStatus::None }; - KeyEventResults { - context, - keycode, - keysym, - compose, - } + KeyEventResults { context, keycode, keysym, compose } } pub fn key(&mut self) -> (Key, KeyLocation) { @@ -323,23 +289,18 @@ impl<'a, 'b> KeyEventResults<'a, 'b> { } pub fn key_without_modifiers(&mut self) -> (Key, KeyLocation) { - // This will become a pointer to an array which libxkbcommon owns, so we don't need to deallocate it. + // This will become a pointer to an array which libxkbcommon owns, so we don't need to + // deallocate it. let layout = self.context.state.layout(self.keycode); - let keysym = self - .context - .keymap - .first_keysym_by_level(layout, self.keycode); + let keysym = self.context.keymap.first_keysym_by_level(layout, self.keycode); match self.keysym_to_key(keysym) { Ok((key, location)) => (key, location), Err((key, location)) => { - let key = self - .context - .keysym_to_utf8_raw(keysym) - .map(Key::Character) - .unwrap_or(key); + let key = + self.context.keysym_to_utf8_raw(keysym).map(Key::Character).unwrap_or(key); (key, location) - } + }, } } @@ -354,8 +315,7 @@ impl<'a, 'b> KeyEventResults<'a, 'b> { } pub fn text(&mut self) -> Option { - self.composed_text() - .unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym)) + self.composed_text().unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym)) } // The current behaviour makes it so composing a character overrides attempts to input a @@ -364,10 +324,7 @@ impl<'a, 'b> KeyEventResults<'a, 'b> { pub fn text_with_all_modifiers(&mut self) -> Option { match self.composed_text() { Ok(text) => text, - Err(_) => self - .context - .state - .get_utf8_raw(self.keycode, self.context.scratch_buffer), + Err(_) => self.context.state.get_utf8_raw(self.keycode, self.context.scratch_buffer), } } @@ -377,7 +334,7 @@ impl<'a, 'b> KeyEventResults<'a, 'b> { xkb_compose_status::XKB_COMPOSE_COMPOSED => { let state = self.context.compose_state1.as_mut().unwrap(); Ok(state.get_string(self.context.scratch_buffer)) - } + }, xkb_compose_status::XKB_COMPOSE_COMPOSING | xkb_compose_status::XKB_COMPOSE_CANCELLED => Ok(None), xkb_compose_status::XKB_COMPOSE_NOTHING => Err(()), @@ -436,10 +393,7 @@ where // The allocated buffer must include space for the null-terminator. scratch_buffer.reserve(size + 1); unsafe { - let written = f( - scratch_buffer.as_mut_ptr().cast(), - scratch_buffer.capacity(), - ); + let written = f(scratch_buffer.as_mut_ptr().cast(), scratch_buffer.capacity()); if usize::try_from(written).unwrap() != size { // This will likely never happen. return None; @@ -456,10 +410,7 @@ fn byte_slice_to_smol_str(bytes: &[u8]) -> Option { std::str::from_utf8(bytes) .map(SmolStr::new) .map_err(|e| { - tracing::warn!( - "UTF-8 received from libxkbcommon ({:?}) was invalid: {e}", - bytes - ) + tracing::warn!("UTF-8 received from libxkbcommon ({:?}) was invalid: {e}", bytes) }) .ok() } diff --git a/src/platform_impl/linux/mod.rs b/src/platform_impl/linux/mod.rs index 5f7c548a2c..7f0877f6a3 100644 --- a/src/platform_impl/linux/mod.rs +++ b/src/platform_impl/linux/mod.rs @@ -3,10 +3,11 @@ #[cfg(all(not(x11_platform), not(wayland_platform)))] compile_error!("Please select a feature to build for unix: `x11`, `wayland`"); +use std::collections::VecDeque; use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; use std::sync::Arc; use std::time::Duration; -use std::{collections::VecDeque, env, fmt}; +use std::{env, fmt}; #[cfg(x11_platform)] use std::{ffi::CStr, mem::MaybeUninit, os::raw::*, sync::Mutex}; @@ -16,22 +17,19 @@ use smol_str::SmolStr; #[cfg(x11_platform)] use self::x11::{X11Error, XConnection, XError, XNotSupported}; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{EventLoopError, ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event_loop::{ + ActiveEventLoop as RootELW, AsyncRequestSerial, ControlFlow, DeviceEvents, EventLoopClosed, +}; +use crate::icon::Icon; +use crate::keyboard::Key; +use crate::platform::pump_events::PumpStatus; #[cfg(x11_platform)] use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook}; -use crate::window::{CustomCursor, CustomCursorSource}; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize, Position, Size}, - error::{EventLoopError, ExternalError, NotSupportedError, OsError as RootOsError}, - event_loop::{ - ActiveEventLoop as RootELW, AsyncRequestSerial, ControlFlow, DeviceEvents, EventLoopClosed, - }, - icon::Icon, - keyboard::Key, - platform::pump_events::PumpStatus, - window::{ - ActivationToken, Cursor, CursorGrabMode, ImePurpose, ResizeDirection, Theme, - UserAttentionType, WindowAttributes, WindowButtons, WindowLevel, - }, +use crate::window::{ + ActivationToken, Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, ImePurpose, + ResizeDirection, Theme, UserAttentionType, WindowAttributes, WindowButtons, WindowLevel, }; pub(crate) use self::common::xkb::{physicalkey_to_scancode, scancode_to_physicalkey}; @@ -294,11 +292,11 @@ impl Window { #[cfg(wayland_platform)] ActiveEventLoop::Wayland(ref window_target) => { wayland::Window::new(window_target, attribs).map(Window::Wayland) - } + }, #[cfg(x11_platform)] ActiveEventLoop::X(ref window_target) => { x11::Window::new(window_target, attribs).map(Window::X) - } + }, } } @@ -534,6 +532,7 @@ impl Window { pub fn focus_window(&self) { x11_or_wayland!(match self; Window(w) => w.focus_window()) } + pub fn request_user_attention(&self, request_type: Option) { x11_or_wayland!(match self; Window(w) => w.request_user_attention(request_type)) } @@ -557,17 +556,13 @@ impl Window { pub fn available_monitors(&self) -> VecDeque { match self { #[cfg(x11_platform)] - Window::X(ref window) => window - .available_monitors() - .into_iter() - .map(MonitorHandle::X) - .collect(), + Window::X(ref window) => { + window.available_monitors().into_iter().map(MonitorHandle::X).collect() + }, #[cfg(wayland_platform)] - Window::Wayland(ref window) => window - .available_monitors() - .into_iter() - .map(MonitorHandle::Wayland) - .collect(), + Window::Wayland(ref window) => { + window.available_monitors().into_iter().map(MonitorHandle::Wayland).collect() + }, } } @@ -741,12 +736,10 @@ impl EventLoop { .or_else(|| env::var("WAYLAND_SOCKET").ok()) .filter(|var| !var.is_empty()) .is_some(), - env::var("DISPLAY") - .map(|var| !var.is_empty()) - .unwrap_or(false), + env::var("DISPLAY").map(|var| !var.is_empty()).unwrap_or(false), ) { // User is forcing a backend. - (Some(backend), _, _) => backend, + (Some(backend), ..) => backend, // Wayland is present. #[cfg(wayland_platform)] (None, true, _) => Backend::Wayland, @@ -756,14 +749,16 @@ impl EventLoop { // No backend is present. (_, wayland_display, x11_display) => { let msg = if wayland_display && !cfg!(wayland_platform) { - "DISPLAY is not set; note: enable the `winit/wayland` feature to support Wayland" + "DISPLAY is not set; note: enable the `winit/wayland` feature to support \ + Wayland" } else if x11_display && !cfg!(x11_platform) { - "neither WAYLAND_DISPLAY nor WAYLAND_SOCKET is set; note: enable the `winit/x11` feature to support X11" + "neither WAYLAND_DISPLAY nor WAYLAND_SOCKET is set; note: enable the \ + `winit/x11` feature to support X11" } else { "neither WAYLAND_DISPLAY nor WAYLAND_SOCKET nor DISPLAY is set." }; return Err(EventLoopError::Os(os_error!(OsError::Misc(msg)))); - } + }, }; // Create the display based on the backend. @@ -864,14 +859,13 @@ impl ActiveEventLoop { pub fn available_monitors(&self) -> VecDeque { match *self { #[cfg(wayland_platform)] - ActiveEventLoop::Wayland(ref evlp) => evlp - .available_monitors() - .map(MonitorHandle::Wayland) - .collect(), + ActiveEventLoop::Wayland(ref evlp) => { + evlp.available_monitors().map(MonitorHandle::Wayland).collect() + }, #[cfg(x11_platform)] ActiveEventLoop::X(ref evlp) => { evlp.available_monitors().map(MonitorHandle::X).collect() - } + }, } } @@ -961,7 +955,7 @@ impl OwnedDisplayHandle { xlib_handle.display = xconn.display.cast(); xlib_handle.screen = xconn.default_screen_index() as _; xlib_handle.into() - } + }, #[cfg(wayland_platform)] Self::Wayland(conn) => { @@ -970,7 +964,7 @@ impl OwnedDisplayHandle { let mut wayland_handle = rwh_05::WaylandDisplayHandle::empty(); wayland_handle.display = conn.display().id().as_ptr() as *mut _; wayland_handle.into() - } + }, } } @@ -997,7 +991,7 @@ impl OwnedDisplayHandle { NonNull::new(conn.display().id().as_ptr().cast()).unwrap(), ) .into()) - } + }, } } } @@ -1006,9 +1000,7 @@ impl OwnedDisplayHandle { /// equates to an infinite timeout, not a zero timeout (so can't just use /// `Option::min`) fn min_timeout(a: Option, b: Option) -> Option { - a.map_or(b, |a_timeout| { - b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))) - }) + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) } #[cfg(target_os = "linux")] diff --git a/src/platform_impl/linux/wayland/event_loop/mod.rs b/src/platform_impl/linux/wayland/event_loop/mod.rs index 36ce8f5638..f379841a6a 100644 --- a/src/platform_impl/linux/wayland/event_loop/mod.rs +++ b/src/platform_impl/linux/wayland/event_loop/mod.rs @@ -12,8 +12,7 @@ use std::time::{Duration, Instant}; use sctk::reexports::calloop::Error as CalloopError; use sctk::reexports::calloop_wayland_source::WaylandSource; -use sctk::reexports::client::globals; -use sctk::reexports::client::{Connection, QueueHandle}; +use sctk::reexports::client::{globals, Connection, QueueHandle}; use crate::cursor::OnlyCursorImage; use crate::dpi::LogicalSize; @@ -81,26 +80,19 @@ impl EventLoop { let connection = map_err!(Connection::connect_to_env(), WaylandError::Connection)?; - let (globals, mut event_queue) = map_err!( - globals::registry_queue_init(&connection), - WaylandError::Global - )?; + let (globals, mut event_queue) = + map_err!(globals::registry_queue_init(&connection), WaylandError::Global)?; let queue_handle = event_queue.handle(); - let event_loop = map_err!( - calloop::EventLoop::::try_new(), - WaylandError::Calloop - )?; + let event_loop = + map_err!(calloop::EventLoop::::try_new(), WaylandError::Calloop)?; let mut winit_state = WinitState::new(&globals, &queue_handle, event_loop.handle()) .map_err(|error| os_error!(error))?; // NOTE: do a roundtrip after binding the globals to prevent potential // races with the server. - map_err!( - event_queue.roundtrip(&mut winit_state), - WaylandError::Dispatch - )?; + map_err!(event_queue.roundtrip(&mut winit_state), WaylandError::Dispatch)?; // Register Wayland source. let wayland_source = WaylandSource::new(connection.clone(), event_queue); @@ -117,9 +109,7 @@ impl EventLoop { }); map_err!( - event_loop - .handle() - .register_dispatcher(wayland_dispatcher.clone()), + event_loop.handle().register_dispatcher(wayland_dispatcher.clone()), WaylandError::Calloop )?; @@ -129,15 +119,12 @@ impl EventLoop { let (user_events_sender, user_events_channel) = calloop::channel::channel(); let result = event_loop .handle() - .insert_source( - user_events_channel, - move |event, _, winit_state: &mut WinitState| { - if let calloop::channel::Event::Msg(msg) = event { - winit_state.dispatched_events = true; - pending_user_events_clone.borrow_mut().push(msg); - } - }, - ) + .insert_source(user_events_channel, move |event, _, winit_state: &mut WinitState| { + if let calloop::channel::Event::Msg(msg) = event { + winit_state.dispatched_events = true; + pending_user_events_clone.borrow_mut().push(msg); + } + }) .map_err(|error| error.error); map_err!(result, WaylandError::Calloop)?; @@ -150,13 +137,10 @@ impl EventLoop { let result = event_loop .handle() - .insert_source( - event_loop_awakener_source, - move |_, _, winit_state: &mut WinitState| { - // Mark that we have something to dispatch. - winit_state.dispatched_events = true; - }, - ) + .insert_source(event_loop_awakener_source, move |_, _, winit_state: &mut WinitState| { + // Mark that we have something to dispatch. + winit_state.dispatched_events = true; + }) .map_err(|error| error.error); map_err!(result, WaylandError::Calloop)?; @@ -197,13 +181,13 @@ impl EventLoop { match self.pump_events(None, &mut event_handler) { PumpStatus::Exit(0) => { break Ok(()); - } + }, PumpStatus::Exit(code) => { break Err(EventLoopError::ExitFailure(code)); - } + }, _ => { continue; - } + }, } }; @@ -256,7 +240,7 @@ impl EventLoop { ControlFlow::Poll => Some(Duration::ZERO), ControlFlow::WaitUntil(wait_deadline) => { Some(wait_deadline.saturating_duration_since(start)) - } + }, }; min_timeout(control_flow_timeout, timeout) }; @@ -274,11 +258,12 @@ impl EventLoop { if let Err(error) = self.loop_dispatch(timeout) { // NOTE We exit on errors from dispatches, since if we've got protocol error - // libwayland-client/wayland-rs will inform us anyway, but crashing downstream is not - // really an option. Instead we inform that the event loop got destroyed. We may - // communicate an error that something was terminated, but winit doesn't provide us - // with an API to do that via some event. - // Still, we set the exit code to the error's OS error code, or to 1 if not possible. + // libwayland-client/wayland-rs will inform us anyway, but crashing downstream is + // not really an option. Instead we inform that the event loop got + // destroyed. We may communicate an error that something was + // terminated, but winit doesn't provide us with an API to do that + // via some event. Still, we set the exit code to the error's OS + // error code, or to 1 if not possible. let exit_code = error.raw_os_error().unwrap_or(1); self.set_exit_code(exit_code); return; @@ -288,23 +273,14 @@ impl EventLoop { // to be considered here let cause = match self.control_flow() { ControlFlow::Poll => StartCause::Poll, - ControlFlow::Wait => StartCause::WaitCancelled { - start, - requested_resume: None, - }, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, ControlFlow::WaitUntil(deadline) => { if Instant::now() < deadline { - StartCause::WaitCancelled { - start, - requested_resume: Some(deadline), - } + StartCause::WaitCancelled { start, requested_resume: Some(deadline) } } else { - StartCause::ResumeTimeReached { - start, - requested_resume: deadline, - } + StartCause::ResumeTimeReached { start, requested_resume: deadline } } - } + }, }; // Reduce spurious wake-ups. @@ -471,13 +447,8 @@ impl EventLoop { return Some(WindowEvent::Destroyed); } - let mut window = state - .windows - .get_mut() - .get_mut(window_id) - .unwrap() - .lock() - .unwrap(); + let mut window = + state.windows.get_mut().get_mut(window_id).unwrap().lock().unwrap(); if window.frame_callback_state() == FrameCallbackState::Requested { return None; @@ -485,10 +456,8 @@ impl EventLoop { // Reset the frame callbacks state. window.frame_callback_reset(); - let mut redraw_requested = window_requests - .get(window_id) - .unwrap() - .take_redraw_requested(); + let mut redraw_requested = + window_requests.get(window_id).unwrap().take_redraw_requested(); // Redraw the frame while at it. redraw_requested |= window.refresh_frame(); @@ -498,10 +467,7 @@ impl EventLoop { if let Some(event) = event { callback( - Event::WindowEvent { - window_id: crate::window::WindowId(*window_id), - event, - }, + Event::WindowEvent { window_id: crate::window::WindowId(*window_id), event }, &self.window_target, ); } @@ -532,7 +498,7 @@ impl EventLoop { } refresh - } + }, None => false, }); } @@ -545,7 +511,7 @@ impl EventLoop { match &self.window_target.p { PlatformActiveEventLoop::Wayland(window_target) => { window_target.event_loop_awakener.ping(); - } + }, #[cfg(x11_platform)] PlatformActiveEventLoop::X(_) => unreachable!(), } @@ -599,9 +565,7 @@ impl EventLoop { let mut wayland_source = self.wayland_dispatcher.as_source_mut(); let event_queue = wayland_source.queue(); event_queue.roundtrip(state).map_err(|error| { - os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch( - error - )))) + os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error)))) }) } diff --git a/src/platform_impl/linux/wayland/event_loop/proxy.rs b/src/platform_impl/linux/wayland/event_loop/proxy.rs index dad64ef2c9..9dc7d99280 100644 --- a/src/platform_impl/linux/wayland/event_loop/proxy.rs +++ b/src/platform_impl/linux/wayland/event_loop/proxy.rs @@ -13,9 +13,7 @@ pub struct EventLoopProxy { impl Clone for EventLoopProxy { fn clone(&self) -> Self { - EventLoopProxy { - user_events_sender: self.user_events_sender.clone(), - } + EventLoopProxy { user_events_sender: self.user_events_sender.clone() } } } @@ -25,8 +23,6 @@ impl EventLoopProxy { } pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { - self.user_events_sender - .send(event) - .map_err(|SendError(error)| EventLoopClosed(error)) + self.user_events_sender.send(event).map_err(|SendError(error)| EventLoopClosed(error)) } } diff --git a/src/platform_impl/linux/wayland/event_loop/sink.rs b/src/platform_impl/linux/wayland/event_loop/sink.rs index 13daeee357..e506b4a84f 100644 --- a/src/platform_impl/linux/wayland/event_loop/sink.rs +++ b/src/platform_impl/linux/wayland/event_loop/sink.rs @@ -38,10 +38,7 @@ impl EventSink { /// Add new window event to a queue. #[inline] pub fn push_window_event(&mut self, event: WindowEvent, window_id: WindowId) { - self.window_events.push(Event::WindowEvent { - event, - window_id: RootWindowId(window_id), - }); + self.window_events.push(Event::WindowEvent { event, window_id: RootWindowId(window_id) }); } #[inline] diff --git a/src/platform_impl/linux/wayland/output.rs b/src/platform_impl/linux/wayland/output.rs index 666c1b38a3..ae6c1b0695 100644 --- a/src/platform_impl/linux/wayland/output.rs +++ b/src/platform_impl/linux/wayland/output.rs @@ -11,11 +11,7 @@ use super::event_loop::ActiveEventLoop; impl ActiveEventLoop { #[inline] pub fn available_monitors(&self) -> impl Iterator { - self.state - .borrow() - .output_state - .outputs() - .map(MonitorHandle::new) + self.state.borrow().output_state.outputs().map(MonitorHandle::new) } #[inline] @@ -52,9 +48,7 @@ impl MonitorHandle { pub fn size(&self) -> PhysicalSize { let output_data = self.proxy.data::().unwrap(); let dimensions = output_data.with_output_info(|info| { - info.modes - .iter() - .find_map(|mode| mode.current.then_some(mode.dimensions)) + info.modes.iter().find_map(|mode| mode.current.then_some(mode.dimensions)) }); match dimensions { @@ -85,9 +79,7 @@ impl MonitorHandle { pub fn refresh_rate_millihertz(&self) -> Option { let output_data = self.proxy.data::().unwrap(); output_data.with_output_info(|info| { - info.modes - .iter() - .find_map(|mode| mode.current.then_some(mode.refresh_rate as u32)) + info.modes.iter().find_map(|mode| mode.current.then_some(mode.refresh_rate as u32)) }) } diff --git a/src/platform_impl/linux/wayland/seat/keyboard/mod.rs b/src/platform_impl/linux/wayland/seat/keyboard/mod.rs index c471c61c57..4e731d47e7 100644 --- a/src/platform_impl/linux/wayland/seat/keyboard/mod.rs +++ b/src/platform_impl/linux/wayland/seat/keyboard/mod.rs @@ -7,9 +7,8 @@ use calloop::timer::{TimeoutAction, Timer}; use calloop::{LoopHandle, RegistrationToken}; use tracing::warn; -use sctk::reexports::client::protocol::wl_keyboard::WlKeyboard; use sctk::reexports::client::protocol::wl_keyboard::{ - Event as WlKeyboardEvent, KeyState as WlKeyState, KeymapFormat as WlKeymapFormat, + Event as WlKeyboardEvent, KeyState as WlKeyState, KeymapFormat as WlKeymapFormat, WlKeyboard, }; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, WEnum}; @@ -42,16 +41,16 @@ impl Dispatch for WinitState { WEnum::Value(format) => match format { WlKeymapFormat::NoKeymap => { warn!("non-xkb compatible keymap") - } + }, WlKeymapFormat::XkbV1 => { let context = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_context; context.set_keymap_from_fd(fd, size as usize); - } + }, _ => unreachable!(), }, WEnum::Unknown(value) => { warn!("unknown keymap format 0x{:x}", value) - } + }, }, WlKeyboardEvent::Enter { surface, .. } => { let window_id = wayland::make_wid(&surface); @@ -63,7 +62,7 @@ impl Dispatch for WinitState { let was_unfocused = !window.has_focus(); window.add_seat_focus(data.seat.id()); was_unfocused - } + }, None => return, }; @@ -78,9 +77,7 @@ impl Dispatch for WinitState { // The keyboard focus is considered as general focus. if was_unfocused { - state - .events_sink - .push_window_event(WindowEvent::Focused(true), window_id); + state.events_sink.push_window_event(WindowEvent::Focused(true), window_id); } // HACK: this is just for GNOME not fixing their ordering issue of modifiers. @@ -90,7 +87,7 @@ impl Dispatch for WinitState { window_id, ); } - } + }, WlKeyboardEvent::Leave { surface, .. } => { let window_id = wayland::make_wid(&surface); @@ -109,7 +106,7 @@ impl Dispatch for WinitState { let mut window = window.lock().unwrap(); window.remove_seat_focus(&data.seat.id()); window.has_focus() - } + }, None => return, }; @@ -124,16 +121,10 @@ impl Dispatch for WinitState { window_id, ); - state - .events_sink - .push_window_event(WindowEvent::Focused(false), window_id); + state.events_sink.push_window_event(WindowEvent::Focused(false), window_id); } - } - WlKeyboardEvent::Key { - key, - state: WEnum::Value(WlKeyState::Pressed), - .. - } => { + }, + WlKeyboardEvent::Key { key, state: WEnum::Value(WlKeyState::Pressed), .. } => { let key = key + 8; key_input( @@ -151,12 +142,7 @@ impl Dispatch for WinitState { RepeatInfo::Disable => return, }; - if !keyboard_state - .xkb_context - .keymap_mut() - .unwrap() - .key_repeats(key) - { + if !keyboard_state.xkb_context.keymap_mut().unwrap().key_repeats(key) { return; } @@ -203,12 +189,8 @@ impl Dispatch for WinitState { } }) .ok(); - } - WlKeyboardEvent::Key { - key, - state: WEnum::Value(WlKeyState::Released), - .. - } => { + }, + WlKeyboardEvent::Key { key, state: WEnum::Value(WlKeyState::Released), .. } => { let key = key + 8; key_input( @@ -222,11 +204,7 @@ impl Dispatch for WinitState { let keyboard_state = seat_state.keyboard_state.as_mut().unwrap(); if keyboard_state.repeat_info != RepeatInfo::Disable - && keyboard_state - .xkb_context - .keymap_mut() - .unwrap() - .key_repeats(key) + && keyboard_state.xkb_context.keymap_mut().unwrap().key_repeats(key) && Some(key) == keyboard_state.current_repeat { keyboard_state.current_repeat = None; @@ -234,13 +212,9 @@ impl Dispatch for WinitState { keyboard_state.loop_handle.remove(token); } } - } + }, WlKeyboardEvent::Modifiers { - mods_depressed, - mods_latched, - mods_locked, - group, - .. + mods_depressed, mods_latched, mods_locked, group, .. } => { let xkb_context = &mut seat_state.keyboard_state.as_mut().unwrap().xkb_context; let xkb_state = match xkb_context.state_mut() { @@ -257,14 +231,14 @@ impl Dispatch for WinitState { None => { seat_state.modifiers_pending = true; return; - } + }, }; state.events_sink.push_window_event( WindowEvent::ModifiersChanged(seat_state.modifiers.into()), window_id, ); - } + }, WlKeyboardEvent::RepeatInfo { rate, delay } => { let keyboard_state = seat_state.keyboard_state.as_mut().unwrap(); keyboard_state.repeat_info = if rate == 0 { @@ -279,7 +253,7 @@ impl Dispatch for WinitState { let delay = Duration::from_millis(delay as u64); RepeatInfo::Repeat { gap, delay } }; - } + }, _ => unreachable!(), } } @@ -353,10 +327,7 @@ impl Default for RepeatInfo { /// /// The values are picked based on the default in various compositors and Xorg. fn default() -> Self { - Self::Repeat { - gap: Duration::from_millis(40), - delay: Duration::from_millis(200), - } + Self::Repeat { gap: Duration::from_millis(40), delay: Duration::from_millis(200) } } } @@ -372,10 +343,7 @@ pub struct KeyboardData { impl KeyboardData { pub fn new(seat: WlSeat) -> Self { - Self { - window_id: Default::default(), - seat, - } + Self { window_id: Default::default(), seat } } } @@ -397,11 +365,7 @@ fn key_input( let device_id = crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(DeviceId)); if let Some(mut key_context) = keyboard_state.xkb_context.key_context() { let event = key_context.process_key_event(keycode, state, repeat); - let event = WindowEvent::KeyboardInput { - device_id, - event, - is_synthetic: false, - }; + let event = WindowEvent::KeyboardInput { device_id, event, is_synthetic: false }; event_sink.push_window_event(event, window_id); } } diff --git a/src/platform_impl/linux/wayland/seat/mod.rs b/src/platform_impl/linux/wayland/seat/mod.rs index 6ddda26bea..103cf6fce0 100644 --- a/src/platform_impl/linux/wayland/seat/mod.rs +++ b/src/platform_impl/linux/wayland/seat/mod.rs @@ -81,12 +81,12 @@ impl SeatHandler for WinitState { match capability { SeatCapability::Touch if seat_state.touch.is_none() => { seat_state.touch = self.seat_state.get_touch(queue_handle, &seat).ok(); - } + }, SeatCapability::Keyboard if seat_state.keyboard_state.is_none() => { let keyboard = seat.get_keyboard(queue_handle, KeyboardData::new(seat.clone())); seat_state.keyboard_state = Some(KeyboardState::new(keyboard, self.loop_handle.clone())); - } + }, SeatCapability::Pointer if seat_state.pointer.is_none() => { let surface = self.compositor_state.create_surface(queue_handle); let surface_id = surface.id(); @@ -114,19 +114,15 @@ impl SeatHandler for WinitState { let themed_pointer = Arc::new(themed_pointer); // Register cursor surface. - self.pointer_surfaces - .insert(surface_id, themed_pointer.clone()); + self.pointer_surfaces.insert(surface_id, themed_pointer.clone()); seat_state.pointer = Some(themed_pointer); - } + }, _ => (), } - if let Some(text_input_state) = seat_state - .text_input - .is_none() - .then_some(self.text_input_state.as_ref()) - .flatten() + if let Some(text_input_state) = + seat_state.text_input.is_none().then_some(self.text_input_state.as_ref()).flatten() { seat_state.text_input = Some(Arc::new(text_input_state.get_text_input( &seat, @@ -156,7 +152,7 @@ impl SeatHandler for WinitState { touch.release(); } } - } + }, SeatCapability::Pointer => { if let Some(relative_pointer) = seat_state.relative_pointer.take() { relative_pointer.destroy(); @@ -177,11 +173,11 @@ impl SeatHandler for WinitState { pointer.pointer().release(); } } - } + }, SeatCapability::Keyboard => { seat_state.keyboard_state = None; self.on_keyboard_destroy(&seat.id()); - } + }, _ => (), } } @@ -213,8 +209,7 @@ impl WinitState { let had_focus = window.has_focus(); window.remove_seat_focus(seat); if had_focus != window.has_focus() { - self.events_sink - .push_window_event(WindowEvent::Focused(false), *window_id); + self.events_sink.push_window_event(WindowEvent::Focused(false), *window_id); } } } diff --git a/src/platform_impl/linux/wayland/seat/pointer/mod.rs b/src/platform_impl/linux/wayland/seat/pointer/mod.rs index e9dee8f21f..f26c326e9c 100644 --- a/src/platform_impl/linux/wayland/seat/pointer/mod.rs +++ b/src/platform_impl/linux/wayland/seat/pointer/mod.rs @@ -19,8 +19,9 @@ use sctk::reexports::csd_frame::FrameClick; use sctk::compositor::SurfaceData; use sctk::globals::GlobalData; -use sctk::seat::pointer::{PointerData, PointerDataExt}; -use sctk::seat::pointer::{PointerEvent, PointerEventKind, PointerHandler}; +use sctk::seat::pointer::{ + PointerData, PointerDataExt, PointerEvent, PointerEventKind, PointerHandler, +}; use sctk::seat::SeatState; use crate::dpi::{LogicalPosition, PhysicalPosition}; @@ -81,20 +82,14 @@ impl PointerHandler for WinitState { let _ = pointer.set_cursor(connection, icon); } } - } + }, PointerEventKind::Leave { .. } if parent_surface != surface => { window.frame_point_left(); - } - ref kind @ PointerEventKind::Press { - button, - serial, - time, - } - | ref kind @ PointerEventKind::Release { - button, - serial, - time, - } if parent_surface != surface => { + }, + ref kind @ PointerEventKind::Press { button, serial, time } + | ref kind @ PointerEventKind::Release { button, serial, time } + if parent_surface != surface => + { let click = match wayland_button_to_winit(button) { MouseButton::Left => FrameClick::Normal, MouseButton::Right => FrameClick::Alternate, @@ -112,7 +107,7 @@ impl PointerHandler for WinitState { window_id, &mut self.window_compositor_updates, ); - } + }, // Regular events on the main surface. PointerEventKind::Enter { .. } => { self.events_sink @@ -126,13 +121,10 @@ impl PointerHandler for WinitState { pointer.winit_data().inner.lock().unwrap().surface = Some(window_id); self.events_sink.push_window_event( - WindowEvent::CursorMoved { - device_id, - position, - }, + WindowEvent::CursorMoved { device_id, position }, window_id, ); - } + }, PointerEventKind::Leave { .. } => { if let Some(pointer) = seat_state.pointer.as_ref().map(Arc::downgrade) { window.pointer_left(pointer); @@ -143,25 +135,17 @@ impl PointerHandler for WinitState { self.events_sink .push_window_event(WindowEvent::CursorLeft { device_id }, window_id); - } + }, PointerEventKind::Motion { .. } => { self.events_sink.push_window_event( - WindowEvent::CursorMoved { - device_id, - position, - }, + WindowEvent::CursorMoved { device_id, position }, window_id, ); - } + }, ref kind @ PointerEventKind::Press { button, serial, .. } | ref kind @ PointerEventKind::Release { button, serial, .. } => { // Update the last button serial. - pointer - .winit_data() - .inner - .lock() - .unwrap() - .latest_button_serial = serial; + pointer.winit_data().inner.lock().unwrap().latest_button_serial = serial; let button = wayland_button_to_winit(button); let state = if matches!(kind, PointerEventKind::Press { .. }) { @@ -170,19 +154,11 @@ impl PointerHandler for WinitState { ElementState::Released }; self.events_sink.push_window_event( - WindowEvent::MouseInput { - device_id, - state, - button, - }, + WindowEvent::MouseInput { device_id, state, button }, window_id, ); - } - PointerEventKind::Axis { - horizontal, - vertical, - .. - } => { + }, + PointerEventKind::Axis { horizontal, vertical, .. } => { // Get the current phase. let mut pointer_data = pointer.winit_data().inner.lock().unwrap(); @@ -223,14 +199,10 @@ impl PointerHandler for WinitState { }; self.events_sink.push_window_event( - WindowEvent::MouseWheel { - device_id, - delta, - phase, - }, + WindowEvent::MouseWheel { device_id, delta, phase }, window_id, ) - } + }, } } } @@ -407,8 +379,7 @@ pub trait WinitPointerDataExt { impl WinitPointerDataExt for WlPointer { fn winit_data(&self) -> &WinitPointerData { - self.data::() - .expect("failed to get pointer data.") + self.data::().expect("failed to get pointer data.") } } @@ -422,14 +393,13 @@ impl PointerConstraintsState { queue_handle: &QueueHandle, ) -> Result { let pointer_constraints = globals.bind(queue_handle, 1..=1, GlobalData)?; - Ok(Self { - pointer_constraints, - }) + Ok(Self { pointer_constraints }) } } impl Deref for PointerConstraintsState { type Target = ZwpPointerConstraintsV1; + fn deref(&self) -> &Self::Target { &self.pointer_constraints } diff --git a/src/platform_impl/linux/wayland/seat/pointer/relative_pointer.rs b/src/platform_impl/linux/wayland/seat/pointer/relative_pointer.rs index f7364e3771..a9ce2760b6 100644 --- a/src/platform_impl/linux/wayland/seat/pointer/relative_pointer.rs +++ b/src/platform_impl/linux/wayland/seat/pointer/relative_pointer.rs @@ -61,31 +61,19 @@ impl Dispatch for RelativePointerS _qhandle: &QueueHandle, ) { let (dx_unaccel, dy_unaccel) = match event { - zwp_relative_pointer_v1::Event::RelativeMotion { - dx_unaccel, - dy_unaccel, - .. - } => (dx_unaccel, dy_unaccel), + zwp_relative_pointer_v1::Event::RelativeMotion { dx_unaccel, dy_unaccel, .. } => { + (dx_unaccel, dy_unaccel) + }, _ => return, }; + state + .events_sink + .push_device_event(DeviceEvent::Motion { axis: 0, value: dx_unaccel }, super::DeviceId); + state + .events_sink + .push_device_event(DeviceEvent::Motion { axis: 1, value: dy_unaccel }, super::DeviceId); state.events_sink.push_device_event( - DeviceEvent::Motion { - axis: 0, - value: dx_unaccel, - }, - super::DeviceId, - ); - state.events_sink.push_device_event( - DeviceEvent::Motion { - axis: 1, - value: dy_unaccel, - }, - super::DeviceId, - ); - state.events_sink.push_device_event( - DeviceEvent::MouseMotion { - delta: (dx_unaccel, dy_unaccel), - }, + DeviceEvent::MouseMotion { delta: (dx_unaccel, dy_unaccel) }, super::DeviceId, ); } diff --git a/src/platform_impl/linux/wayland/seat/text_input/mod.rs b/src/platform_impl/linux/wayland/seat/text_input/mod.rs index 69cdb4b985..49d9363597 100644 --- a/src/platform_impl/linux/wayland/seat/text_input/mod.rs +++ b/src/platform_impl/linux/wayland/seat/text_input/mod.rs @@ -3,14 +3,12 @@ use std::ops::Deref; use sctk::globals::GlobalData; use sctk::reexports::client::{Connection, Proxy, QueueHandle}; -use sctk::reexports::client::delegate_dispatch; use sctk::reexports::client::globals::{BindError, GlobalList}; use sctk::reexports::client::protocol::wl_surface::WlSurface; -use sctk::reexports::client::Dispatch; +use sctk::reexports::client::{delegate_dispatch, Dispatch}; use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; -use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::Event as TextInputEvent; use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::{ - ContentHint, ContentPurpose, ZwpTextInputV3, + ContentHint, ContentPurpose, Event as TextInputEvent, ZwpTextInputV3, }; use crate::event::{Ime, WindowEvent}; @@ -77,13 +75,11 @@ impl Dispatch for TextInputState { text_input.enable(); text_input.set_content_type_by_purpose(window.ime_purpose()); text_input.commit(); - state - .events_sink - .push_window_event(WindowEvent::Ime(Ime::Enabled), window_id); + state.events_sink.push_window_event(WindowEvent::Ime(Ime::Enabled), window_id); } window.text_input_entered(text_input); - } + }, TextInputEvent::Leave { surface } => { text_input_data.surface = None; @@ -102,15 +98,9 @@ impl Dispatch for TextInputState { window.text_input_left(text_input); - state - .events_sink - .push_window_event(WindowEvent::Ime(Ime::Disabled), window_id); - } - TextInputEvent::PreeditString { - text, - cursor_begin, - cursor_end, - } => { + state.events_sink.push_window_event(WindowEvent::Ime(Ime::Disabled), window_id); + }, + TextInputEvent::PreeditString { text, cursor_begin, cursor_end } => { let text = text.unwrap_or_default(); let cursor_begin = usize::try_from(cursor_begin) .ok() @@ -119,16 +109,12 @@ impl Dispatch for TextInputState { .ok() .and_then(|idx| text.is_char_boundary(idx).then_some(idx)); - text_input_data.pending_preedit = Some(Preedit { - text, - cursor_begin, - cursor_end, - }) - } + text_input_data.pending_preedit = Some(Preedit { text, cursor_begin, cursor_end }) + }, TextInputEvent::CommitString { text } => { text_input_data.pending_preedit = None; text_input_data.pending_commit = text; - } + }, TextInputEvent::Done { .. } => { let window_id = match text_input_data.surface.as_ref() { Some(surface) => wayland::make_wid(surface), @@ -150,20 +136,19 @@ impl Dispatch for TextInputState { // Send preedit. if let Some(preedit) = text_input_data.pending_preedit.take() { - let cursor_range = preedit - .cursor_begin - .map(|b| (b, preedit.cursor_end.unwrap_or(b))); + let cursor_range = + preedit.cursor_begin.map(|b| (b, preedit.cursor_end.unwrap_or(b))); state.events_sink.push_window_event( WindowEvent::Ime(Ime::Preedit(preedit.text, cursor_range)), window_id, ); } - } + }, TextInputEvent::DeleteSurroundingText { .. } => { // Not handled. - } - _ => {} + }, + _ => {}, } } } diff --git a/src/platform_impl/linux/wayland/seat/touch/mod.rs b/src/platform_impl/linux/wayland/seat/touch/mod.rs index 7232b2279f..a037ae9f37 100644 --- a/src/platform_impl/linux/wayland/seat/touch/mod.rs +++ b/src/platform_impl/linux/wayland/seat/touch/mod.rs @@ -36,9 +36,7 @@ impl TouchHandler for WinitState { let seat_state = self.seats.get_mut(&touch.seat().id()).unwrap(); // Update the state of the point. - seat_state - .touch_map - .insert(id, TouchPoint { surface, location }); + seat_state.touch_map.insert(id, TouchPoint { surface, location }); self.events_sink.push_window_event( WindowEvent::Touch(Touch { @@ -190,9 +188,7 @@ pub trait TouchDataExt { impl TouchDataExt for WlTouch { fn seat(&self) -> &WlSeat { - self.data::() - .expect("failed to get touch data.") - .seat() + self.data::().expect("failed to get touch data.").seat() } } diff --git a/src/platform_impl/linux/wayland/state.rs b/src/platform_impl/linux/wayland/state.rs index d74120c2a5..8c021bb9fd 100644 --- a/src/platform_impl/linux/wayland/state.rs +++ b/src/platform_impl/linux/wayland/state.rs @@ -135,7 +135,7 @@ impl WinitState { Err(e) => { tracing::warn!("Subcompositor protocol not available, ignoring CSD: {e:?}"); None - } + }, }; let output_state = OutputState::new(globals, queue_handle); @@ -218,8 +218,7 @@ impl WinitState { { pos } else { - self.window_compositor_updates - .push(WindowCompositorUpdate::new(window_id)); + self.window_compositor_updates.push(WindowCompositorUpdate::new(window_id)); self.window_compositor_updates.len() - 1 }; @@ -240,9 +239,7 @@ impl WinitState { } pub fn queue_close(updates: &mut Vec, window_id: WindowId) { - let pos = if let Some(pos) = updates - .iter() - .position(|update| update.window_id == window_id) + let pos = if let Some(pos) = updates.iter().position(|update| update.window_id == window_id) { pos } else { @@ -276,15 +273,12 @@ impl WindowHandler for WinitState { ) { let window_id = super::make_wid(window.wl_surface()); - let pos = if let Some(pos) = self - .window_compositor_updates - .iter() - .position(|update| update.window_id == window_id) + let pos = if let Some(pos) = + self.window_compositor_updates.iter().position(|update| update.window_id == window_id) { pos } else { - self.window_compositor_updates - .push(WindowCompositorUpdate::new(window_id)); + self.window_compositor_updates.push(WindowCompositorUpdate::new(window_id)); self.window_compositor_updates.len() - 1 }; @@ -318,10 +312,7 @@ impl OutputHandler for WinitState { } fn new_output(&mut self, _: &Connection, _: &QueueHandle, output: WlOutput) { - self.monitors - .lock() - .unwrap() - .push(MonitorHandle::new(output)); + self.monitors.lock().unwrap().push(MonitorHandle::new(output)); } fn update_output(&mut self, _: &Connection, _: &QueueHandle, updated: WlOutput) { @@ -388,11 +379,11 @@ impl CompositorHandler for WinitState { } impl ProvidesRegistryState for WinitState { + sctk::registry_handlers![OutputState, SeatState]; + fn registry(&mut self) -> &mut RegistryState { &mut self.registry_state } - - sctk::registry_handlers![OutputState, SeatState]; } // The window update coming from the compositor. @@ -413,12 +404,7 @@ pub struct WindowCompositorUpdate { impl WindowCompositorUpdate { fn new(window_id: WindowId) -> Self { - Self { - window_id, - resized: false, - scale_changed: false, - close_window: false, - } + Self { window_id, resized: false, scale_changed: false, close_window: false } } } diff --git a/src/platform_impl/linux/wayland/types/kwin_blur.rs b/src/platform_impl/linux/wayland/types/kwin_blur.rs index 159f0fbaf0..83e82ad78a 100644 --- a/src/platform_impl/linux/wayland/types/kwin_blur.rs +++ b/src/platform_impl/linux/wayland/types/kwin_blur.rs @@ -2,11 +2,9 @@ use sctk::reexports::client::globals::{BindError, GlobalList}; use sctk::reexports::client::protocol::wl_surface::WlSurface; -use sctk::reexports::client::Dispatch; -use sctk::reexports::client::{delegate_dispatch, Connection, Proxy, QueueHandle}; -use wayland_protocols_plasma::blur::client::{ - org_kde_kwin_blur::OrgKdeKwinBlur, org_kde_kwin_blur_manager::OrgKdeKwinBlurManager, -}; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; +use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur; +use wayland_protocols_plasma::blur::client::org_kde_kwin_blur_manager::OrgKdeKwinBlurManager; use sctk::globals::GlobalData; diff --git a/src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs b/src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs index ead1e06b2d..2dfc9dbbe5 100644 --- a/src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs +++ b/src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs @@ -2,11 +2,11 @@ use sctk::reexports::client::globals::{BindError, GlobalList}; use sctk::reexports::client::protocol::wl_surface::WlSurface; -use sctk::reexports::client::Dispatch; -use sctk::reexports::client::{delegate_dispatch, Connection, Proxy, QueueHandle}; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1; -use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1::Event as FractionalScalingEvent; -use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1::WpFractionalScaleV1; +use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1::{ + Event as FractionalScalingEvent, WpFractionalScaleV1, +}; use sctk::globals::GlobalData; @@ -41,11 +41,8 @@ impl FractionalScalingManager { surface: &WlSurface, queue_handle: &QueueHandle, ) -> WpFractionalScaleV1 { - let data = FractionalScaling { - surface: surface.clone(), - }; - self.manager - .get_fractional_scale(surface, queue_handle, data) + let data = FractionalScaling { surface: surface.clone() }; + self.manager.get_fractional_scale(surface, queue_handle, data) } } diff --git a/src/platform_impl/linux/wayland/types/wp_viewporter.rs b/src/platform_impl/linux/wayland/types/wp_viewporter.rs index a8f399c3a7..90764825d0 100644 --- a/src/platform_impl/linux/wayland/types/wp_viewporter.rs +++ b/src/platform_impl/linux/wayland/types/wp_viewporter.rs @@ -2,8 +2,7 @@ use sctk::reexports::client::globals::{BindError, GlobalList}; use sctk::reexports::client::protocol::wl_surface::WlSurface; -use sctk::reexports::client::Dispatch; -use sctk::reexports::client::{delegate_dispatch, Connection, Proxy, QueueHandle}; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport; use sctk::reexports::protocols::wp::viewporter::client::wp_viewporter::WpViewporter; @@ -33,8 +32,7 @@ impl ViewporterState { surface: &WlSurface, queue_handle: &QueueHandle, ) -> WpViewport { - self.viewporter - .get_viewport(surface, queue_handle, GlobalData) + self.viewporter.get_viewport(surface, queue_handle, GlobalData) } } diff --git a/src/platform_impl/linux/wayland/types/xdg_activation.rs b/src/platform_impl/linux/wayland/types/xdg_activation.rs index be546d15bf..8bd21d0abb 100644 --- a/src/platform_impl/linux/wayland/types/xdg_activation.rs +++ b/src/platform_impl/linux/wayland/types/xdg_activation.rs @@ -3,12 +3,9 @@ use std::sync::atomic::AtomicBool; use std::sync::Weak; -use sctk::reexports::client::delegate_dispatch; -use sctk::reexports::client::globals::BindError; -use sctk::reexports::client::globals::GlobalList; +use sctk::reexports::client::globals::{BindError, GlobalList}; use sctk::reexports::client::protocol::wl_surface::WlSurface; -use sctk::reexports::client::Dispatch; -use sctk::reexports::client::{Connection, Proxy, QueueHandle}; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_token_v1::{ Event as ActivationTokenEvent, XdgActivationTokenV1, }; @@ -78,7 +75,7 @@ impl Dispatch for XdgA if let Some(attention_requested) = fence.upgrade() { attention_requested.store(false, std::sync::atomic::Ordering::Relaxed); } - } + }, XdgActivationTokenData::Obtain((window_id, serial)) => { state.events_sink.push_window_event( crate::event::WindowEvent::ActivationTokenDone { @@ -87,7 +84,7 @@ impl Dispatch for XdgA }, *window_id, ); - } + }, } proxy.destroy(); diff --git a/src/platform_impl/linux/wayland/window/mod.rs b/src/platform_impl/linux/wayland/window/mod.rs index 1e4ebea15b..103454ce05 100644 --- a/src/platform_impl/linux/wayland/window/mod.rs +++ b/src/platform_impl/linux/wayland/window/mod.rs @@ -5,13 +5,11 @@ use std::sync::{Arc, Mutex}; use sctk::reexports::client::protocol::wl_display::WlDisplay; use sctk::reexports::client::protocol::wl_surface::WlSurface; -use sctk::reexports::client::Proxy; -use sctk::reexports::client::QueueHandle; +use sctk::reexports::client::{Proxy, QueueHandle}; use sctk::compositor::{CompositorState, Region, SurfaceData}; use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1; -use sctk::shell::xdg::window::Window as SctkWindow; -use sctk::shell::xdg::window::WindowDecorations; +use sctk::shell::xdg::window::{Window as SctkWindow, WindowDecorations}; use sctk::shell::WaylandSurface; use tracing::warn; @@ -90,15 +88,11 @@ impl Window { let surface = state.compositor_state.create_surface(&queue_handle); let compositor = state.compositor_state.clone(); - let xdg_activation = state - .xdg_activation - .as_ref() - .map(|activation_state| activation_state.global().clone()); + let xdg_activation = + state.xdg_activation.as_ref().map(|activation_state| activation_state.global().clone()); let display = event_loop_window_target.connection.display(); - let size: Size = attributes - .inner_size - .unwrap_or(LogicalSize::new(800., 600.).into()); + let size: Size = attributes.inner_size.unwrap_or(LogicalSize::new(800., 600.).into()); // We prefer server side decorations, however to not have decorations we ask for client // side decorations instead. @@ -109,9 +103,7 @@ impl Window { }; let window = - state - .xdg_shell - .create_window(surface.clone(), default_decorations, &queue_handle); + state.xdg_shell.create_window(surface.clone(), default_decorations, &queue_handle); let mut window_state = WindowState::new( event_loop_window_target.connection.clone(), @@ -152,7 +144,7 @@ impl Window { match attributes.fullscreen.map(Into::into) { Some(Fullscreen::Exclusive(_)) => { warn!("`Fullscreen::Exclusive` is ignored on Wayland"); - } + }, #[cfg_attr(not(x11_platform), allow(clippy::bind_instead_of_map))] Some(Fullscreen::Borderless(monitor)) => { let output = monitor.and_then(|monitor| match monitor { @@ -162,7 +154,7 @@ impl Window { }); window.set_fullscreen(output.as_ref()) - } + }, _ if attributes.maximized => window.set_maximized(), _ => (), }; @@ -173,10 +165,9 @@ impl Window { } // Activate the window when the token is passed. - if let (Some(xdg_activation), Some(token)) = ( - xdg_activation.as_ref(), - attributes.platform_specific.activation_token, - ) { + if let (Some(xdg_activation), Some(token)) = + (xdg_activation.as_ref(), attributes.platform_specific.activation_token) + { xdg_activation.activate(token._token, &surface); } @@ -186,20 +177,14 @@ impl Window { // Add the window and window requests into the state. let window_state = Arc::new(Mutex::new(window_state)); let window_id = super::make_wid(&surface); - state - .windows - .get_mut() - .insert(window_id, window_state.clone()); + state.windows.get_mut().insert(window_id, window_state.clone()); let window_requests = WindowRequests { redraw_requested: AtomicBool::new(true), closed: AtomicBool::new(false), }; let window_requests = Arc::new(window_requests); - state - .window_requests - .get_mut() - .insert(window_id, window_requests.clone()); + state.window_requests.get_mut().insert(window_id, window_requests.clone()); // Setup the event sync to insert `WindowEvents` right from the window. let window_events_sink = state.window_events_sink.clone(); @@ -209,17 +194,13 @@ impl Window { // Do a roundtrip. event_queue.roundtrip(&mut state).map_err(|error| { - os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch( - error - )))) + os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error)))) })?; // XXX Wait for the initial configure to arrive. while !window_state.lock().unwrap().is_configured() { event_queue.blocking_dispatch(&mut state).map_err(|error| { - os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch( - error - )))) + os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error)))) })?; } @@ -329,10 +310,7 @@ impl Window { pub fn set_min_inner_size(&self, min_size: Option) { let scale_factor = self.scale_factor(); let min_size = min_size.map(|size| size.to_logical(scale_factor)); - self.window_state - .lock() - .unwrap() - .set_min_inner_size(min_size); + self.window_state.lock().unwrap().set_min_inner_size(min_size); // NOTE: Requires commit to be applied. self.request_redraw(); } @@ -342,10 +320,7 @@ impl Window { pub fn set_max_inner_size(&self, max_size: Option) { let scale_factor = self.scale_factor(); let max_size = max_size.map(|size| size.to_logical(scale_factor)); - self.window_state - .lock() - .unwrap() - .set_max_inner_size(max_size); + self.window_state.lock().unwrap().set_max_inner_size(max_size); // NOTE: Requires commit to be applied. self.request_redraw(); } @@ -362,10 +337,7 @@ impl Window { #[inline] pub fn set_transparent(&self, transparent: bool) { - self.window_state - .lock() - .unwrap() - .set_transparent(transparent); + self.window_state.lock().unwrap().set_transparent(transparent); } #[inline] @@ -388,10 +360,7 @@ impl Window { #[inline] pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { - self.window_state - .lock() - .unwrap() - .drag_resize_window(direction) + self.window_state.lock().unwrap().drag_resize_window(direction) } #[inline] @@ -499,7 +468,7 @@ impl Window { match fullscreen { Some(Fullscreen::Exclusive(_)) => { warn!("`Fullscreen::Exclusive` is ignored on Wayland"); - } + }, #[cfg_attr(not(x11_platform), allow(clippy::bind_instead_of_map))] Some(Fullscreen::Borderless(monitor)) => { let output = monitor.and_then(|monitor| match monitor { @@ -509,7 +478,7 @@ impl Window { }); self.window.set_fullscreen(output.as_ref()) - } + }, None => self.window.unset_fullscreen(), } } @@ -526,10 +495,7 @@ impl Window { #[inline] pub fn set_cursor_visible(&self, visible: bool) { - self.window_state - .lock() - .unwrap() - .set_cursor_visible(visible); + self.window_state.lock().unwrap().set_cursor_visible(visible); } pub fn request_user_attention(&self, request_type: Option) { @@ -538,7 +504,7 @@ impl Window { None => { warn!("`request_user_attention` isn't supported"); return; - } + }, }; // Urgency is only removed by the compositor and there's no need to raise urgency when it @@ -630,10 +596,7 @@ impl Window { if window_state.ime_allowed() != allowed && window_state.set_ime_allowed(allowed) { let event = WindowEvent::Ime(if allowed { Ime::Enabled } else { Ime::Disabled }); - self.window_events_sink - .lock() - .unwrap() - .push_window_event(event, self.window_id); + self.window_events_sink.lock().unwrap().push_window_event(event, self.window_id); self.event_loop_awakener.ping(); } } diff --git a/src/platform_impl/linux/wayland/window/state.rs b/src/platform_impl/linux/wayland/window/state.rs index 28e41ee13f..7685b85952 100644 --- a/src/platform_impl/linux/wayland/window/state.rs +++ b/src/platform_impl/linux/wayland/window/state.rs @@ -226,13 +226,10 @@ impl WindowState { &self, callback: F, ) { - self.pointers - .iter() - .filter_map(Weak::upgrade) - .for_each(|pointer| { - let data = pointer.pointer().winit_data(); - callback(pointer.as_ref(), data); - }) + self.pointers.iter().filter_map(Weak::upgrade).for_each(|pointer| { + let data = pointer.pointer().winit_data(); + callback(pointer.as_ref(), data); + }) } /// Get the current state of the frame callback. @@ -257,7 +254,7 @@ impl WindowState { FrameCallbackState::None | FrameCallbackState::Received => { self.frame_callback_state = FrameCallbackState::Requested; surface.frame(&self.queue_handle, surface.clone()); - } + }, FrameCallbackState::Requested => (), } } @@ -297,11 +294,11 @@ impl WindowState { // Hide the frame if we were asked to not decorate. frame.set_hidden(!self.decorate); self.frame = Some(frame); - } + }, Err(err) => { warn!("Failed to create client side decorations frame: {err}"); self.csd_fails = true; - } + }, } } else if configure.decoration_mode == DecorationMode::Server { // Drop the frame for server side decorations to save resources. @@ -320,8 +317,8 @@ impl WindowState { let width = width.map(|w| w.get()).unwrap_or(1); let height = height.map(|h| h.get()).unwrap_or(1); ((width, height).into(), false) - } - (_, _) if stateless => (self.stateless_size, true), + }, + (..) if stateless => (self.stateless_size, true), _ => (self.size, true), } } else { @@ -335,10 +332,8 @@ impl WindowState { // Apply configure bounds only when compositor let the user decide what size to pick. if constrain { let bounds = self.inner_size_bounds(&configure); - new_size.width = bounds - .0 - .map(|bound_w| new_size.width.min(bound_w.get())) - .unwrap_or(new_size.width); + new_size.width = + bounds.0.map(|bound_w| new_size.width.min(bound_w.get())).unwrap_or(new_size.width); new_size.height = bounds .1 .map(|bound_h| new_size.height.min(bound_h.get())) @@ -346,10 +341,7 @@ impl WindowState { } let new_state = configure.state; - let old_state = self - .last_configure - .as_ref() - .map(|configure| configure.state); + let old_state = self.last_configure.as_ref().map(|configure| configure.state); let state_change_requires_resize = old_state .map(|old_state| { @@ -387,10 +379,7 @@ impl WindowState { configure_bounds.0.unwrap_or(NonZeroU32::new(1).unwrap()), configure_bounds.1.unwrap_or(NonZeroU32::new(1).unwrap()), ); - ( - configure_bounds.0.and(width), - configure_bounds.1.and(height), - ) + (configure_bounds.0.and(width), configure_bounds.1.and(height)) } else { configure_bounds } @@ -460,7 +449,7 @@ impl WindowState { _ => return None, }; self.window.resize(seat, serial, edge); - } + }, FrameAction::ShowMenu(x, y) => self.window.show_window_menu(seat, serial, (x, y)), _ => (), }; @@ -643,12 +632,7 @@ impl WindowState { /// Try to resize the window when the user can do so. pub fn request_inner_size(&mut self, inner_size: Size) -> PhysicalSize { - if self - .last_configure - .as_ref() - .map(Self::is_stateless) - .unwrap_or(true) - { + if self.last_configure.as_ref().map(Self::is_stateless).unwrap_or(true) { self.resize(inner_size.to_logical(self.scale_factor())) } @@ -674,10 +658,7 @@ impl WindowState { ); } - ( - frame.location(), - frame.add_borders(self.size.width, self.size.height).into(), - ) + (frame.location(), frame.add_borders(self.size.width, self.size.height).into()) } else { ((0, 0), self.size) }; @@ -724,16 +705,12 @@ impl WindowState { /// Set the custom cursor icon. pub(crate) fn set_custom_cursor(&mut self, cursor: RootCustomCursor) { let cursor = match cursor { - RootCustomCursor { - inner: PlatformCustomCursor::Wayland(cursor), - } => cursor.0, + RootCustomCursor { inner: PlatformCustomCursor::Wayland(cursor) } => cursor.0, #[cfg(x11_platform)] - RootCustomCursor { - inner: PlatformCustomCursor::X(_), - } => { + RootCustomCursor { inner: PlatformCustomCursor::X(_) } => { tracing::error!("passed a X11 cursor to Wayland backend"); return; - } + }, }; let cursor = { @@ -752,11 +729,7 @@ impl WindowState { self.apply_on_pointer(|pointer, _| { let surface = pointer.surface(); - let scale = surface - .data::() - .unwrap() - .surface_data() - .scale_factor(); + let scale = surface.data::().unwrap().surface_data().scale_factor(); surface.set_buffer_scale(scale); surface.attach(Some(cursor.buffer.wl_buffer()), 0, 0); @@ -864,7 +837,7 @@ impl WindowState { }), CursorGrabMode::Locked => { self.apply_on_pointer(|_, data| data.unlock_pointer()); - } + }, } let surface = self.window.wl_surface(); @@ -879,7 +852,7 @@ impl WindowState { }), CursorGrabMode::None => { // Current lock/confine was already removed. - } + }, } Ok(()) @@ -902,11 +875,9 @@ impl WindowState { // Position can be set only for locked cursor. if self.cursor_grab_mode.current_grab_mode != CursorGrabMode::Locked { - return Err(ExternalError::Os(os_error!( - crate::platform_impl::OsError::Misc( - "cursor position can be set only for locked cursor." - ) - ))); + return Err(ExternalError::Os(os_error!(crate::platform_impl::OsError::Misc( + "cursor position can be set only for locked cursor." + )))); } self.apply_on_pointer(|_, data| { @@ -929,9 +900,7 @@ impl WindowState { for pointer in self.pointers.iter().filter_map(|pointer| pointer.upgrade()) { let latest_enter_serial = pointer.pointer().winit_data().latest_enter_serial(); - pointer - .pointer() - .set_cursor(latest_enter_serial, None, 0, 0); + pointer.pointer().set_cursor(latest_enter_serial, None, 0, 0); } } } @@ -945,19 +914,12 @@ impl WindowState { self.decorate = decorate; - match self - .last_configure - .as_ref() - .map(|configure| configure.decoration_mode) - { + match self.last_configure.as_ref().map(|configure| configure.decoration_mode) { Some(DecorationMode::Server) if !self.decorate => { // To disable decorations we should request client and hide the frame. - self.window - .request_decoration_mode(Some(DecorationMode::Client)) - } - _ if self.decorate => self - .window - .request_decoration_mode(Some(DecorationMode::Server)), + self.window.request_decoration_mode(Some(DecorationMode::Client)) + }, + _ if self.decorate => self.window.request_decoration_mode(Some(DecorationMode::Server)), _ => (), } @@ -1054,10 +1016,7 @@ impl WindowState { info!("Blur manager unavailable, unable to change blur") } } else if !blurred && self.blur.is_some() { - self.blur_manager - .as_ref() - .unwrap() - .unset(self.window.wl_surface()); + self.blur_manager.as_ref().unwrap().unset(self.window.wl_surface()); self.blur.take().unwrap().release(); } } @@ -1146,10 +1105,7 @@ struct GrabState { impl GrabState { fn new() -> Self { - Self { - user_grab_mode: CursorGrabMode::None, - current_grab_mode: CursorGrabMode::None, - } + Self { user_grab_mode: CursorGrabMode::None, current_grab_mode: CursorGrabMode::None } } } diff --git a/src/platform_impl/linux/x11/activation.rs b/src/platform_impl/linux/x11/activation.rs index 7ae910d506..a5e961bb9d 100644 --- a/src/platform_impl/linux/x11/activation.rs +++ b/src/platform_impl/linux/x11/activation.rs @@ -5,7 +5,8 @@ //! X11 has a "startup notification" specification similar to Wayland's, see this URL: //! -use super::{atoms::*, VoidCookie, X11Error, XConnection}; +use super::atoms::*; +use super::{VoidCookie, X11Error, XConnection}; use std::ffi::CString; use std::fmt::Write; @@ -105,11 +106,9 @@ impl XConnection { 0, xproto::WindowClass::INPUT_OUTPUT, screen.root_visual, - &xproto::CreateWindowAux::new() - .override_redirect(1) - .event_mask( - xproto::EventMask::STRUCTURE_NOTIFY | xproto::EventMask::PROPERTY_CHANGE, - ), + &xproto::CreateWindowAux::new().override_redirect(1).event_mask( + xproto::EventMask::STRUCTURE_NOTIFY | xproto::EventMask::PROPERTY_CHANGE, + ), )?; // Serialize the messages in 20-byte chunks. @@ -130,12 +129,7 @@ impl XConnection { .try_for_each(|event| { // Send each event in order. self.xcb_connection() - .send_event( - false, - screen.root, - xproto::EventMask::PROPERTY_CHANGE, - event, - ) + .send_event(false, screen.root, xproto::EventMask::PROPERTY_CHANGE, event) .map(VoidCookie::ignore_error) })?; diff --git a/src/platform_impl/linux/x11/dnd.rs b/src/platform_impl/linux/x11/dnd.rs index 18436374b4..691e40af9b 100644 --- a/src/platform_impl/linux/x11/dnd.rs +++ b/src/platform_impl/linux/x11/dnd.rs @@ -1,18 +1,15 @@ -use std::{ - io, - os::raw::*, - path::{Path, PathBuf}, - str::Utf8Error, - sync::Arc, -}; +use std::io; +use std::os::raw::*; +use std::path::{Path, PathBuf}; +use std::str::Utf8Error; +use std::sync::Arc; use percent_encoding::percent_decode; use x11rb::protocol::xproto::{self, ConnectionExt}; -use super::{ - atoms::{AtomName::None as DndNone, *}, - util, CookieResultExt, X11Error, XConnection, -}; +use super::atoms::AtomName::None as DndNone; +use super::atoms::*; +use super::{util, CookieResultExt, X11Error, XConnection}; #[derive(Debug, Clone, Copy)] pub enum DndState { @@ -54,13 +51,7 @@ pub struct Dnd { impl Dnd { pub fn new(xconn: Arc) -> Result { - Ok(Dnd { - xconn, - version: None, - type_list: None, - source_window: None, - result: None, - }) + Ok(Dnd { xconn, version: None, type_list: None, source_window: None, result: None }) } pub fn reset(&mut self) { @@ -82,13 +73,13 @@ impl Dnd { DndState::Rejected => (0, atoms[DndNone]), }; self.xconn - .send_client_msg( - target_window, - target_window, - atoms[XdndStatus] as _, - None, - [this_window, accepted, 0, 0, action as _], - )? + .send_client_msg(target_window, target_window, atoms[XdndStatus] as _, None, [ + this_window, + accepted, + 0, + 0, + action as _, + ])? .ignore_error(); Ok(()) @@ -106,13 +97,13 @@ impl Dnd { DndState::Rejected => (0, atoms[DndNone]), }; self.xconn - .send_client_msg( - target_window, - target_window, - atoms[XdndFinished] as _, - None, - [this_window, accepted, action as _, 0, 0], - )? + .send_client_msg(target_window, target_window, atoms[XdndFinished] as _, None, [ + this_window, + accepted, + action as _, + 0, + 0, + ])? .ignore_error(); Ok(()) @@ -149,8 +140,7 @@ impl Dnd { window: xproto::Window, ) -> Result, util::GetPropertyError> { let atoms = self.xconn.atoms(); - self.xconn - .get_property(window, atoms[XdndSelection], atoms[TextUriList]) + self.xconn.get_property(window, atoms[XdndSelection], atoms[TextUriList]) } pub fn parse_data(&self, data: &mut [c_uchar]) -> Result, DndDataParseError> { diff --git a/src/platform_impl/linux/x11/event_processor.rs b/src/platform_impl/linux/x11/event_processor.rs index 4673fe8764..19cbba7f30 100644 --- a/src/platform_impl/linux/x11/event_processor.rs +++ b/src/platform_impl/linux/x11/event_processor.rs @@ -16,16 +16,14 @@ use x11_dl::xlib::{ use x11rb::protocol::xinput; use x11rb::protocol::xkb::ID as XkbId; use x11rb::protocol::xproto::{self, ConnectionExt as _, ModMask}; -use x11rb::x11_utils::ExtensionInformation; -use x11rb::x11_utils::Serialize; +use x11rb::x11_utils::{ExtensionInformation, Serialize}; use xkbcommon_dl::xkb_mod_mask_t; use crate::dpi::{PhysicalPosition, PhysicalSize}; use crate::event::{ - DeviceEvent, ElementState, Event, Ime, MouseScrollDelta, RawKeyEvent, Touch, TouchPhase, - WindowEvent, + DeviceEvent, ElementState, Event, Ime, InnerSizeWriter, MouseButton, MouseScrollDelta, + RawKeyEvent, Touch, TouchPhase, WindowEvent, }; -use crate::event::{InnerSizeWriter, MouseButton}; use crate::event_loop::ActiveEventLoop as RootAEL; use crate::keyboard::ModifiersState; use crate::platform_impl::common::xkb::{self, XkbState}; @@ -33,10 +31,11 @@ use crate::platform_impl::platform::common::xkb::Context; use crate::platform_impl::platform::x11::ime::{ImeEvent, ImeEventReceiver, ImeRequest}; use crate::platform_impl::platform::x11::ActiveEventLoop; use crate::platform_impl::platform::ActiveEventLoop as PlatformActiveEventLoop; +use crate::platform_impl::x11::atoms::*; use crate::platform_impl::x11::util::cookie::GenericEventCookie; use crate::platform_impl::x11::{ - atoms::*, mkdid, mkwid, util, CookieResultExt, Device, DeviceId, DeviceInfo, Dnd, DndState, - ImeReceiver, ScrollOrientation, UnownedWindow, WindowId, + mkdid, mkwid, util, CookieResultExt, Device, DeviceId, DeviceInfo, Dnd, DndState, ImeReceiver, + ScrollOrientation, UnownedWindow, WindowId, }; /// The maximum amount of X modifiers to replay. @@ -91,10 +90,10 @@ impl EventProcessor { match request { ImeRequest::Position(window_id, x, y) => { ime.send_xim_spot(window_id, x, y); - } + }, ImeRequest::Allow(window_id, allowed) => { ime.set_ime_allowed(window_id, allowed); - } + }, } } @@ -106,19 +105,19 @@ impl EventProcessor { ImeEvent::Start => { self.is_composing = true; WindowEvent::Ime(Ime::Preedit("".to_owned(), None)) - } + }, ImeEvent::Update(text, position) if self.is_composing => { WindowEvent::Ime(Ime::Preedit(text, Some((position, position)))) - } + }, ImeEvent::End => { self.is_composing = false; // Issue empty preedit on `Done`. WindowEvent::Ime(Ime::Preedit(String::new(), None)) - } + }, ImeEvent::Disabled => { self.is_composing = false; WindowEvent::Ime(Ime::Disabled) - } + }, _ => continue, }; @@ -182,7 +181,7 @@ impl EventProcessor { }; self.xinput_key_input(xev.as_mut(), state, &mut callback); - } + }, xlib::GenericEvent => { let wt = Self::window_target(&self.target); let xev: GenericEventCookie = @@ -209,7 +208,7 @@ impl EventProcessor { &mut callback, ); self.xinput2_button_input(xev, state, &mut callback); - } + }, xinput2::XI_Motion => { let xev: &XIDeviceEvent = unsafe { xev.as_event() }; self.update_mods_from_xinput2_event( @@ -219,11 +218,11 @@ impl EventProcessor { &mut callback, ); self.xinput2_mouse_motion(xev, &mut callback); - } + }, xinput2::XI_Enter => { let xev: &XIEnterEvent = unsafe { xev.as_event() }; self.xinput2_mouse_enter(xev, &mut callback); - } + }, xinput2::XI_Leave => { let xev: &XILeaveEvent = unsafe { xev.as_event() }; self.update_mods_from_xinput2_event( @@ -233,15 +232,15 @@ impl EventProcessor { &mut callback, ); self.xinput2_mouse_left(xev, &mut callback); - } + }, xinput2::XI_FocusIn => { let xev: &XIFocusInEvent = unsafe { xev.as_event() }; self.xinput2_focused(xev, &mut callback); - } + }, xinput2::XI_FocusOut => { let xev: &XIFocusOutEvent = unsafe { xev.as_event() }; self.xinput2_unfocused(xev, &mut callback); - } + }, xinput2::XI_TouchBegin | xinput2::XI_TouchUpdate | xinput2::XI_TouchEnd => { let phase = match evtype { xinput2::XI_TouchBegin => TouchPhase::Started, @@ -252,7 +251,7 @@ impl EventProcessor { let xev: &XIDeviceEvent = unsafe { xev.as_event() }; self.xinput2_touch(xev, phase, &mut callback); - } + }, xinput2::XI_RawButtonPress | xinput2::XI_RawButtonRelease => { let state = match evtype { xinput2::XI_RawButtonPress => ElementState::Pressed, @@ -262,11 +261,11 @@ impl EventProcessor { let xev: &XIRawEvent = unsafe { xev.as_event() }; self.xinput2_raw_button_input(xev, state, &mut callback); - } + }, xinput2::XI_RawMotion => { let xev: &XIRawEvent = unsafe { xev.as_event() }; self.xinput2_raw_mouse_motion(xev, &mut callback); - } + }, xinput2::XI_RawKeyPress | xinput2::XI_RawKeyRelease => { let state = match evtype { xinput2::XI_RawKeyPress => ElementState::Pressed, @@ -276,15 +275,15 @@ impl EventProcessor { let xev: &xinput2::XIRawEvent = unsafe { xev.as_event() }; self.xinput2_raw_key_input(xev, state, &mut callback); - } + }, xinput2::XI_HierarchyChanged => { let xev: &XIHierarchyEvent = unsafe { xev.as_event() }; self.xinput2_hierarchy_changed(xev, &mut callback); - } - _ => {} + }, + _ => {}, } - } + }, _ => { if event_type == self.xkbext.first_event as _ { let xev: &XkbAnyEvent = unsafe { &*(xev as *const _ as *const XkbAnyEvent) }; @@ -293,7 +292,7 @@ impl EventProcessor { if event_type == self.randr_event_offset as c_int { self.process_dpi_change(&mut callback); } - } + }, } } @@ -399,10 +398,7 @@ impl EventProcessor { let window_id = mkwid(window); if xev.data.get_long(0) as xproto::Atom == wt.wm_delete_window { - let event = Event::WindowEvent { - window_id, - event: WindowEvent::CloseRequested, - }; + let event = Event::WindowEvent { window_id, event: WindowEvent::CloseRequested }; callback(&self.target, event); return; } @@ -467,16 +463,16 @@ impl EventProcessor { // where `shift = mem::size_of::() * 8` // Note that coordinates are in "desktop space", not "window space" // (in X11 parlance, they're root window coordinates) - //let packed_coordinates = xev.data.get_long(2); - //let shift = mem::size_of::() * 8; - //let x = packed_coordinates >> shift; - //let y = packed_coordinates & !(x << shift); + // let packed_coordinates = xev.data.get_long(2); + // let shift = mem::size_of::() * 8; + // let x = packed_coordinates >> shift; + // let y = packed_coordinates & !(x << shift); // By our own state flow, `version` should never be `None` at this point. let version = self.dnd.version.unwrap_or(5); // Action is specified in versions 2 and up, though we don't need it anyway. - //let action = xev.data.get_long(4); + // let action = xev.data.get_long(4); let accepted = if let Some(ref type_list) = self.dnd.type_list { type_list.contains(&atoms[TextUriList]) @@ -533,8 +529,8 @@ impl EventProcessor { } (source_window, DndState::Accepted) } else { - // `source_window` won't be part of our DND state if we already rejected the drop in our - // `XdndPosition` handler. + // `source_window` won't be part of our DND state if we already rejected the drop in + // our `XdndPosition` handler. let source_window = xev.data.get_long(0) as xproto::Window; (source_window, DndState::Rejected) }; @@ -551,10 +547,7 @@ impl EventProcessor { if xev.message_type == atoms[XdndLeave] as c_ulong { self.dnd.reset(); - let event = Event::WindowEvent { - window_id, - event: WindowEvent::HoveredFileCancelled, - }; + let event = Event::WindowEvent { window_id, event: WindowEvent::HoveredFileCancelled }; callback(&self.target, event); } } @@ -628,8 +621,8 @@ impl EventProcessor { util::maybe_change(&mut shared_state_lock.inner_position, new_inner_position) } else { // Detect when frame extents change. - // Since this isn't synthetic, as per the notes above, this position is relative to the - // parent window. + // Since this isn't synthetic, as per the notes above, this position is relative to + // the parent window. let rel_parent = new_inner_position; if util::maybe_change(&mut shared_state_lock.inner_position_rel_parent, rel_parent) { @@ -651,11 +644,8 @@ impl EventProcessor { let mut shared_state_lock = window.shared_state_lock(); // We need to convert client area position to window position. - let frame_extents = shared_state_lock - .frame_extents - .as_ref() - .cloned() - .unwrap_or_else(|| { + let frame_extents = + shared_state_lock.frame_extents.as_ref().cloned().unwrap_or_else(|| { let frame_extents = wt.xconn.get_frame_extents_heuristic(xwindow, wt.root); shared_state_lock.frame_extents = Some(frame_extents.clone()); frame_extents @@ -668,24 +658,21 @@ impl EventProcessor { drop(shared_state_lock); if moved { - callback( - &self.target, - Event::WindowEvent { - window_id, - event: WindowEvent::Moved(outer.into()), - }, - ); + callback(&self.target, Event::WindowEvent { + window_id, + event: WindowEvent::Moved(outer.into()), + }); } outer }; if is_synthetic { let mut shared_state_lock = window.shared_state_lock(); - // If we don't use the existing adjusted value when available, then the user can screw up the - // resizing by dragging across monitors *without* dropping the window. - let (width, height) = shared_state_lock - .dpi_adjusted - .unwrap_or((xev.width as u32, xev.height as u32)); + // If we don't use the existing adjusted value when available, then the user can screw + // up the resizing by dragging across monitors *without* dropping the + // window. + let (width, height) = + shared_state_lock.dpi_adjusted.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 = { @@ -719,16 +706,13 @@ impl EventProcessor { drop(shared_state_lock); let inner_size = Arc::new(Mutex::new(new_inner_size)); - callback( - &self.target, - Event::WindowEvent { - window_id, - event: WindowEvent::ScaleFactorChanged { - scale_factor: new_scale_factor, - inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&inner_size)), - }, + callback(&self.target, Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor: new_scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&inner_size)), }, - ); + }); let new_inner_size = *inner_size.lock().unwrap(); drop(inner_size); @@ -775,13 +759,10 @@ impl EventProcessor { } if resized { - callback( - &self.target, - Event::WindowEvent { - window_id, - event: WindowEvent::Resized(new_inner_size.into()), - }, - ); + callback(&self.target, Event::WindowEvent { + window_id, + event: WindowEvent::Resized(new_inner_size.into()), + }); } } @@ -812,13 +793,8 @@ impl EventProcessor { // The purpose of it is to deliver initial focused state of the newly created // window, given that we can't rely on `CreateNotify`, due to it being not // sent. - let focus = self - .with_window(window, |window| window.has_focus()) - .unwrap_or_default(); - let event = Event::WindowEvent { - window_id, - event: WindowEvent::Focused(focus), - }; + let focus = self.with_window(window, |window| window.has_focus()).unwrap_or_default(); + let event = Event::WindowEvent { window_id, event: WindowEvent::Focused(focus) }; callback(&self.target, event); } @@ -844,13 +820,7 @@ impl EventProcessor { .expect("Failed to destroy input context"); } - callback( - &self.target, - Event::WindowEvent { - window_id, - event: WindowEvent::Destroyed, - }, - ); + callback(&self.target, Event::WindowEvent { window_id, event: WindowEvent::Destroyed }); } fn property_notify(&mut self, xev: &XPropertyEvent, mut callback: F) @@ -895,10 +865,7 @@ impl EventProcessor { let window = xev.window as xproto::Window; let window_id = mkwid(window); - let event = Event::WindowEvent { - window_id, - event: WindowEvent::RedrawRequested, - }; + let event = Event::WindowEvent { window_id, event: WindowEvent::RedrawRequested }; callback(&self.target, event); } @@ -937,11 +904,8 @@ impl EventProcessor { // Only keys that can repeat should change the held_key_press state since a // continuously held repeatable key may continue repeating after the press of a // non-repeatable key. - let key_repeats = self - .xkb_context - .keymap_mut() - .map(|k| k.key_repeats(keycode)) - .unwrap_or(false); + let key_repeats = + self.xkb_context.keymap_mut().map(|k| k.key_repeats(keycode)).unwrap_or(false); let repeat = if key_repeats { let is_latest_held = self.held_key_press == Some(keycode); @@ -964,16 +928,12 @@ impl EventProcessor { // NOTE: When the modifier was captured by the XFilterEvents the modifiers for the modifier // itself are out of sync due to XkbState being delivered before XKeyEvent, since it's // being replayed by the XIM, thus we should replay ourselves. - let replay = if let Some(position) = self - .xfiltered_modifiers - .iter() - .rev() - .position(|&s| s == xev.serial) + let replay = if let Some(position) = + self.xfiltered_modifiers.iter().rev().position(|&s| s == xev.serial) { // We don't have to replay modifiers pressed before the current event if some events // were not forwarded to us, since their state is irrelevant. - self.xfiltered_modifiers - .resize(self.xfiltered_modifiers.len() - 1 - position, 0); + self.xfiltered_modifiers.resize(self.xfiltered_modifiers.len() - 1 - position, 0); true } else { false @@ -994,11 +954,7 @@ impl EventProcessor { let event = key_processor.process_key_event(keycode, state, repeat); let event = Event::WindowEvent { window_id, - event: WindowEvent::KeyboardInput { - device_id, - event, - is_synthetic: false, - }, + event: WindowEvent::KeyboardInput { device_id, event, is_synthetic: false }, }; callback(&self.target, event); } @@ -1013,10 +969,8 @@ impl EventProcessor { let wt = Self::window_target(&self.target); - if let Some(ic) = wt - .ime - .as_ref() - .and_then(|ime| ime.borrow().get_context(window as XWindow)) + if let Some(ic) = + wt.ime.as_ref().and_then(|ime| ime.borrow().get_context(window as XWindow)) { let written = wt.xconn.lookup_utf8(ic, xev); if !written.is_empty() { @@ -1026,10 +980,8 @@ impl EventProcessor { }; callback(&self.target, event); - let event = Event::WindowEvent { - window_id, - event: WindowEvent::Ime(Ime::Commit(written)), - }; + let event = + Event::WindowEvent { window_id, event: WindowEvent::Ime(Ime::Commit(written)) }; self.is_composing = false; callback(&self.target, event); @@ -1064,10 +1016,8 @@ impl EventProcessor { xkb_state.update_modifiers(mask, 0, 0, 0, 0, Self::core_keyboard_group(state)); let mods: ModifiersState = xkb_state.modifiers().into(); - let event = Event::WindowEvent { - window_id, - event: WindowEvent::ModifiersChanged(mods.into()), - }; + let event = + Event::WindowEvent { window_id, event: WindowEvent::ModifiersChanged(mods.into()) }; callback(&self.target, event); } @@ -1093,26 +1043,21 @@ impl EventProcessor { } let event = match event.detail as u32 { - xlib::Button1 => WindowEvent::MouseInput { - device_id, - state, - button: MouseButton::Left, + xlib::Button1 => { + WindowEvent::MouseInput { device_id, state, button: MouseButton::Left } }, - xlib::Button2 => WindowEvent::MouseInput { - device_id, - state, - button: MouseButton::Middle, + xlib::Button2 => { + WindowEvent::MouseInput { device_id, state, button: MouseButton::Middle } }, - xlib::Button3 => WindowEvent::MouseInput { - device_id, - state, - button: MouseButton::Right, + xlib::Button3 => { + WindowEvent::MouseInput { device_id, state, button: MouseButton::Right } }, - // Suppress emulated scroll wheel clicks, since we handle the real motion events for those. - // In practice, even clicky scroll wheels appear to be reported by evdev (and XInput2 in - // turn) as axis motion, so we don't otherwise special-case these button presses. + // Suppress emulated scroll wheel clicks, since we handle the real motion events for + // those. In practice, even clicky scroll wheels appear to be reported by + // evdev (and XInput2 in turn) as axis motion, so we don't otherwise + // special-case these button presses. 4..=7 => WindowEvent::MouseWheel { device_id, delta: match event.detail { @@ -1124,22 +1069,10 @@ impl EventProcessor { }, phase: TouchPhase::Moved, }, - 8 => WindowEvent::MouseInput { - device_id, - state, - button: MouseButton::Back, - }, + 8 => WindowEvent::MouseInput { device_id, state, button: MouseButton::Back }, - 9 => WindowEvent::MouseInput { - device_id, - state, - button: MouseButton::Forward, - }, - x => WindowEvent::MouseInput { - device_id, - state, - button: MouseButton::Other(x as u16), - }, + 9 => WindowEvent::MouseInput { device_id, state, button: MouseButton::Forward }, + x => WindowEvent::MouseInput { device_id, state, button: MouseButton::Other(x as u16) }, }; let event = Event::WindowEvent { window_id, event }; @@ -1170,10 +1103,7 @@ impl EventProcessor { let event = Event::WindowEvent { window_id, - event: WindowEvent::CursorMoved { - device_id, - position, - }, + event: WindowEvent::CursorMoved { device_id, position }, }; callback(&self.target, event); } else if cursor_moved.is_none() { @@ -1199,10 +1129,8 @@ impl EventProcessor { let x = unsafe { *value }; - let event = if let Some(&mut (_, ref mut info)) = physical_device - .scroll_axes - .iter_mut() - .find(|&&mut (axis, _)| axis == i as _) + let event = if let Some(&mut (_, ref mut info)) = + physical_device.scroll_axes.iter_mut().find(|&&mut (axis, _)| axis == i as _) { let delta = (x - info.position) / info.increment; info.position = x; @@ -1210,21 +1138,13 @@ impl EventProcessor { let delta = match info.orientation { ScrollOrientation::Horizontal => { MouseScrollDelta::LineDelta(-delta as f32, 0.0) - } + }, ScrollOrientation::Vertical => MouseScrollDelta::LineDelta(0.0, -delta as f32), }; - WindowEvent::MouseWheel { - device_id, - delta, - phase: TouchPhase::Moved, - } + WindowEvent::MouseWheel { device_id, delta, phase: TouchPhase::Moved } } else { - WindowEvent::AxisMotion { - device_id, - axis: i as u32, - value: unsafe { *value }, - } + WindowEvent::AxisMotion { device_id, axis: i as u32, value: unsafe { *value } } }; events.push(Event::WindowEvent { window_id, event }); @@ -1253,12 +1173,11 @@ impl EventProcessor { if let Some(all_info) = DeviceInfo::get(&wt.xconn, super::ALL_DEVICES.into()) { let mut devices = self.devices.borrow_mut(); for device_info in all_info.iter() { + // The second expression is need for resetting to work correctly on i3, and + // presumably some other WMs. On those, `XI_Enter` doesn't include the physical + // device ID, so both `sourceid` and `deviceid` are the virtual device. if device_info.deviceid == event.sourceid - // This is needed for resetting to work correctly on i3, and - // presumably some other WMs. On those, `XI_Enter` doesn't include - // the physical device ID, so both `sourceid` and `deviceid` are - // the virtual device. - || device_info.attachment == event.sourceid + || device_info.attachment == event.sourceid { let device_id = DeviceId(device_info.deviceid as _); if let Some(device) = devices.get_mut(&device_id) { @@ -1271,18 +1190,13 @@ impl EventProcessor { if self.window_exists(window) { let position = PhysicalPosition::new(event.event_x, event.event_y); - let event = Event::WindowEvent { - window_id, - event: WindowEvent::CursorEntered { device_id }, - }; + let event = + Event::WindowEvent { window_id, event: WindowEvent::CursorEntered { device_id } }; callback(&self.target, event); let event = Event::WindowEvent { window_id, - event: WindowEvent::CursorMoved { - device_id, - position, - }, + event: WindowEvent::CursorMoved { device_id, position }, }; callback(&self.target, event); } @@ -1322,9 +1236,7 @@ impl EventProcessor { wt.xconn.set_timestamp(xev.time as xproto::Timestamp); if let Some(ime) = wt.ime.as_ref() { - ime.borrow_mut() - .focus(xev.event) - .expect("Failed to focus input context"); + ime.borrow_mut().focus(xev.event).expect("Failed to focus input context"); } if self.active_window == Some(window) { @@ -1342,10 +1254,7 @@ impl EventProcessor { window.shared_state_lock().has_focus = true; } - let event = Event::WindowEvent { - window_id, - event: WindowEvent::Focused(true), - }; + let event = Event::WindowEvent { window_id, event: WindowEvent::Focused(true) }; callback(&self.target, event); // Issue key press events for all pressed keys @@ -1370,10 +1279,7 @@ impl EventProcessor { let event = Event::WindowEvent { window_id, - event: WindowEvent::CursorMoved { - device_id: mkdid(pointer_id as _), - position, - }, + event: WindowEvent::CursorMoved { device_id: mkdid(pointer_id as _), position }, }; callback(&self.target, event); } @@ -1393,9 +1299,7 @@ impl EventProcessor { } if let Some(ime) = wt.ime.as_ref() { - ime.borrow_mut() - .unfocus(xev.event) - .expect("Failed to unfocus input context"); + ime.borrow_mut().unfocus(xev.event).expect("Failed to unfocus input context"); } if self.active_window.take() == Some(window) { @@ -1427,10 +1331,7 @@ impl EventProcessor { window.shared_state_lock().has_focus = false; } - let event = Event::WindowEvent { - window_id, - event: WindowEvent::Focused(false), - }; + let event = Event::WindowEvent { window_id, event: WindowEvent::Focused(false) }; callback(&self.target, event) } } @@ -1497,10 +1398,7 @@ impl EventProcessor { if xev.flags & xinput2::XIPointerEmulated == 0 { let event = Event::DeviceEvent { device_id: mkdid(xev.deviceid as xinput::DeviceId), - event: DeviceEvent::Button { - state, - button: xev.detail as u32, - }, + event: DeviceEvent::Button { state, button: xev.detail as u32 }, }; callback(&self.target, event); } @@ -1535,15 +1433,12 @@ impl EventProcessor { 1 => mouse_delta.set_y(x), 2 => scroll_delta.set_x(x as f32), 3 => scroll_delta.set_y(x as f32), - _ => {} + _ => {}, } let event = Event::DeviceEvent { device_id: did, - event: DeviceEvent::Motion { - axis: i as u32, - value: x, - }, + event: DeviceEvent::Motion { axis: i as u32, value: x }, }; callback(&self.target, event); @@ -1589,16 +1484,10 @@ impl EventProcessor { } let physical_key = xkb::raw_keycode_to_physicalkey(keycode); - callback( - &self.target, - Event::DeviceEvent { - device_id, - event: DeviceEvent::Key(RawKeyEvent { - physical_key, - state, - }), - }, - ); + callback(&self.target, Event::DeviceEvent { + device_id, + event: DeviceEvent::Key(RawKeyEvent { physical_key, state }), + }); } fn xinput2_hierarchy_changed(&mut self, xev: &XIHierarchyEvent, mut callback: F) @@ -1613,21 +1502,15 @@ impl EventProcessor { for info in infos { if 0 != info.flags & (xinput2::XISlaveAdded | xinput2::XIMasterAdded) { self.init_device(info.deviceid as xinput::DeviceId); - callback( - &self.target, - Event::DeviceEvent { - device_id: mkdid(info.deviceid as xinput::DeviceId), - event: DeviceEvent::Added, - }, - ); + callback(&self.target, Event::DeviceEvent { + device_id: mkdid(info.deviceid as xinput::DeviceId), + event: DeviceEvent::Added, + }); } else if 0 != info.flags & (xinput2::XISlaveRemoved | xinput2::XIMasterRemoved) { - callback( - &self.target, - Event::DeviceEvent { - device_id: mkdid(info.deviceid as xinput::DeviceId), - event: DeviceEvent::Removed, - }, - ); + callback(&self.target, Event::DeviceEvent { + device_id: mkdid(info.deviceid as xinput::DeviceId), + event: DeviceEvent::Removed, + }); let mut devices = self.devices.borrow_mut(); devices.remove(&DeviceId(info.deviceid as xinput::DeviceId)); } @@ -1669,7 +1552,7 @@ impl EventProcessor { self.send_modifiers(window_id, mods, true, &mut callback); } } - } + }, xlib::XkbMapNotify => { let xcb = wt.xconn.xcb_connection().get_raw_xcb_connection(); self.xkb_context.set_keymap_from_x11(xcb); @@ -1683,7 +1566,7 @@ impl EventProcessor { let mods = state.modifiers().into(); self.send_modifiers(window_id, mods, true, &mut callback); } - } + }, xlib::XkbStateNotify => { let xev = unsafe { &*(xev as *const _ as *const xlib::XkbStateNotifyEvent) }; @@ -1708,8 +1591,8 @@ impl EventProcessor { let mods = state.modifiers().into(); self.send_modifiers(window_id, mods, true, &mut callback); } - } - _ => {} + }, + _ => {}, } } @@ -1825,22 +1708,13 @@ impl EventProcessor { // Build the XKB modifiers from the regular state. let mut depressed = 0u32; - if let Some(shift) = mods_indices - .shift - .filter(|_| ModMask::SHIFT.intersects(state)) - { + if let Some(shift) = mods_indices.shift.filter(|_| ModMask::SHIFT.intersects(state)) { depressed |= 1 << shift; } - if let Some(caps) = mods_indices - .caps - .filter(|_| ModMask::LOCK.intersects(state)) - { + if let Some(caps) = mods_indices.caps.filter(|_| ModMask::LOCK.intersects(state)) { depressed |= 1 << caps; } - if let Some(ctrl) = mods_indices - .ctrl - .filter(|_| ModMask::CONTROL.intersects(state)) - { + if let Some(ctrl) = mods_indices.ctrl.filter(|_| ModMask::CONTROL.intersects(state)) { depressed |= 1 << ctrl; } if let Some(alt) = mods_indices.alt.filter(|_| ModMask::M1.intersects(state)) { @@ -1897,10 +1771,7 @@ impl EventProcessor { // Update modifiers state and emit key events based on which keys are currently pressed. let window_target = Self::window_target(target); - let xcb = window_target - .xconn - .xcb_connection() - .get_raw_xcb_connection(); + let xcb = window_target.xconn.xcb_connection().get_raw_xcb_connection(); let keymap = match xkb_context.keymap_mut() { Some(keymap) => keymap, @@ -1917,20 +1788,13 @@ impl EventProcessor { None => return, }; - for keycode in window_target - .xconn - .query_keymap() - .into_iter() - .filter(|k| *k >= KEYCODE_OFFSET) + for keycode in + window_target.xconn.query_keymap().into_iter().filter(|k| *k >= KEYCODE_OFFSET) { let event = key_processor.process_key_event(keycode as u32, state, false); let event = Event::WindowEvent { window_id, - event: WindowEvent::KeyboardInput { - device_id, - event, - is_synthetic: true, - }, + event: WindowEvent::KeyboardInput { device_id, event, is_synthetic: true }, }; callback(target, event); } @@ -1941,9 +1805,7 @@ impl EventProcessor { F: FnMut(&RootAEL, Event), { let wt = Self::window_target(&self.target); - wt.xconn - .reload_database() - .expect("failed to reload Xft database"); + wt.xconn.reload_database().expect("failed to reload Xft database"); // In the future, it would be quite easy to emit monitor hotplug events. let prev_list = { @@ -1954,10 +1816,7 @@ impl EventProcessor { } }; - let new_list = wt - .xconn - .available_monitors() - .expect("Failed to get monitor list"); + let new_list = wt.xconn.available_monitors().expect("Failed to get monitor list"); for new_monitor in new_list { // Previous list may be empty, in case of disconnecting and // reconnecting the only one monitor. We still need to emit events in @@ -1988,13 +1847,13 @@ fn is_first_touch(first: &mut Option, num: &mut u32, id: u64, phase: TouchP *first = Some(id); } *num += 1; - } + }, TouchPhase::Cancelled | TouchPhase::Ended => { if *first == Some(id) { *first = None; } *num = num.saturating_sub(1); - } + }, _ => (), } diff --git a/src/platform_impl/linux/x11/ffi.rs b/src/platform_impl/linux/x11/ffi.rs index f44f9b5a4e..57bd78e95d 100644 --- a/src/platform_impl/linux/x11/ffi.rs +++ b/src/platform_impl/linux/x11/ffi.rs @@ -1 +1,5 @@ -pub use x11_dl::{error::OpenError, xcursor::*, xinput2::*, xlib::*, xlib_xcb::*}; +pub use x11_dl::error::OpenError; +pub use x11_dl::xcursor::*; +pub use x11_dl::xinput2::*; +pub use x11_dl::xlib::*; +pub use x11_dl::xlib_xcb::*; diff --git a/src/platform_impl/linux/x11/ime/callbacks.rs b/src/platform_impl/linux/x11/ime/callbacks.rs index 02e26410a6..c75724ec83 100644 --- a/src/platform_impl/linux/x11/ime/callbacks.rs +++ b/src/platform_impl/linux/x11/ime/callbacks.rs @@ -1,12 +1,13 @@ -use std::{collections::HashMap, os::raw::c_char, ptr, sync::Arc}; +use std::collections::HashMap; +use std::os::raw::c_char; +use std::ptr; +use std::sync::Arc; use super::{ffi, XConnection, XError}; -use super::{ - context::{ImeContext, ImeContextCreationError}, - inner::{close_im, ImeInner}, - input_method::PotentialInputMethods, -}; +use super::context::{ImeContext, ImeContextCreationError}; +use super::inner::{close_im, ImeInner}; +use super::input_method::PotentialInputMethods; pub(crate) unsafe fn xim_set_callback( xconn: &Arc, @@ -24,8 +25,8 @@ pub(crate) unsafe fn xim_set_callback( // available. Note that this has nothing to do with what input methods are open or able to be // opened, and simply uses the modifiers that are set when the callback is set. // * This is called per locale modifier, not per input method opened with that locale modifier. -// * Trying to set this for multiple locale modifiers causes problems, i.e. one of the rebuilt -// input contexts would always silently fail to use the input method. +// * Trying to set this for multiple locale modifiers causes problems, i.e. one of the rebuilt input +// contexts would always silently fail to use the input method. pub(crate) unsafe fn set_instantiate_callback( xconn: &Arc, client_data: ffi::XPointer, @@ -119,18 +120,12 @@ unsafe fn replace_im(inner: *mut ImeInner) -> Result<(), ReplaceImError> { let spot = old_context.as_ref().map(|old_context| old_context.ic_spot); // Check if the IME was allowed on that context. - let is_allowed = old_context - .as_ref() - .map(|old_context| old_context.is_allowed()) - .unwrap_or_default(); + let is_allowed = + old_context.as_ref().map(|old_context| old_context.is_allowed()).unwrap_or_default(); // We can't use the style from the old context here, since it may change on reload, so // pick style from the new XIM based on the old state. - let style = if is_allowed { - new_im.preedit_style - } else { - new_im.none_style - }; + let style = if is_allowed { new_im.preedit_style } else { new_im.none_style }; let new_context = { let result = unsafe { @@ -208,7 +203,7 @@ pub unsafe extern "C" fn xim_destroy_callback( Err(err) => { // We have no usable input methods! panic!("Failed to open fallback input method: {err:?}"); - } + }, } } } diff --git a/src/platform_impl/linux/x11/ime/context.rs b/src/platform_impl/linux/x11/ime/context.rs index 565748f007..1cc8c355b9 100644 --- a/src/platform_impl/linux/x11/ime/context.rs +++ b/src/platform_impl/linux/x11/ime/context.rs @@ -26,10 +26,7 @@ type XIMProcNonnull = unsafe extern "C" fn(ffi::XIM, ffi::XPointer, ffi::XPointe /// Wrapper for creating XIM callbacks. #[inline] fn create_xim_callback(client_data: ffi::XPointer, callback: XIMProcNonnull) -> ffi::XIMCallback { - XIMCallback { - client_data, - callback: Some(callback), - } + XIMCallback { client_data, callback: Some(callback) } } /// The server started preedit. @@ -68,9 +65,7 @@ extern "C" fn preedit_done_callback( } fn calc_byte_position(text: &[char], pos: usize) -> usize { - text.iter() - .take(pos) - .fold(0, |byte_pos, text| byte_pos + text.len_utf8()) + text.iter().take(pos).fold(0, |byte_pos, text| byte_pos + text.len_utf8()) } /// Preedit text information to be drawn inline by the client. @@ -112,9 +107,7 @@ extern "C" fn preedit_draw_callback( let new_text = unsafe { CStr::from_ptr(new_text) }; - String::from(new_text.to_str().expect("Invalid UTF-8 String from IME")) - .chars() - .collect() + String::from(new_text.to_str().expect("Invalid UTF-8 String from IME")).chars().collect() }; let mut old_text_tail = client_data.text.split_off(chg_range.end); client_data.text.truncate(chg_range.start); @@ -171,12 +164,7 @@ impl PreeditCallbacks { let caret_callback = create_xim_callback(client_data, preedit_caret_callback); let draw_callback = create_xim_callback(client_data, preedit_draw_callback); - PreeditCallbacks { - start_callback, - done_callback, - caret_callback, - draw_callback, - } + PreeditCallbacks { start_callback, done_callback, caret_callback, draw_callback } } } @@ -195,8 +183,8 @@ pub struct ImeContext { pub(crate) ic: ffi::XIC, pub(crate) ic_spot: ffi::XPoint, pub(crate) style: Style, - // Since the data is passed shared between X11 XIM callbacks, but couldn't be directly free from - // there we keep the pointer to automatically deallocate it. + // Since the data is passed shared between X11 XIM callbacks, but couldn't be directly free + // from there we keep the pointer to automatically deallocate it. _client_data: Box, } @@ -233,9 +221,7 @@ impl ImeContext { } .ok_or(ImeContextCreationError::Null)?; - xconn - .check_errors() - .map_err(ImeContextCreationError::XError)?; + xconn.check_errors().map_err(ImeContextCreationError::XError)?; let mut context = ImeContext { ic, diff --git a/src/platform_impl/linux/x11/ime/inner.rs b/src/platform_impl/linux/x11/ime/inner.rs index fba2cf46d8..4d4f7cb473 100644 --- a/src/platform_impl/linux/x11/ime/inner.rs +++ b/src/platform_impl/linux/x11/ime/inner.rs @@ -1,11 +1,11 @@ -use std::{collections::HashMap, mem, sync::Arc}; +use std::collections::HashMap; +use std::mem; +use std::sync::Arc; use super::{ffi, XConnection, XError}; -use super::{ - context::ImeContext, - input_method::{InputMethod, PotentialInputMethods}, -}; +use super::context::ImeContext; +use super::input_method::{InputMethod, PotentialInputMethods}; use crate::platform_impl::platform::x11::ime::ImeEventSender; pub(crate) unsafe fn close_im(xconn: &Arc, im: ffi::XIM) -> Result<(), XError> { diff --git a/src/platform_impl/linux/x11/ime/input_method.rs b/src/platform_impl/linux/x11/ime/input_method.rs index 5bce4b6782..b9d3ca7101 100644 --- a/src/platform_impl/linux/x11/ime/input_method.rs +++ b/src/platform_impl/linux/x11/ime/input_method.rs @@ -1,13 +1,10 @@ -use std::{ - env, - ffi::{CStr, CString, IntoStringError}, - fmt, - os::raw::{c_char, c_ulong, c_ushort}, - ptr, - sync::{Arc, Mutex}, -}; - -use super::{super::atoms::*, ffi, util, XConnection, XError}; +use std::ffi::{CStr, CString, IntoStringError}; +use std::os::raw::{c_char, c_ulong, c_ushort}; +use std::sync::{Arc, Mutex}; +use std::{env, fmt, ptr}; + +use super::super::atoms::*; +use super::{ffi, util, XConnection, XError}; use x11rb::protocol::xproto; static GLOBAL_LOCK: Mutex<()> = Mutex::new(()); @@ -18,17 +15,12 @@ unsafe fn open_im(xconn: &Arc, locale_modifiers: &CStr) -> Option { preedit_style = Some(Style::Preedit(*style)); - } + }, XIM_NOTHING_STYLE if preedit_style.is_none() => { preedit_style = Some(Style::Nothing(*style)) - } + }, XIM_NONE_STYLE => none_style = Some(Style::None(*style)), _ => (), }); @@ -91,12 +83,7 @@ impl InputMethod { let preedit_style = preedit_style.unwrap_or_else(|| none_style.unwrap()); let none_style = none_style.unwrap_or(preedit_style); - Some(InputMethod { - im, - _name: name, - preedit_style, - none_style, - }) + Some(InputMethod { im, _name: name, preedit_style, none_style }) } } @@ -232,10 +219,7 @@ impl InputMethodName { pub fn from_str(string: &str) -> Self { let c_string = CString::new(string).expect("String used to construct CString contained null byte"); - InputMethodName { - c_string, - string: string.to_owned(), - } + InputMethodName { c_string, string: string.to_owned() } } } @@ -253,17 +237,11 @@ struct PotentialInputMethod { impl PotentialInputMethod { pub fn from_string(string: String) -> Self { - PotentialInputMethod { - name: InputMethodName::from_string(string), - successful: None, - } + PotentialInputMethod { name: InputMethodName::from_string(string), successful: None } } pub fn from_str(string: &str) -> Self { - PotentialInputMethod { - name: InputMethodName::from_str(string), - successful: None, - } + PotentialInputMethod { name: InputMethodName::from_str(string), successful: None } } pub fn reset(&mut self) { @@ -297,9 +275,7 @@ pub(crate) struct PotentialInputMethods { impl PotentialInputMethods { pub fn new(xconn: &Arc) -> Self { - let xmodifiers = env::var("XMODIFIERS") - .ok() - .map(PotentialInputMethod::from_string); + let xmodifiers = env::var("XMODIFIERS").ok().map(PotentialInputMethod::from_string); PotentialInputMethods { // Since passing "" to XSetLocaleModifiers results in it defaulting to the value of // XMODIFIERS, it's worth noting what happens if XMODIFIERS is also "". If simply diff --git a/src/platform_impl/linux/x11/ime/mod.rs b/src/platform_impl/linux/x11/ime/mod.rs index 53666bcc09..606e00d9f3 100644 --- a/src/platform_impl/linux/x11/ime/mod.rs +++ b/src/platform_impl/linux/x11/ime/mod.rs @@ -5,10 +5,8 @@ mod context; mod inner; mod input_method; -use std::sync::{ - mpsc::{Receiver, Sender}, - Arc, -}; +use std::sync::mpsc::{Receiver, Sender}; +use std::sync::Arc; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -16,13 +14,11 @@ use tracing::debug; use super::{ffi, util, XConnection, XError}; +use self::callbacks::*; +use self::context::ImeContext; pub use self::context::ImeContextCreationError; -use self::{ - callbacks::*, - context::ImeContext, - inner::{close_im, ImeInner}, - input_method::{PotentialInputMethods, Style}, -}; +use self::inner::{close_im, ImeInner}; +use self::input_method::{PotentialInputMethods, Style}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] @@ -73,10 +69,8 @@ impl Ime { let mut inner = Box::new(ImeInner::new(xconn, potential_input_methods, event_sender)); let inner_ptr = Box::into_raw(inner); let client_data = inner_ptr as _; - let destroy_callback = ffi::XIMCallback { - client_data, - callback: Some(xim_destroy_callback), - }; + let destroy_callback = + ffi::XIMCallback { client_data, callback: Some(xim_destroy_callback) }; inner = unsafe { Box::from_raw(inner_ptr) }; inner.destroy_callback = destroy_callback; (inner, client_data) @@ -105,9 +99,7 @@ impl Ime { inner.im = Some(input_method); Ok(Ime { xconn, inner }) } else { - Err(ImeCreationError::OpenFailure(Box::new( - inner.potential_input_methods, - ))) + Err(ImeCreationError::OpenFailure(Box::new(inner.potential_input_methods))) } } @@ -129,11 +121,7 @@ impl Ime { None } else { let im = self.inner.im.as_ref().unwrap(); - let style = if with_preedit { - im.preedit_style - } else { - im.none_style - }; + let style = if with_preedit { im.preedit_style } else { im.none_style }; let context = unsafe { ImeContext::new( @@ -159,10 +147,7 @@ impl Ime { ImeEvent::Enabled }; - self.inner - .event_sender - .send((window, event)) - .expect("Failed to send enabled event"); + self.inner.event_sender.send((window, event)).expect("Failed to send enabled event"); Some(context) }; diff --git a/src/platform_impl/linux/x11/mod.rs b/src/platform_impl/linux/x11/mod.rs index 72b9a5c9e6..6a4708e7b5 100644 --- a/src/platform_impl/linux/x11/mod.rs +++ b/src/platform_impl/linux/x11/mod.rs @@ -3,7 +3,6 @@ use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet, VecDeque}; use std::ffi::CStr; -use std::fmt; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::ops::Deref; @@ -12,11 +11,11 @@ use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; use std::sync::{Arc, Weak}; use std::time::{Duration, Instant}; -use std::{ptr, slice, str}; +use std::{fmt, ptr, slice, str}; use calloop::generic::Generic; -use calloop::EventLoop as Loop; -use calloop::{ping::Ping, Readiness}; +use calloop::ping::Ping; +use calloop::{EventLoop as Loop, Readiness}; use libc::{setlocale, LC_CTYPE}; use tracing::warn; @@ -78,10 +77,7 @@ struct WakeSender { impl Clone for WakeSender { fn clone(&self) -> Self { - Self { - sender: self.sender.clone(), - waker: self.waker.clone(), - } + Self { sender: self.sender.clone(), waker: self.waker.clone() } } } @@ -104,6 +100,7 @@ impl PeekableReceiver { pub fn from_recv(recv: Receiver) -> Self { Self { recv, first: None } } + pub fn has_incoming(&mut self) -> bool { if self.first.is_some() { return true; @@ -113,14 +110,15 @@ impl PeekableReceiver { Ok(v) => { self.first = Some(v); true - } + }, Err(TryRecvError::Empty) => false, Err(TryRecvError::Disconnected) => { warn!("Channel was disconnected when checking incoming"); false - } + }, } } + pub fn try_recv(&mut self) -> Result { if let Some(first) = self.first.take() { return Ok(first); @@ -171,9 +169,7 @@ pub struct EventLoopProxy { impl Clone for EventLoopProxy { fn clone(&self) -> Self { - EventLoopProxy { - user_sender: self.user_sender.clone(), - } + EventLoopProxy { user_sender: self.user_sender.clone() } } } @@ -223,9 +219,8 @@ impl EventLoop { let ime = ime.ok().map(RefCell::new); - let randr_event_offset = xconn - .select_xrandr_input(root) - .expect("Failed to query XRandR extension"); + let randr_event_offset = + xconn.select_xrandr_input(root).expect("Failed to query XRandR extension"); let xi2ext = xconn .xcb_connection() @@ -315,10 +310,8 @@ impl EventLoop { // Set initial device event filter. window_target.update_listen_device_events(true); - let root_window_target = RootAEL { - p: PlatformActiveEventLoop::X(window_target), - _marker: PhantomData, - }; + let root_window_target = + RootAEL { p: PlatformActiveEventLoop::X(window_target), _marker: PhantomData }; let event_processor = EventProcessor { target: root_window_target, @@ -372,18 +365,13 @@ impl EventLoop { activation_receiver: PeekableReceiver::from_recv(activation_token_channel), user_receiver: PeekableReceiver::from_recv(user_channel), user_sender, - state: EventLoopState { - x11_readiness: Readiness::EMPTY, - }, + state: EventLoopState { x11_readiness: Readiness::EMPTY }, } } pub fn create_proxy(&self) -> EventLoopProxy { EventLoopProxy { - user_sender: WakeSender { - sender: self.user_sender.clone(), - waker: self.waker.clone(), - }, + user_sender: WakeSender { sender: self.user_sender.clone(), waker: self.waker.clone() }, } } @@ -399,13 +387,13 @@ impl EventLoop { match self.pump_events(None, &mut event_handler) { PumpStatus::Exit(0) => { break Ok(()); - } + }, PumpStatus::Exit(code) => { break Err(EventLoopError::ExitFailure(code)); - } + }, _ => { continue; - } + }, } }; @@ -471,17 +459,15 @@ impl EventLoop { ControlFlow::Poll => Some(Duration::ZERO), ControlFlow::WaitUntil(wait_deadline) => { Some(wait_deadline.saturating_duration_since(start)) - } + }, }; min_timeout(control_flow_timeout, timeout) }; self.state.x11_readiness = Readiness::EMPTY; - if let Err(error) = self - .event_loop - .dispatch(timeout, &mut self.state) - .map_err(std::io::Error::from) + if let Err(error) = + self.event_loop.dispatch(timeout, &mut self.state).map_err(std::io::Error::from) { tracing::error!("Failed to poll for events: {error:?}"); let exit_code = error.raw_os_error().unwrap_or(1); @@ -493,23 +479,14 @@ impl EventLoop { // to be considered here let cause = match self.control_flow() { ControlFlow::Poll => StartCause::Poll, - ControlFlow::Wait => StartCause::WaitCancelled { - start, - requested_resume: None, - }, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, ControlFlow::WaitUntil(deadline) => { if Instant::now() < deadline { - StartCause::WaitCancelled { - start, - requested_resume: Some(deadline), - } + StartCause::WaitCancelled { start, requested_resume: Some(deadline) } } else { - StartCause::ResumeTimeReached { - start, - requested_resume: deadline, - } + StartCause::ResumeTimeReached { start, requested_resume: deadline } } - } + }, }; // False positive / spurious wake ups could lead to us spamming @@ -521,10 +498,7 @@ impl EventLoop { // running a loop iteration. // If we don't have any pending `_receiver` if !self.has_pending() - && !matches!( - &cause, - StartCause::ResumeTimeReached { .. } | StartCause::Poll - ) + && !matches!(&cause, StartCause::ResumeTimeReached { .. } | StartCause::Poll) { return; } @@ -549,11 +523,9 @@ impl EventLoop { // Empty activation tokens. while let Ok((window_id, serial)) = self.activation_receiver.try_recv() { - let token = self - .event_processor - .with_window(window_id.0 as xproto::Window, |window| { - window.generate_activation_token() - }); + let token = self.event_processor.with_window(window_id.0 as xproto::Window, |window| { + window.generate_activation_token() + }); match token { Some(Ok(token)) => { @@ -565,11 +537,11 @@ impl EventLoop { }, }; callback(event, &self.event_processor.target) - } + }, Some(Err(e)) => { tracing::error!("Failed to get activation token: {}", e); - } - None => {} + }, + None => {}, } } @@ -591,10 +563,7 @@ impl EventLoop { for window_id in windows { let window_id = crate::window::WindowId(window_id); callback( - Event::WindowEvent { - window_id, - event: WindowEvent::RedrawRequested, - }, + Event::WindowEvent { window_id, event: WindowEvent::RedrawRequested }, &self.event_processor.target, ); } @@ -614,19 +583,18 @@ impl EventLoop { while unsafe { self.event_processor.poll_one_event(xev.as_mut_ptr()) } { let mut xev = unsafe { xev.assume_init() }; - self.event_processor - .process_event(&mut xev, |window_target, event| { - if let Event::WindowEvent { - window_id: crate::window::WindowId(wid), - event: WindowEvent::RedrawRequested, - } = event - { - let window_target = EventProcessor::window_target(window_target); - window_target.redraw_sender.send(wid).unwrap(); - } else { - callback(event, window_target); - } - }); + self.event_processor.process_event(&mut xev, |window_target, event| { + if let Event::WindowEvent { + window_id: crate::window::WindowId(wid), + event: WindowEvent::RedrawRequested, + } = event + { + let window_target = EventProcessor::window_target(window_target); + window_target.redraw_sender.send(wid).unwrap(); + } else { + callback(event, window_target); + } + }); } } @@ -679,9 +647,7 @@ impl ActiveEventLoop { } pub(crate) fn create_custom_cursor(&self, cursor: CustomCursorSource) -> RootCustomCursor { - RootCustomCursor { - inner: PlatformCustomCursor::X(CustomCursor::new(self, cursor.inner)), - } + RootCustomCursor { inner: PlatformCustomCursor::X(CustomCursor::new(self, cursor.inner)) } } pub fn listen_device_events(&self, allowed: DeviceEvents) { @@ -761,9 +727,7 @@ impl ActiveEventLoop { impl EventLoopProxy { pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { - self.user_sender - .send(event) - .map_err(|e| EventLoopClosed(e.0)) + self.user_sender.send(event).map_err(|e| EventLoopClosed(e.0)) } } @@ -783,11 +747,7 @@ impl<'a> DeviceInfo<'a> { if info.is_null() || count == 0 { None } else { - Some(DeviceInfo { - xconn, - info, - count: count as usize, - }) + Some(DeviceInfo { xconn, info, count: count as usize }) } } } @@ -802,6 +762,7 @@ impl<'a> Drop for DeviceInfo<'a> { impl<'a> Deref for DeviceInfo<'a> { type Target = [ffi::XIDeviceInfo]; + fn deref(&self) -> &Self::Target { unsafe { slice::from_raw_parts(self.info, self.count) } } @@ -821,6 +782,7 @@ pub(crate) struct Window(Arc); impl Deref for Window { type Target = UnownedWindow; + #[inline] fn deref(&self) -> &UnownedWindow { &self.0 @@ -833,10 +795,7 @@ impl Window { attribs: WindowAttributes, ) -> Result { let window = Arc::new(UnownedWindow::new(event_loop, attribs)?); - event_loop - .windows - .borrow_mut() - .insert(window.id(), Arc::downgrade(&window)); + event_loop.windows.borrow_mut().insert(window.id(), Arc::downgrade(&window)); Ok(Window(window)) } } @@ -846,10 +805,7 @@ impl Drop for Window { let window = self.deref(); let xconn = &window.xconn; - if let Ok(c) = xconn - .xcb_connection() - .destroy_window(window.id().0 as xproto::Window) - { + if let Ok(c) = xconn.xcb_connection().destroy_window(window.id().0 as xproto::Window) { c.ignore_error(); } } @@ -909,15 +865,11 @@ impl fmt::Display for X11Error { ), X11Error::MissingExtension(s) => write!(f, "Missing X11 extension: {}", s), X11Error::NoSuchVisual(visualid) => { - write!( - f, - "Could not find a matching X11 visual for ID `{:x}`", - visualid - ) - } + write!(f, "Could not find a matching X11 visual for ID `{:x}`", visualid) + }, X11Error::XsettingsParse(err) => { write!(f, "Failed to parse xsettings: {:?}", err) - } + }, } } } @@ -1053,27 +1005,21 @@ impl Device { let ty = unsafe { (*class_ptr)._type }; if ty == ffi::XIScrollClass { let info = unsafe { &*(class_ptr as *const ffi::XIScrollClassInfo) }; - scroll_axes.push(( - info.number, - ScrollAxis { - increment: info.increment, - orientation: match info.scroll_type { - ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, - ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, - _ => unreachable!(), - }, - position: 0.0, + scroll_axes.push((info.number, ScrollAxis { + increment: info.increment, + orientation: match info.scroll_type { + ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, + ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, + _ => unreachable!(), }, - )); + position: 0.0, + })); } } } - let mut device = Device { - _name: name.into_owned(), - scroll_axes, - attachment: info.attachment, - }; + let mut device = + Device { _name: name.into_owned(), scroll_axes, attachment: info.attachment }; device.reset_scroll_position(info); device } @@ -1084,10 +1030,8 @@ impl Device { let ty = unsafe { (*class_ptr)._type }; if ty == ffi::XIValuatorClass { let info = unsafe { &*(class_ptr as *const ffi::XIValuatorClassInfo) }; - if let Some(&mut (_, ref mut axis)) = self - .scroll_axes - .iter_mut() - .find(|&&mut (axis, _)| axis == info.number) + if let Some(&mut (_, ref mut axis)) = + self.scroll_axes.iter_mut().find(|&&mut (axis, _)| axis == info.number) { axis.position = info.value; } diff --git a/src/platform_impl/linux/x11/monitor.rs b/src/platform_impl/linux/x11/monitor.rs index 731b1aaca5..6580ac30de 100644 --- a/src/platform_impl/linux/x11/monitor.rs +++ b/src/platform_impl/linux/x11/monitor.rs @@ -1,15 +1,9 @@ use super::{util, X11Error, XConnection}; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize}, - platform_impl::VideoModeHandle as PlatformVideoModeHandle, -}; -use x11rb::{ - connection::RequestConnection, - protocol::{ - randr::{self, ConnectionExt as _}, - xproto, - }, -}; +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::platform_impl::VideoModeHandle as PlatformVideoModeHandle; +use x11rb::connection::RequestConnection; +use x11rb::protocol::randr::{self, ConnectionExt as _}; +use x11rb::protocol::xproto; // Used for testing. This should always be committed as false. const DISABLE_MONITOR_LIST_CACHING: bool = false; @@ -240,18 +234,12 @@ impl XConnection { // Pipeline all of the get-crtc requests. let mut crtc_cookies = Vec::with_capacity(resources.crtcs().len()); for &crtc in resources.crtcs() { - crtc_cookies.push( - self.xcb_connection() - .randr_get_crtc_info(crtc, x11rb::CURRENT_TIME)?, - ); + crtc_cookies + .push(self.xcb_connection().randr_get_crtc_info(crtc, x11rb::CURRENT_TIME)?); } // Do this here so we do all of our requests in one shot. - let primary = self - .xcb_connection() - .randr_get_output_primary(root.root)? - .reply()? - .output; + let primary = self.xcb_connection().randr_get_output_primary(root.root)?.reply()?.output; let mut crtc_infos = Vec::with_capacity(crtc_cookies.len()); for cookie in crtc_cookies { @@ -293,7 +281,7 @@ impl XConnection { *monitors_lock = Some(monitors.clone()); } Ok(monitors) - } + }, } } @@ -347,9 +335,7 @@ impl ScreenResources { (major_version, minor_version): (u32, u32), ) -> Result { if (major_version == 1 && minor_version >= 3) || major_version > 1 { - let reply = conn - .randr_get_screen_resources_current(root.root)? - .reply()?; + let reply = conn.randr_get_screen_resources_current(root.root)?.reply()?; Ok(Self::from_get_screen_resources_current_reply(reply)) } else { let reply = conn.randr_get_screen_resources(root.root)?.reply()?; @@ -358,18 +344,12 @@ impl ScreenResources { } pub(crate) fn from_get_screen_resources_reply(reply: randr::GetScreenResourcesReply) -> Self { - Self { - modes: reply.modes, - crtcs: reply.crtcs, - } + Self { modes: reply.modes, crtcs: reply.crtcs } } pub(crate) fn from_get_screen_resources_current_reply( reply: randr::GetScreenResourcesCurrentReply, ) -> Self { - Self { - modes: reply.modes, - crtcs: reply.crtcs, - } + Self { modes: reply.modes, crtcs: reply.crtcs } } } diff --git a/src/platform_impl/linux/x11/util/cursor.rs b/src/platform_impl/linux/x11/util/cursor.rs index f86907a464..169748d14d 100644 --- a/src/platform_impl/linux/x11/util/cursor.rs +++ b/src/platform_impl/linux/x11/util/cursor.rs @@ -1,13 +1,12 @@ -use std::{ - ffi::CString, - hash::{Hash, Hasher}, - iter, slice, - sync::Arc, -}; +use std::ffi::CString; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; +use std::{iter, slice}; use x11rb::connection::Connection; -use crate::{platform_impl::PlatformCustomCursorSource, window::CursorIcon}; +use crate::platform_impl::PlatformCustomCursorSource; +use crate::window::CursorIcon; use super::super::ActiveEventLoop; use super::*; @@ -21,13 +20,11 @@ impl XConnection { .entry(cursor) .or_insert_with(|| self.get_cursor(cursor)); - self.update_cursor(window, cursor) - .expect("Failed to set cursor"); + self.update_cursor(window, cursor).expect("Failed to set cursor"); } pub(crate) fn set_custom_cursor(&self, window: xproto::Window, cursor: &CustomCursor) { - self.update_cursor(window, cursor.inner.cursor) - .expect("Failed to set cursor"); + self.update_cursor(window, cursor.inner.cursor).expect("Failed to set cursor"); } fn create_empty_cursor(&self) -> ffi::Cursor { @@ -151,12 +148,7 @@ impl CustomCursor { let cursor = (event_loop.xconn.xcursor.XcursorImageLoadCursor)(event_loop.xconn.display, ximage); (event_loop.xconn.xcursor.XcursorImageDestroy)(ximage); - Self { - inner: Arc::new(CustomCursorInner { - xconn: event_loop.xconn.clone(), - cursor, - }), - } + Self { inner: Arc::new(CustomCursorInner { xconn: event_loop.xconn.clone(), cursor }) } } } } diff --git a/src/platform_impl/linux/x11/util/geometry.rs b/src/platform_impl/linux/x11/util/geometry.rs index bf0c957835..e28b92e4af 100644 --- a/src/platform_impl/linux/x11/util/geometry.rs +++ b/src/platform_impl/linux/x11/util/geometry.rs @@ -15,12 +15,7 @@ impl AaRect { pub fn new((x, y): (i32, i32), (width, height): (u32, u32)) -> Self { let (x, y) = (x as i64, y as i64); let (width, height) = (width as i64, height as i64); - AaRect { - x, - y, - width, - height, - } + AaRect { x, y, width, height } } pub fn contains_point(&self, x: i64, y: i64) -> bool { @@ -50,12 +45,7 @@ pub struct FrameExtents { impl FrameExtents { pub fn new(left: u32, right: u32, top: u32, bottom: u32) -> Self { - FrameExtents { - left, - right, - top, - bottom, - } + FrameExtents { left, right, top, bottom } } pub fn from_border(border: u32) -> Self { @@ -80,10 +70,7 @@ impl FrameExtentsHeuristic { pub fn inner_pos_to_outer(&self, x: i32, y: i32) -> (i32, i32) { use self::FrameExtentsHeuristicPath::*; if self.heuristic_path != UnsupportedBordered { - ( - x - self.frame_extents.left as i32, - y - self.frame_extents.top as i32, - ) + (x - self.frame_extents.left as i32, y - self.frame_extents.top as i32) } else { (x, y) } @@ -92,14 +79,10 @@ impl FrameExtentsHeuristic { pub fn inner_size_to_outer(&self, width: u32, height: u32) -> (u32, u32) { ( width.saturating_add( - self.frame_extents - .left - .saturating_add(self.frame_extents.right) as _, + self.frame_extents.left.saturating_add(self.frame_extents.right) as _ ), height.saturating_add( - self.frame_extents - .top - .saturating_add(self.frame_extents.bottom) as _, + self.frame_extents.top.saturating_add(self.frame_extents.bottom) as _ ), ) } @@ -112,10 +95,7 @@ impl XConnection { window: xproto::Window, root: xproto::Window, ) -> Result { - self.xcb_connection() - .translate_coordinates(window, root, 0, 0)? - .reply() - .map_err(Into::into) + self.xcb_connection().translate_coordinates(window, root, 0, 0)?.reply().map_err(Into::into) } // This is adequate for inner_size @@ -123,10 +103,7 @@ impl XConnection { &self, window: xproto::Window, ) -> Result { - self.xcb_connection() - .get_geometry(window)? - .reply() - .map_err(Into::into) + self.xcb_connection().get_geometry(window)?.reply().map_err(Into::into) } fn get_frame_extents(&self, window: xproto::Window) -> Option { @@ -141,11 +118,7 @@ impl XConnection { // support this. As this is part of EWMH (Extended Window Manager Hints), it's likely to // be unsupported by many smaller WMs. let extents: Option> = self - .get_property( - window, - extents_atom, - xproto::Atom::from(xproto::AtomEnum::CARDINAL), - ) + .get_property(window, extents_atom, xproto::Atom::from(xproto::AtomEnum::CARDINAL)) .ok(); extents.and_then(|extents| { @@ -171,11 +144,7 @@ impl XConnection { } let client_list: Option> = self - .get_property( - root, - client_list_atom, - xproto::Atom::from(xproto::AtomEnum::WINDOW), - ) + .get_property(root, client_list_atom, xproto::Atom::from(xproto::AtomEnum::WINDOW)) .ok(); client_list.map(|client_list| client_list.contains(&(window as xproto::Window))) @@ -221,14 +190,9 @@ impl XConnection { }; let (width, height, border) = { - let inner_geometry = self - .get_geometry(window) - .expect("Failed to get inner window geometry"); - ( - inner_geometry.width, - inner_geometry.height, - inner_geometry.border_width, - ) + let inner_geometry = + self.get_geometry(window).expect("Failed to get inner window geometry"); + (inner_geometry.width, inner_geometry.height, inner_geometry.border_width) }; // The first condition is only false for un-nested windows, but isn't always false for @@ -253,39 +217,29 @@ impl XConnection { // known discrepancies: // * Mutter/Muffin/Budgie gives decorated windows a margin of 9px (only 7px on top) in // addition to a 1px semi-transparent border. The margin can be easily observed by - // using a screenshot tool to get a screenshot of a selected window, and is - // presumably used for drawing drop shadows. Getting window geometry information - // via hierarchy-climbing results in this margin being included in both the - // position and outer size, so a window positioned at (0, 0) would be reported as - // having a position (-10, -8). - // * Compiz has a drop shadow margin just like Mutter/Muffin/Budgie, though it's 10px - // on all sides, and there's no additional border. - // * Enlightenment otherwise gets a y position equivalent to inner_y_rel_root. - // Without decorations, there's no difference. This is presumably related to - // Enlightenment's fairly unique concept of window position; it interprets - // positions given to XMoveWindow as a client area position rather than a position - // of the overall window. - - FrameExtentsHeuristic { - frame_extents, - heuristic_path: Supported, - } + // using a screenshot tool to get a screenshot of a selected window, and is presumably + // used for drawing drop shadows. Getting window geometry information via + // hierarchy-climbing results in this margin being included in both the position and + // outer size, so a window positioned at (0, 0) would be reported as having a position + // (-10, -8). + // * Compiz has a drop shadow margin just like Mutter/Muffin/Budgie, though it's 10px on + // all sides, and there's no additional border. + // * Enlightenment otherwise gets a y position equivalent to inner_y_rel_root. Without + // decorations, there's no difference. This is presumably related to Enlightenment's + // fairly unique concept of window position; it interprets positions given to + // XMoveWindow as a client area position rather than a position of the overall window. + + FrameExtentsHeuristic { frame_extents, heuristic_path: Supported } } else if nested { // If the position value we have is for a nested window used as the client area, we'll // just climb up the hierarchy and get the geometry of the outermost window we're // nested in. - let outer_window = self - .climb_hierarchy(window, root) - .expect("Failed to climb window hierarchy"); + let outer_window = + self.climb_hierarchy(window, root).expect("Failed to climb window hierarchy"); let (outer_y, outer_width, outer_height) = { - let outer_geometry = self - .get_geometry(outer_window) - .expect("Failed to get outer window geometry"); - ( - outer_geometry.y, - outer_geometry.width, - outer_geometry.height, - ) + let outer_geometry = + self.get_geometry(outer_window).expect("Failed to get outer window geometry"); + (outer_geometry.y, outer_geometry.width, outer_geometry.height) }; // Since we have the geometry of the outermost window and the geometry of the client @@ -300,18 +254,12 @@ impl XConnection { let bottom = diff_y.saturating_sub(offset_y); let frame_extents = FrameExtents::new(left, right, top, bottom); - FrameExtentsHeuristic { - frame_extents, - heuristic_path: UnsupportedNested, - } + FrameExtentsHeuristic { frame_extents, heuristic_path: UnsupportedNested } } 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()); - FrameExtentsHeuristic { - frame_extents, - heuristic_path: UnsupportedBordered, - } + FrameExtentsHeuristic { frame_extents, heuristic_path: UnsupportedBordered } } } } diff --git a/src/platform_impl/linux/x11/util/hint.rs b/src/platform_impl/linux/x11/util/hint.rs index ae95ea12e1..a31872d5b4 100644 --- a/src/platform_impl/linux/x11/util/hint.rs +++ b/src/platform_impl/linux/x11/util/hint.rs @@ -76,13 +76,7 @@ mod mwm { impl MotifHints { pub fn new() -> MotifHints { MotifHints { - hints: MwmHints { - flags: 0, - functions: 0, - decorations: 0, - input_mode: 0, - status: 0, - }, + hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0 }, } } diff --git a/src/platform_impl/linux/x11/util/input.rs b/src/platform_impl/linux/x11/util/input.rs index b27d208a9a..37d21d1191 100644 --- a/src/platform_impl/linux/x11/util/input.rs +++ b/src/platform_impl/linux/x11/util/input.rs @@ -1,8 +1,6 @@ use std::{slice, str}; -use x11rb::protocol::{ - xinput::{self, ConnectionExt as _}, - xkb, -}; +use x11rb::protocol::xinput::{self, ConnectionExt as _}; +use x11rb::protocol::xkb; use super::*; @@ -22,13 +20,10 @@ impl XConnection { mask: xinput::XIEventMask, ) -> Result, X11Error> { self.xcb_connection() - .xinput_xi_select_events( - window, - &[xinput::EventMask { - deviceid: device_id, - mask: vec![mask], - }], - ) + .xinput_xi_select_events(window, &[xinput::EventMask { + deviceid: device_id, + mask: vec![mask], + }]) .map_err(Into::into) } diff --git a/src/platform_impl/linux/x11/util/keys.rs b/src/platform_impl/linux/x11/util/keys.rs index 6fff11d775..a6ad291c3f 100644 --- a/src/platform_impl/linux/x11/util/keys.rs +++ b/src/platform_impl/linux/x11/util/keys.rs @@ -1,4 +1,5 @@ -use std::{iter::Enumerate, slice::Iter}; +use std::iter::Enumerate; +use std::slice::Iter; use super::*; @@ -14,17 +15,13 @@ pub struct KeymapIter<'a> { impl Keymap { pub fn iter(&self) -> KeymapIter<'_> { - KeymapIter { - iter: self.keys.iter().enumerate(), - index: 0, - item: None, - } + KeymapIter { iter: self.keys.iter().enumerate(), index: 0, item: None } } } impl<'a> IntoIterator for &'a Keymap { - type Item = ffi::KeyCode; type IntoIter = KeymapIter<'a>; + type Item = ffi::KeyCode; fn into_iter(self) -> Self::IntoIter { self.iter() diff --git a/src/platform_impl/linux/x11/util/mod.rs b/src/platform_impl/linux/x11/util/mod.rs index f97005ce8a..5c30293c31 100644 --- a/src/platform_impl/linux/x11/util/mod.rs +++ b/src/platform_impl/linux/x11/util/mod.rs @@ -1,11 +1,9 @@ // Welcome to the util module, where we try to keep you from shooting yourself in the foot. // *results may vary -use std::{ - mem::{self, MaybeUninit}, - ops::BitAnd, - os::raw::*, -}; +use std::mem::{self, MaybeUninit}; +use std::ops::BitAnd; +use std::os::raw::*; mod client_msg; pub mod cookie; @@ -22,12 +20,17 @@ mod window_property; mod wm; mod xmodmap; -pub use self::{ - cursor::*, geometry::*, hint::*, input::*, mouse::*, window_property::*, wm::*, - xmodmap::ModifierKeymap, -}; +pub use self::cursor::*; +pub use self::geometry::*; +pub use self::hint::*; +pub use self::input::*; +pub use self::mouse::*; +pub use self::window_property::*; +pub use self::wm::*; +pub use self::xmodmap::ModifierKeymap; -use super::{atoms::*, ffi, VoidCookie, X11Error, XConnection, XError}; +use super::atoms::*; +use super::{ffi, VoidCookie, X11Error, XConnection, XError}; use x11rb::protocol::xproto::{self, ConnectionExt as _}; pub fn maybe_change(field: &mut Option, value: T) -> bool { @@ -54,12 +57,13 @@ impl XConnection { // 1. `XPending`, `XNextEvent`, and `XWindowEvent` flush "as needed" // 2. `XFlush` explicitly flushes // 3. `XSync` flushes and blocks until all requests are responded to - // 4. Calls that have a return dependent on a response (i.e. `XGetWindowProperty`) sync internally. - // When in doubt, check the X11 source; if a function calls `_XReply`, it flushes and waits. + // 4. Calls that have a return dependent on a response (i.e. `XGetWindowProperty`) sync + // internally. When in doubt, check the X11 source; if a function calls `_XReply`, it flushes + // and waits. // All util functions that abstract an async function will return a `Flusher`. pub fn flush_requests(&self) -> Result<(), XError> { unsafe { (self.xlib.XFlush)(self.display) }; - //println!("XFlush"); + // println!("XFlush"); // This isn't necessarily a useful time to check for errors (since our request hasn't // necessarily been processed yet) self.check_errors() @@ -67,7 +71,7 @@ impl XConnection { pub fn sync_with_server(&self) -> Result<(), XError> { unsafe { (self.xlib.XSync)(self.display, ffi::False) }; - //println!("XSync"); + // println!("XSync"); self.check_errors() } } diff --git a/src/platform_impl/linux/x11/util/mouse.rs b/src/platform_impl/linux/x11/util/mouse.rs index 9f22266da3..e66a76c396 100644 --- a/src/platform_impl/linux/x11/util/mouse.rs +++ b/src/platform_impl/linux/x11/util/mouse.rs @@ -8,10 +8,7 @@ pub struct Delta { impl Default for Delta { fn default() -> Self { - Self { - x: Default::default(), - y: Default::default(), - } + Self { x: Default::default(), y: Default::default() } } } diff --git a/src/platform_impl/linux/x11/util/randr.rs b/src/platform_impl/linux/x11/util/randr.rs index e55c042c0b..6097bc517c 100644 --- a/src/platform_impl/linux/x11/util/randr.rs +++ b/src/platform_impl/linux/x11/util/randr.rs @@ -1,8 +1,9 @@ -use std::{env, str, str::FromStr}; +use std::str::FromStr; +use std::{env, str}; use super::*; -use crate::platform_impl::platform::x11::monitor; -use crate::{dpi::validate_scale_factor, platform_impl::platform::x11::VideoModeHandle}; +use crate::dpi::validate_scale_factor; +use crate::platform_impl::platform::x11::{monitor, VideoModeHandle}; use tracing::warn; use x11rb::protocol::randr::{self, ConnectionExt as _}; @@ -42,16 +43,14 @@ impl XConnection { if let Some(xsettings_screen) = self.xsettings_screen() { match self.xsettings_dpi(xsettings_screen) { Ok(Some(dpi)) => return Some(dpi), - Ok(None) => {} + Ok(None) => {}, Err(err) => { tracing::warn!("failed to fetch XSettings: {err}"); - } + }, } } - self.database() - .get_string("Xft.dpi", "") - .and_then(|s| f64::from_str(s).ok()) + self.database().get_string("Xft.dpi", "").and_then(|s| f64::from_str(s).ok()) } pub fn get_output_info( @@ -69,7 +68,7 @@ impl XConnection { Err(err) => { warn!("Failed to get output info: {:?}", err); return None; - } + }, }; let bit_depth = self.default_root().root_depth; @@ -100,14 +99,15 @@ impl XConnection { Err(err) => { warn!("Failed to get output name: {:?}", err); return None; - } + }, }; // Override DPI if `WINIT_X11_SCALE_FACTOR` variable is set let deprecated_dpi_override = env::var("WINIT_HIDPI_FACTOR").ok(); if deprecated_dpi_override.is_some() { warn!( - "The WINIT_HIDPI_FACTOR environment variable is deprecated; use WINIT_X11_SCALE_FACTOR" - ) + "The WINIT_HIDPI_FACTOR environment variable is deprecated; use \ + WINIT_X11_SCALE_FACTOR" + ) } let dpi_env = env::var("WINIT_X11_SCALE_FACTOR").ok().map_or_else( || EnvVarDPI::NotSet, @@ -120,7 +120,8 @@ impl XConnection { EnvVarDPI::NotSet } else { panic!( - "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{var}`" + "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal \ + floats greater than 0, or `randr`. Got `{var}`" ); } }, @@ -134,11 +135,12 @@ impl XConnection { EnvVarDPI::Scale(dpi_override) => { if !validate_scale_factor(dpi_override) { panic!( - "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{dpi_override}`", + "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal \ + floats greater than 0, or `randr`. Got `{dpi_override}`", ); } dpi_override - } + }, EnvVarDPI::NotSet => { if let Some(dpi) = self.get_xft_dpi() { dpi / 96. @@ -148,7 +150,7 @@ impl XConnection { (output_info.mm_width as _, output_info.mm_height as _), ) } - } + }, }; Some((name, scale_factor, modes)) @@ -159,10 +161,8 @@ impl XConnection { crtc_id: randr::Crtc, mode_id: randr::Mode, ) -> Result<(), X11Error> { - let crtc = self - .xcb_connection() - .randr_get_crtc_info(crtc_id, x11rb::CURRENT_TIME)? - .reply()?; + let crtc = + self.xcb_connection().randr_get_crtc_info(crtc_id, x11rb::CURRENT_TIME)?.reply()?; self.xcb_connection() .randr_set_crtc_config( @@ -181,10 +181,6 @@ impl XConnection { } pub fn get_crtc_mode(&self, crtc_id: randr::Crtc) -> Result { - Ok(self - .xcb_connection() - .randr_get_crtc_info(crtc_id, x11rb::CURRENT_TIME)? - .reply()? - .mode) + Ok(self.xcb_connection().randr_get_crtc_info(crtc_id, x11rb::CURRENT_TIME)?.reply()?.mode) } } diff --git a/src/platform_impl/linux/x11/util/window_property.rs b/src/platform_impl/linux/x11/util/window_property.rs index eb5f6cb57e..0f4ca165d6 100644 --- a/src/platform_impl/linux/x11/util/window_property.rs +++ b/src/platform_impl/linux/x11/util/window_property.rs @@ -87,10 +87,7 @@ impl XConnection { property, property_type, (mem::size_of::() * 8) as u8, - new_value - .len() - .try_into() - .expect("too many items for property"), + new_value.len().try_into().expect("too many items for property"), bytemuck::cast_slice::(new_value), ) .map_err(Into::into) diff --git a/src/platform_impl/linux/x11/util/wm.rs b/src/platform_impl/linux/x11/util/wm.rs index 6c96ff143c..be70b835d4 100644 --- a/src/platform_impl/linux/x11/util/wm.rs +++ b/src/platform_impl/linux/x11/util/wm.rs @@ -38,12 +38,8 @@ impl XConnection { fn get_supported_hints(&self, root: xproto::Window) -> Vec { let atoms = self.atoms(); let supported_atom = atoms[_NET_SUPPORTED]; - self.get_property( - root, - supported_atom, - xproto::Atom::from(xproto::AtomEnum::ATOM), - ) - .unwrap_or_else(|_| Vec::with_capacity(0)) + self.get_property(root, supported_atom, xproto::Atom::from(xproto::AtomEnum::ATOM)) + .unwrap_or_else(|_| Vec::with_capacity(0)) } #[allow(clippy::useless_conversion)] @@ -57,22 +53,22 @@ impl XConnection { // inavailability of time machines, we'll just try to get _NET_SUPPORTING_WM_CHECK // regardless of whether or not the WM claims to support it. // - // Blackbox 0.70 also incorrectly reports not supporting this, though that appears to be fixed - // in 0.72. - /*if !supported_hints.contains(&check_atom) { - return None; - }*/ + // Blackbox 0.70 also incorrectly reports not supporting this, though that appears to be + // fixed in 0.72. + // if !supported_hints.contains(&check_atom) { + // return None; + // } // IceWM (1.3.x and earlier) doesn't report supporting _NET_WM_NAME, but will nonetheless // provide us with a value for it. Note that the unofficial 1.4 fork of IceWM works fine. - /*if !supported_hints.contains(&wm_name_atom) { - return None; - }*/ + // if !supported_hints.contains(&wm_name_atom) { + // return None; + // } // Of the WMs tested, only xmonad and dwm fail to provide a WM name. - // Querying this property on the root window will give us the ID of a child window created by - // the WM. + // Querying this property on the root window will give us the ID of a child window created + // by the WM. let root_window_wm_check = { let result = self.get_property::( root, diff --git a/src/platform_impl/linux/x11/window.rs b/src/platform_impl/linux/x11/window.rs index 94c50d2abe..ea7c02354a 100644 --- a/src/platform_impl/linux/x11/window.rs +++ b/src/platform_impl/linux/x11/window.rs @@ -1,50 +1,40 @@ -use std::{ - cmp, env, - ffi::CString, - mem::replace, - os::raw::*, - path::Path, - sync::{Arc, Mutex, MutexGuard}, -}; +use std::ffi::CString; +use std::mem::replace; +use std::os::raw::*; +use std::path::Path; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::{cmp, env}; use tracing::{debug, info, warn}; -use x11rb::{ - connection::Connection, - properties::{WmHints, WmSizeHints, WmSizeHintsSpecification}, - protocol::{ - randr, - shape::SK, - xfixes::{ConnectionExt, RegionWrapper}, - xinput, - xproto::{self, ConnectionExt as _, Rectangle}, - }, +use x11rb::connection::Connection; +use x11rb::properties::{WmHints, WmSizeHints, WmSizeHintsSpecification}; +use x11rb::protocol::shape::SK; +use x11rb::protocol::xfixes::{ConnectionExt, RegionWrapper}; +use x11rb::protocol::xproto::{self, ConnectionExt as _, Rectangle}; +use x11rb::protocol::{randr, xinput}; + +use crate::cursor::{Cursor, CustomCursor as RootCustomCursor}; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event::{Event, InnerSizeWriter, WindowEvent}; +use crate::event_loop::AsyncRequestSerial; +use crate::platform::x11::WindowType; +use crate::platform_impl::x11::atoms::*; +use crate::platform_impl::x11::{ + xinput_fp1616_to_float, MonitorHandle as X11MonitorHandle, WakeSender, X11Error, }; - -use crate::{ - cursor::{Cursor, CustomCursor as RootCustomCursor}, - dpi::{PhysicalPosition, PhysicalSize, Position, Size}, - error::{ExternalError, NotSupportedError, OsError as RootOsError}, - event::{Event, InnerSizeWriter, WindowEvent}, - event_loop::AsyncRequestSerial, - platform::x11::WindowType, - platform_impl::{ - x11::{ - atoms::*, xinput_fp1616_to_float, MonitorHandle as X11MonitorHandle, WakeSender, - X11Error, - }, - Fullscreen, MonitorHandle as PlatformMonitorHandle, OsError, PlatformCustomCursor, - PlatformIcon, VideoModeHandle as PlatformVideoModeHandle, - }, - window::{ - CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, - WindowButtons, WindowLevel, - }, +use crate::platform_impl::{ + Fullscreen, MonitorHandle as PlatformMonitorHandle, OsError, PlatformCustomCursor, + PlatformIcon, VideoModeHandle as PlatformVideoModeHandle, +}; +use crate::window::{ + CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, + WindowButtons, WindowLevel, }; +use super::util::{self, SelectedCursor}; use super::{ - ffi, - util::{self, SelectedCursor}, - ActiveEventLoop, CookieResultExt, ImeRequest, ImeSender, VoidCookie, WindowId, XConnection, + ffi, ActiveEventLoop, CookieResultExt, ImeRequest, ImeSender, VoidCookie, WindowId, XConnection, }; #[derive(Debug)] @@ -86,11 +76,8 @@ pub enum Visibility { impl SharedState { fn new(last_monitor: X11MonitorHandle, window_attributes: &WindowAttributes) -> Mutex { - let visibility = if window_attributes.visible { - Visibility::YesWait - } else { - Visibility::No - }; + let visibility = + if window_attributes.visible { Visibility::YesWait } else { Visibility::No }; Mutex::new(SharedState { last_monitor, @@ -191,16 +178,13 @@ impl UnownedWindow { info!("Guessed window scale factor: {}", scale_factor); - let max_inner_size: Option<(u32, u32)> = window_attrs - .max_inner_size - .map(|size| size.to_physical::(scale_factor).into()); - let min_inner_size: Option<(u32, u32)> = window_attrs - .min_inner_size - .map(|size| size.to_physical::(scale_factor).into()); + let max_inner_size: Option<(u32, u32)> = + window_attrs.max_inner_size.map(|size| size.to_physical::(scale_factor).into()); + let min_inner_size: Option<(u32, u32)> = + window_attrs.min_inner_size.map(|size| size.to_physical::(scale_factor).into()); - let position = window_attrs - .position - .map(|position| position.to_physical::(scale_factor)); + let position = + window_attrs.position.map(|position| position.to_physical::(scale_factor)); let dimensions = { // x11 only applies constraints when the window is actively resized @@ -219,10 +203,7 @@ impl UnownedWindow { dimensions.0 = cmp::max(dimensions.0, min.0); dimensions.1 = cmp::max(dimensions.1, min.1); } - debug!( - "Calculated physical dimensions: {}x{}", - dimensions.0, dimensions.1 - ); + debug!("Calculated physical dimensions: {}x{}", dimensions.0, dimensions.1); dimensions }; @@ -238,41 +219,37 @@ impl UnownedWindow { .roots .iter() .flat_map(|root| &root.allowed_depths) - .flat_map(|depth| { - depth - .visuals - .iter() - .map(move |visual| (visual, depth.depth)) - }); + .flat_map(|depth| depth.visuals.iter().map(move |visual| (visual, depth.depth))); // creating - let (visualtype, depth, require_colormap) = match window_attrs - .platform_specific - .x11 - .visual_id - { - Some(vi) => { - // Find this specific visual. - let (visualtype, depth) = all_visuals - .find(|(visual, _)| visual.visual_id == vi) - .ok_or_else(|| os_error!(OsError::XError(X11Error::NoSuchVisual(vi).into())))?; - - (Some(visualtype), depth, true) - } - None if window_attrs.transparent => { - // Find a suitable visual, true color with 32 bits of depth. - all_visuals - .find_map(|(visual, depth)| { - (depth == 32 && visual.class == xproto::VisualClass::TRUE_COLOR) - .then_some((Some(visual), depth, true)) - }) - .unwrap_or_else(|| { - debug!("Could not set transparency, because XMatchVisualInfo returned zero for the required parameters"); - (None as _, x11rb::COPY_FROM_PARENT as _, false) - }) - } - _ => (None, x11rb::COPY_FROM_PARENT as _, false), - }; + let (visualtype, depth, require_colormap) = + match window_attrs.platform_specific.x11.visual_id { + Some(vi) => { + // Find this specific visual. + let (visualtype, depth) = + all_visuals.find(|(visual, _)| visual.visual_id == vi).ok_or_else( + || os_error!(OsError::XError(X11Error::NoSuchVisual(vi).into())), + )?; + + (Some(visualtype), depth, true) + }, + None if window_attrs.transparent => { + // Find a suitable visual, true color with 32 bits of depth. + all_visuals + .find_map(|(visual, depth)| { + (depth == 32 && visual.class == xproto::VisualClass::TRUE_COLOR) + .then_some((Some(visual), depth, true)) + }) + .unwrap_or_else(|| { + debug!( + "Could not set transparency, because XMatchVisualInfo returned \ + zero for the required parameters" + ); + (None as _, x11rb::COPY_FROM_PARENT as _, false) + }) + }, + _ => (None, x11rb::COPY_FROM_PARENT as _, false), + }; let mut visual = visualtype.map_or(x11rb::COPY_FROM_PARENT, |v| v.visual_id); let window_attributes = { @@ -320,11 +297,7 @@ impl UnownedWindow { }; // Figure out the window's parent. - let parent = window_attrs - .platform_specific - .x11 - .embed_window - .unwrap_or(root); + let parent = window_attrs.platform_specific.x11.embed_window.unwrap_or(root); // finally creating the window let xwindow = { @@ -419,9 +392,7 @@ impl UnownedWindow { .map(|bin_name| bin_name.to_owned()) .unwrap_or_else(|| window_attrs.title.clone()); // This environment variable is extraordinarily unlikely to actually be used... - let instance = env::var("RESOURCE_NAME") - .ok() - .unwrap_or_else(|| class.clone()); + let instance = env::var("RESOURCE_NAME").ok().unwrap_or_else(|| class.clone()); (instance, class) }; @@ -444,12 +415,10 @@ impl UnownedWindow { .ignore_error(); // Set size hints. - let mut min_inner_size = window_attrs - .min_inner_size - .map(|size| size.to_physical::(scale_factor)); - let mut max_inner_size = window_attrs - .max_inner_size - .map(|size| size.to_physical::(scale_factor)); + let mut min_inner_size = + window_attrs.min_inner_size.map(|size| size.to_physical::(scale_factor)); + let mut max_inner_size = + window_attrs.max_inner_size.map(|size| size.to_physical::(scale_factor)); if !window_attrs.resizable { if util::wm_name_is_one_of(&["Xfwm4"]) { @@ -534,9 +503,7 @@ impl UnownedWindow { &mut supported_ptr, ); if supported_ptr == ffi::False { - return Err(os_error!(OsError::Misc( - "`XkbSetDetectableAutoRepeat` failed" - ))); + return Err(os_error!(OsError::Misc("`XkbSetDetectableAutoRepeat` failed"))); } } @@ -556,9 +523,7 @@ impl UnownedWindow { // Try to create input context for the window. if let Some(ime) = event_loop.ime.as_ref() { - let result = ime - .borrow_mut() - .create_context(window.xwindow as ffi::Window, false); + let result = ime.borrow_mut().create_context(window.xwindow as ffi::Window, false); leap!(result); } @@ -647,10 +612,7 @@ impl UnownedWindow { fn set_window_types(&self, window_types: Vec) -> Result, X11Error> { let atoms = self.xconn.atoms(); let hint_atom = atoms[_NET_WM_WINDOW_TYPE]; - let atoms: Vec<_> = window_types - .iter() - .map(|t| t.as_atom(&self.xconn)) - .collect(); + let atoms: Vec<_> = window_types.iter().map(|t| t.as_atom(&self.xconn)).collect(); self.xconn.change_property( self.xwindow, @@ -682,13 +644,9 @@ impl UnownedWindow { #[inline] pub fn set_theme(&self, theme: Option) { - self.set_theme_inner(theme) - .expect("Failed to change window theme") - .ignore_error(); + self.set_theme_inner(theme).expect("Failed to change window theme").ignore_error(); - self.xconn - .flush_requests() - .expect("Failed to change window theme"); + self.xconn.flush_requests().expect("Failed to change window theme"); } fn set_netwm( @@ -703,13 +661,7 @@ impl UnownedWindow { self.root, state_atom, Some(xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY), - [ - operation as u32, - properties.0, - properties.1, - properties.2, - properties.3, - ], + [operation as u32, properties.0, properties.1, properties.2, properties.3], ) } @@ -723,11 +675,7 @@ impl UnownedWindow { // locking up the user's display. self.xconn .xcb_connection() - .set_input_focus( - xproto::InputFocus::PARENT, - self.xwindow, - x11rb::CURRENT_TIME, - )? + .set_input_focus(xproto::InputFocus::PARENT, self.xwindow, x11rb::CURRENT_TIME)? .ignore_error(); } @@ -745,7 +693,7 @@ impl UnownedWindow { Visibility::No | Visibility::YesWait => { shared_state_lock.desired_fullscreen = Some(fullscreen); return Ok(None); - } + }, Visibility::Yes => (), } @@ -768,11 +716,9 @@ impl UnownedWindow { let monitor = video_mode.monitor.as_ref().unwrap(); shared_state_lock.desktop_video_mode = Some(( monitor.id, - self.xconn - .get_crtc_mode(monitor.id) - .expect("Failed to get desktop video mode"), + self.xconn.get_crtc_mode(monitor.id).expect("Failed to get desktop video mode"), )); - } + }, // Restore desktop video mode upon exiting exclusive fullscreen (&Some(Fullscreen::Exclusive(_)), &None) | (&Some(Fullscreen::Exclusive(_)), &Some(Fullscreen::Borderless(_))) => { @@ -780,7 +726,7 @@ impl UnownedWindow { self.xconn .set_crtc_config(monitor_id, mode_id) .expect("failed to restore desktop video mode"); - } + }, _ => (), } @@ -796,18 +742,18 @@ impl UnownedWindow { .expect_then_ignore_error("Failed to restore window position"); } flusher.map(Some) - } + }, Some(fullscreen) => { let (video_mode, monitor) = match fullscreen { Fullscreen::Exclusive(PlatformVideoModeHandle::X(ref video_mode)) => { (Some(video_mode), video_mode.monitor.clone().unwrap()) - } + }, Fullscreen::Borderless(Some(PlatformMonitorHandle::X(monitor))) => { (None, monitor) - } + }, Fullscreen::Borderless(None) => { (None, self.shared_state_lock().last_monitor.clone()) - } + }, #[cfg(wayland_platform)] _ => unreachable!(), }; @@ -854,7 +800,7 @@ impl UnownedWindow { self.set_position_inner(monitor_origin.0, monitor_origin.1) .expect_then_ignore_error("Failed to set window position"); self.set_fullscreen_hint(true).map(Some) - } + }, } } @@ -862,21 +808,15 @@ impl UnownedWindow { pub(crate) fn fullscreen(&self) -> Option { let shared_state = self.shared_state_lock(); - shared_state - .desired_fullscreen - .clone() - .unwrap_or_else(|| shared_state.fullscreen.clone()) + shared_state.desired_fullscreen.clone().unwrap_or_else(|| shared_state.fullscreen.clone()) } #[inline] pub(crate) fn set_fullscreen(&self, fullscreen: Option) { - if let Some(flusher) = self - .set_fullscreen_inner(fullscreen) - .expect("Failed to change window fullscreen state") + if let Some(flusher) = + self.set_fullscreen_inner(fullscreen).expect("Failed to change window fullscreen state") { - flusher - .check() - .expect("Failed to change window fullscreen state"); + flusher.check().expect("Failed to change window fullscreen state"); self.invalidate_cached_frame_extents(); } } @@ -899,7 +839,7 @@ impl UnownedWindow { drop(shared_state); self.set_fullscreen(fullscreen); } - } + }, } } @@ -908,17 +848,11 @@ impl UnownedWindow { } pub fn available_monitors(&self) -> Vec { - self.xconn - .available_monitors() - .expect("Failed to get available monitors") + self.xconn.available_monitors().expect("Failed to get available monitors") } pub fn primary_monitor(&self) -> Option { - Some( - self.xconn - .primary_monitor() - .expect("Failed to get primary monitor"), - ) + Some(self.xconn.primary_monitor().expect("Failed to get primary monitor")) } #[inline] @@ -933,9 +867,9 @@ impl UnownedWindow { let hidden_atom = atoms[_NET_WM_STATE_HIDDEN]; Some(match state { - Ok(atoms) => atoms - .iter() - .any(|atom: &xproto::Atom| *atom as xproto::Atom == hidden_atom), + Ok(atoms) => { + atoms.iter().any(|atom: &xproto::Atom| *atom as xproto::Atom == hidden_atom) + }, _ => false, }) } @@ -1020,9 +954,7 @@ impl UnownedWindow { self.set_minimized_inner(minimized) .expect_then_ignore_error("Failed to change window minimization"); - self.xconn - .flush_requests() - .expect("Failed to change window minimization"); + self.xconn.flush_requests().expect("Failed to change window minimization"); } #[inline] @@ -1041,7 +973,7 @@ impl UnownedWindow { let horz_maximized = atoms.iter().any(|atom: &xproto::Atom| *atom == horz_atom); let vert_maximized = atoms.iter().any(|atom: &xproto::Atom| *atom == vert_atom); horz_maximized && vert_maximized - } + }, _ => false, } } @@ -1058,9 +990,7 @@ impl UnownedWindow { pub fn set_maximized(&self, maximized: bool) { self.set_maximized_inner(maximized) .expect_then_ignore_error("Failed to change window maximization"); - self.xconn - .flush_requests() - .expect("Failed to change window maximization"); + self.xconn.flush_requests().expect("Failed to change window maximization"); self.invalidate_cached_frame_extents(); } @@ -1088,12 +1018,9 @@ impl UnownedWindow { #[inline] pub fn set_title(&self, title: &str) { - self.set_title_inner(title) - .expect_then_ignore_error("Failed to set window title"); + self.set_title_inner(title).expect_then_ignore_error("Failed to set window title"); - self.xconn - .flush_requests() - .expect("Failed to set window title"); + self.xconn.flush_requests().expect("Failed to set window title"); } #[inline] @@ -1115,9 +1042,7 @@ impl UnownedWindow { pub fn set_decorations(&self, decorations: bool) { self.set_decorations_inner(decorations) .expect_then_ignore_error("Failed to set decoration state"); - self.xconn - .flush_requests() - .expect("Failed to set decoration state"); + self.xconn.flush_requests().expect("Failed to set decoration state"); self.invalidate_cached_frame_extents(); } @@ -1141,8 +1066,7 @@ impl UnownedWindow { } fn set_window_level_inner(&self, level: WindowLevel) -> Result, X11Error> { - self.toggle_atom(_NET_WM_STATE_ABOVE, level == WindowLevel::AlwaysOnTop)? - .ignore_error(); + self.toggle_atom(_NET_WM_STATE_ABOVE, level == WindowLevel::AlwaysOnTop)?.ignore_error(); self.toggle_atom(_NET_WM_STATE_BELOW, level == WindowLevel::AlwaysOnBottom) } @@ -1150,9 +1074,7 @@ impl UnownedWindow { pub fn set_window_level(&self, level: WindowLevel) { self.set_window_level_inner(level) .expect_then_ignore_error("Failed to set window-level state"); - self.xconn - .flush_requests() - .expect("Failed to set window-level state"); + self.xconn.flush_requests().expect("Failed to set window-level state"); } fn set_icon_inner(&self, icon: PlatformIcon) -> Result, X11Error> { @@ -1199,7 +1121,7 @@ impl UnownedWindow { match (visible, shared_state.visibility) { (true, Visibility::Yes) | (true, Visibility::YesWait) | (false, Visibility::No) => { return - } + }, _ => (), } @@ -1215,18 +1137,14 @@ impl UnownedWindow { &xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::ABOVE), ) .expect_then_ignore_error("Failed to call `xcb_configure_window`"); - self.xconn - .flush_requests() - .expect("Failed to call XMapRaised"); + self.xconn.flush_requests().expect("Failed to call XMapRaised"); shared_state.visibility = Visibility::YesWait; } else { self.xconn .xcb_connection() .unmap_window(self.xwindow) .expect_then_ignore_error("Failed to call `xcb_unmap_window`"); - self.xconn - .flush_requests() - .expect("Failed to call XUnmapWindow"); + self.xconn.flush_requests().expect("Failed to call XUnmapWindow"); shared_state.visibility = Visibility::No; } } @@ -1237,9 +1155,7 @@ impl UnownedWindow { } fn update_cached_frame_extents(&self) { - let extents = self - .xconn - .get_frame_extents_heuristic(self.xwindow, self.root); + let extents = self.xconn.get_frame_extents_heuristic(self.xwindow, self.root); self.shared_state_lock().frame_extents = Some(extents); } @@ -1309,8 +1225,7 @@ impl UnownedWindow { } pub(crate) fn set_position_physical(&self, x: i32, y: i32) { - self.set_position_inner(x, y) - .expect_then_ignore_error("Failed to call `XMoveWindow`"); + self.set_position_inner(x, y).expect_then_ignore_error("Failed to call `XMoveWindow`"); } #[inline] @@ -1350,14 +1265,10 @@ impl UnownedWindow { .xcb_connection() .configure_window( self.xwindow, - &xproto::ConfigureWindowAux::new() - .width(width) - .height(height), + &xproto::ConfigureWindowAux::new().width(width).height(height), ) .expect_then_ignore_error("Failed to call `xcb_configure_window`"); - self.xconn - .flush_requests() - .expect("Failed to call XResizeWindow"); + self.xconn.flush_requests().expect("Failed to call XResizeWindow"); // cursor_hittest needs to be reapplied after each window resize. if self.shared_state_lock().cursor_hittest.unwrap_or(false) { let _ = self.set_cursor_hittest(true); @@ -1488,19 +1399,17 @@ impl UnownedWindow { pub fn set_resizable(&self, resizable: bool) { if util::wm_name_is_one_of(&["Xfwm4"]) { - // Making the window unresizable on Xfwm prevents further changes to `WM_NORMAL_HINTS` from being detected. - // This makes it impossible for resizing to be re-enabled, and also breaks DPI scaling. As such, we choose - // the lesser of two evils and do nothing. + // Making the window unresizable on Xfwm prevents further changes to `WM_NORMAL_HINTS` + // from being detected. This makes it impossible for resizing to be + // re-enabled, and also breaks DPI scaling. As such, we choose the lesser of + // two evils and do nothing. warn!("To avoid a WM bug, disabling resizing has no effect on Xfwm4"); return; } let (min_size, max_size) = if resizable { let shared_state_lock = self.shared_state_lock(); - ( - shared_state_lock.min_inner_size, - shared_state_lock.max_inner_size, - ) + (shared_state_lock.min_inner_size, shared_state_lock.max_inner_size) } else { let window_size = Some(Size::from(self.inner_size())); (window_size, window_size) @@ -1559,21 +1468,19 @@ impl UnownedWindow { { self.xconn.set_cursor_icon(self.xwindow, Some(icon)); } - } - Cursor::Custom(RootCustomCursor { - inner: PlatformCustomCursor::X(cursor), - }) => { + }, + Cursor::Custom(RootCustomCursor { inner: PlatformCustomCursor::X(cursor) }) => { #[allow(clippy::mutex_atomic)] if *self.cursor_visible.lock().unwrap() { self.xconn.set_custom_cursor(self.xwindow, &cursor); } *self.selected_cursor.lock().unwrap() = SelectedCursor::Custom(cursor); - } + }, #[cfg(wayland_platform)] - Cursor::Custom(RootCustomCursor { - inner: PlatformCustomCursor::Wayland(_), - }) => tracing::error!("passed a Wayland cursor to X11 backend"), + Cursor::Custom(RootCustomCursor { inner: PlatformCustomCursor::Wayland(_) }) => { + tracing::error!("passed a Wayland cursor to X11 backend") + }, } } @@ -1629,23 +1536,23 @@ impl UnownedWindow { xproto::GrabStatus::SUCCESS => Ok(()), xproto::GrabStatus::ALREADY_GRABBED => { Err("Cursor could not be confined: already confined by another client") - } + }, xproto::GrabStatus::INVALID_TIME => { Err("Cursor could not be confined: invalid time") - } + }, xproto::GrabStatus::NOT_VIEWABLE => { Err("Cursor could not be confined: confine location not viewable") - } + }, xproto::GrabStatus::FROZEN => { Err("Cursor could not be confined: frozen by another client") - } + }, _ => unreachable!(), } .map_err(|err| ExternalError::Os(os_error!(OsError::Misc(err)))) - } + }, CursorGrabMode::Locked => { return Err(ExternalError::NotSupported(NotSupportedError::new())); - } + }, }; if result.is_ok() { @@ -1662,23 +1569,20 @@ impl UnownedWindow { if visible == *visible_lock { return; } - let cursor = if visible { - Some((*self.selected_cursor.lock().unwrap()).clone()) - } else { - None - }; + let cursor = + if visible { Some((*self.selected_cursor.lock().unwrap()).clone()) } else { None }; *visible_lock = visible; drop(visible_lock); match cursor { Some(SelectedCursor::Custom(cursor)) => { self.xconn.set_custom_cursor(self.xwindow, &cursor); - } + }, Some(SelectedCursor::Named(cursor)) => { self.xconn.set_cursor_icon(self.xwindow, Some(cursor)); - } + }, None => { self.xconn.set_cursor_icon(self.xwindow, None); - } + }, } } @@ -1831,8 +1735,7 @@ impl UnownedWindow { let state_atom = atoms[WM_STATE]; let state_type_atom = atoms[CARD32]; let is_minimized = if let Ok(state) = - self.xconn - .get_property::(self.xwindow, state_atom, state_type_atom) + self.xconn.get_property::(self.xwindow, state_atom, state_type_atom) { state.contains(&super::ICONIC_STATE) } else { @@ -1915,9 +1818,7 @@ impl UnownedWindow { #[inline] pub fn request_redraw(&self) { - self.redraw_sender - .send(WindowId(self.xwindow as _)) - .unwrap(); + self.redraw_sender.send(WindowId(self.xwindow as _)).unwrap(); } #[inline] @@ -2001,10 +1902,7 @@ fn cast_dimension_to_hint(val: u32) -> i32 { /// Use the above strategy to cast a physical size into a hinted size. fn cast_physical_size_to_hint(size: PhysicalSize) -> (i32, i32) { let PhysicalSize { width, height } = size; - ( - cast_dimension_to_hint(width), - cast_dimension_to_hint(height), - ) + (cast_dimension_to_hint(width), cast_dimension_to_hint(height)) } /// Use the above strategy to cast a size into a hinted size. diff --git a/src/platform_impl/linux/x11/xdisplay.rs b/src/platform_impl/linux/x11/xdisplay.rs index dd46cbee1e..0a56f290a4 100644 --- a/src/platform_impl/linux/x11/xdisplay.rs +++ b/src/platform_impl/linux/x11/xdisplay.rs @@ -1,25 +1,19 @@ -use std::{ - collections::HashMap, - error::Error, - fmt, ptr, - sync::{ - atomic::{AtomicU32, Ordering}, - Arc, Mutex, RwLock, RwLockReadGuard, - }, -}; +use std::collections::HashMap; +use std::error::Error; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard}; +use std::{fmt, ptr}; use crate::window::CursorIcon; -use super::{atoms::Atoms, ffi, monitor::MonitorHandle}; -use x11rb::{ - connection::Connection, - protocol::{ - randr::ConnectionExt as _, - xproto::{self, ConnectionExt}, - }, - resource_manager, - xcb_ffi::XCBConnection, -}; +use super::atoms::Atoms; +use super::ffi; +use super::monitor::MonitorHandle; +use x11rb::connection::Connection; +use x11rb::protocol::randr::ConnectionExt as _; +use x11rb::protocol::xproto::{self, ConnectionExt}; +use x11rb::resource_manager; +use x11rb::xcb_ffi::XCBConnection; /// A connection to an X server. pub struct XConnection { @@ -158,14 +152,9 @@ impl XConnection { .atom; // Get PropertyNotify events from the XSETTINGS window. - // TODO: The XSETTINGS window here can change. In the future, listen for DestroyNotify on this window - // in order to accommodate for a changed window here. - let selector_window = xcb - .get_selection_owner(xsettings_screen) - .ok()? - .reply() - .ok()? - .owner; + // TODO: The XSETTINGS window here can change. In the future, listen for DestroyNotify on + // this window in order to accommodate for a changed window here. + let selector_window = xcb.get_selection_owner(xsettings_screen).ok()?.reply().ok()?.owner; xcb.change_window_attributes( selector_window, @@ -198,9 +187,7 @@ impl XConnection { /// Get the underlying XCB connection. #[inline] pub fn xcb_connection(&self) -> &XCBConnection { - self.xcb - .as_ref() - .expect("xcb_connection somehow called after drop?") + self.xcb.as_ref().expect("xcb_connection somehow called after drop?") } /// Get the list of atoms. diff --git a/src/platform_impl/linux/x11/xsettings.rs b/src/platform_impl/linux/x11/xsettings.rs index c2d26bdda1..dd5b074f76 100644 --- a/src/platform_impl/linux/x11/xsettings.rs +++ b/src/platform_impl/linux/x11/xsettings.rs @@ -9,7 +9,8 @@ use std::num::NonZeroUsize; use x11rb::protocol::xproto::{self, ConnectionExt}; -use super::{atoms::*, XConnection}; +use super::atoms::*; +use super::XConnection; type Result = core::result::Result; @@ -27,17 +28,11 @@ impl XConnection { let atoms = self.atoms(); // Get the current owner of the screen's settings. - let owner = self - .xcb_connection() - .get_selection_owner(xsettings_screen)? - .reply()?; + let owner = self.xcb_connection().get_selection_owner(xsettings_screen)?.reply()?; // Read the _XSETTINGS_SETTINGS property. - let data: Vec = self.get_property( - owner.owner, - atoms[_XSETTINGS_SETTINGS], - atoms[_XSETTINGS_SETTINGS], - )?; + let data: Vec = + self.get_property(owner.owner, atoms[_XSETTINGS_SETTINGS], atoms[_XSETTINGS_SETTINGS])?; // Parse the property. let dpi_setting = read_settings(&data)? @@ -48,10 +43,10 @@ impl XConnection { SettingData::Integer(dpi) => dpi as f64, SettingData::String(_) => { return Err(ParserError::BadType(SettingType::String).into()) - } + }, SettingData::Color(_) => { return Err(ParserError::BadType(SettingType::Color).into()) - } + }, }; Ok(Some(base_dpi / DPI_MULTIPLIER)) @@ -111,7 +106,7 @@ impl<'a> Setting<'a> { SettingType::Integer => { // Read a 32-bit integer. SettingData::Integer(parser.i32()?) - } + }, SettingType::String => { // Read the data. @@ -120,7 +115,7 @@ impl<'a> Setting<'a> { parser.pad(data.len(), 4)?; SettingData::String(data) - } + }, SettingType::Color => { // Read i16's of color. @@ -128,7 +123,7 @@ impl<'a> Setting<'a> { (parser.i16()?, parser.i16()?, parser.i16()?, parser.i16()?); SettingData::Color([red, blue, green, alpha]) - } + }, }; Ok(Setting { name, data }) @@ -164,9 +159,7 @@ struct Parser<'a> { impl<'a> Parser<'a> { /// Create a new parser. fn new(bytes: &'a [u8]) -> Result { - let (endianness, bytes) = bytes - .split_first() - .ok_or_else(|| ParserError::ran_out(1, 0))?; + let (endianness, bytes) = bytes.split_first().ok_or_else(|| ParserError::ran_out(1, 0))?; let endianness = match *endianness { BIG_ENDIAN => Endianness::Big, LITTLE_ENDIAN => Endianness::Little, @@ -175,9 +168,7 @@ impl<'a> Parser<'a> { Ok(Self { // Ignore three bytes of padding and the four-byte serial. - bytes: bytes - .get(7..) - .ok_or_else(|| ParserError::ran_out(7, bytes.len()))?, + bytes: bytes.get(7..).ok_or_else(|| ParserError::ran_out(7, bytes.len()))?, endianness, }) } @@ -255,10 +246,7 @@ impl Endianness { #[derive(Debug)] pub enum ParserError { /// Ran out of bytes. - NoMoreBytes { - expected: NonZeroUsize, - found: usize, - }, + NoMoreBytes { expected: NonZeroUsize, found: usize }, /// Invalid type. InvalidType(i8), @@ -291,7 +279,7 @@ mod tests { ParserError::NoMoreBytes { expected, found } => { assert_eq!(expected.get(), 1); assert_eq!(found, 0); - } + }, _ => panic!(), } @@ -308,10 +296,7 @@ mod tests { }) .collect::>(); - let settings = read_settings(&data) - .unwrap() - .collect::>>() - .unwrap(); + let settings = read_settings(&data).unwrap().collect::>>().unwrap(); let dpi = settings.iter().find(|s| s.name == b"Xft/DPI").unwrap(); assert_int(&dpi.data, 96 * 1024); @@ -320,10 +305,7 @@ mod tests { let rgba = settings.iter().find(|s| s.name == b"Xft/RGBA").unwrap(); assert_string(&rgba.data, "rgb"); - let lcd = settings - .iter() - .find(|s| s.name == b"Xft/Lcdfilter") - .unwrap(); + let lcd = settings.iter().find(|s| s.name == b"Xft/Lcdfilter").unwrap(); assert_string(&lcd.data, "lcddefault"); } diff --git a/src/platform_impl/macos/app.rs b/src/platform_impl/macos/app.rs index a97ae57d73..f3544dd2ed 100644 --- a/src/platform_impl/macos/app.rs +++ b/src/platform_impl/macos/app.rs @@ -58,37 +58,29 @@ fn maybe_dispatch_device_event(delegate: &ApplicationDelegate, event: &NSEvent) let delta_y = unsafe { event.deltaY() } as f64; if delta_x != 0.0 { - delegate.queue_device_event(DeviceEvent::Motion { - axis: 0, - value: delta_x, - }); + delegate.queue_device_event(DeviceEvent::Motion { axis: 0, value: delta_x }); } if delta_y != 0.0 { - delegate.queue_device_event(DeviceEvent::Motion { - axis: 1, - value: delta_y, - }) + delegate.queue_device_event(DeviceEvent::Motion { axis: 1, value: delta_y }) } if delta_x != 0.0 || delta_y != 0.0 { - delegate.queue_device_event(DeviceEvent::MouseMotion { - delta: (delta_x, delta_y), - }); + delegate.queue_device_event(DeviceEvent::MouseMotion { delta: (delta_x, delta_y) }); } - } + }, NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => { delegate.queue_device_event(DeviceEvent::Button { button: unsafe { event.buttonNumber() } as u32, state: ElementState::Pressed, }); - } + }, NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => { delegate.queue_device_event(DeviceEvent::Button { button: unsafe { event.buttonNumber() } as u32, state: ElementState::Released, }); - } + }, _ => (), } } diff --git a/src/platform_impl/macos/app_delegate.rs b/src/platform_impl/macos/app_delegate.rs index 0c396fec13..ffb25abcaf 100644 --- a/src/platform_impl/macos/app_delegate.rs +++ b/src/platform_impl/macos/app_delegate.rs @@ -240,10 +240,7 @@ impl ApplicationDelegate { } pub fn queue_device_event(&self, event: DeviceEvent) { - self.ivars() - .pending_events - .borrow_mut() - .push_back(QueuedEvent::DeviceEvent(event)); + self.ivars().pending_events.borrow_mut().push_back(QueuedEvent::DeviceEvent(event)); } pub fn queue_static_scale_factor_changed_event( @@ -252,14 +249,11 @@ impl ApplicationDelegate { suggested_size: PhysicalSize, scale_factor: f64, ) { - self.ivars() - .pending_events - .borrow_mut() - .push_back(QueuedEvent::ScaleFactorChanged { - window, - suggested_size, - scale_factor, - }); + self.ivars().pending_events.borrow_mut().push_back(QueuedEvent::ScaleFactorChanged { + window, + suggested_size, + scale_factor, + }); } pub fn handle_redraw(&self, window_id: WindowId) { @@ -272,8 +266,9 @@ impl ApplicationDelegate { event: WindowEvent::RedrawRequested, }); - // `pump_events` will request to stop immediately _after_ dispatching RedrawRequested events - // as a way to ensure that `pump_events` can't block an external loop indefinitely + // `pump_events` will request to stop immediately _after_ dispatching RedrawRequested + // events as a way to ensure that `pump_events` can't block an external loop + // indefinitely if self.ivars().stop_on_redraw.get() { let app = NSApplication::sharedApplication(mtm); stop_app_immediately(&app); @@ -290,9 +285,7 @@ impl ApplicationDelegate { } fn handle_event(&self, event: Event) { - self.ivars() - .event_handler - .handle_event(event, &ActiveEventLoop::new_root(self.retain())) + self.ivars().event_handler.handle_event(event, &ActiveEventLoop::new_root(self.retain())) } /// dispatch `NewEvents(Init)` + `Resumed` @@ -323,23 +316,14 @@ impl ApplicationDelegate { let start = self.ivars().start_time.get().unwrap(); let cause = match self.control_flow() { ControlFlow::Poll => StartCause::Poll, - ControlFlow::Wait => StartCause::WaitCancelled { - start, - requested_resume: None, - }, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, ControlFlow::WaitUntil(requested_resume) => { if Instant::now() >= requested_resume { - StartCause::ResumeTimeReached { - start, - requested_resume, - } + StartCause::ResumeTimeReached { start, requested_resume } } else { - StartCause::WaitCancelled { - start, - requested_resume: Some(requested_resume), - } + StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) } } - } + }, }; self.handle_event(Event::NewEvents(cause)); @@ -369,18 +353,11 @@ impl ApplicationDelegate { window_id: RootWindowId(window_id), event, }); - } + }, QueuedEvent::DeviceEvent(event) => { - self.handle_event(Event::DeviceEvent { - device_id: DEVICE_ID, - event, - }); - } - QueuedEvent::ScaleFactorChanged { - window, - suggested_size, - scale_factor, - } => { + self.handle_event(Event::DeviceEvent { device_id: DEVICE_ID, event }); + }, + QueuedEvent::ScaleFactorChanged { window, suggested_size, scale_factor } => { let new_inner_size = Arc::new(Mutex::new(suggested_size)); let scale_factor_changed_event = Event::WindowEvent { window_id: RootWindowId(window.id()), @@ -405,7 +382,7 @@ impl ApplicationDelegate { event: WindowEvent::Resized(physical_size), }; self.handle_event(resized_event); - } + }, } } @@ -435,10 +412,7 @@ impl ApplicationDelegate { ControlFlow::Poll => Some(Instant::now()), ControlFlow::WaitUntil(instant) => Some(instant), }; - self.ivars() - .waker - .borrow_mut() - .start_at(min_timeout(wait_timeout, app_timeout)); + self.ivars().waker.borrow_mut().start_at(min_timeout(wait_timeout, app_timeout)); } } @@ -460,9 +434,7 @@ pub(crate) struct HandlePendingUserEvents; /// equates to an infinite timeout, not a zero timeout (so can't just use /// `Option::min`) fn min_timeout(a: Option, b: Option) -> Option { - a.map_or(b, |a_timeout| { - b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))) - }) + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) } /// A hack to make activation of multiple windows work when creating them before diff --git a/src/platform_impl/macos/cursor.rs b/src/platform_impl/macos/cursor.rs index 6d06393d06..4084be122e 100644 --- a/src/platform_impl/macos/cursor.rs +++ b/src/platform_impl/macos/cursor.rs @@ -11,8 +11,7 @@ use objc2_foundation::{ NSString, }; -use crate::cursor::CursorImage; -use crate::cursor::OnlyCursorImageSource; +use crate::cursor::{CursorImage, OnlyCursorImageSource}; use crate::window::CursorIcon; #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -118,7 +117,10 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Id { // cursors, and will seem completely standard to macOS users. // // https://stackoverflow.com/a/21786835/5435443 - let root = ns_string!("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors"); + let root = ns_string!( + "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/\ + HIServices.framework/Versions/A/Resources/cursors" + ); let cursor_path = root.stringByAppendingPathComponent(name); let pdf_path = cursor_path.stringByAppendingPathComponent(ns_string!("cursor.pdf")); @@ -166,10 +168,10 @@ pub(crate) fn invisible_cursor() -> Id { // You can reproduce this via ImageMagick. // $ convert -size 16x16 xc:none cursor.gif static CURSOR_BYTES: &[u8] = &[ - 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, - 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0E, 0x84, 0x8F, 0xA9, 0xCB, 0xED, 0x0F, - 0xA3, 0x9C, 0xB4, 0xDA, 0x8B, 0xB3, 0x3E, 0x05, 0x00, 0x3B, + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0e, 0x84, 0x8f, 0xa9, 0xcb, 0xed, 0x0f, + 0xa3, 0x9c, 0xb4, 0xda, 0x8b, 0xb3, 0x3e, 0x05, 0x00, 0x3b, ]; fn new_invisible() -> Id { @@ -182,10 +184,7 @@ pub(crate) fn invisible_cursor() -> Id { // Cache this for efficiency static CURSOR: OnceLock = OnceLock::new(); - CURSOR - .get_or_init(|| CustomCursor(new_invisible())) - .0 - .clone() + CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone() } pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Id { diff --git a/src/platform_impl/macos/event.rs b/src/platform_impl/macos/event.rs index d83d2ca7d0..a22cccc81d 100644 --- a/src/platform_impl/macos/event.rs +++ b/src/platform_impl/macos/event.rs @@ -1,22 +1,18 @@ use std::ffi::c_void; -use core_foundation::{ - base::CFRelease, - data::{CFDataGetBytePtr, CFDataRef}, -}; +use core_foundation::base::CFRelease; +use core_foundation::data::{CFDataGetBytePtr, CFDataRef}; use objc2::rc::Id; use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventSubtype, NSEventType}; use objc2_foundation::{run_on_main, NSPoint}; use smol_str::SmolStr; -use crate::{ - event::{ElementState, KeyEvent, Modifiers}, - keyboard::{ - Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, - NativeKeyCode, PhysicalKey, - }, - platform_impl::platform::ffi, +use crate::event::{ElementState, KeyEvent, Modifiers}; +use crate::keyboard::{ + Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, + PhysicalKey, }; +use crate::platform_impl::platform::ffi; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct KeyEventExtra { @@ -67,10 +63,7 @@ pub fn get_modifierless_char(scancode: u16) -> Key { CFRelease(input_source as *mut c_void); } if translate_result != 0 { - tracing::error!( - "`UCKeyTranslate` returned with the non-zero value: {}", - translate_result - ); + tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result); return Key::Unidentified(NativeKey::MacOS(scancode)); } if result_len == 0 { @@ -121,9 +114,8 @@ pub(crate) fn create_key_event( let text_with_all_modifiers: Option = if key_override.is_some() { None } else { - let characters = unsafe { ns_event.characters() } - .map(|s| s.to_string()) - .unwrap_or_default(); + let characters = + unsafe { ns_event.characters() }.map(|s| s.to_string()).unwrap_or_default(); if characters.is_empty() { None } else { @@ -153,7 +145,7 @@ pub(crate) fn create_key_event( Some(text) if !has_ctrl && !has_cmd => { // Character heeding both SHIFT and ALT. Key::Character(text.clone()) - } + }, _ => match key_without_modifiers.as_ref() { // Character heeding just SHIFT, ignoring ALT. @@ -169,11 +161,7 @@ pub(crate) fn create_key_event( (key_from_code.clone(), key_from_code) }; - let text = if is_press { - logical_key.to_text().map(SmolStr::new) - } else { - None - }; + let text = if is_press { logical_key.to_text().map(SmolStr::new) } else { None }; let location = code_to_location(physical_key); @@ -184,10 +172,7 @@ pub(crate) fn create_key_event( repeat: is_repeat, state, text, - platform_specific: KeyEventExtra { - text_with_all_modifiers, - key_without_modifiers, - }, + platform_specific: KeyEventExtra { text_with_all_modifiers, key_without_modifiers }, } } @@ -341,58 +326,31 @@ pub(super) fn event_mods(event: &NSEvent) -> Modifiers { ModifiersState::SHIFT, flags_contains(flags, NSEventModifierFlags::NSEventModifierFlagShift), ); - pressed_mods.set( - ModifiersKeys::LSHIFT, - flags_contains(flags, NX_DEVICELSHIFTKEYMASK), - ); - pressed_mods.set( - ModifiersKeys::RSHIFT, - flags_contains(flags, NX_DEVICERSHIFTKEYMASK), - ); + pressed_mods.set(ModifiersKeys::LSHIFT, flags_contains(flags, NX_DEVICELSHIFTKEYMASK)); + pressed_mods.set(ModifiersKeys::RSHIFT, flags_contains(flags, NX_DEVICERSHIFTKEYMASK)); state.set( ModifiersState::CONTROL, flags_contains(flags, NSEventModifierFlags::NSEventModifierFlagControl), ); - pressed_mods.set( - ModifiersKeys::LCONTROL, - flags_contains(flags, NX_DEVICELCTLKEYMASK), - ); - pressed_mods.set( - ModifiersKeys::RCONTROL, - flags_contains(flags, NX_DEVICERCTLKEYMASK), - ); + pressed_mods.set(ModifiersKeys::LCONTROL, flags_contains(flags, NX_DEVICELCTLKEYMASK)); + pressed_mods.set(ModifiersKeys::RCONTROL, flags_contains(flags, NX_DEVICERCTLKEYMASK)); state.set( ModifiersState::ALT, flags_contains(flags, NSEventModifierFlags::NSEventModifierFlagOption), ); - pressed_mods.set( - ModifiersKeys::LALT, - flags_contains(flags, NX_DEVICELALTKEYMASK), - ); - pressed_mods.set( - ModifiersKeys::RALT, - flags_contains(flags, NX_DEVICERALTKEYMASK), - ); + pressed_mods.set(ModifiersKeys::LALT, flags_contains(flags, NX_DEVICELALTKEYMASK)); + pressed_mods.set(ModifiersKeys::RALT, flags_contains(flags, NX_DEVICERALTKEYMASK)); state.set( ModifiersState::SUPER, flags_contains(flags, NSEventModifierFlags::NSEventModifierFlagCommand), ); - pressed_mods.set( - ModifiersKeys::LSUPER, - flags_contains(flags, NX_DEVICELCMDKEYMASK), - ); - pressed_mods.set( - ModifiersKeys::RSUPER, - flags_contains(flags, NX_DEVICERCMDKEYMASK), - ); + pressed_mods.set(ModifiersKeys::LSUPER, flags_contains(flags, NX_DEVICELCMDKEYMASK)); + pressed_mods.set(ModifiersKeys::RSUPER, flags_contains(flags, NX_DEVICERCMDKEYMASK)); - Modifiers { - state, - pressed_mods, - } + Modifiers { state, pressed_mods } } pub(super) fn dummy_event() -> Option> { @@ -545,7 +503,7 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x07 => KeyCode::KeyX, 0x08 => KeyCode::KeyC, 0x09 => KeyCode::KeyV, - //0x0a => World 1, + // 0x0a => World 1, 0x0b => KeyCode::KeyB, 0x0c => KeyCode::KeyQ, 0x0d => KeyCode::KeyW, @@ -587,7 +545,7 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x31 => KeyCode::Space, 0x32 => KeyCode::Backquote, 0x33 => KeyCode::Backspace, - //0x34 => unknown, + // 0x34 => unknown, 0x35 => KeyCode::Escape, 0x36 => KeyCode::SuperRight, 0x37 => KeyCode::SuperLeft, @@ -601,22 +559,23 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x3f => KeyCode::Fn, 0x40 => KeyCode::F17, 0x41 => KeyCode::NumpadDecimal, - //0x42 -> unknown, + // 0x42 -> unknown, 0x43 => KeyCode::NumpadMultiply, - //0x44 => unknown, + // 0x44 => unknown, 0x45 => KeyCode::NumpadAdd, - //0x46 => unknown, + // 0x46 => unknown, 0x47 => KeyCode::NumLock, - //0x48 => KeyCode::NumpadClear, + // 0x48 => KeyCode::NumpadClear, // TODO: (Artur) for me, kVK_VolumeUp is 0x48 // macOS 10.11 - // /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h + // /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/ + // Versions/A/Headers/Events.h 0x49 => KeyCode::AudioVolumeUp, 0x4a => KeyCode::AudioVolumeDown, 0x4b => KeyCode::NumpadDivide, 0x4c => KeyCode::NumpadEnter, - //0x4d => unknown, + // 0x4d => unknown, 0x4e => KeyCode::NumpadSubtract, 0x4f => KeyCode::F18, 0x50 => KeyCode::F19, @@ -633,25 +592,25 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x5b => KeyCode::Numpad8, 0x5c => KeyCode::Numpad9, 0x5d => KeyCode::IntlYen, - //0x5e => JIS Ro, - //0x5f => unknown, + // 0x5e => JIS Ro, + // 0x5f => unknown, 0x60 => KeyCode::F5, 0x61 => KeyCode::F6, 0x62 => KeyCode::F7, 0x63 => KeyCode::F3, 0x64 => KeyCode::F8, 0x65 => KeyCode::F9, - //0x66 => JIS Eisuu (macOS), + // 0x66 => JIS Eisuu (macOS), 0x67 => KeyCode::F11, - //0x68 => JIS Kanna (macOS), + // 0x68 => JIS Kanna (macOS), 0x69 => KeyCode::F13, 0x6a => KeyCode::F16, 0x6b => KeyCode::F14, - //0x6c => unknown, + // 0x6c => unknown, 0x6d => KeyCode::F10, - //0x6e => unknown, + // 0x6e => unknown, 0x6f => KeyCode::F12, - //0x70 => unknown, + // 0x70 => unknown, 0x71 => KeyCode::F15, 0x72 => KeyCode::Insert, 0x73 => KeyCode::Home, @@ -666,7 +625,7 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x7c => KeyCode::ArrowRight, 0x7d => KeyCode::ArrowDown, 0x7e => KeyCode::ArrowUp, - //0x7f => unknown, + // 0x7f => unknown, // 0xA is the caret (^) an macOS's German QERTZ layout. This key is at the same location as // backquote (`) on Windows' US layout. diff --git a/src/platform_impl/macos/event_handler.rs b/src/platform_impl/macos/event_handler.rs index c690dc197b..dbd89d7e83 100644 --- a/src/platform_impl/macos/event_handler.rs +++ b/src/platform_impl/macos/event_handler.rs @@ -1,6 +1,5 @@ use std::cell::RefCell; -use std::fmt; -use std::mem; +use std::{fmt, mem}; use super::app_delegate::HandlePendingUserEvents; use crate::event::Event; @@ -53,13 +52,13 @@ impl EventHandler { match self.inner.try_borrow_mut().as_deref_mut() { Ok(Some(_)) => { unreachable!("tried to set handler while another was already set"); - } + }, Ok(data @ None) => { *data = Some(EventHandlerData { handler }); - } + }, Err(_) => { unreachable!("tried to set handler that is currently in use"); - } + }, } struct ClearOnDrop<'a>(&'a EventHandler); @@ -69,10 +68,10 @@ impl EventHandler { match self.0.inner.try_borrow_mut().as_deref_mut() { Ok(data @ Some(_)) => { *data = None; - } + }, Ok(None) => { tracing::error!("tried to clear handler, but no handler was set"); - } + }, Err(_) => { // Note: This is not expected to ever happen, this // module generally controls the `RefCell`, and @@ -83,7 +82,7 @@ impl EventHandler { // weren't able to unset the handler. eprintln!("tried to clear handler that is currently in use"); std::process::abort(); - } + }, } } } @@ -120,17 +119,17 @@ impl EventHandler { // If the handler unwinds, the `RefMut` will ensure that the // handler is no longer borrowed. (handler)(event, event_loop); - } + }, Ok(None) => { // `NSApplication`, our app delegate and this handler are all // global state and so it's not impossible that we could get // an event after the application has exited the `EventLoop`. tracing::error!("tried to run event handler, but no handler was set"); - } + }, Err(_) => { // Prevent re-entrancy. panic!("tried to handle event while another event is currently being handled"); - } + }, } } } diff --git a/src/platform_impl/macos/event_loop.rs b/src/platform_impl/macos/event_loop.rs index 56f802d524..6b4f8369c0 100644 --- a/src/platform_impl/macos/event_loop.rs +++ b/src/platform_impl/macos/event_loop.rs @@ -1,44 +1,39 @@ -use std::{ - any::Any, - cell::Cell, - collections::VecDeque, - marker::PhantomData, - os::raw::c_void, - panic::{catch_unwind, resume_unwind, RefUnwindSafe, UnwindSafe}, - ptr, - rc::{Rc, Weak}, - sync::mpsc, - time::{Duration, Instant}, -}; +use std::any::Any; +use std::cell::Cell; +use std::collections::VecDeque; +use std::marker::PhantomData; +use std::os::raw::c_void; +use std::panic::{catch_unwind, resume_unwind, RefUnwindSafe, UnwindSafe}; +use std::ptr; +use std::rc::{Rc, Weak}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; use core_foundation::base::{CFIndex, CFRelease}; use core_foundation::runloop::{ kCFRunLoopCommonModes, CFRunLoopAddSource, CFRunLoopGetMain, CFRunLoopSourceContext, CFRunLoopSourceCreate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp, }; +use objc2::rc::{autoreleasepool, Id}; +use objc2::runtime::ProtocolObject; use objc2::{msg_send_id, ClassType}; -use objc2::{ - rc::{autoreleasepool, Id}, - runtime::ProtocolObject, -}; use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSWindow}; use objc2_foundation::{MainThreadMarker, NSObjectProtocol}; +use super::app::WinitApplication; +use super::app_delegate::{ApplicationDelegate, HandlePendingUserEvents}; use super::event::dummy_event; -use super::{ - app::WinitApplication, - app_delegate::{ApplicationDelegate, HandlePendingUserEvents}, - monitor::{self, MonitorHandle}, - observer::setup_control_flow_observers, +use super::monitor::{self, MonitorHandle}; +use super::observer::setup_control_flow_observers; +use crate::error::EventLoopError; +use crate::event::Event; +use crate::event_loop::{ + ActiveEventLoop as RootWindowTarget, ControlFlow, DeviceEvents, EventLoopClosed, }; +use crate::platform::macos::ActivationPolicy; +use crate::platform::pump_events::PumpStatus; use crate::platform_impl::platform::cursor::CustomCursor; use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource}; -use crate::{ - error::EventLoopError, - event::Event, - event_loop::{ActiveEventLoop as RootWindowTarget, ControlFlow, DeviceEvents, EventLoopClosed}, - platform::{macos::ActivationPolicy, pump_events::PumpStatus}, -}; #[derive(Default)] pub struct PanicInfo { @@ -57,12 +52,14 @@ impl PanicInfo { self.inner.set(inner); result } + /// Overwrites the curret state if the current state is not panicking pub fn set_panic(&self, p: Box) { if !self.is_panicking() { self.inner.set(Some(p)); } } + pub fn take(&self) -> Option> { self.inner.take() } @@ -78,16 +75,11 @@ impl ActiveEventLoop { pub(super) fn new_root(delegate: Id) -> RootWindowTarget { let mtm = MainThreadMarker::from(&*delegate); let p = Self { delegate, mtm }; - RootWindowTarget { - p, - _marker: PhantomData, - } + RootWindowTarget { p, _marker: PhantomData } } pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { - RootCustomCursor { - inner: CustomCursor::new(source.inner), - } + RootCustomCursor { inner: CustomCursor::new(source.inner) } } #[inline] @@ -115,9 +107,7 @@ impl ActiveEventLoop { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::AppKit( - rwh_06::AppKitDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new())) } pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { @@ -173,7 +163,7 @@ fn map_user_event( for event in receiver.try_iter() { (handler)(Event::UserEvent(event), window_target); } - } + }, } } @@ -225,7 +215,10 @@ impl EventLoop { unsafe { msg_send_id![WinitApplication::class(), sharedApplication] }; if !app.is_kind_of::() { - panic!("`winit` requires control over the principal class. You must create the event loop before other parts of your application initialize NSApplication"); + panic!( + "`winit` requires control over the principal class. You must create the event \ + loop before other parts of your application initialize NSApplication" + ); } let activation_policy = match attributes.activation_policy { @@ -323,8 +316,8 @@ impl EventLoop { self.delegate.set_event_handler(handler, || { autoreleasepool(|_| { - // As a special case, if the application hasn't been launched yet then we at least run - // the loop until it has fully launched. + // As a special case, if the application hasn't been launched yet then we at least + // run the loop until it has fully launched. if !self.delegate.is_launched() { debug_assert!(!self.delegate.is_running()); @@ -332,31 +325,34 @@ impl EventLoop { // SAFETY: We do not run the application re-entrantly unsafe { self.app.run() }; - // Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application has launched + // Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application + // has launched } else if !self.delegate.is_running() { - // Even though the application may have been launched, it's possible we aren't running - // if the `EventLoop` was run before and has since exited. This indicates that - // we just starting to re-run the same `EventLoop` again. + // Even though the application may have been launched, it's possible we aren't + // running if the `EventLoop` was run before and has since + // exited. This indicates that we just starting to re-run + // the same `EventLoop` again. self.delegate.set_is_running(true); self.delegate.dispatch_init_events(); } else { - // Only run for as long as the given `Duration` allows so we don't block the external loop. + // Only run for as long as the given `Duration` allows so we don't block the + // external loop. match timeout { Some(Duration::ZERO) => { self.delegate.set_wait_timeout(None); self.delegate.set_stop_before_wait(true); - } + }, Some(duration) => { self.delegate.set_stop_before_wait(false); let timeout = Instant::now() + duration; self.delegate.set_wait_timeout(Some(timeout)); self.delegate.set_stop_after_wait(true); - } + }, None => { self.delegate.set_wait_timeout(None); self.delegate.set_stop_before_wait(false); self.delegate.set_stop_after_wait(true); - } + }, } self.delegate.set_stop_on_redraw(true); // SAFETY: We do not run the application re-entrantly @@ -437,7 +433,7 @@ pub fn stop_app_on_panic R + UnwindSafe, R>( let app = NSApplication::sharedApplication(mtm); stop_app_immediately(&app); None - } + }, } } @@ -494,9 +490,7 @@ impl EventLoopProxy { } pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { - self.sender - .send(event) - .map_err(|mpsc::SendError(x)| EventLoopClosed(x))?; + self.sender.send(event).map_err(|mpsc::SendError(x)| EventLoopClosed(x))?; unsafe { // let the main thread know there's a new event CFRunLoopSourceSignal(self.source); diff --git a/src/platform_impl/macos/ffi.rs b/src/platform_impl/macos/ffi.rs index fed212ca4e..92d4874e4b 100644 --- a/src/platform_impl/macos/ffi.rs +++ b/src/platform_impl/macos/ffi.rs @@ -4,14 +4,14 @@ use std::ffi::c_void; -use core_foundation::{ - array::CFArrayRef, dictionary::CFDictionaryRef, string::CFStringRef, uuid::CFUUIDRef, -}; -use core_graphics::{ - base::CGError, - display::{CGDirectDisplayID, CGDisplayConfigRef}, -}; -use objc2::{ffi::NSInteger, runtime::AnyObject}; +use core_foundation::array::CFArrayRef; +use core_foundation::dictionary::CFDictionaryRef; +use core_foundation::string::CFStringRef; +use core_foundation::uuid::CFUUIDRef; +use core_graphics::base::CGError; +use core_graphics::display::{CGDirectDisplayID, CGDisplayConfigRef}; +use objc2::ffi::NSInteger; +use objc2::runtime::AnyObject; pub type CGDisplayFadeInterval = f32; pub type CGDisplayReservationInterval = f32; diff --git a/src/platform_impl/macos/menu.rs b/src/platform_impl/macos/menu.rs index 319047331d..6f93bfd963 100644 --- a/src/platform_impl/macos/menu.rs +++ b/src/platform_impl/macos/menu.rs @@ -20,12 +20,8 @@ pub fn initialize(app: &NSApplication) { // About menu item let about_item_title = ns_string!("About ").stringByAppendingString(&process_name); - let about_item = menu_item( - mtm, - &about_item_title, - Some(sel!(orderFrontStandardAboutPanel:)), - None, - ); + let about_item = + menu_item(mtm, &about_item_title, Some(sel!(orderFrontStandardAboutPanel:)), None); // Services menu item let services_menu = NSMenu::new(mtm); @@ -41,10 +37,7 @@ pub fn initialize(app: &NSApplication) { mtm, &hide_item_title, Some(sel!(hide:)), - Some(KeyEquivalent { - key: ns_string!("h"), - masks: None, - }), + Some(KeyEquivalent { key: ns_string!("h"), masks: None }), ); // Hide other applications menu item @@ -64,12 +57,8 @@ pub fn initialize(app: &NSApplication) { // Show applications menu item let show_all_item_title = ns_string!("Show All"); - let show_all_item = menu_item( - mtm, - show_all_item_title, - Some(sel!(unhideAllApplications:)), - None, - ); + let show_all_item = + menu_item(mtm, show_all_item_title, Some(sel!(unhideAllApplications:)), None); // Separator menu item let sep = NSMenuItem::separatorItem(mtm); @@ -80,10 +69,7 @@ pub fn initialize(app: &NSApplication) { mtm, &quit_item_title, Some(sel!(terminate:)), - Some(KeyEquivalent { - key: ns_string!("q"), - masks: None, - }), + Some(KeyEquivalent { key: ns_string!("q"), masks: None }), ); app_menu.addItem(&about_item); diff --git a/src/platform_impl/macos/mod.rs b/src/platform_impl/macos/mod.rs index 2d0d306e7f..3049c9c863 100644 --- a/src/platform_impl/macos/mod.rs +++ b/src/platform_impl/macos/mod.rs @@ -17,16 +17,14 @@ mod window_delegate; use std::fmt; -pub(crate) use self::{ - event::{physicalkey_to_scancode, scancode_to_physicalkey, KeyEventExtra}, - event_loop::{ - ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, - PlatformSpecificEventLoopAttributes, - }, - monitor::{MonitorHandle, VideoModeHandle}, - window::WindowId, - window_delegate::PlatformSpecificWindowAttributes, +pub(crate) use self::event::{physicalkey_to_scancode, scancode_to_physicalkey, KeyEventExtra}; +pub(crate) use self::event_loop::{ + ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, + PlatformSpecificEventLoopAttributes, }; +pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle}; +pub(crate) use self::window::WindowId; +pub(crate) use self::window_delegate::PlatformSpecificWindowAttributes; use crate::event::DeviceId as RootDeviceId; pub(crate) use self::cursor::CustomCursor as PlatformCustomCursor; diff --git a/src/platform_impl/macos/monitor.rs b/src/platform_impl/macos/monitor.rs index a47ba6674d..6229e5070d 100644 --- a/src/platform_impl/macos/monitor.rs +++ b/src/platform_impl/macos/monitor.rs @@ -1,16 +1,16 @@ #![allow(clippy::unnecessary_cast)] -use std::{collections::VecDeque, fmt}; +use std::collections::VecDeque; +use std::fmt; -use core_foundation::{ - array::{CFArrayGetCount, CFArrayGetValueAtIndex}, - base::{CFRelease, TCFType}, - string::CFString, -}; +use core_foundation::array::{CFArrayGetCount, CFArrayGetValueAtIndex}; +use core_foundation::base::{CFRelease, TCFType}; +use core_foundation::string::CFString; use core_graphics::display::{ CGDirectDisplayID, CGDisplay, CGDisplayBounds, CGDisplayCopyDisplayMode, }; -use objc2::{rc::Id, runtime::AnyObject}; +use objc2::rc::Id; +use objc2::runtime::AnyObject; use objc2_app_kit::NSScreen; use objc2_foundation::{ns_string, run_on_main, MainThreadMarker, NSNumber, NSPoint, NSRect}; @@ -233,9 +233,7 @@ impl MonitorHandle { return None; } - (time.time_scale as i64) - .checked_div(time.time_value) - .map(|v| (v * 1000) as u32) + (time.time_scale as i64).checked_div(time.time_value).map(|v| (v * 1000) as u32) } } diff --git a/src/platform_impl/macos/observer.rs b/src/platform_impl/macos/observer.rs index ca5dd5f18d..25571f09df 100644 --- a/src/platform_impl/macos/observer.rs +++ b/src/platform_impl/macos/observer.rs @@ -1,10 +1,8 @@ -use std::{ - ffi::c_void, - panic::{AssertUnwindSafe, UnwindSafe}, - ptr, - rc::Weak, - time::Instant, -}; +use std::ffi::c_void; +use std::panic::{AssertUnwindSafe, UnwindSafe}; +use std::ptr; +use std::rc::Weak; +use std::time::Instant; use core_foundation::base::{CFIndex, CFOptionFlags, CFRelease}; use core_foundation::date::CFAbsoluteTimeGetCurrent; @@ -17,11 +15,9 @@ use core_foundation::runloop::{ }; use objc2_foundation::MainThreadMarker; +use super::app_delegate::ApplicationDelegate; +use super::event_loop::{stop_app_on_panic, PanicInfo}; use super::ffi; -use super::{ - app_delegate::ApplicationDelegate, - event_loop::{stop_app_on_panic, PanicInfo}, -}; unsafe fn control_flow_handler(panic_info: *mut c_void, f: F) where @@ -55,10 +51,10 @@ extern "C" fn control_flow_begin_handler( #[allow(non_upper_case_globals)] match activity { kCFRunLoopAfterWaiting => { - //trace!("Triggered `CFRunLoopAfterWaiting`"); + // trace!("Triggered `CFRunLoopAfterWaiting`"); ApplicationDelegate::get(MainThreadMarker::new().unwrap()).wakeup(panic_info); - //trace!("Completed `CFRunLoopAfterWaiting`"); - } + // trace!("Completed `CFRunLoopAfterWaiting`"); + }, _ => unreachable!(), } }); @@ -77,11 +73,11 @@ extern "C" fn control_flow_end_handler( #[allow(non_upper_case_globals)] match activity { kCFRunLoopBeforeWaiting => { - //trace!("Triggered `CFRunLoopBeforeWaiting`"); + // trace!("Triggered `CFRunLoopBeforeWaiting`"); ApplicationDelegate::get(MainThreadMarker::new().unwrap()).cleared(panic_info); - //trace!("Completed `CFRunLoopBeforeWaiting`"); - } - kCFRunLoopExit => (), //unimplemented!(), // not expected to ever happen + // trace!("Completed `CFRunLoopBeforeWaiting`"); + }, + kCFRunLoopExit => (), // unimplemented!(), // not expected to ever happen _ => unreachable!(), } }); @@ -186,11 +182,7 @@ impl Default for EventLoopWaker { ptr::null_mut(), ); CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopCommonModes); - EventLoopWaker { - timer, - start_instant: Instant::now(), - next_fire_date: None, - } + EventLoopWaker { timer, start_instant: Instant::now(), next_fire_date: None } } } } @@ -215,7 +207,7 @@ impl EventLoopWaker { match instant { Some(instant) if now >= instant => { self.start(); - } + }, Some(instant) => { if self.next_fire_date != Some(instant) { self.next_fire_date = Some(instant); @@ -227,10 +219,10 @@ impl EventLoopWaker { CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs) } } - } + }, None => { self.stop(); - } + }, } } } diff --git a/src/platform_impl/macos/util.rs b/src/platform_impl/macos/util.rs index 4a1b7cb425..e6b7c2d876 100644 --- a/src/platform_impl/macos/util.rs +++ b/src/platform_impl/macos/util.rs @@ -1,10 +1,7 @@ use objc2_foundation::{NSNotFound, NSRange, NSUInteger}; use tracing::trace; -pub static EMPTY_RANGE: NSRange = NSRange { - location: NSNotFound as NSUInteger, - length: 0, -}; +pub static EMPTY_RANGE: NSRange = NSRange { location: NSNotFound as NSUInteger, length: 0 }; macro_rules! trace_scope { ($s:literal) => { @@ -21,20 +18,13 @@ impl TraceGuard { #[inline] pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self { trace!(target = module_path, "Triggered `{}`", called_from_fn); - Self { - module_path, - called_from_fn, - } + Self { module_path, called_from_fn } } } impl Drop for TraceGuard { #[inline] fn drop(&mut self) { - trace!( - target = self.module_path, - "Completed `{}`", - self.called_from_fn - ); + trace!(target = self.module_path, "Completed `{}`", self.called_from_fn); } } diff --git a/src/platform_impl/macos/view.rs b/src/platform_impl/macos/view.rs index 9303946045..c80b44262d 100644 --- a/src/platform_impl/macos/view.rs +++ b/src/platform_impl/macos/view.rs @@ -26,15 +26,13 @@ use super::event::{ }; use super::window::WinitWindow; use super::{util, DEVICE_ID}; -use crate::{ - dpi::{LogicalPosition, LogicalSize}, - event::{ - DeviceEvent, ElementState, Ime, Modifiers, MouseButton, MouseScrollDelta, TouchPhase, - WindowEvent, - }, - keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey}, - platform::macos::OptionAsAlt, +use crate::dpi::{LogicalPosition, LogicalSize}; +use crate::event::{ + DeviceEvent, ElementState, Ime, Modifiers, MouseButton, MouseScrollDelta, TouchPhase, + WindowEvent, }; +use crate::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey}; +use crate::platform::macos::OptionAsAlt; #[derive(Debug)] struct CursorState { @@ -44,10 +42,7 @@ struct CursorState { impl Default for CursorState { fn default() -> Self { - Self { - visible: true, - cursor: default_cursor(), - } + Self { visible: true, cursor: default_cursor() } } } @@ -819,10 +814,7 @@ impl WinitView { // (which is incompatible with `frameDidChange:`) // // unsafe { msg_send_id![self, window] } - self.ivars() - ._ns_window - .load() - .expect("view to have a window") + self.ivars()._ns_window.load().expect("view to have a window") } fn queue_event(&self, event: WindowEvent) { @@ -950,9 +942,7 @@ impl WinitView { let location_mask = ModLocationMask::from_location(event.location); let mut phys_mod_state = self.ivars().phys_modifiers.borrow_mut(); - let phys_mod = phys_mod_state - .entry(key) - .or_insert(ModLocationMask::empty()); + let phys_mod = phys_mod_state.entry(key).or_insert(ModLocationMask::empty()); let is_active = current_modifiers.state().contains(event_modifier); let mut events = VecDeque::with_capacity(2); @@ -1102,9 +1092,7 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Id { if ignore_alt_characters { let ns_chars = unsafe { - event - .charactersIgnoringModifiers() - .expect("expected characters to be non-null") + event.charactersIgnoringModifiers().expect("expected characters to be non-null") }; unsafe { diff --git a/src/platform_impl/macos/window.rs b/src/platform_impl/macos/window.rs index e585c78002..5d20b4e8a3 100644 --- a/src/platform_impl/macos/window.rs +++ b/src/platform_impl/macos/window.rs @@ -18,8 +18,7 @@ pub(crate) struct Window { impl Drop for Window { fn drop(&mut self) { - self.window - .get_on_main(|window| autoreleasepool(|_| window.close())) + self.window.get_on_main(|window| autoreleasepool(|_| window.close())) } } @@ -65,9 +64,7 @@ impl Window { pub(crate) fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::AppKit( - rwh_06::AppKitDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new())) } } diff --git a/src/platform_impl/macos/window_delegate.rs b/src/platform_impl/macos/window_delegate.rs index bbb958aa75..7e48df075f 100644 --- a/src/platform_impl/macos/window_delegate.rs +++ b/src/platform_impl/macos/window_delegate.rs @@ -448,7 +448,7 @@ fn new_window(attrs: &WindowAttributes, mtm: MainThreadMarker) -> Option { monitor.ns_screen(mtm).or_else(|| NSScreen::mainScreen(mtm)) - } + }, Some(Fullscreen::Borderless(None)) => NSScreen::mainScreen(mtm), None => None, }; @@ -462,7 +462,7 @@ fn new_window(attrs: &WindowAttributes, mtm: MainThreadMarker) -> Option { let size = size.to_logical(scale_factor); NSSize::new(size.width, size.height) - } + }, None => NSSize::new(800.0, 600.0), }; let position = match attrs.position { @@ -472,12 +472,12 @@ fn new_window(attrs: &WindowAttributes, mtm: MainThreadMarker) -> Option NSPoint::new(0.0, 0.0), }; NSRect::new(position, size) - } + }, }; let mut masks = if (!attrs.decorations && screen.is_none()) @@ -631,30 +631,27 @@ impl WindowDelegate { let parent_view: Id = unsafe { Id::retain(handle.ns_view.as_ptr().cast()) }.unwrap(); let parent = parent_view.window().ok_or_else(|| { - os_error!(OsError::CreationError( - "parent view should be installed in a window" - )) + os_error!(OsError::CreationError("parent view should be installed in a window")) })?; - // SAFETY: We know that there are no parent -> child -> parent cycles since the only place in `winit` - // where we allow making a window a child window is right here, just after it's been created. + // SAFETY: We know that there are no parent -> child -> parent cycles since the only + // place in `winit` where we allow making a window a child window is + // right here, just after it's been created. unsafe { parent.addChildWindow_ordered(&window, NSWindowOrderingMode::NSWindowAbove) }; - } + }, Some(raw) => panic!("invalid raw window handle {raw:?} on macOS"), None => (), } - let resize_increments = match attrs - .resize_increments - .map(|i| i.to_logical(window.backingScaleFactor() as _)) - { - Some(LogicalSize { width, height }) if width >= 1. && height >= 1. => { - NSSize::new(width, height) - } - _ => NSSize::new(1., 1.), - }; + let resize_increments = + match attrs.resize_increments.map(|i| i.to_logical(window.backingScaleFactor() as _)) { + Some(LogicalSize { width, height }) if width >= 1. && height >= 1. => { + NSSize::new(width, height) + }, + _ => NSSize::new(1., 1.), + }; let scale_factor = window.backingScaleFactor() as _; @@ -771,10 +768,7 @@ impl WindowDelegate { }; self.ivars().previous_scale_factor.set(scale_factor); - let content_size = self - .window() - .contentRectForFrameRect(self.window().frame()) - .size; + let content_size = self.window().contentRectForFrameRect(self.window().frame()).size; let content_size = LogicalSize::new(content_size.width, content_size.height); let app_delegate = ApplicationDelegate::get(MainThreadMarker::from(self)); @@ -885,26 +879,20 @@ impl WindowDelegate { pub fn request_inner_size(&self, size: Size) -> Option> { let scale_factor = self.scale_factor(); let size = size.to_logical(scale_factor); - self.window() - .setContentSize(NSSize::new(size.width, size.height)); + self.window().setContentSize(NSSize::new(size.width, size.height)); None } pub fn set_min_inner_size(&self, dimensions: Option) { - let dimensions = dimensions.unwrap_or(Size::Logical(LogicalSize { - width: 0.0, - height: 0.0, - })); + let dimensions = + dimensions.unwrap_or(Size::Logical(LogicalSize { width: 0.0, height: 0.0 })); let min_size = dimensions.to_logical::(self.scale_factor()); let min_size = NSSize::new(min_size.width, min_size.height); unsafe { self.window().setContentMinSize(min_size) }; // If necessary, resize the window to match constraint - let mut current_size = self - .window() - .contentRectForFrameRect(self.window().frame()) - .size; + let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size; if current_size.width < min_size.width { current_size.width = min_size.width; } @@ -926,10 +914,7 @@ impl WindowDelegate { unsafe { self.window().setContentMaxSize(max_size) }; // If necessary, resize the window to match constraint - let mut current_size = self - .window() - .contentRectForFrameRect(self.window().frame()) - .size; + let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size; if max_size.width < current_size.width { current_size.width = max_size.width; } @@ -1013,9 +998,7 @@ impl WindowDelegate { // We edit the button directly instead of using `NSResizableWindowMask`, // since that mask also affect the resizability of the window (which is // controllable by other means in `winit`). - if let Some(button) = self - .window() - .standardWindowButton(NSWindowButton::NSWindowZoomButton) + if let Some(button) = self.window().standardWindowButton(NSWindowButton::NSWindowZoomButton) { button.setEnabled(buttons.contains(WindowButtons::MAXIMIZE)); } @@ -1064,7 +1047,7 @@ impl WindowDelegate { CursorGrabMode::None => true, CursorGrabMode::Confined => { return Err(ExternalError::NotSupported(NotSupportedError::new())) - } + }, }; // TODO: Do this for real https://stackoverflow.com/a/40922095/5435443 @@ -1107,9 +1090,7 @@ impl WindowDelegate { #[inline] pub fn drag_window(&self) -> Result<(), ExternalError> { let mtm = MainThreadMarker::from(self); - let event = NSApplication::sharedApplication(mtm) - .currentEvent() - .unwrap(); + let event = NSApplication::sharedApplication(mtm).currentEvent().unwrap(); self.window().performWindowDragWithEvent(&event); Ok(()) } @@ -1151,12 +1132,8 @@ impl WindowDelegate { } fn saved_style(&self) -> NSWindowStyleMask { - let base_mask = self - .ivars() - .saved_style - .take() - .unwrap_or_else(|| self.window().styleMask()) - .0; + let base_mask = + self.ivars().saved_style.take().unwrap_or_else(|| self.window().styleMask()).0; NSWindowStyleMask(if self.ivars().resizable.get() { base_mask | NSWindowStyleMask::Resizable.0 } else { @@ -1225,10 +1202,7 @@ impl WindowDelegate { let screen = NSScreen::mainScreen(mtm).expect("no screen found"); screen.visibleFrame() } else { - self.ivars() - .standard_frame - .get() - .unwrap_or(DEFAULT_STANDARD_FRAME) + self.ivars().standard_frame.get().unwrap_or(DEFAULT_STANDARD_FRAME) }; self.window().setFrame_display(new_rect, false); } @@ -1275,7 +1249,7 @@ impl WindowDelegate { } else { return; } - } + }, Fullscreen::Exclusive(video_mode) => video_mode.monitor(), } .ns_screen(mtm) @@ -1305,9 +1279,7 @@ impl WindowDelegate { let mut fade_token = ffi::kCGDisplayFadeReservationInvalidToken; if matches!(old_fullscreen, Some(Fullscreen::Borderless(_))) { - self.ivars() - .save_presentation_opts - .replace(Some(app.presentationOptions())); + self.ivars().save_presentation_opts.replace(Some(app.presentationOptions())); } unsafe { @@ -1380,11 +1352,11 @@ impl WindowDelegate { self.ivars().saved_style.set(Some(curr_mask)); } toggle_fullscreen(self.window()); - } + }, (Some(Fullscreen::Borderless(_)), None) => { // State is restored by `window_did_exit_fullscreen` toggle_fullscreen(self.window()); - } + }, (Some(Fullscreen::Exclusive(ref video_mode)), None) => { unsafe { ffi::CGRestorePermanentDisplayConfiguration(); @@ -1394,7 +1366,7 @@ impl WindowDelegate { ); }; toggle_fullscreen(self.window()); - } + }, (Some(Fullscreen::Borderless(_)), Some(Fullscreen::Exclusive(_))) => { // If we're already in fullscreen mode, calling // `CGDisplayCapture` will place the shielding window on top of @@ -1404,9 +1376,7 @@ impl WindowDelegate { // of the menu bar, and this looks broken, so we must make sure // that the menu bar is disabled. This is done in the window // delegate in `window:willUseFullScreenPresentationOptions:`. - self.ivars() - .save_presentation_opts - .set(Some(app.presentationOptions())); + self.ivars().save_presentation_opts.set(Some(app.presentationOptions())); let presentation_options = NSApplicationPresentationOptions( NSApplicationPresentationOptions::NSApplicationPresentationFullScreen.0 @@ -1417,7 +1387,7 @@ impl WindowDelegate { let window_level = unsafe { ffi::CGShieldingWindowLevel() } as NSWindowLevel + 1; self.window().setLevel(window_level); - } + }, (Some(Fullscreen::Exclusive(ref video_mode)), Some(Fullscreen::Borderless(_))) => { let presentation_options = self.ivars().save_presentation_opts.get().unwrap_or( NSApplicationPresentationOptions(NSApplicationPresentationOptions::NSApplicationPresentationFullScreen.0 @@ -1436,10 +1406,9 @@ impl WindowDelegate { // Restore the normal window level following the Borderless fullscreen // `CGShieldingWindowLevel() + 1` hack. - self.window() - .setLevel(ffi::kCGNormalWindowLevel as NSWindowLevel); - } - _ => {} + self.window().setLevel(ffi::kCGNormalWindowLevel as NSWindowLevel); + }, + _ => {}, }; } @@ -1628,9 +1597,7 @@ impl WindowDelegate { pub fn set_theme(&self, theme: Option) { let mtm = MainThreadMarker::from(self); set_ns_theme(theme, mtm); - self.ivars() - .current_theme - .set(theme.or_else(|| Some(get_ns_theme(mtm)))); + self.ivars().current_theme.set(theme.or_else(|| Some(get_ns_theme(mtm)))); } #[inline] @@ -1676,15 +1643,11 @@ impl WindowExtMacOS for WindowDelegate { if fullscreen { // Remember the original window's settings // Exclude title bar - self.ivars().standard_frame.set(Some( - self.window().contentRectForFrameRect(self.window().frame()), - )); self.ivars() - .saved_style - .set(Some(self.window().styleMask())); - self.ivars() - .save_presentation_opts - .set(Some(app.presentationOptions())); + .standard_frame + .set(Some(self.window().contentRectForFrameRect(self.window().frame()))); + self.ivars().saved_style.set(Some(self.window().styleMask())); + self.ivars().save_presentation_opts.set(Some(app.presentationOptions())); // Tell our window's state that we're in fullscreen self.ivars().is_simple_fullscreen.set(true); @@ -1700,10 +1663,7 @@ impl WindowExtMacOS for WindowDelegate { self.toggle_style_mask(NSWindowStyleMask::Titled, false); // Set the window frame to the screen frame size - let screen = self - .window() - .screen() - .expect("expected screen to be available"); + let screen = self.window().screen().expect("expected screen to be available"); self.window().setFrame_display(screen.frame(), true); // Fullscreen windows can't be resized, minimized, or moved @@ -1718,11 +1678,7 @@ impl WindowExtMacOS for WindowDelegate { self.ivars().is_simple_fullscreen.set(false); let save_presentation_opts = self.ivars().save_presentation_opts.get(); - let frame = self - .ivars() - .standard_frame - .get() - .unwrap_or(DEFAULT_STANDARD_FRAME); + let frame = self.ivars().standard_frame.get().unwrap_or(DEFAULT_STANDARD_FRAME); if let Some(presentation_opts) = save_presentation_opts { app.setPresentationOptions(presentation_opts); @@ -1747,8 +1703,7 @@ impl WindowExtMacOS for WindowDelegate { #[inline] fn set_tabbing_identifier(&self, identifier: &str) { - self.window() - .setTabbingIdentifier(&NSString::from_str(identifier)) + self.window().setTabbingIdentifier(&NSString::from_str(identifier)) } #[inline] @@ -1779,9 +1734,7 @@ impl WindowExtMacOS for WindowDelegate { #[inline] fn num_tabs(&self) -> usize { - unsafe { self.window().tabbedWindows() } - .map(|windows| windows.len()) - .unwrap_or(1) + unsafe { self.window().tabbedWindows() }.map(|windows| windows.len()).unwrap_or(1) } fn is_document_edited(&self) -> bool { diff --git a/src/platform_impl/mod.rs b/src/platform_impl/mod.rs index 1e2acead17..a25fb3a209 100644 --- a/src/platform_impl/mod.rs +++ b/src/platform_impl/mod.rs @@ -25,7 +25,8 @@ mod platform; pub use self::platform::*; -/// Helper for converting between platform-specific and generic [`VideoModeHandle`]/[`MonitorHandle`] +/// Helper for converting between platform-specific and generic +/// [`VideoModeHandle`]/[`MonitorHandle`] #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Fullscreen { Exclusive(VideoModeHandle), @@ -47,10 +48,10 @@ impl From for RootFullscreen { match f { Fullscreen::Exclusive(video_mode) => { Self::Exclusive(RootVideoModeHandle { video_mode }) - } + }, Fullscreen::Borderless(Some(inner)) => { Self::Borderless(Some(RootMonitorHandle { inner })) - } + }, Fullscreen::Borderless(None) => Self::Borderless(None), } } diff --git a/src/platform_impl/orbital/event_loop.rs b/src/platform_impl/orbital/event_loop.rs index 11216e1176..59ba9e522d 100644 --- a/src/platform_impl/orbital/event_loop.rs +++ b/src/platform_impl/orbital/event_loop.rs @@ -1,11 +1,9 @@ -use std::{ - cell::Cell, - collections::VecDeque, - marker::PhantomData, - mem, slice, - sync::{mpsc, Arc, Mutex}, - time::Instant, -}; +use std::cell::Cell; +use std::collections::VecDeque; +use std::marker::PhantomData; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::Instant; +use std::{mem, slice}; use bitflags::bitflags; use orbclient::{ @@ -14,15 +12,15 @@ use orbclient::{ }; use smol_str::SmolStr; -use crate::{ - error::EventLoopError, - event::{self, Ime, Modifiers, StartCause}, - event_loop::{self, ControlFlow, DeviceEvents}, - keyboard::{ - Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, - NativeKeyCode, PhysicalKey, - }, - window::{CustomCursor as RootCustomCursor, CustomCursorSource, WindowId as RootWindowId}, +use crate::error::EventLoopError; +use crate::event::{self, Ime, Modifiers, StartCause}; +use crate::event_loop::{self, ControlFlow, DeviceEvents}; +use crate::keyboard::{ + Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, + PhysicalKey, +}; +use crate::window::{ + CustomCursor as RootCustomCursor, CustomCursorSource, WindowId as RootWindowId, }; use super::{ @@ -181,7 +179,7 @@ impl EventState { if character.is_ascii_lowercase() { return ((character as u8 - b'a') + 1) as char; } - //TODO: more control key variants? + // TODO: more control key variants? } // Return character as-is if no special handling required @@ -235,74 +233,41 @@ impl EventState { let mut state = ModifiersState::empty(); let mut pressed_mods = ModifiersKeys::empty(); - if self - .keyboard - .intersects(KeyboardModifierState::LSHIFT | KeyboardModifierState::RSHIFT) - { + if self.keyboard.intersects(KeyboardModifierState::LSHIFT | KeyboardModifierState::RSHIFT) { state |= ModifiersState::SHIFT; } - pressed_mods.set( - ModifiersKeys::LSHIFT, - self.keyboard.contains(KeyboardModifierState::LSHIFT), - ); - pressed_mods.set( - ModifiersKeys::RSHIFT, - self.keyboard.contains(KeyboardModifierState::RSHIFT), - ); + pressed_mods + .set(ModifiersKeys::LSHIFT, self.keyboard.contains(KeyboardModifierState::LSHIFT)); + pressed_mods + .set(ModifiersKeys::RSHIFT, self.keyboard.contains(KeyboardModifierState::RSHIFT)); - if self - .keyboard - .intersects(KeyboardModifierState::LCTRL | KeyboardModifierState::RCTRL) - { + if self.keyboard.intersects(KeyboardModifierState::LCTRL | KeyboardModifierState::RCTRL) { state |= ModifiersState::CONTROL; } - pressed_mods.set( - ModifiersKeys::LCONTROL, - self.keyboard.contains(KeyboardModifierState::LCTRL), - ); - pressed_mods.set( - ModifiersKeys::RCONTROL, - self.keyboard.contains(KeyboardModifierState::RCTRL), - ); + pressed_mods + .set(ModifiersKeys::LCONTROL, self.keyboard.contains(KeyboardModifierState::LCTRL)); + pressed_mods + .set(ModifiersKeys::RCONTROL, self.keyboard.contains(KeyboardModifierState::RCTRL)); - if self - .keyboard - .intersects(KeyboardModifierState::LALT | KeyboardModifierState::RALT) - { + if self.keyboard.intersects(KeyboardModifierState::LALT | KeyboardModifierState::RALT) { state |= ModifiersState::ALT; } - pressed_mods.set( - ModifiersKeys::LALT, - self.keyboard.contains(KeyboardModifierState::LALT), - ); - pressed_mods.set( - ModifiersKeys::RALT, - self.keyboard.contains(KeyboardModifierState::RALT), - ); + pressed_mods.set(ModifiersKeys::LALT, self.keyboard.contains(KeyboardModifierState::LALT)); + pressed_mods.set(ModifiersKeys::RALT, self.keyboard.contains(KeyboardModifierState::RALT)); - if self - .keyboard - .intersects(KeyboardModifierState::LSUPER | KeyboardModifierState::RSUPER) - { + if self.keyboard.intersects(KeyboardModifierState::LSUPER | KeyboardModifierState::RSUPER) { state |= ModifiersState::SUPER } - pressed_mods.set( - ModifiersKeys::LSUPER, - self.keyboard.contains(KeyboardModifierState::LSUPER), - ); - pressed_mods.set( - ModifiersKeys::RSUPER, - self.keyboard.contains(KeyboardModifierState::RSUPER), - ); + pressed_mods + .set(ModifiersKeys::LSUPER, self.keyboard.contains(KeyboardModifierState::LSUPER)); + pressed_mods + .set(ModifiersKeys::RSUPER, self.keyboard.contains(KeyboardModifierState::RSUPER)); - Modifiers { - state, - pressed_mods, - } + Modifiers { state, pressed_mods } } } @@ -366,11 +331,7 @@ impl EventLoop { F: FnMut(event::Event), { match event_option { - EventOption::Key(KeyEvent { - character, - scancode, - pressed, - }) => { + EventOption::Key(KeyEvent { character, scancode, pressed }) => { // Convert scancode let (physical_key, named_key_opt) = convert_scancode(scancode); @@ -437,7 +398,7 @@ impl EventLoop { event: event::WindowEvent::ModifiersChanged(event_state.modifiers()), }) } - } + }, EventOption::TextInput(TextInputEvent { character }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), @@ -447,7 +408,7 @@ impl EventLoop { window_id: RootWindowId(window_id), event: event::WindowEvent::Ime(Ime::Commit(character.into())), }); - } + }, EventOption::Mouse(MouseEvent { x, y }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), @@ -456,20 +417,14 @@ impl EventLoop { position: (x, y).into(), }, }); - } + }, EventOption::MouseRelative(MouseRelativeEvent { dx, dy }) => { event_handler(event::Event::DeviceEvent { device_id: event::DeviceId(DeviceId), - event: event::DeviceEvent::MouseMotion { - delta: (dx as f64, dy as f64), - }, + event: event::DeviceEvent::MouseMotion { delta: (dx as f64, dy as f64) }, }); - } - EventOption::Button(ButtonEvent { - left, - middle, - right, - }) => { + }, + EventOption::Button(ButtonEvent { left, middle, right }) => { while let Some((button, state)) = event_state.mouse(left, middle, right) { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), @@ -480,7 +435,7 @@ impl EventLoop { }, }); } - } + }, EventOption::Scroll(ScrollEvent { x, y }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), @@ -490,25 +445,25 @@ impl EventLoop { phase: event::TouchPhase::Moved, }, }); - } + }, EventOption::Quit(QuitEvent {}) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::CloseRequested, }); - } + }, EventOption::Focus(FocusEvent { focused }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::Focused(focused), }); - } + }, EventOption::Move(MoveEvent { x, y }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::Moved((x, y).into()), }); - } + }, EventOption::Resize(ResizeEvent { width, height }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), @@ -517,8 +472,8 @@ impl EventLoop { // Acknowledge resize after event loop. event_state.resize_opt = Some((width, height)); - } - //TODO: Screen, Clipboard, Drop + }, + // TODO: Screen, Clipboard, Drop EventOption::Hover(HoverEvent { entered }) => { if entered { event_handler(event::Event::WindowEvent { @@ -535,10 +490,10 @@ impl EventLoop { }, }); } - } + }, other => { tracing::warn!("unhandled event: {:?}", other); - } + }, } } @@ -565,9 +520,7 @@ impl EventLoop { let mut creates = self.window_target.p.creates.lock().unwrap(); creates.pop_front() } { - let window_id = WindowId { - fd: window.fd as u64, - }; + let window_id = WindowId { fd: window.fd as u64 }; let mut buf: [u8; 4096] = [0; 4096]; let path = window.fpath(&mut buf).expect("failed to read properties"); @@ -607,22 +560,20 @@ impl EventLoop { &self.window_target, ); - self.windows - .retain(|(window, _event_state)| window.fd as u64 != destroy_id.fd); + self.windows.retain(|(window, _event_state)| window.fd as u64 != destroy_id.fd); } // Handle window events. let mut i = 0; // While loop is used here because the same window may be processed more than once. while let Some((window, event_state)) = self.windows.get_mut(i) { - let window_id = WindowId { - fd: window.fd as u64, - }; + let window_id = WindowId { fd: window.fd as u64 }; let mut event_buf = [0u8; 16 * mem::size_of::()]; let count = syscall::read(window.fd, &mut event_buf).expect("failed to read window events"); - // Safety: orbclient::Event is a packed struct designed to be transferred over a socket. + // Safety: orbclient::Event is a packed struct designed to be transferred over a + // socket. let events = unsafe { slice::from_raw_parts( event_buf.as_ptr() as *const orbclient::Event, @@ -640,7 +591,8 @@ impl EventLoop { } if count == event_buf.len() { - // If event buf was full, process same window again to ensure all events are drained. + // If event buf was full, process same window again to ensure all events are + // drained. continue; } @@ -689,7 +641,7 @@ impl EventLoop { ControlFlow::Poll => { start_cause = StartCause::Poll; continue; - } + }, ControlFlow::Wait => None, ControlFlow::WaitUntil(instant) => Some(instant), }; @@ -734,18 +686,12 @@ impl EventLoop { Some(requested_resume) if event.id == timeout_socket.0.fd => { // If the event is from the special timeout socket, report that resume // time was reached. - start_cause = StartCause::ResumeTimeReached { - start, - requested_resume, - }; - } + start_cause = StartCause::ResumeTimeReached { start, requested_resume }; + }, _ => { // Normal window event or spurious timeout. - start_cause = StartCause::WaitCancelled { - start, - requested_resume, - }; - } + start_cause = StartCause::WaitCancelled { start, requested_resume }; + }, } } @@ -807,9 +753,7 @@ pub struct ActiveEventLoop { impl ActiveEventLoop { pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { let _ = source.inner; - RootCustomCursor { - inner: super::PlatformCustomCursor, - } + RootCustomCursor { inner: super::PlatformCustomCursor } } pub fn primary_monitor(&self) -> Option { @@ -836,9 +780,7 @@ impl ActiveEventLoop { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Orbital( - rwh_06::OrbitalDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Orbital(rwh_06::OrbitalDisplayHandle::new())) } pub fn set_control_flow(&self, control_flow: ControlFlow) { diff --git a/src/platform_impl/orbital/mod.rs b/src/platform_impl/orbital/mod.rs index c9be8b55ea..91d85c3d16 100644 --- a/src/platform_impl/orbital/mod.rs +++ b/src/platform_impl/orbital/mod.rs @@ -6,10 +6,8 @@ use std::sync::Arc; use smol_str::SmolStr; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize}, - keyboard::Key, -}; +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::keyboard::Key; pub(crate) use self::event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle}; mod event_loop; @@ -105,9 +103,7 @@ pub struct WindowId { impl WindowId { pub const fn dummy() -> Self { - WindowId { - fd: u64::max_value(), - } + WindowId { fd: u64::max_value() } } } @@ -149,27 +145,12 @@ impl<'a> WindowProperties<'a> { // orbital:flags/x/y/w/h/t let mut parts = path.splitn(6, '/'); let flags = parts.next().unwrap_or(""); - let x = parts - .next() - .map_or(0, |part| part.parse::().unwrap_or(0)); - let y = parts - .next() - .map_or(0, |part| part.parse::().unwrap_or(0)); - let w = parts - .next() - .map_or(0, |part| part.parse::().unwrap_or(0)); - let h = parts - .next() - .map_or(0, |part| part.parse::().unwrap_or(0)); + let x = parts.next().map_or(0, |part| part.parse::().unwrap_or(0)); + let y = parts.next().map_or(0, |part| part.parse::().unwrap_or(0)); + let w = parts.next().map_or(0, |part| part.parse::().unwrap_or(0)); + let h = parts.next().map_or(0, |part| part.parse::().unwrap_or(0)); let title = parts.next().unwrap_or(""); - Self { - flags, - x, - y, - w, - h, - title, - } + Self { flags, x, y, w, h, title } } } @@ -198,8 +179,9 @@ impl Display for OsError { } } -pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursor; -pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursorSource; +pub(crate) use crate::cursor::{ + NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource, +}; pub(crate) use crate::icon::NoIcon as PlatformIcon; #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] diff --git a/src/platform_impl/orbital/window.rs b/src/platform_impl/orbital/window.rs index 0352ced29c..d90d6a4584 100644 --- a/src/platform_impl/orbital/window.rs +++ b/src/platform_impl/orbital/window.rs @@ -1,16 +1,11 @@ -use std::{ - collections::VecDeque, - sync::{Arc, Mutex}, -}; +use std::collections::VecDeque; +use std::sync::{Arc, Mutex}; -use crate::{ - cursor::Cursor, - dpi::{PhysicalPosition, PhysicalSize, Position, Size}, - error, - platform_impl::Fullscreen, - window, - window::ImePurpose, -}; +use crate::cursor::Cursor; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::platform_impl::Fullscreen; +use crate::window::ImePurpose; +use crate::{error, window}; use super::{ ActiveEventLoop, MonitorHandle, OsError, RedoxSocket, TimeSocket, WindowId, WindowProperties, @@ -54,7 +49,7 @@ impl Window { (1024, 768) }; - //TODO: min/max inner_size + // TODO: min/max inner_size // Async by default. let mut flag_str = ORBITAL_FLAG_ASYNC.to_string(); @@ -67,7 +62,7 @@ impl Window { flag_str.push(ORBITAL_FLAG_RESIZABLE); } - //TODO: fullscreen + // TODO: fullscreen if attrs.transparent { flag_str.push(ORBITAL_FLAG_TRANSPARENT); @@ -84,14 +79,14 @@ impl Window { match attrs.window_level { window::WindowLevel::AlwaysOnBottom => { flag_str.push(ORBITAL_FLAG_BACK); - } - window::WindowLevel::Normal => {} + }, + window::WindowLevel::Normal => {}, window::WindowLevel::AlwaysOnTop => { flag_str.push(ORBITAL_FLAG_FRONT); - } + }, } - //TODO: window_icon + // TODO: window_icon // Open window. let window = RedoxSocket::orbital(&WindowProperties { @@ -158,9 +153,7 @@ impl Window { #[inline] pub fn id(&self) -> WindowId { - WindowId { - fd: self.window_socket.fd as u64, - } + WindowId { fd: self.window_socket.fd as u64 } } #[inline] @@ -207,36 +200,28 @@ impl Window { #[inline] pub fn inner_position(&self) -> Result, error::NotSupportedError> { let mut buf: [u8; 4096] = [0; 4096]; - let path = self - .window_socket - .fpath(&mut buf) - .expect("failed to read properties"); + let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); let properties = WindowProperties::new(path); Ok((properties.x, properties.y).into()) } #[inline] pub fn outer_position(&self) -> Result, error::NotSupportedError> { - //TODO: adjust for window decorations + // TODO: adjust for window decorations self.inner_position() } #[inline] pub fn set_outer_position(&self, position: Position) { - //TODO: adjust for window decorations + // TODO: adjust for window decorations let (x, y): (i32, i32) = position.to_physical::(self.scale_factor()).into(); - self.window_socket - .write(format!("P,{x},{y}").as_bytes()) - .expect("failed to set position"); + self.window_socket.write(format!("P,{x},{y}").as_bytes()).expect("failed to set position"); } #[inline] pub fn inner_size(&self) -> PhysicalSize { let mut buf: [u8; 4096] = [0; 4096]; - let path = self - .window_socket - .fpath(&mut buf) - .expect("failed to read properties"); + let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); let properties = WindowProperties::new(path); (properties.w, properties.h).into() } @@ -244,15 +229,13 @@ impl Window { #[inline] pub fn request_inner_size(&self, size: Size) -> Option> { let (w, h): (u32, u32) = size.to_physical::(self.scale_factor()).into(); - self.window_socket - .write(format!("S,{w},{h}").as_bytes()) - .expect("failed to set size"); + self.window_socket.write(format!("S,{w},{h}").as_bytes()).expect("failed to set size"); None } #[inline] pub fn outer_size(&self) -> PhysicalSize { - //TODO: adjust for window decorations + // TODO: adjust for window decorations self.inner_size() } @@ -265,19 +248,14 @@ impl Window { #[inline] pub fn title(&self) -> String { let mut buf: [u8; 4096] = [0; 4096]; - let path = self - .window_socket - .fpath(&mut buf) - .expect("failed to read properties"); + let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); let properties = WindowProperties::new(path); properties.title.to_string() } #[inline] pub fn set_title(&self, title: &str) { - self.window_socket - .write(format!("T,{title}").as_bytes()) - .expect("failed to set title"); + self.window_socket.write(format!("T,{title}").as_bytes()).expect("failed to set title"); } #[inline] @@ -357,14 +335,14 @@ impl Window { match level { window::WindowLevel::AlwaysOnBottom => { let _ = self.set_flag(ORBITAL_FLAG_BACK, true); - } + }, window::WindowLevel::Normal => { let _ = self.set_flag(ORBITAL_FLAG_BACK, false); let _ = self.set_flag(ORBITAL_FLAG_FRONT, false); - } + }, window::WindowLevel::AlwaysOnTop => { let _ = self.set_flag(ORBITAL_FLAG_FRONT, true); - } + }, } } @@ -391,9 +369,7 @@ impl Window { #[inline] pub fn set_cursor_position(&self, _: Position) -> Result<(), error::ExternalError> { - Err(error::ExternalError::NotSupported( - error::NotSupportedError::new(), - )) + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) } #[inline] @@ -417,9 +393,7 @@ impl Window { #[inline] pub fn set_cursor_visible(&self, visible: bool) { - let _ = self - .window_socket - .write(format!("M,C,{}", if visible { 1 } else { 0 }).as_bytes()); + let _ = self.window_socket.write(format!("M,C,{}", if visible { 1 } else { 0 }).as_bytes()); } #[inline] @@ -456,9 +430,7 @@ impl Window { #[inline] pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), error::ExternalError> { - Err(error::ExternalError::NotSupported( - error::NotSupportedError::new(), - )) + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) } #[cfg(feature = "rwh_04")] @@ -498,9 +470,7 @@ impl Window { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Orbital( - rwh_06::OrbitalDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Orbital(rwh_06::OrbitalDisplayHandle::new())) } #[inline] diff --git a/src/platform_impl/web/async/abortable.rs b/src/platform_impl/web/async/abortable.rs index 2608fc4046..671ae87934 100644 --- a/src/platform_impl/web/async/abortable.rs +++ b/src/platform_impl/web/async/abortable.rs @@ -19,10 +19,7 @@ pub struct Abortable { impl Abortable { pub fn new(handle: AbortHandle, future: F) -> Self { - Self { - future, - shared: handle.0, - } + Self { future, shared: handle.0 } } } @@ -59,10 +56,7 @@ pub struct AbortHandle(Arc); impl AbortHandle { pub fn new() -> Self { - Self(Arc::new(Shared { - waker: AtomicWaker::new(), - aborted: AtomicBool::new(false), - })) + Self(Arc::new(Shared { waker: AtomicWaker::new(), aborted: AtomicBool::new(false) })) } pub fn abort(&self) { diff --git a/src/platform_impl/web/async/channel.rs b/src/platform_impl/web/async/channel.rs index 6b313f32e7..42401a2824 100644 --- a/src/platform_impl/web/async/channel.rs +++ b/src/platform_impl/web/async/channel.rs @@ -9,19 +9,11 @@ use super::AtomicWaker; pub fn channel() -> (Sender, Receiver) { let (sender, receiver) = mpsc::channel(); - let shared = Arc::new(Shared { - closed: AtomicBool::new(false), - waker: AtomicWaker::new(), - }); - - let sender = Sender(Arc::new(SenderInner { - sender: Mutex::new(sender), - shared: Arc::clone(&shared), - })); - let receiver = Receiver { - receiver: Rc::new(receiver), - shared, - }; + let shared = Arc::new(Shared { closed: AtomicBool::new(false), waker: AtomicWaker::new() }); + + let sender = + Sender(Arc::new(SenderInner { sender: Mutex::new(sender), shared: Arc::clone(&shared) })); + let receiver = Receiver { receiver: Rc::new(receiver), shared }; (sender, receiver) } @@ -85,10 +77,10 @@ impl Receiver { } else { Poll::Pending } - } + }, Err(TryRecvError::Disconnected) => Poll::Ready(Err(RecvError)), } - } + }, Err(TryRecvError::Disconnected) => Poll::Ready(Err(RecvError)), }) .await @@ -105,10 +97,7 @@ impl Receiver { impl Clone for Receiver { fn clone(&self) -> Self { - Self { - receiver: Rc::clone(&self.receiver), - shared: Arc::clone(&self.shared), - } + Self { receiver: Rc::clone(&self.receiver), shared: Arc::clone(&self.shared) } } } diff --git a/src/platform_impl/web/async/concurrent_queue.rs b/src/platform_impl/web/async/concurrent_queue.rs index 2d7efacd50..70afb3ddd2 100644 --- a/src/platform_impl/web/async/concurrent_queue.rs +++ b/src/platform_impl/web/async/concurrent_queue.rs @@ -19,10 +19,7 @@ pub enum PopError { impl ConcurrentQueue { pub fn unbounded() -> Self { - Self { - queue: RefCell::new(Vec::new()), - closed: Cell::new(false), - } + Self { queue: RefCell::new(Vec::new()), closed: Cell::new(false) } } pub fn push(&self, value: T) -> Result<(), PushError> { diff --git a/src/platform_impl/web/async/dispatcher.rs b/src/platform_impl/web/async/dispatcher.rs index a83d4ab2f9..6623572154 100644 --- a/src/platform_impl/web/async/dispatcher.rs +++ b/src/platform_impl/web/async/dispatcher.rs @@ -1,9 +1,7 @@ use super::super::main_thread::MainThreadMarker; use super::{channel, Receiver, Sender, Wrapper}; -use std::{ - cell::Ref, - sync::{Arc, Condvar, Mutex}, -}; +use std::cell::Ref; +use std::sync::{Arc, Condvar, Mutex}; pub struct Dispatcher(Wrapper>, Closure>); @@ -18,24 +16,25 @@ impl Dispatcher { main_thread, value, |value, Closure(closure)| { - // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything - // funny with it here. See `Self::queue()`. + // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do + // anything funny with it here. See `Self::queue()`. closure(value.borrow().as_ref().unwrap()) }, { let receiver = receiver.clone(); move |value| async move { while let Ok(Closure(closure)) = receiver.next().await { - // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything - // funny with it here. See `Self::queue()`. + // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't + // do anything funny with it here. See + // `Self::queue()`. closure(value.borrow().as_ref().unwrap()) } } }, sender, |sender, closure| { - // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything - // funny with it here. See `Self::queue()`. + // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do + // anything funny with it here. See `Self::queue()`. sender.send(closure).unwrap() }, ) @@ -91,19 +90,12 @@ pub struct DispatchRunner { impl DispatchRunner { pub fn run(&self) { - while let Some(Closure(closure)) = self - .receiver - .try_recv() - .expect("should only be closed when `Dispatcher` is dropped") + while let Some(Closure(closure)) = + self.receiver.try_recv().expect("should only be closed when `Dispatcher` is dropped") { // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything // funny with it here. See `Self::queue()`. - closure( - &self - .wrapper - .value() - .expect("don't call this outside the main thread"), - ) + closure(&self.wrapper.value().expect("don't call this outside the main thread")) } } } diff --git a/src/platform_impl/web/async/notifier.rs b/src/platform_impl/web/async/notifier.rs index 6387b7e5da..81655d1849 100644 --- a/src/platform_impl/web/async/notifier.rs +++ b/src/platform_impl/web/async/notifier.rs @@ -1,10 +1,7 @@ use std::future::Future; use std::pin::Pin; -use std::sync::Arc; -use std::sync::OnceLock; -use std::task::Context; -use std::task::Poll; -use std::task::Waker; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll, Waker}; use super::{ConcurrentQueue, PushError}; @@ -13,10 +10,7 @@ pub struct Notifier(Arc>); impl Notifier { pub fn new() -> Self { - Self(Arc::new(Inner { - queue: ConcurrentQueue::unbounded(), - value: OnceLock::new(), - })) + Self(Arc::new(Inner { queue: ConcurrentQueue::unbounded(), value: OnceLock::new() })) } pub fn notify(self, value: T) { @@ -52,11 +46,11 @@ impl Future for Notified { self.0 = Some(this); return Poll::Pending; } - } + }, Err(PushError::Closed(_)) => (), Err(PushError::Full(_)) => { unreachable!("found full queue despite using unbounded queue") - } + }, } } diff --git a/src/platform_impl/web/async/waker.rs b/src/platform_impl/web/async/waker.rs index 8280e13da8..86771714db 100644 --- a/src/platform_impl/web/async/waker.rs +++ b/src/platform_impl/web/async/waker.rs @@ -92,8 +92,7 @@ impl WakerSpawner { "this should only be called from the main thread" ); - self.0 - .with_sender_data(|inner| inner.0.counter.swap(0, Ordering::Relaxed)) + self.0.with_sender_data(|inner| inner.0.counter.swap(0, Ordering::Relaxed)) } } diff --git a/src/platform_impl/web/async/wrapper.rs b/src/platform_impl/web/async/wrapper.rs index 1825df132b..2c7f6940d4 100644 --- a/src/platform_impl/web/async/wrapper.rs +++ b/src/platform_impl/web/async/wrapper.rs @@ -17,10 +17,9 @@ struct Value { // SAFETY: // This value must not be accessed if not on the main thread. // - // - We wrap this in an `Arc` to allow it to be safely cloned without - // accessing the value. - // - The `RefCell` lets us mutably access in the main thread but is safe to - // drop in any thread because it has no `Drop` behavior. + // - We wrap this in an `Arc` to allow it to be safely cloned without accessing the value. + // - The `RefCell` lets us mutably access in the main thread but is safe to drop in any thread + // because it has no `Drop` behavior. // - The `Option` lets us safely drop `T` only in the main thread. value: Arc>>, // Prevent's `Send` or `Sync` to be automatically implemented. @@ -53,10 +52,7 @@ impl Wrapper { }); Some(Self { - value: Value { - value, - local: PhantomData, - }, + value: Value { value, local: PhantomData }, handler, sender_data, sender_handler, @@ -84,10 +80,7 @@ impl Wrapper { impl Clone for Wrapper { fn clone(&self) -> Self { Self { - value: Value { - value: self.value.value.clone(), - local: PhantomData, - }, + value: Value { value: self.value.value.clone(), local: PhantomData }, handler: self.handler, sender_data: self.sender_data.clone(), sender_handler: self.sender_handler, diff --git a/src/platform_impl/web/cursor.rs b/src/platform_impl/web/cursor.rs index 96a666d387..2844b2da50 100644 --- a/src/platform_impl/web/cursor.rs +++ b/src/platform_impl/web/cursor.rs @@ -11,8 +11,9 @@ use std::time::Duration; use cursor_icon::CursorIcon; use js_sys::{Array, Object}; +use wasm_bindgen::closure::Closure; use wasm_bindgen::prelude::wasm_bindgen; -use wasm_bindgen::{closure::Closure, JsCast}; +use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; use web_sys::{ Blob, Document, DomException, HtmlCanvasElement, HtmlImageElement, ImageBitmap, @@ -29,15 +30,8 @@ use crate::platform::web::CustomCursorError; #[derive(Debug)] pub(crate) enum CustomCursorSource { Image(CursorImage), - Url { - url: String, - hotspot_x: u16, - hotspot_y: u16, - }, - Animation { - duration: Duration, - cursors: Vec, - }, + Url { url: String, hotspot_x: u16, hotspot_y: u16 }, + Animation { duration: Duration, cursors: Vec }, } impl CustomCursorSource { @@ -79,18 +73,10 @@ impl CustomCursor { match source { CustomCursorSource::Image(image) => Self::build_spawn( event_loop, - from_rgba( - event_loop.runner.window(), - event_loop.runner.document().clone(), - &image, - ), + from_rgba(event_loop.runner.window(), event_loop.runner.document().clone(), &image), false, ), - CustomCursorSource::Url { - url, - hotspot_x, - hotspot_y, - } => Self::build_spawn( + CustomCursorSource::Url { url, hotspot_x, hotspot_y } => Self::build_spawn( event_loop, from_url(UrlType::Plain(url), hotspot_x, hotspot_y), false, @@ -130,9 +116,7 @@ impl CustomCursor { async move { let result = task.await; - let this = weak - .upgrade() - .expect("`CursorHandler` invalidated without aborting"); + let this = weak.upgrade().expect("`CursorHandler` invalidated without aborting"); let mut this = this.get(main_thread).borrow_mut(); match result { @@ -143,7 +127,7 @@ impl CustomCursor { unreachable!("found invalid state"); }; notifier.notify(Ok(())); - } + }, Err(error) => { let ImageState::Loading { notifier, .. } = mem::replace(this.deref_mut(), ImageState::Failed(error.clone())) @@ -151,7 +135,7 @@ impl CustomCursor { unreachable!("found invalid state"); }; notifier.notify(Err(error)); - } + }, } } }); @@ -175,11 +159,7 @@ impl CustomCursor { let notified = notifier.notified(); drop(binding); - CustomCursorFuture { - notified, - animation, - state: Some(state), - } + CustomCursorFuture { notified, animation, state: Some(state) } } } @@ -199,15 +179,9 @@ impl Future for CustomCursorFuture { } let result = ready!(Pin::new(&mut self.notified).poll(cx)); - let state = self - .state - .take() - .expect("`CustomCursorFuture` polled after completion"); - - Poll::Ready(result.map(|_| CustomCursor { - animation: self.animation, - state, - })) + let state = self.state.take().expect("`CustomCursorFuture` polled after completion"); + + Poll::Ready(result.map(|_| CustomCursor { animation: self.animation, state })) } } @@ -244,10 +218,8 @@ impl CursorHandler { match cursor { Cursor::Icon(icon) => { if let SelectedCursor::Icon(old_icon) - | SelectedCursor::Loading { - previous: Previous::Icon(old_icon), - .. - } = &this.cursor + | SelectedCursor::Loading { previous: Previous::Icon(old_icon), .. } = + &this.cursor { if *old_icon == icon { return; @@ -256,17 +228,13 @@ impl CursorHandler { this.cursor = SelectedCursor::Icon(icon); this.set_style(); - } + }, Cursor::Custom(cursor) => { let cursor = cursor.inner; - if let SelectedCursor::Loading { - cursor: old_cursor, .. - } + if let SelectedCursor::Loading { cursor: old_cursor, .. } | SelectedCursor::Image(old_cursor) - | SelectedCursor::Animation { - cursor: old_cursor, .. - } = &this.cursor + | SelectedCursor::Animation { cursor: old_cursor, .. } = &this.cursor { if *old_cursor == cursor { return; @@ -299,17 +267,17 @@ impl CursorHandler { previous: mem::take(&mut this.cursor).into(), _handle: handle, }; - } + }, ImageState::Failed(error) => { tracing::error!( "trying to load custom cursor that has failed to load: {error}" ) - } + }, ImageState::Image(_) => { drop(state); this.cursor = SelectedCursor::Image(cursor); this.set_style(); - } + }, ImageState::Animation(animation) => { let canvas: &CanvasAnimateExt = this.canvas.unchecked_ref(); let animation = canvas.animate_with_keyframe_animation_options( @@ -327,9 +295,9 @@ impl CursorHandler { cursor, }; this.set_style(); - } + }, }; - } + }, } } @@ -355,37 +323,29 @@ impl Inner { if self.visible { match &self.cursor { SelectedCursor::Icon(icon) - | SelectedCursor::Loading { - previous: Previous::Icon(icon), - .. - } => self.style.set("cursor", icon.name()), - SelectedCursor::Loading { - previous: Previous::Image(cursor), - .. - } + | SelectedCursor::Loading { previous: Previous::Icon(icon), .. } => { + self.style.set("cursor", icon.name()) + }, + SelectedCursor::Loading { previous: Previous::Image(cursor), .. } | SelectedCursor::Image(cursor) => { match cursor.state.get(self.main_thread).borrow().deref() { ImageState::Image(Image { style, .. }) => self.style.set("cursor", style), _ => unreachable!("found invalid saved state"), } - } + }, SelectedCursor::Loading { - previous: Previous::Animation { animation, .. }, - .. + previous: Previous::Animation { animation, .. }, .. } | SelectedCursor::Animation { animation, .. } => { self.style.remove("cursor"); animation.0.play() - } + }, } } } fn notify(&mut self) { - let SelectedCursor::Loading { - cursor, previous, .. - } = mem::take(&mut self.cursor) - else { + let SelectedCursor::Loading { cursor, previous, .. } = mem::take(&mut self.cursor) else { unreachable!("found wrong state") }; @@ -395,7 +355,7 @@ impl Inner { drop(state); self.cursor = SelectedCursor::Image(cursor); self.set_style(); - } + }, ImageState::Animation(animation) => { let canvas: &CanvasAnimateExt = self.canvas.unchecked_ref(); let animation = canvas.animate_with_keyframe_animation_options( @@ -408,16 +368,14 @@ impl Inner { animation.cancel(); } - self.cursor = SelectedCursor::Animation { - animation: AnimationDropper(animation), - cursor, - }; + self.cursor = + SelectedCursor::Animation { animation: AnimationDropper(animation), cursor }; self.set_style(); - } + }, ImageState::Failed(error) => { tracing::error!("custom cursor failed to load: {error}"); self.cursor = previous.into() - } + }, ImageState::Loading { .. } => unreachable!("notified without being ready"), } } @@ -426,16 +384,9 @@ impl Inner { #[derive(Debug)] enum SelectedCursor { Icon(CursorIcon), - Loading { - cursor: CustomCursor, - previous: Previous, - _handle: DropAbortHandle, - }, + Loading { cursor: CustomCursor, previous: Previous, _handle: DropAbortHandle }, Image(CustomCursor), - Animation { - cursor: CustomCursor, - animation: AnimationDropper, - }, + Animation { cursor: CustomCursor, animation: AnimationDropper }, } impl Default for SelectedCursor { @@ -458,10 +409,7 @@ impl From for SelectedCursor { enum Previous { Icon(CursorIcon), Image(CustomCursor), - Animation { - cursor: CustomCursor, - animation: AnimationDropper, - }, + Animation { cursor: CustomCursor, animation: AnimationDropper }, } impl From for Previous { @@ -472,17 +420,14 @@ impl From for Previous { SelectedCursor::Image(image) => Self::Image(image), SelectedCursor::Animation { cursor, animation } => { Self::Animation { cursor, animation } - } + }, } } } #[derive(Debug)] enum ImageState { - Loading { - notifier: Notifier>, - _handle: DropAbortHandle, - }, + Loading { notifier: Notifier>, _handle: DropAbortHandle }, Failed(CustomCursorError), Image(Image), Animation(Animation), @@ -601,23 +546,13 @@ fn from_rgba( .expect("unexpected exception in `createImageBitmap()`"), ); - let CursorImage { - width, - height, - hotspot_x, - hotspot_y, - .. - } = *image; + let CursorImage { width, height, hotspot_x, hotspot_y, .. } = *image; async move { - let bitmap: ImageBitmap = bitmap - .await - .expect("found invalid state in `ImageData`") - .unchecked_into(); + let bitmap: ImageBitmap = + bitmap.await.expect("found invalid state in `ImageData`").unchecked_into(); - let canvas: HtmlCanvasElement = document - .create_element("canvas") - .expect("invalid tag name") - .unchecked_into(); + let canvas: HtmlCanvasElement = + document.create_element("canvas").expect("invalid tag name").unchecked_into(); #[allow(clippy::disallowed_methods)] canvas.set_width(width as u32); #[allow(clippy::disallowed_methods)] @@ -724,7 +659,7 @@ async fn from_animation( let notified = notifier.notified(); drop(state); notified.await?; - } + }, ImageState::Failed(error) => return Err(error.clone()), ImageState::Image(_) => drop(state), ImageState::Animation(_) => unreachable!("check in `CustomCursorSource` failed"), @@ -750,11 +685,7 @@ async fn from_animation( options.set_duration(duration.as_millis() as f64); options.set_iterations(f64::INFINITY); - Ok(Animation { - keyframes, - options, - _images: images, - }) + Ok(Animation { keyframes, options, _images: images }) } #[wasm_bindgen] diff --git a/src/platform_impl/web/event_loop/mod.rs b/src/platform_impl/web/event_loop/mod.rs index 84cd171559..263a5fd964 100644 --- a/src/platform_impl/web/event_loop/mod.rs +++ b/src/platform_impl/web/event_loop/mod.rs @@ -27,25 +27,15 @@ pub(crate) struct PlatformSpecificEventLoopAttributes {} impl EventLoop { pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Result { let (user_event_sender, user_event_receiver) = mpsc::channel(); - let elw = RootActiveEventLoop { - p: ActiveEventLoop::new(), - _marker: PhantomData, - }; - Ok(EventLoop { - elw, - user_event_sender, - user_event_receiver, - }) + let elw = RootActiveEventLoop { p: ActiveEventLoop::new(), _marker: PhantomData }; + Ok(EventLoop { elw, user_event_sender, user_event_receiver }) } pub fn run(self, mut event_handler: F) -> ! where F: FnMut(Event, &RootActiveEventLoop), { - let target = RootActiveEventLoop { - p: self.elw.p.clone(), - _marker: PhantomData, - }; + let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData }; // SAFETY: Don't use `move` to make sure we leak the `event_handler` and `target`. let handler: Box)> = Box::new(|event| { @@ -79,10 +69,7 @@ impl EventLoop { where F: 'static + FnMut(Event, &RootActiveEventLoop), { - let target = RootActiveEventLoop { - p: self.elw.p.clone(), - _marker: PhantomData, - }; + let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData }; self.elw.p.run( Box::new(move |event| { diff --git a/src/platform_impl/web/event_loop/proxy.rs b/src/platform_impl/web/event_loop/proxy.rs index 691efa32b8..bd8e714635 100644 --- a/src/platform_impl/web/event_loop/proxy.rs +++ b/src/platform_impl/web/event_loop/proxy.rs @@ -16,9 +16,7 @@ impl EventLoopProxy { } pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { - self.sender - .send(event) - .map_err(|SendError(event)| EventLoopClosed(event))?; + self.sender.send(event).map_err(|SendError(event)| EventLoopClosed(event))?; self.runner.wake(); Ok(()) } @@ -26,9 +24,6 @@ impl EventLoopProxy { impl Clone for EventLoopProxy { fn clone(&self) -> Self { - Self { - runner: self.runner.clone(), - sender: self.sender.clone(), - } + Self { runner: self.runner.clone(), sender: self.sender.clone() } } } diff --git a/src/platform_impl/web/event_loop/runner.rs b/src/platform_impl/web/event_loop/runner.rs index 64fab9b064..14311d6890 100644 --- a/src/platform_impl/web/event_loop/runner.rs +++ b/src/platform_impl/web/event_loop/runner.rs @@ -1,6 +1,7 @@ use super::super::main_thread::MainThreadMarker; use super::super::DeviceId; -use super::{backend, state::State}; +use super::backend; +use super::state::State; use crate::dpi::PhysicalSize; use crate::event::{ DeviceEvent, DeviceId as RootDeviceId, ElementState, Event, RawKeyEvent, StartCause, @@ -13,13 +14,11 @@ use crate::platform_impl::platform::r#async::{DispatchRunner, Waker, WakerSpawne use crate::platform_impl::platform::window::Inner; use crate::window::WindowId; -use std::{ - cell::{Cell, RefCell}, - collections::{HashSet, VecDeque}, - iter, - ops::Deref, - rc::{Rc, Weak}, -}; +use std::cell::{Cell, RefCell}; +use std::collections::{HashSet, VecDeque}; +use std::iter; +use std::ops::Deref; +use std::rc::{Rc, Weak}; use wasm_bindgen::prelude::Closure; use web_sys::{Document, KeyboardEvent, PageTransitionEvent, PointerEvent, WheelEvent}; use web_time::{Duration, Instant}; @@ -50,13 +49,7 @@ pub struct Execution { window: web_sys::Window, document: Document, #[allow(clippy::type_complexity)] - all_canvases: RefCell< - Vec<( - WindowId, - Weak>, - DispatchRunner, - )>, - >, + all_canvases: RefCell>, DispatchRunner)>>, redraw_pending: RefCell>, destroy_pending: RefCell>, page_transition_event_handle: RefCell>, @@ -97,10 +90,7 @@ struct Runner { impl Runner { pub fn new(event_handler: Box) -> Self { - Runner { - state: State::Init, - event_handler, - } + Runner { state: State::Init, event_handler } } /// Returns the corresponding `StartCause` for the current `state`, or `None` @@ -109,13 +99,9 @@ impl Runner { Some(match self.state { State::Init => StartCause::Init, State::Poll { .. } => StartCause::Poll, - State::Wait { start } => StartCause::WaitCancelled { - start, - requested_resume: None, - }, - State::WaitUntil { start, end, .. } => StartCause::WaitCancelled { - start, - requested_resume: Some(end), + State::Wait { start } => StartCause::WaitCancelled { start, requested_resume: None }, + State::WaitUntil { start, end, .. } => { + StartCause::WaitCancelled { start, requested_resume: Some(end) } }, State::Exit => return None, }) @@ -124,11 +110,7 @@ impl Runner { fn handle_single_event(&mut self, runner: &Shared, event: impl Into) { match event.into() { EventWrapper::Event(event) => (self.event_handler)(event), - EventWrapper::ScaleChange { - canvas, - size, - scale, - } => { + EventWrapper::ScaleChange { canvas, size, scale } => { if let Some(canvas) = canvas.upgrade() { canvas.borrow().handle_scale_change( runner, @@ -137,7 +119,7 @@ impl Runner { scale, ) } - } + }, } } } @@ -280,10 +262,7 @@ impl Shared { runner.send_event(Event::DeviceEvent { device_id, - event: DeviceEvent::Button { - button: button.to_id(), - state, - }, + event: DeviceEvent::Button { button: button.to_id(), state }, }); return; @@ -292,35 +271,22 @@ impl Shared { // pointer move event let mut delta = backend::event::MouseDelta::init(&window, &event); runner.send_events(backend::event::pointer_move_event(event).flat_map(|event| { - let delta = delta - .delta(&event) - .to_physical(backend::scale_factor(&window)); + let delta = delta.delta(&event).to_physical(backend::scale_factor(&window)); let x_motion = (delta.x != 0.0).then_some(Event::DeviceEvent { device_id, - event: DeviceEvent::Motion { - axis: 0, - value: delta.x, - }, + event: DeviceEvent::Motion { axis: 0, value: delta.x }, }); let y_motion = (delta.y != 0.0).then_some(Event::DeviceEvent { device_id, - event: DeviceEvent::Motion { - axis: 1, - value: delta.y, - }, + event: DeviceEvent::Motion { axis: 1, value: delta.y }, }); - x_motion - .into_iter() - .chain(y_motion) - .chain(iter::once(Event::DeviceEvent { - device_id, - event: DeviceEvent::MouseMotion { - delta: (delta.x, delta.y), - }, - })) + x_motion.into_iter().chain(y_motion).chain(iter::once(Event::DeviceEvent { + device_id, + event: DeviceEvent::MouseMotion { delta: (delta.x, delta.y) }, + })) })); }), )); @@ -482,10 +448,8 @@ impl Shared { // Run the logic for waking from a WaitUntil, which involves clearing the queue // Generally there shouldn't be events built up when this is called pub fn resume_time_reached(&self, start: Instant, requested_resume: Instant) { - let start_cause = Event::NewEvents(StartCause::ResumeTimeReached { - start, - requested_resume, - }); + let start_cause = + Event::NewEvents(StartCause::ResumeTimeReached { start, requested_resume }); self.run_until_cleared(iter::once(start_cause)); } @@ -508,30 +472,28 @@ impl Shared { let mut process_immediately = true; match self.0.runner.try_borrow().as_ref().map(Deref::deref) { Ok(RunnerEnum::Running(ref runner)) => { - // If we're currently polling, queue this and wait for the poll() method to be called + // If we're currently polling, queue this and wait for the poll() method to be + // called if let State::Poll { .. } = runner.state { process_immediately = false; } - } + }, Ok(RunnerEnum::Pending) => { // The runner still hasn't been attached: queue this event and wait for it to be process_immediately = false; - } + }, // Some other code is mutating the runner, which most likely means // the event loop is running and busy. So we queue this event for // it to be processed later. Err(_) => { process_immediately = false; - } + }, // This is unreachable since `self.is_closed() == true`. Ok(RunnerEnum::Destroyed) => unreachable!(), } if !process_immediately { // Queue these events to look at later - self.0 - .events - .borrow_mut() - .extend(events.into_iter().map(Into::into)); + self.0.events.borrow_mut().extend(events.into_iter().map(Into::into)); return; } // At this point, we know this is a fresh set of events @@ -558,10 +520,7 @@ impl Shared { // `run_until_cleared`, somewhere between emitting `NewEvents` and `AboutToWait`. fn process_destroy_pending_windows(&self) { while let Some(id) = self.0.destroy_pending.borrow_mut().pop_front() { - self.0 - .all_canvases - .borrow_mut() - .retain(|&(item_id, _, _)| item_id != id); + self.0.all_canvases.borrow_mut().retain(|&(item_id, ..)| item_id != id); self.handle_event(Event::WindowEvent { window_id: id, event: crate::event::WindowEvent::Destroyed, @@ -617,7 +576,7 @@ impl Shared { match *self.0.runner.borrow_mut() { RunnerEnum::Running(ref mut runner) => { runner.handle_single_event(self, event); - } + }, // If an event is being handled without a runner somehow, add it to the event queue so // it will eventually be processed RunnerEnum::Pending => self.0.events.borrow_mut().push_back(event.into()), @@ -675,18 +634,12 @@ impl Shared { move || cloned.poll(), ), } - } - ControlFlow::Wait => State::Wait { - start: Instant::now(), }, + ControlFlow::Wait => State::Wait { start: Instant::now() }, ControlFlow::WaitUntil(end) => { let start = Instant::now(); - let delay = if end <= start { - Duration::from_millis(0) - } else { - end - start - }; + let delay = if end <= start { Duration::from_millis(0) } else { end - start }; let cloned = self.clone(); @@ -699,7 +652,7 @@ impl Shared { delay, ), } - } + }, } }; @@ -732,11 +685,10 @@ impl Shared { } // At this point, the `self.0` `Rc` should only be strongly referenced // by the following: - // * `self`, i.e. the item which triggered this event loop wakeup, which - // is usually a `wasm-bindgen` `Closure`, which will be dropped after - // returning to the JS glue code. - // * The `ActiveEventLoop` leaked inside `EventLoop::run_app` due to the - // JS exception thrown at the end. + // * `self`, i.e. the item which triggered this event loop wakeup, which is usually a + // `wasm-bindgen` `Closure`, which will be dropped after returning to the JS glue code. + // * The `ActiveEventLoop` leaked inside `EventLoop::run_app` due to the JS exception thrown + // at the end. // * For each undropped `Window`: // * The `register_redraw_request` closure. // * The `destroy_fn` closure. @@ -774,7 +726,7 @@ impl Shared { false } }) - } + }, DeviceEvents::Never => false, } } @@ -814,11 +766,7 @@ impl Shared { pub(crate) enum EventWrapper { Event(Event<()>), - ScaleChange { - canvas: Weak>, - size: PhysicalSize, - scale: f64, - }, + ScaleChange { canvas: Weak>, size: PhysicalSize, scale: f64 }, } impl From> for EventWrapper { diff --git a/src/platform_impl/web/event_loop/state.rs b/src/platform_impl/web/event_loop/state.rs index 309a93fddf..d06e30edd6 100644 --- a/src/platform_impl/web/event_loop/state.rs +++ b/src/platform_impl/web/event_loop/state.rs @@ -5,17 +5,9 @@ use web_time::Instant; #[derive(Debug)] pub enum State { Init, - WaitUntil { - _timeout: backend::Schedule, - start: Instant, - end: Instant, - }, - Wait { - start: Instant, - }, - Poll { - _request: backend::Schedule, - }, + WaitUntil { _timeout: backend::Schedule, start: Instant, end: Instant }, + Wait { start: Instant }, + Poll { _request: backend::Schedule }, Exit, } diff --git a/src/platform_impl/web/event_loop/window_target.rs b/src/platform_impl/web/event_loop/window_target.rs index 3d23d9ce84..142466ab0b 100644 --- a/src/platform_impl/web/event_loop/window_target.rs +++ b/src/platform_impl/web/event_loop/window_target.rs @@ -1,26 +1,24 @@ use std::cell::{Cell, RefCell}; use std::clone::Clone; -use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque}; +use std::collections::vec_deque::IntoIter as VecDequeIter; +use std::collections::VecDeque; use std::iter; use std::rc::{Rc, Weak}; use web_sys::Element; +use super::super::monitor::MonitorHandle; +use super::super::KeyEventExtra; +use super::device::DeviceId; use super::runner::{EventWrapper, Execution}; -use super::{ - super::{monitor::MonitorHandle, KeyEventExtra}, - backend, - device::DeviceId, - runner, - window::WindowId, -}; +use super::window::WindowId; +use super::{backend, runner}; use crate::event::{ DeviceId as RootDeviceId, ElementState, Event, KeyEvent, Touch, TouchPhase, WindowEvent, }; use crate::event_loop::{ControlFlow, DeviceEvents}; use crate::keyboard::ModifiersState; -use crate::platform::web::CustomCursorFuture; -use crate::platform::web::PollStrategy; +use crate::platform::web::{CustomCursorFuture, PollStrategy}; use crate::platform_impl::platform::cursor::CustomCursor; use crate::platform_impl::platform::r#async::Waker; use crate::window::{ @@ -54,10 +52,7 @@ pub struct ActiveEventLoop { impl ActiveEventLoop { pub fn new() -> Self { - Self { - runner: runner::Shared::new(), - modifiers: ModifiersShared::default(), - } + Self { runner: runner::Shared::new(), modifiers: ModifiersShared::default() } } pub fn run(&self, event_handler: Box, event_loop_recreation: bool) { @@ -70,9 +65,7 @@ impl ActiveEventLoop { } pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { - RootCustomCursor { - inner: CustomCursor::new(self, source.inner), - } + RootCustomCursor { inner: CustomCursor::new(self, source.inner) } } pub fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture { @@ -101,14 +94,10 @@ impl ActiveEventLoop { } }); - runner.send_events( - clear_modifiers - .into_iter() - .chain(iter::once(Event::WindowEvent { - window_id: RootWindowId(id), - event: WindowEvent::Focused(false), - })), - ); + runner.send_events(clear_modifiers.into_iter().chain(iter::once(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Focused(false), + }))); }); let runner = self.runner.clone(); @@ -304,10 +293,7 @@ impl ActiveEventLoop { iter::once(Event::WindowEvent { window_id: RootWindowId(id), - event: WindowEvent::CursorMoved { - device_id, - position, - }, + event: WindowEvent::CursorMoved { device_id, position }, }) }))); } @@ -374,18 +360,11 @@ impl ActiveEventLoop { runner.send_events(modifiers.into_iter().chain([ Event::WindowEvent { window_id: RootWindowId(id), - event: WindowEvent::CursorMoved { - device_id, - position, - }, + event: WindowEvent::CursorMoved { device_id, position }, }, Event::WindowEvent { window_id: RootWindowId(id), - event: WindowEvent::MouseInput { - device_id, - state, - button, - }, + event: WindowEvent::MouseInput { device_id, state, button }, }, ])); } @@ -428,10 +407,7 @@ impl ActiveEventLoop { runner.send_events(modifiers.into_iter().chain([ Event::WindowEvent { window_id: RootWindowId(id), - event: WindowEvent::CursorMoved { - device_id, - position, - }, + event: WindowEvent::CursorMoved { device_id, position }, }, Event::WindowEvent { window_id: RootWindowId(id), @@ -512,10 +488,7 @@ impl ActiveEventLoop { runner.send_events(modifiers.into_iter().chain([ Event::WindowEvent { window_id: RootWindowId(id), - event: WindowEvent::CursorMoved { - device_id, - position, - }, + event: WindowEvent::CursorMoved { device_id, position }, }, Event::WindowEvent { window_id: RootWindowId(id), @@ -599,11 +572,7 @@ impl ActiveEventLoop { let runner = self.runner.clone(); canvas.on_dark_mode(move |is_dark_mode| { - let theme = if is_dark_mode { - Theme::Dark - } else { - Theme::Light - }; + let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::ThemeChanged(theme), @@ -682,9 +651,7 @@ impl ActiveEventLoop { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Web( - rwh_06::WebDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new())) } pub fn listen_device_events(&self, allowed: DeviceEvents) { diff --git a/src/platform_impl/web/mod.rs b/src/platform_impl/web/mod.rs index ad10909b7a..df1da5aa1f 100644 --- a/src/platform_impl/web/mod.rs +++ b/src/platform_impl/web/mod.rs @@ -45,6 +45,7 @@ pub use self::window::{PlatformSpecificWindowAttributes, Window, WindowId}; pub(crate) use self::keyboard::KeyEventExtra; pub(crate) use crate::icon::NoIcon as PlatformIcon; pub(crate) use crate::platform_impl::Fullscreen; -pub(crate) use cursor::CustomCursor as PlatformCustomCursor; -pub(crate) use cursor::CustomCursorFuture; -pub(crate) use cursor::CustomCursorSource as PlatformCustomCursorSource; +pub(crate) use cursor::{ + CustomCursor as PlatformCustomCursor, CustomCursorFuture, + CustomCursorSource as PlatformCustomCursorSource, +}; diff --git a/src/platform_impl/web/web_sys/animation_frame.rs b/src/platform_impl/web/web_sys/animation_frame.rs index b761f9a9a7..17aa8f6808 100644 --- a/src/platform_impl/web/web_sys/animation_frame.rs +++ b/src/platform_impl/web/web_sys/animation_frame.rs @@ -17,11 +17,7 @@ impl AnimationFrameHandler { move || handle.set(None) }); - Self { - window, - closure, - handle, - } + Self { window, closure, handle } } pub fn on_animation_frame(&mut self, mut f: F) @@ -37,9 +33,7 @@ impl AnimationFrameHandler { pub fn request(&self) { if let Some(handle) = self.handle.take() { - self.window - .cancel_animation_frame(handle) - .expect("Failed to cancel animation frame"); + self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame"); } let handle = self @@ -52,9 +46,7 @@ impl AnimationFrameHandler { pub fn cancel(&mut self) { if let Some(handle) = self.handle.take() { - self.window - .cancel_animation_frame(handle) - .expect("Failed to cancel animation frame"); + self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame"); } } } @@ -62,9 +54,7 @@ impl AnimationFrameHandler { impl Drop for AnimationFrameHandler { fn drop(&mut self) { if let Some(handle) = self.handle.take() { - self.window - .cancel_animation_frame(handle) - .expect("Failed to cancel animation frame"); + self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame"); } } } diff --git a/src/platform_impl/web/web_sys/canvas.rs b/src/platform_impl/web/web_sys/canvas.rs index f47b2dc3f6..0450ba8e0d 100644 --- a/src/platform_impl/web/web_sys/canvas.rs +++ b/src/platform_impl/web/web_sys/canvas.rs @@ -4,7 +4,8 @@ use std::rc::Rc; use std::sync::{Arc, Mutex}; use smol_str::SmolStr; -use wasm_bindgen::{closure::Closure, JsCast}; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::JsCast; use web_sys::{ CssStyleDeclaration, Document, Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, PointerEvent, WheelEvent, @@ -53,8 +54,9 @@ pub struct Canvas { pub struct Common { pub window: web_sys::Window, pub document: Document, - /// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained. - /// Note: this is read-only because we use a pointer to this for [`WindowHandle`][rwh_06::WindowHandle]. + /// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure + /// the DPI factor is maintained. Note: this is read-only because we use a pointer to this + /// for [`WindowHandle`][rwh_06::WindowHandle]. raw: Rc, style: Style, old_size: Rc>>, @@ -188,10 +190,7 @@ impl Canvas { pub fn position(&self) -> LogicalPosition { let bounds = self.common.raw.get_bounding_client_rect(); - let mut position = LogicalPosition { - x: bounds.x(), - y: bounds.y(), - }; + let mut position = LogicalPosition { x: bounds.x(), y: bounds.y() }; if self.document().contains(Some(self.raw())) && self.style().get("display") != "none" { position.x += super::style_size_property(self.style(), "border-left-width") @@ -298,9 +297,8 @@ impl Canvas { F: 'static + FnMut(PhysicalKey, Key, Option, KeyLocation, bool, ModifiersState), { let prevent_default = Rc::clone(&self.prevent_default); - self.on_keyboard_press = Some(self.common.add_event( - "keydown", - move |event: KeyboardEvent| { + self.on_keyboard_press = + Some(self.common.add_event("keydown", move |event: KeyboardEvent| { if prevent_default.get() { event.prevent_default(); } @@ -314,8 +312,7 @@ impl Canvas { event.repeat(), modifiers, ); - }, - )); + })); } pub fn on_cursor_leave(&mut self, handler: F) @@ -459,14 +456,12 @@ impl Canvas { pub(crate) fn on_context_menu(&mut self) { let prevent_default = Rc::clone(&self.prevent_default); - self.on_context_menu = Some(self.common.add_event( - "contextmenu", - move |event: PointerEvent| { + self.on_context_menu = + Some(self.common.add_event("contextmenu", move |event: PointerEvent| { if prevent_default.get() { event.prevent_default(); } - }, - )); + })); } pub fn request_fullscreen(&self) { @@ -580,20 +575,14 @@ impl Style { } pub(crate) fn get(&self, property: &str) -> String { - self.read - .get_property_value(property) - .expect("Invalid property") + self.read.get_property_value(property).expect("Invalid property") } pub(crate) fn remove(&self, property: &str) { - self.write - .remove_property(property) - .expect("Property is read only"); + self.write.remove_property(property).expect("Property is read only"); } pub(crate) fn set(&self, property: &str, value: &str) { - self.write - .set_property(property, value) - .expect("Property is read only"); + self.write.set_property(property, value).expect("Property is read only"); } } diff --git a/src/platform_impl/web/web_sys/event.rs b/src/platform_impl/web/web_sys/event.rs index 3eb6cbac78..51df63714b 100644 --- a/src/platform_impl/web/web_sys/event.rs +++ b/src/platform_impl/web/web_sys/event.rs @@ -59,10 +59,9 @@ pub fn mouse_button(event: &MouseEvent) -> Option { 2 => Some(MouseButton::Right), 3 => Some(MouseButton::Back), 4 => Some(MouseButton::Forward), - i => Some(MouseButton::Other( - i.try_into() - .expect("unexpected negative mouse button value"), - )), + i => { + Some(MouseButton::Other(i.try_into().expect("unexpected negative mouse button value"))) + }, } } @@ -93,10 +92,7 @@ pub fn mouse_position(event: &MouseEvent) -> LogicalPosition { let event: &MouseEventExt = event.unchecked_ref(); - LogicalPosition { - x: event.offset_x(), - y: event.offset_y(), - } + LogicalPosition { x: event.offset_x(), y: event.offset_y() } } // TODO: Remove this when Firefox supports correct movement values in coalesced events. @@ -114,17 +110,15 @@ impl MouseDelta { // for `pointerrawupdate` support. Presumably an implementation of `pointerrawupdate` // should require correct movement values, otherwise uncoalesced events might be broken as // well. - Self( - (!has_pointer_raw_support(window) && has_coalesced_events_support(event)).then(|| { - MouseDeltaInner { - old_position: mouse_position(event), - old_delta: LogicalPosition { - x: event.movement_x() as f64, - y: event.movement_y() as f64, - }, - } - }), - ) + Self((!has_pointer_raw_support(window) && has_coalesced_events_support(event)).then(|| { + MouseDeltaInner { + old_position: mouse_position(event), + old_delta: LogicalPosition { + x: event.movement_x() as f64, + y: event.movement_y() as f64, + }, + } + })) } pub fn delta(&mut self, event: &MouseEvent) -> LogicalPosition { @@ -136,10 +130,7 @@ impl MouseDelta { inner.old_delta = LogicalPosition::new(0., 0.); LogicalPosition::new(x, y) } else { - LogicalPosition { - x: event.movement_x() as f64, - y: event.movement_y() as f64, - } + LogicalPosition { x: event.movement_x() as f64, y: event.movement_y() as f64 } } } } @@ -156,7 +147,7 @@ pub fn mouse_scroll_delta( WheelEvent::DOM_DELTA_PIXEL => { let delta = LogicalPosition::new(x, y).to_physical(super::scale_factor(window)); Some(MouseScrollDelta::PixelDelta(delta)) - } + }, _ => None, } } @@ -192,7 +183,7 @@ pub fn key_location(event: &KeyboardEvent) -> KeyLocation { location => { tracing::warn!("Unexpected key location: {location}"); KeyLocation::Standard - } + }, } } @@ -238,14 +229,9 @@ pub fn pointer_move_event(event: PointerEvent) -> impl Iterator { @@ -16,11 +17,7 @@ impl EventListenerHandle { target .add_event_listener_with_callback(event_type, listener.as_ref().unchecked_ref()) .expect("Failed to add event listener"); - EventListenerHandle { - target, - event_type, - listener, - } + EventListenerHandle { target, event_type, listener } } } diff --git a/src/platform_impl/web/web_sys/fullscreen.rs b/src/platform_impl/web/web_sys/fullscreen.rs index b365c88b4e..867d34a623 100644 --- a/src/platform_impl/web/web_sys/fullscreen.rs +++ b/src/platform_impl/web/web_sys/fullscreen.rs @@ -58,7 +58,7 @@ pub fn is_fullscreen(document: &Document, canvas: &HtmlCanvasElement) -> bool { Some(element) => { let canvas: &Element = canvas; canvas == &element - } + }, None => false, } } diff --git a/src/platform_impl/web/web_sys/intersection_handle.rs b/src/platform_impl/web/web_sys/intersection_handle.rs index cae8eeb722..9f63e84cb1 100644 --- a/src/platform_impl/web/web_sys/intersection_handle.rs +++ b/src/platform_impl/web/web_sys/intersection_handle.rs @@ -1,5 +1,6 @@ use js_sys::Array; -use wasm_bindgen::{prelude::Closure, JsCast}; +use wasm_bindgen::prelude::Closure; +use wasm_bindgen::JsCast; use web_sys::{Element, IntersectionObserver, IntersectionObserverEntry}; pub(super) struct IntersectionObserverHandle { @@ -21,10 +22,7 @@ impl IntersectionObserverHandle { .expect("Invalid `options`"); observer.observe(element); - Self { - observer, - _closure: closure, - } + Self { observer, _closure: closure } } } diff --git a/src/platform_impl/web/web_sys/media_query_handle.rs b/src/platform_impl/web/web_sys/media_query_handle.rs index ad78ffd6c3..766157a681 100644 --- a/src/platform_impl/web/web_sys/media_query_handle.rs +++ b/src/platform_impl/web/web_sys/media_query_handle.rs @@ -1,4 +1,5 @@ -use wasm_bindgen::{prelude::Closure, JsCast}; +use wasm_bindgen::prelude::Closure; +use wasm_bindgen::JsCast; use web_sys::MediaQueryList; pub(super) struct MediaQueryListHandle { @@ -41,8 +42,7 @@ impl Drop for MediaQueryListHandle { } fn remove_listener(mql: &MediaQueryList, listener: &Closure) { - mql.remove_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref())) - .unwrap_or_else(|e| { - web_sys::console::error_2(&"Error removing media query listener".into(), &e) - }); + mql.remove_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref())).unwrap_or_else( + |e| web_sys::console::error_2(&"Error removing media query listener".into(), &e), + ); } diff --git a/src/platform_impl/web/web_sys/mod.rs b/src/platform_impl/web/web_sys/mod.rs index 089d6e8525..b0a8fbae42 100644 --- a/src/platform_impl/web/web_sys/mod.rs +++ b/src/platform_impl/web/web_sys/mod.rs @@ -9,8 +9,7 @@ mod pointer; mod resize_scaling; mod schedule; -pub use self::canvas::Canvas; -pub use self::canvas::Style; +pub use self::canvas::{Canvas, Style}; pub use self::event::ButtonsState; pub use self::event_handle::EventListenerHandle; pub use self::resize_scaling::ResizeScaleHandle; @@ -40,10 +39,7 @@ pub fn on_page_transition( let show_listener = event_handle::EventListenerHandle::new(window.clone(), "pageshow", show_closure); let hide_listener = event_handle::EventListenerHandle::new(window, "pagehide", hide_closure); - PageTransitionEventHandle { - _show_listener: show_listener, - _hide_listener: hide_listener, - } + PageTransitionEventHandle { _show_listener: show_listener, _hide_listener: hide_listener } } pub fn scale_factor(window: &web_sys::Window) -> f64 { @@ -154,11 +150,7 @@ pub fn style_size_property(style: &Style, property: &str) -> f64 { } pub fn is_dark_mode(window: &web_sys::Window) -> Option { - window - .match_media("(prefers-color-scheme: dark)") - .ok() - .flatten() - .map(|media| media.matches()) + window.match_media("(prefers-color-scheme: dark)").ok().flatten().map(|media| media.matches()) } pub fn is_visible(document: &Document) -> bool { diff --git a/src/platform_impl/web/web_sys/pointer.rs b/src/platform_impl/web/web_sys/pointer.rs index 0c07c4abc8..90e8b27b7f 100644 --- a/src/platform_impl/web/web_sys/pointer.rs +++ b/src/platform_impl/web/web_sys/pointer.rs @@ -37,9 +37,8 @@ impl PointerHandler { where F: 'static + FnMut(ModifiersState, Option), { - self.on_cursor_leave = Some(canvas_common.add_event( - "pointerout", - move |event: PointerEvent| { + self.on_cursor_leave = + Some(canvas_common.add_event("pointerout", move |event: PointerEvent| { let modifiers = event::mouse_modifiers(&event); // touch events are handled separately @@ -48,17 +47,15 @@ impl PointerHandler { let pointer_id = (event.pointer_type() == "mouse").then(|| event.pointer_id()); handler(modifiers, pointer_id); - }, - )); + })); } pub fn on_cursor_enter(&mut self, canvas_common: &Common, mut handler: F) where F: 'static + FnMut(ModifiersState, Option), { - self.on_cursor_enter = Some(canvas_common.add_event( - "pointerover", - move |event: PointerEvent| { + self.on_cursor_enter = + Some(canvas_common.add_event("pointerover", move |event: PointerEvent| { let modifiers = event::mouse_modifiers(&event); // touch events are handled separately @@ -67,8 +64,7 @@ impl PointerHandler { let pointer_id = (event.pointer_type() == "mouse").then(|| event.pointer_id()); handler(modifiers, pointer_id); - }, - )); + })); } pub fn on_mouse_release( @@ -83,9 +79,8 @@ impl PointerHandler { T: 'static + FnMut(ModifiersState, i32, PhysicalPosition, Force), { let window = canvas_common.window.clone(); - self.on_pointer_release = Some(canvas_common.add_event( - "pointerup", - move |event: PointerEvent| { + self.on_pointer_release = + Some(canvas_common.add_event("pointerup", move |event: PointerEvent| { let modifiers = event::mouse_modifiers(&event); match event.pointer_type().as_str() { @@ -103,8 +98,7 @@ impl PointerHandler { ), _ => modifier_handler(modifiers), } - }, - )); + })); } pub fn on_mouse_press( @@ -121,9 +115,8 @@ impl PointerHandler { { let window = canvas_common.window.clone(); let canvas = canvas_common.raw().clone(); - self.on_pointer_press = Some(canvas_common.add_event( - "pointerdown", - move |event: PointerEvent| { + self.on_pointer_press = + Some(canvas_common.add_event("pointerdown", move |event: PointerEvent| { if prevent_default.get() { // prevent text selection event.prevent_default(); @@ -141,7 +134,7 @@ impl PointerHandler { event::mouse_position(&event).to_physical(super::scale_factor(&window)), Force::Normalized(event.pressure() as f64), ); - } + }, "mouse" => { mouse_handler( modifiers, @@ -150,15 +143,15 @@ impl PointerHandler { event::mouse_button(&event).expect("no mouse button pressed"), ); - // Error is swallowed here since the error would occur every time the mouse is - // clicked when the cursor is grabbed, and there is probably not a situation where - // this could fail, that we care if it fails. + // Error is swallowed here since the error would occur every time the mouse + // is clicked when the cursor is grabbed, and there + // is probably not a situation where this could + // fail, that we care if it fails. let _e = canvas.set_pointer_capture(event.pointer_id()); - } + }, _ => modifier_handler(modifiers), } - }, - )); + })); } pub fn on_cursor_move( @@ -178,9 +171,8 @@ impl PointerHandler { { let window = canvas_common.window.clone(); let canvas = canvas_common.raw().clone(); - self.on_cursor_move = Some(canvas_common.add_event( - "pointermove", - move |event: PointerEvent| { + self.on_cursor_move = + Some(canvas_common.add_event("pointermove", move |event: PointerEvent| { let modifiers = event::mouse_modifiers(&event); let pointer_type = event.pointer_type(); @@ -239,8 +231,7 @@ impl PointerHandler { ), _ => unreachable!("didn't return early before"), }; - }, - )); + })); } pub fn on_touch_cancel(&mut self, canvas_common: &Common, mut handler: F) @@ -248,9 +239,8 @@ impl PointerHandler { F: 'static + FnMut(i32, PhysicalPosition, Force), { let window = canvas_common.window.clone(); - self.on_touch_cancel = Some(canvas_common.add_event( - "pointercancel", - move |event: PointerEvent| { + self.on_touch_cancel = + Some(canvas_common.add_event("pointercancel", move |event: PointerEvent| { if event.pointer_type() == "touch" { handler( event.pointer_id(), @@ -258,8 +248,7 @@ impl PointerHandler { Force::Normalized(event.pressure() as f64), ); } - }, - )); + })); } pub fn remove_listeners(&mut self) { diff --git a/src/platform_impl/web/web_sys/resize_scaling.rs b/src/platform_impl/web/web_sys/resize_scaling.rs index de7dc78f2e..e22fba54b8 100644 --- a/src/platform_impl/web/web_sys/resize_scaling.rs +++ b/src/platform_impl/web/web_sys/resize_scaling.rs @@ -210,9 +210,8 @@ impl ResizeScaleInternal { // This should never happen, but if it does then apparently the scale factor didn't change. if mql.matches() { warn!( - "media query tracking scale factor was triggered without a change:\n\ - Media Query: {}\n\ - Current Scale: {scale}", + "media query tracking scale factor was triggered without a change:\nMedia Query: \ + {}\nCurrent Scale: {scale}", mql.media(), ); return; @@ -240,10 +239,8 @@ impl ResizeScaleInternal { .to_physical(backend::scale_factor(&self.window)); } - let entry: ResizeObserverSize = entry - .device_pixel_content_box_size() - .get(0) - .unchecked_into(); + let entry: ResizeObserverSize = + entry.device_pixel_content_box_size().get(0).unchecked_into(); let writing_mode = self.style.get("writing-mode"); @@ -259,14 +256,14 @@ impl ResizeScaleInternal { _ if writing_mode.starts_with("horizontal") => true, _ if writing_mode.starts_with("vertical") | writing_mode.starts_with("sideways") => { false - } + }, // deprecated values "lr" | "lr-tb" | "rl" => true, "tb" | "tb-lr" | "tb-rl" => false, _ => { warn!("unrecognized `writing-mode`, assuming horizontal"); true - } + }, }; if horizontal { diff --git a/src/platform_impl/web/web_sys/schedule.rs b/src/platform_impl/web/web_sys/schedule.rs index 9bc4d1d71a..c8b82b2e9f 100644 --- a/src/platform_impl/web/web_sys/schedule.rs +++ b/src/platform_impl/web/web_sys/schedule.rs @@ -89,10 +89,7 @@ impl Schedule { .catch(handler); }); - Schedule { - _closure: closure, - inner: Inner::Scheduler { controller }, - } + Schedule { _closure: closure, inner: Inner::Scheduler { controller } } } fn new_idle_callback(window: web_sys::Window, f: F) -> Schedule @@ -104,10 +101,7 @@ impl Schedule { .request_idle_callback(closure.as_ref().unchecked_ref()) .expect("Failed to request idle callback"); - Schedule { - _closure: closure, - inner: Inner::IdleCallback { window, handle }, - } + Schedule { _closure: closure, inner: Inner::IdleCallback { window, handle } } } fn new_timeout(window: web_sys::Window, f: F, duration: Option) -> Schedule @@ -122,9 +116,7 @@ impl Schedule { let port_2 = channel.port2(); let timeout_closure = Closure::new(move || { - port_2 - .post_message(&JsValue::UNDEFINED) - .expect("Failed to send message") + port_2.post_message(&JsValue::UNDEFINED).expect("Failed to send message") }); let handle = if let Some(duration) = duration { // `Duration::as_millis()` always rounds down (because of truncation), we want to round @@ -168,16 +160,11 @@ impl Drop for Schedule { match &self.inner { Inner::Scheduler { controller, .. } => controller.abort(), Inner::IdleCallback { window, handle, .. } => window.cancel_idle_callback(*handle), - Inner::Timeout { - window, - handle, - port, - .. - } => { + Inner::Timeout { window, handle, port, .. } => { window.clear_timeout_with_handle(*handle); port.close(); port.set_onmessage(None); - } + }, } } } diff --git a/src/platform_impl/web/window.rs b/src/platform_impl/web/window.rs index 9c477221c7..acfefe3063 100644 --- a/src/platform_impl/web/window.rs +++ b/src/platform_impl/web/window.rs @@ -7,8 +7,9 @@ use crate::window::{ }; use super::main_thread::{MainThreadMarker, MainThreadSafe}; +use super::monitor::MonitorHandle; use super::r#async::Dispatcher; -use super::{backend, monitor::MonitorHandle, ActiveEventLoop, Fullscreen}; +use super::{backend, ActiveEventLoop, Fullscreen}; use web_sys::HtmlCanvasElement; use std::cell::RefCell; @@ -50,12 +51,7 @@ impl Window { let runner = target.runner.clone(); let destroy_fn = Box::new(move || runner.notify_destroy_window(RootWI(id))); - let inner = Inner { - id, - window: window.clone(), - canvas, - destroy_fn: Some(destroy_fn), - }; + let inner = Inner { id, window: window.clone(), canvas, destroy_fn: Some(destroy_fn) }; inner.set_title(&attr.title); inner.set_maximized(attr.maximized); @@ -79,19 +75,15 @@ impl Window { } pub fn canvas(&self) -> Option { - self.inner - .value() - .map(|inner| inner.canvas.borrow().raw().clone()) + self.inner.value().map(|inner| inner.canvas.borrow().raw().clone()) } pub(crate) fn prevent_default(&self) -> bool { - self.inner - .queue(|inner| inner.canvas.borrow().prevent_default.get()) + self.inner.queue(|inner| inner.canvas.borrow().prevent_default.get()) } pub(crate) fn set_prevent_default(&self, prevent_default: bool) { - self.inner - .dispatch(move |inner| inner.canvas.borrow().prevent_default.set(prevent_default)) + self.inner.dispatch(move |inner| inner.canvas.borrow().prevent_default.set(prevent_default)) } #[cfg(feature = "rwh_06")] @@ -115,9 +107,7 @@ impl Window { pub(crate) fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Web( - rwh_06::WebDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new())) } } @@ -146,11 +136,7 @@ impl Inner { pub fn pre_present_notify(&self) {} pub fn outer_position(&self) -> Result, NotSupportedError> { - Ok(self - .canvas - .borrow() - .position() - .to_physical(self.scale_factor())) + Ok(self.canvas.borrow().position().to_physical(self.scale_factor())) } pub fn inner_position(&self) -> Result, NotSupportedError> { @@ -247,13 +233,10 @@ impl Inner { CursorGrabMode::Locked => true, CursorGrabMode::Confined => { return Err(ExternalError::NotSupported(NotSupportedError::new())) - } + }, }; - self.canvas - .borrow() - .set_cursor_lock(lock) - .map_err(ExternalError::Os) + self.canvas.borrow().set_cursor_lock(lock).map_err(ExternalError::Os) } #[inline] @@ -489,11 +472,6 @@ impl PlatformSpecificWindowAttributes { impl Default for PlatformSpecificWindowAttributes { fn default() -> Self { - Self { - canvas: None, - prevent_default: true, - focusable: true, - append: false, - } + Self { canvas: None, prevent_default: true, focusable: true, append: false } } } diff --git a/src/platform_impl/windows/dark_mode.rs b/src/platform_impl/windows/dark_mode.rs index 11b6977657..4f910ad5c9 100644 --- a/src/platform_impl/windows/dark_mode.rs +++ b/src/platform_impl/windows/dark_mode.rs @@ -3,21 +3,13 @@ use std::{ffi::c_void, ptr}; use crate::utils::Lazy; -use windows_sys::{ - core::PCSTR, - Win32::{ - Foundation::{BOOL, HWND, NTSTATUS, S_OK}, - System::{ - LibraryLoader::{GetProcAddress, LoadLibraryA}, - SystemInformation::OSVERSIONINFOW, - }, - UI::{ - Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTA}, - Controls::SetWindowTheme, - WindowsAndMessaging::{SystemParametersInfoA, SPI_GETHIGHCONTRAST}, - }, - }, -}; +use windows_sys::core::PCSTR; +use windows_sys::Win32::Foundation::{BOOL, HWND, NTSTATUS, S_OK}; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; +use windows_sys::Win32::System::SystemInformation::OSVERSIONINFOW; +use windows_sys::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTA}; +use windows_sys::Win32::UI::Controls::SetWindowTheme; +use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoA, SPI_GETHIGHCONTRAST}; use crate::window::Theme; @@ -72,11 +64,7 @@ pub fn try_theme(hwnd: HWND, preferred_theme: Option) -> Theme { None => should_use_dark_mode(), }; - let theme = if is_dark_mode { - Theme::Dark - } else { - Theme::Light - }; + let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; let theme_name = match theme { Theme::Dark => DARK_THEME_NAME.as_ptr(), Theme::Light => LIGHT_THEME_NAME.as_ptr(), @@ -161,11 +149,7 @@ fn should_apps_use_dark_mode() -> bool { } fn is_high_contrast() -> bool { - let mut hc = HIGHCONTRASTA { - cbSize: 0, - dwFlags: 0, - lpszDefaultScheme: ptr::null_mut(), - }; + let mut hc = HIGHCONTRASTA { cbSize: 0, dwFlags: 0, lpszDefaultScheme: ptr::null_mut() }; let ok = unsafe { SystemParametersInfoA( diff --git a/src/platform_impl/windows/definitions.rs b/src/platform_impl/windows/definitions.rs index b4a461c947..c015ffc4e3 100644 --- a/src/platform_impl/windows/definitions.rs +++ b/src/platform_impl/windows/definitions.rs @@ -3,14 +3,10 @@ use std::ffi::c_void; -use windows_sys::{ - core::{IUnknown, GUID, HRESULT}, - Win32::{ - Foundation::{BOOL, HWND, POINTL}, - System::Com::{ - IAdviseSink, IDataObject, IEnumFORMATETC, IEnumSTATDATA, FORMATETC, STGMEDIUM, - }, - }, +use windows_sys::core::{IUnknown, GUID, HRESULT}; +use windows_sys::Win32::Foundation::{BOOL, HWND, POINTL}; +use windows_sys::Win32::System::Com::{ + IAdviseSink, IDataObject, IEnumFORMATETC, IEnumSTATDATA, FORMATETC, STGMEDIUM, }; #[repr(C)] @@ -138,10 +134,10 @@ pub const CLSID_TaskbarList: GUID = GUID { }; pub const IID_ITaskbarList: GUID = GUID { - data1: 0x56FDF342, - data2: 0xFD6D, - data3: 0x11D0, - data4: [0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90], + data1: 0x56fdf342, + data2: 0xfd6d, + data3: 0x11d0, + data4: [0x95, 0x8a, 0x00, 0x60, 0x97, 0xc9, 0xa0, 0x90], }; pub const IID_ITaskbarList2: GUID = GUID { diff --git a/src/platform_impl/windows/dpi.rs b/src/platform_impl/windows/dpi.rs index 5db2e8ee87..5880069c35 100644 --- a/src/platform_impl/windows/dpi.rs +++ b/src/platform_impl/windows/dpi.rs @@ -2,19 +2,15 @@ use std::sync::Once; -use windows_sys::Win32::{ - Foundation::{HWND, S_OK}, - Graphics::Gdi::{ - GetDC, GetDeviceCaps, MonitorFromWindow, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST, - }, - UI::{ - HiDpi::{ - DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, - MDT_EFFECTIVE_DPI, PROCESS_PER_MONITOR_DPI_AWARE, - }, - WindowsAndMessaging::IsProcessDPIAware, - }, +use windows_sys::Win32::Foundation::{HWND, S_OK}; +use windows_sys::Win32::Graphics::Gdi::{ + GetDC, GetDeviceCaps, MonitorFromWindow, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST, }; +use windows_sys::Win32::UI::HiDpi::{ + DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, + MDT_EFFECTIVE_DPI, PROCESS_PER_MONITOR_DPI_AWARE, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::IsProcessDPIAware; use crate::platform_impl::platform::util::{ ENABLE_NON_CLIENT_DPI_SCALING, GET_DPI_FOR_MONITOR, GET_DPI_FOR_WINDOW, SET_PROCESS_DPI_AWARE, diff --git a/src/platform_impl/windows/drop_handler.rs b/src/platform_impl/windows/drop_handler.rs index ff56b98e36..38cb5c54da 100644 --- a/src/platform_impl/windows/drop_handler.rs +++ b/src/platform_impl/windows/drop_handler.rs @@ -1,31 +1,24 @@ -use std::{ - ffi::{c_void, OsString}, - os::windows::ffi::OsStringExt, - path::PathBuf, - ptr, - sync::atomic::{AtomicUsize, Ordering}, -}; - -use windows_sys::{ - core::{IUnknown, GUID, HRESULT}, - Win32::{ - Foundation::{DV_E_FORMATETC, HWND, POINTL, S_OK}, - System::{ - Com::{IDataObject, DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL}, - Ole::{CF_HDROP, DROPEFFECT_COPY, DROPEFFECT_NONE}, - }, - UI::Shell::{DragFinish, DragQueryFileW, HDROP}, - }, -}; +use std::ffi::{c_void, OsString}; +use std::os::windows::ffi::OsStringExt; +use std::path::PathBuf; +use std::ptr; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use windows_sys::core::{IUnknown, GUID, HRESULT}; +use windows_sys::Win32::Foundation::{DV_E_FORMATETC, HWND, POINTL, S_OK}; +use windows_sys::Win32::System::Com::{IDataObject, DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL}; +use windows_sys::Win32::System::Ole::{CF_HDROP, DROPEFFECT_COPY, DROPEFFECT_NONE}; +use windows_sys::Win32::UI::Shell::{DragFinish, DragQueryFileW, HDROP}; use tracing::debug; -use crate::platform_impl::platform::{ - definitions::{IDataObjectVtbl, IDropTarget, IDropTargetVtbl, IUnknownVtbl}, - WindowId, +use crate::platform_impl::platform::definitions::{ + IDataObjectVtbl, IDropTarget, IDropTargetVtbl, IUnknownVtbl, }; +use crate::platform_impl::platform::WindowId; -use crate::{event::Event, window::WindowId as RootWindowId}; +use crate::event::Event; +use crate::window::WindowId as RootWindowId; #[repr(C)] pub struct FileDropHandlerData { @@ -34,7 +27,8 @@ pub struct FileDropHandlerData { window: HWND, send_event: Box)>, cursor_effect: u32, - hovered_is_valid: bool, /* If the currently hovered item is not valid there must not be any `HoveredFileCancelled` emitted */ + hovered_is_valid: bool, /* If the currently hovered item is not valid there must not be any + * `HoveredFileCancelled` emitted */ } pub struct FileDropHandler { @@ -45,18 +39,14 @@ pub struct FileDropHandler { impl FileDropHandler { pub fn new(window: HWND, send_event: Box)>) -> FileDropHandler { let data = Box::new(FileDropHandlerData { - interface: IDropTarget { - lpVtbl: &DROP_TARGET_VTBL as *const IDropTargetVtbl, - }, + interface: IDropTarget { lpVtbl: &DROP_TARGET_VTBL as *const IDropTargetVtbl }, refcount: AtomicUsize::new(1), window, send_event, cursor_effect: DROPEFFECT_NONE, hovered_is_valid: false, }); - FileDropHandler { - data: Box::into_raw(data), - } + FileDropHandler { data: Box::into_raw(data) } } // Implement IUnknown @@ -104,11 +94,8 @@ impl FileDropHandler { }) }; drop_handler.hovered_is_valid = hdrop.is_some(); - drop_handler.cursor_effect = if drop_handler.hovered_is_valid { - DROPEFFECT_COPY - } else { - DROPEFFECT_NONE - }; + drop_handler.cursor_effect = + if drop_handler.hovered_is_valid { DROPEFFECT_COPY } else { DROPEFFECT_NONE }; unsafe { *pdwEffect = drop_handler.cursor_effect; } @@ -190,7 +177,7 @@ impl FileDropHandler { let hdrop = unsafe { medium.u.hGlobal as HDROP }; // The second parameter (0xFFFFFFFF) instructs the function to return the item count - let item_count = unsafe { DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0) }; + let item_count = unsafe { DragQueryFileW(hdrop, 0xffffffff, ptr::null_mut(), 0) }; for i in 0..item_count { // Get the length of the path string NOT including the terminating null character. diff --git a/src/platform_impl/windows/event_loop.rs b/src/platform_impl/windows/event_loop.rs index ae10bec0ab..4fc31553ff 100644 --- a/src/platform_impl/windows/event_loop.rs +++ b/src/platform_impl/windows/event_loop.rs @@ -2,102 +2,91 @@ mod runner; -use std::{ - cell::Cell, - collections::VecDeque, - ffi::c_void, - marker::PhantomData, - mem, panic, ptr, - rc::Rc, - sync::{ - atomic::{AtomicU32, Ordering}, - mpsc::{self, Receiver, Sender}, - Arc, Mutex, MutexGuard, - }, - time::{Duration, Instant}, -}; +use std::cell::Cell; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; +use std::{mem, panic, ptr}; use crate::utils::Lazy; -use windows_sys::Win32::{ - Devices::HumanInterfaceDevice::MOUSE_MOVE_RELATIVE, - Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM}, - Graphics::Gdi::{ - GetMonitorInfoW, MonitorFromRect, MonitorFromWindow, RedrawWindow, ScreenToClient, - ValidateRect, MONITORINFO, MONITOR_DEFAULTTONULL, RDW_INTERNALPAINT, SC_SCREENSAVE, - }, - System::{ - Ole::RevokeDragDrop, - Threading::{GetCurrentThreadId, INFINITE}, - }, - UI::{ - Controls::{HOVER_DEFAULT, WM_MOUSELEAVE}, - Input::{ - Ime::{GCS_COMPSTR, GCS_RESULTSTR, ISC_SHOWUICOMPOSITIONWINDOW}, - KeyboardAndMouse::{ - ReleaseCapture, SetCapture, TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT, - }, - Pointer::{POINTER_FLAG_DOWN, POINTER_FLAG_UP, POINTER_FLAG_UPDATE}, - Touch::{ - CloseTouchInputHandle, GetTouchInputInfo, TOUCHEVENTF_DOWN, TOUCHEVENTF_MOVE, - TOUCHEVENTF_UP, TOUCHINPUT, - }, - RAWINPUT, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE, - }, - WindowsAndMessaging::{ - CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetClientRect, - GetCursorPos, GetMenu, GetMessageW, KillTimer, LoadCursorW, PeekMessageW, PostMessageW, - RegisterClassExW, RegisterWindowMessageA, SetCursor, SetTimer, SetWindowPos, - TranslateMessage, CREATESTRUCTW, GIDC_ARRIVAL, GIDC_REMOVAL, GWL_STYLE, GWL_USERDATA, - HTCAPTION, HTCLIENT, MINMAXINFO, MNC_CLOSE, MSG, NCCALCSIZE_PARAMS, PM_REMOVE, PT_PEN, - PT_TOUCH, RI_MOUSE_HWHEEL, RI_MOUSE_WHEEL, SC_MINIMIZE, SC_RESTORE, SIZE_MAXIMIZED, - SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WHEEL_DELTA, WINDOWPOS, - WMSZ_BOTTOM, WMSZ_BOTTOMLEFT, WMSZ_BOTTOMRIGHT, WMSZ_LEFT, WMSZ_RIGHT, WMSZ_TOP, - WMSZ_TOPLEFT, WMSZ_TOPRIGHT, WM_CAPTURECHANGED, WM_CLOSE, WM_CREATE, WM_DESTROY, - WM_DPICHANGED, WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_GETMINMAXINFO, WM_IME_COMPOSITION, - WM_IME_ENDCOMPOSITION, WM_IME_SETCONTEXT, WM_IME_STARTCOMPOSITION, WM_INPUT, - WM_INPUT_DEVICE_CHANGE, WM_KEYDOWN, WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN, - WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MENUCHAR, WM_MOUSEHWHEEL, WM_MOUSEMOVE, - WM_MOUSEWHEEL, WM_NCACTIVATE, WM_NCCALCSIZE, WM_NCCREATE, WM_NCDESTROY, - WM_NCLBUTTONDOWN, WM_PAINT, WM_POINTERDOWN, WM_POINTERUP, WM_POINTERUPDATE, - WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SETFOCUS, WM_SETTINGCHANGE, WM_SIZE, - WM_SIZING, WM_SYSCOMMAND, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TOUCH, WM_WINDOWPOSCHANGED, - WM_WINDOWPOSCHANGING, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_LAYERED, - WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, WS_OVERLAPPED, WS_POPUP, - WS_VISIBLE, - }, - }, +use windows_sys::Win32::Devices::HumanInterfaceDevice::MOUSE_MOVE_RELATIVE; +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM}; +use windows_sys::Win32::Graphics::Gdi::{ + GetMonitorInfoW, MonitorFromRect, MonitorFromWindow, RedrawWindow, ScreenToClient, + ValidateRect, MONITORINFO, MONITOR_DEFAULTTONULL, RDW_INTERNALPAINT, SC_SCREENSAVE, +}; +use windows_sys::Win32::System::Ole::RevokeDragDrop; +use windows_sys::Win32::System::Threading::{GetCurrentThreadId, INFINITE}; +use windows_sys::Win32::UI::Controls::{HOVER_DEFAULT, WM_MOUSELEAVE}; +use windows_sys::Win32::UI::Input::Ime::{GCS_COMPSTR, GCS_RESULTSTR, ISC_SHOWUICOMPOSITIONWINDOW}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + ReleaseCapture, SetCapture, TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT, +}; +use windows_sys::Win32::UI::Input::Pointer::{ + POINTER_FLAG_DOWN, POINTER_FLAG_UP, POINTER_FLAG_UPDATE, +}; +use windows_sys::Win32::UI::Input::Touch::{ + CloseTouchInputHandle, GetTouchInputInfo, TOUCHEVENTF_DOWN, TOUCHEVENTF_MOVE, TOUCHEVENTF_UP, + TOUCHINPUT, +}; +use windows_sys::Win32::UI::Input::{RAWINPUT, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetClientRect, GetCursorPos, + GetMenu, GetMessageW, KillTimer, LoadCursorW, PeekMessageW, PostMessageW, RegisterClassExW, + RegisterWindowMessageA, SetCursor, SetTimer, SetWindowPos, TranslateMessage, CREATESTRUCTW, + GIDC_ARRIVAL, GIDC_REMOVAL, GWL_STYLE, GWL_USERDATA, HTCAPTION, HTCLIENT, MINMAXINFO, + MNC_CLOSE, MSG, NCCALCSIZE_PARAMS, PM_REMOVE, PT_PEN, PT_TOUCH, RI_MOUSE_HWHEEL, + RI_MOUSE_WHEEL, SC_MINIMIZE, SC_RESTORE, SIZE_MAXIMIZED, SWP_NOACTIVATE, SWP_NOMOVE, + SWP_NOSIZE, SWP_NOZORDER, WHEEL_DELTA, WINDOWPOS, WMSZ_BOTTOM, WMSZ_BOTTOMLEFT, + WMSZ_BOTTOMRIGHT, WMSZ_LEFT, WMSZ_RIGHT, WMSZ_TOP, WMSZ_TOPLEFT, WMSZ_TOPRIGHT, + WM_CAPTURECHANGED, WM_CLOSE, WM_CREATE, WM_DESTROY, WM_DPICHANGED, WM_ENTERSIZEMOVE, + WM_EXITSIZEMOVE, WM_GETMINMAXINFO, WM_IME_COMPOSITION, WM_IME_ENDCOMPOSITION, + WM_IME_SETCONTEXT, WM_IME_STARTCOMPOSITION, WM_INPUT, WM_INPUT_DEVICE_CHANGE, WM_KEYDOWN, + WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, + WM_MENUCHAR, WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_NCACTIVATE, WM_NCCALCSIZE, + WM_NCCREATE, WM_NCDESTROY, WM_NCLBUTTONDOWN, WM_PAINT, WM_POINTERDOWN, WM_POINTERUP, + WM_POINTERUPDATE, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SETFOCUS, WM_SETTINGCHANGE, + WM_SIZE, WM_SIZING, WM_SYSCOMMAND, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TOUCH, WM_WINDOWPOSCHANGED, + WM_WINDOWPOSCHANGING, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_LAYERED, + WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, WS_OVERLAPPED, WS_POPUP, WS_VISIBLE, }; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize}, - error::EventLoopError, - event::{ - DeviceEvent, Event, Force, Ime, InnerSizeWriter, RawKeyEvent, Touch, TouchPhase, - WindowEvent, - }, - event_loop::{ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents, EventLoopClosed}, - keyboard::ModifiersState, - platform::pump_events::PumpStatus, - platform_impl::platform::{ - dark_mode::try_theme, - dpi::{become_dpi_aware, dpi_to_scale_factor}, - drop_handler::FileDropHandler, - icon::WinCursor, - ime::ImeContext, - keyboard::KeyEventBuilder, - keyboard_layout::LAYOUT_CACHE, - monitor::{self, MonitorHandle}, - raw_input, util, - window::InitData, - window_state::{CursorFlags, ImeState, WindowFlags, WindowState}, - wrap_device_id, Fullscreen, WindowId, DEVICE_ID, - }, - window::{CustomCursor as RootCustomCursor, CustomCursorSource, WindowId as RootWindowId}, +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::error::EventLoopError; +use crate::event::{ + DeviceEvent, Event, Force, Ime, InnerSizeWriter, RawKeyEvent, Touch, TouchPhase, WindowEvent, +}; +use crate::event_loop::{ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents, EventLoopClosed}; +use crate::keyboard::ModifiersState; +use crate::platform::pump_events::PumpStatus; +use crate::platform_impl::platform::dark_mode::try_theme; +use crate::platform_impl::platform::dpi::{become_dpi_aware, dpi_to_scale_factor}; +use crate::platform_impl::platform::drop_handler::FileDropHandler; +use crate::platform_impl::platform::icon::WinCursor; +use crate::platform_impl::platform::ime::ImeContext; +use crate::platform_impl::platform::keyboard::KeyEventBuilder; +use crate::platform_impl::platform::keyboard_layout::LAYOUT_CACHE; +use crate::platform_impl::platform::monitor::{self, MonitorHandle}; +use crate::platform_impl::platform::window::InitData; +use crate::platform_impl::platform::window_state::{ + CursorFlags, ImeState, WindowFlags, WindowState, +}; +use crate::platform_impl::platform::{ + raw_input, util, wrap_device_id, Fullscreen, WindowId, DEVICE_ID, +}; +use crate::window::{ + CustomCursor as RootCustomCursor, CustomCursorSource, WindowId as RootWindowId, }; use runner::{EventLoopRunner, EventLoopRunnerShared}; -use super::{window::set_skip_taskbar, SelectedCursor}; +use super::window::set_skip_taskbar; +use super::SelectedCursor; /// some backends like macos uses an uninhabited `Never` type, /// on windows, `UserEvent`s are also dispatched through the @@ -171,11 +160,7 @@ pub(crate) struct PlatformSpecificEventLoopAttributes { impl Default for PlatformSpecificEventLoopAttributes { fn default() -> Self { - Self { - any_thread: false, - dpi_aware: true, - msg_hook: None, - } + Self { any_thread: false, dpi_aware: true, msg_hook: None } } } @@ -219,11 +204,7 @@ impl EventLoop { user_event_sender, user_event_receiver, window_target: RootAEL { - p: ActiveEventLoop { - thread_id, - thread_msg_target, - runner_shared, - }, + p: ActiveEventLoop { thread_id, thread_msg_target, runner_shared }, _marker: PhantomData, }, msg_hook: attributes.msg_hook.take(), @@ -422,7 +403,7 @@ impl EventLoop { ControlFlow::WaitUntil(wait_deadline) => { let start = Instant::now(); Some(wait_deadline.saturating_duration_since(start)) - } + }, }; let timeout = min_timeout(control_flow_timeout, timeout); @@ -438,10 +419,10 @@ impl EventLoop { runner.wakeup(); match msg_status { - None => {} // No MSG to dispatch + None => {}, // No MSG to dispatch Some(PumpStatus::Exit(code)) => { runner.set_exit_code(code); - } + }, Some(PumpStatus::Continue) => { unsafe { let handled = if let Some(callback) = self.msg_hook.as_deref_mut() { @@ -459,7 +440,7 @@ impl EventLoop { runner.reset_runner(); panic::resume_unwind(payload); } - } + }, } } @@ -528,10 +509,7 @@ impl EventLoop { impl ActiveEventLoop { #[inline(always)] pub(crate) fn create_thread_executor(&self) -> EventLoopThreadExecutor { - EventLoopThreadExecutor { - thread_id: self.thread_id, - target_window: self.thread_msg_target, - } + EventLoopThreadExecutor { thread_id: self.thread_id, target_window: self.thread_msg_target } } pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { @@ -540,7 +518,7 @@ impl ActiveEventLoop { Err(err) => { tracing::warn!("Failed to create custom cursor: {err}"); WinCursor::Failed - } + }, }; RootCustomCursor { inner } @@ -565,9 +543,7 @@ impl ActiveEventLoop { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Windows( - rwh_06::WindowsDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Windows(rwh_06::WindowsDisplayHandle::new())) } pub fn listen_device_events(&self, allowed: DeviceEvents) { @@ -667,9 +643,7 @@ fn main_thread_id() -> u32 { /// equates to an infinite timeout, not a zero timeout (so can't just use /// `Option::min`) fn min_timeout(a: Option, b: Option) -> Option { - a.map_or(b, |a_timeout| { - b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))) - }) + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) } // Implementation taken from https://github.com/rust-lang/rust/blob/db5476571d9b27c862b95c1e64764b0ac8980e23/src/libstd/sys/windows/mod.rs @@ -679,25 +653,20 @@ fn dur2timeout(dur: Duration) -> u32 { // have two pieces to take care of: // // * Nanosecond precision is rounded up - // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE - // (never time out). + // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE (never time out). dur.as_secs() .checked_mul(1000) .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) - .and_then(|ms| { - if dur.subsec_nanos() % 1_000_000 > 0 { - ms.checked_add(1) - } else { - Some(ms) - } - }) - .map(|ms| { - if ms > u32::MAX as u64 { - INFINITE - } else { - ms as u32 - } - }) + .and_then( + |ms| { + if dur.subsec_nanos() % 1_000_000 > 0 { + ms.checked_add(1) + } else { + Some(ms) + } + }, + ) + .map(|ms| if ms > u32::MAX as u64 { INFINITE } else { ms as u32 }) .unwrap_or(INFINITE) } @@ -751,10 +720,7 @@ impl EventLoopThreadExecutor { let raw = Box::into_raw(boxed2); let res = PostMessageW(self.target_window, EXEC_MSG_ID.get(), raw as usize, 0); - assert!( - res != false.into(), - "PostMessage failed; is the messages queue full?" - ); + assert!(res != false.into(), "PostMessage failed; is the messages queue full?"); } } } @@ -770,10 +736,7 @@ unsafe impl Send for EventLoopProxy {} impl Clone for EventLoopProxy { fn clone(&self) -> Self { - Self { - target_window: self.target_window, - event_send: self.event_send.clone(), - } + Self { target_window: self.target_window, event_send: self.event_send.clone() } } } @@ -804,10 +767,7 @@ const INVALID_ID: u32 = 0x0; impl LazyMessageId { /// Create a new `LazyId`. const fn new(name: &'static str) -> Self { - Self { - id: AtomicU32::new(INVALID_ID), - name, - } + Self { id: AtomicU32::new(INVALID_ID), name } } /// Get the message ID. @@ -832,9 +792,10 @@ impl LazyMessageId { std::io::Error::last_os_error() ); - // Store the new ID. Since `RegisterWindowMessageA` returns the same value for any given string, - // the target value will always either be a). `INVALID_ID` or b). the correct ID. Therefore a - // compare-and-swap operation here (or really any consideration) is never necessary. + // Store the new ID. Since `RegisterWindowMessageA` returns the same value for any given + // string, the target value will always either be a). `INVALID_ID` or b). the + // correct ID. Therefore a compare-and-swap operation here (or really any + // consideration) is never necessary. self.id.store(new_id, Ordering::Relaxed); new_id @@ -857,13 +818,12 @@ pub(crate) static SET_RETAIN_STATE_ON_SIZE_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::SetRetainMaximized\0"); static THREAD_EVENT_TARGET_WINDOW_CLASS: Lazy> = Lazy::new(|| util::encode_wide("Winit Thread Event Target")); -/// When the taskbar is created, it registers a message with the "TaskbarCreated" string and then broadcasts this message to all top-level windows -/// +/// When the taskbar is created, it registers a message with the "TaskbarCreated" string and then +/// broadcasts this message to all top-level windows pub(crate) static TASKBAR_CREATED: LazyMessageId = LazyMessageId::new("TaskbarCreated\0"); fn create_event_target_window() -> HWND { - use windows_sys::Win32::UI::WindowsAndMessaging::CS_HREDRAW; - use windows_sys::Win32::UI::WindowsAndMessaging::CS_VREDRAW; + use windows_sys::Win32::UI::WindowsAndMessaging::{CS_HREDRAW, CS_VREDRAW}; unsafe { let class = WNDCLASSEXW { cbSize: mem::size_of::() as u32, @@ -884,18 +844,15 @@ fn create_event_target_window() -> HWND { } unsafe { + // WS_EX_TOOLWINDOW prevents this window from ever showing up in the taskbar, which + // we want to avoid. If you remove this style, this window won't show up in the + // taskbar *initially*, but it can show up at some later point. This can sometimes + // happen on its own after several hours have passed, although this has proven + // difficult to reproduce. Alternatively, it can be manually triggered by killing + // `explorer.exe` and then starting the process back up. + // It is unclear why the bug is triggered by waiting for several hours. let window = CreateWindowExW( - WS_EX_NOACTIVATE - | WS_EX_TRANSPARENT - | WS_EX_LAYERED - // WS_EX_TOOLWINDOW prevents this window from ever showing up in the taskbar, which - // we want to avoid. If you remove this style, this window won't show up in the - // taskbar *initially*, but it can show up at some later point. This can sometimes - // happen on its own after several hours have passed, although this has proven - // difficult to reproduce. Alternatively, it can be manually triggered by killing - // `explorer.exe` and then starting the process back up. - // It is unclear why the bug is triggered by waiting for several hours. - | WS_EX_TOOLWINDOW, + WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOOLWINDOW, THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(), ptr::null(), WS_OVERLAPPED, @@ -912,9 +869,9 @@ fn create_event_target_window() -> HWND { super::set_window_long( window, GWL_STYLE, - // The window technically has to be visible to receive WM_PAINT messages (which are used - // for delivering events during resizes), but it isn't displayed to the user because of - // the LAYERED style. + // The window technically has to be visible to receive WM_PAINT messages (which are + // used for delivering events during resizes), but it isn't displayed to + // the user because of the LAYERED style. (WS_VISIBLE | WS_POPUP) as isize, ); window @@ -1008,7 +965,6 @@ unsafe fn lose_active_focus(window: HWND, userdata: &WindowData) { /// Any window whose callback is configured to this function will have its events propagated /// through the events loop of the thread the window was created in. -// // This is the callback that is called by `DispatchMessage` in the events loop. // // Returning 0 tells the Win32 API that the message has been processed. @@ -1035,7 +991,7 @@ pub(super) unsafe extern "system" fn public_window_callback( }; return result; - } + }, // Getting here should quite frankly be impossible, // but we'll make window creation fail here just in case. (0, WM_CREATE) => return -1, @@ -1086,7 +1042,7 @@ unsafe fn public_window_callback_inner( WM_KEYDOWN | WM_SYSKEYDOWN | WM_KEYUP | WM_SYSKEYUP => { update_modifiers(window, userdata); result = ProcResult::Value(0); - } + }, _ => (), }; userdata @@ -1097,9 +1053,7 @@ unsafe fn public_window_callback_inner( let keyboard_callback = || { use crate::event::WindowEvent::KeyboardInput; let events = - userdata - .key_event_builder - .process_message(window, msg, wparam, lparam, &mut result); + userdata.key_event_builder.process_message(window, msg, wparam, lparam, &mut result); for event in events { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), @@ -1157,14 +1111,14 @@ unsafe fn public_window_callback_inner( } result = ProcResult::Value(0); - } + }, WM_ENTERSIZEMOVE => { userdata .window_state_lock() .set_window_flags_in_place(|f| f.insert(WindowFlags::MARKER_IN_SIZE_MOVE)); result = ProcResult::Value(0); - } + }, WM_EXITSIZEMOVE => { let mut state = userdata.window_state_lock(); @@ -1175,14 +1129,14 @@ unsafe fn public_window_callback_inner( state.set_window_flags_in_place(|f| f.remove(WindowFlags::MARKER_IN_SIZE_MOVE)); result = ProcResult::Value(0); - } + }, WM_NCLBUTTONDOWN => { if wparam == HTCAPTION as _ { unsafe { PostMessageW(window, WM_MOUSEMOVE, 0, lparam) }; } result = ProcResult::DefWindowProc(wparam); - } + }, WM_CLOSE => { use crate::event::WindowEvent::CloseRequested; @@ -1191,7 +1145,7 @@ unsafe fn public_window_callback_inner( event: CloseRequested, }); result = ProcResult::Value(0); - } + }, WM_DESTROY => { use crate::event::WindowEvent::Destroyed; @@ -1201,13 +1155,13 @@ unsafe fn public_window_callback_inner( event: Destroyed, }); result = ProcResult::Value(0); - } + }, WM_NCDESTROY => { unsafe { super::set_window_long(window, GWL_USERDATA, 0) }; userdata.userdata_removed.set(true); result = ProcResult::Value(0); - } + }, WM_PAINT => { userdata.window_state_lock().redraw_requested = @@ -1231,7 +1185,7 @@ unsafe fn public_window_callback_inner( if std::mem::take(&mut userdata.window_state_lock().redraw_requested) { unsafe { RedrawWindow(window, ptr::null(), 0, RDW_INTERNALPAINT) }; } - } + }, WM_WINDOWPOSCHANGING => { let mut window_state = userdata.window_state_lock(); if let Some(ref mut fullscreen) = window_state.fullscreen { @@ -1246,8 +1200,10 @@ unsafe fn public_window_callback_inner( const NOMOVE_OR_NOSIZE: u32 = SWP_NOMOVE | SWP_NOSIZE; let new_rect = if window_pos.flags & NOMOVE_OR_NOSIZE != 0 { - let cur_rect = util::WindowArea::Outer.get_rect(window) - .expect("Unexpected GetWindowRect failure; please report this error to rust-windowing/winit"); + let cur_rect = util::WindowArea::Outer.get_rect(window).expect( + "Unexpected GetWindowRect failure; please report this error to \ + rust-windowing/winit", + ); match window_pos.flags & NOMOVE_OR_NOSIZE { NOMOVE_OR_NOSIZE => None, @@ -1292,7 +1248,7 @@ unsafe fn public_window_callback_inner( } *fullscreen_monitor = Some(MonitorHandle::new(new_monitor)); } - } + }, Fullscreen::Exclusive(ref video_mode) => { let old_monitor = video_mode.monitor.hmonitor(); if let Ok(old_monitor_info) = monitor::get_monitor_info(old_monitor) { @@ -1302,13 +1258,13 @@ unsafe fn public_window_callback_inner( window_pos.cx = old_monitor_rect.right - old_monitor_rect.left; window_pos.cy = old_monitor_rect.bottom - old_monitor_rect.top; } - } + }, } } } result = ProcResult::Value(0); - } + }, // WM_MOVE supplies client area positions, so we send Moved here instead. WM_WINDOWPOSCHANGED => { @@ -1326,7 +1282,7 @@ unsafe fn public_window_callback_inner( // This is necessary for us to still get sent WM_SIZE. result = ProcResult::DefWindowProc(wparam); - } + }, WM_SIZE => { use crate::event::WindowEvent::Resized; @@ -1341,18 +1297,16 @@ unsafe fn public_window_callback_inner( { let mut w = userdata.window_state_lock(); - // See WindowFlags::MARKER_RETAIN_STATE_ON_SIZE docs for info on why this `if` check exists. - if !w - .window_flags() - .contains(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE) - { + // See WindowFlags::MARKER_RETAIN_STATE_ON_SIZE docs for info on why this `if` check + // exists. + if !w.window_flags().contains(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE) { let maximized = wparam == SIZE_MAXIMIZED as usize; w.set_window_flags_in_place(|f| f.set(WindowFlags::MAXIMIZED, maximized)); } } userdata.send_event(event); result = ProcResult::Value(0); - } + }, WM_SIZING => { /// Calculate the amount to add to round `value` to the nearest multiple of `increment`. @@ -1396,14 +1350,10 @@ unsafe fn public_window_callback_inner( // Windows won't bound check the value of `rect` after we're done here, so we // have to check manually. If the width/height we snap to would go out of bounds, just // set it equal to the min/max bound. - let min_size = userdata - .window_state_lock() - .min_size - .map(|size| size.to_physical(scale_factor)); - let max_size = userdata - .window_state_lock() - .max_size - .map(|size| size.to_physical(scale_factor)); + let min_size = + userdata.window_state_lock().min_size.map(|size| size.to_physical(scale_factor)); + let max_size = + userdata.window_state_lock().max_size.map(|size| size.to_physical(scale_factor)); let final_width = width + width_delta; let final_height = height + height_delta; if let Some(min_size) = min_size { @@ -1426,29 +1376,29 @@ unsafe fn public_window_callback_inner( match side { WMSZ_LEFT | WMSZ_BOTTOMLEFT | WMSZ_TOPLEFT => { rect.left -= width_delta; - } + }, WMSZ_RIGHT | WMSZ_BOTTOMRIGHT | WMSZ_TOPRIGHT => { rect.right += width_delta; - } - _ => {} + }, + _ => {}, } match side { WMSZ_TOP | WMSZ_TOPLEFT | WMSZ_TOPRIGHT => { rect.top -= height_delta; - } + }, WMSZ_BOTTOM | WMSZ_BOTTOMLEFT | WMSZ_BOTTOMRIGHT => { rect.bottom += height_delta; - } - _ => {} + }, + _ => {}, } result = ProcResult::DefWindowProc(wparam); - } + }, WM_MENUCHAR => { result = ProcResult::Value((MNC_CLOSE << 16) as isize); - } + }, WM_IME_STARTCOMPOSITION => { let ime_allowed = userdata.window_state_lock().ime_allowed; @@ -1462,7 +1412,7 @@ unsafe fn public_window_callback_inner( } result = ProcResult::DefWindowProc(wparam); - } + }, WM_IME_COMPOSITION => { let ime_allowed_and_composing = { @@ -1516,7 +1466,7 @@ unsafe fn public_window_callback_inner( // Not calling DefWindowProc to hide composing text drawn by IME. result = ProcResult::Value(0); - } + }, WM_IME_ENDCOMPOSITION => { let ime_allowed_or_composing = { @@ -1549,13 +1499,13 @@ unsafe fn public_window_callback_inner( } result = ProcResult::DefWindowProc(wparam); - } + }, WM_IME_SETCONTEXT => { // Hide composing text drawn by IME. let wparam = wparam & (!ISC_SHOWUICOMPOSITIONWINDOW as usize); result = ProcResult::DefWindowProc(wparam); - } + }, // this is necessary for us to maintain minimize/restore state WM_SYSCOMMAND => { @@ -1578,7 +1528,7 @@ unsafe fn public_window_callback_inner( } result = ProcResult::DefWindowProc(wparam); - } + }, WM_MOUSEMOVE => { use crate::event::WindowEvent::{CursorEntered, CursorLeft, CursorMoved}; @@ -1602,9 +1552,7 @@ unsafe fn public_window_callback_inner( drop(w); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: CursorEntered { - device_id: DEVICE_ID, - }, + event: CursorEntered { device_id: DEVICE_ID }, }); // Calling TrackMouseEvent in order to receive mouse leave events. @@ -1616,7 +1564,7 @@ unsafe fn public_window_callback_inner( dwHoverTime: HOVER_DEFAULT, }) }; - } + }, PointerMoveKind::Leave => { w.mouse .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)) @@ -1625,11 +1573,9 @@ unsafe fn public_window_callback_inner( drop(w); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: CursorLeft { - device_id: DEVICE_ID, - }, + event: CursorLeft { device_id: DEVICE_ID }, }); - } + }, PointerMoveKind::None => drop(w), } @@ -1646,34 +1592,27 @@ unsafe fn public_window_callback_inner( userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: CursorMoved { - device_id: DEVICE_ID, - position, - }, + event: CursorMoved { device_id: DEVICE_ID, position }, }); } result = ProcResult::Value(0); - } + }, WM_MOUSELEAVE => { use crate::event::WindowEvent::CursorLeft; { let mut w = userdata.window_state_lock(); - w.mouse - .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)) - .ok(); + w.mouse.set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)).ok(); } userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: CursorLeft { - device_id: DEVICE_ID, - }, + event: CursorLeft { device_id: DEVICE_ID }, }); result = ProcResult::Value(0); - } + }, WM_MOUSEWHEEL => { use crate::event::MouseScrollDelta::LineDelta; @@ -1693,7 +1632,7 @@ unsafe fn public_window_callback_inner( }); result = ProcResult::Value(0); - } + }, WM_MOUSEHWHEEL => { use crate::event::MouseScrollDelta::LineDelta; @@ -1713,13 +1652,13 @@ unsafe fn public_window_callback_inner( }); result = ProcResult::Value(0); - } + }, WM_KEYDOWN | WM_SYSKEYDOWN => { if msg == WM_SYSKEYDOWN { result = ProcResult::DefWindowProc(wparam); } - } + }, WM_KEYUP | WM_SYSKEYUP => { if msg == WM_SYSKEYUP && unsafe { GetMenu(window) != 0 } { @@ -1727,10 +1666,12 @@ unsafe fn public_window_callback_inner( // is started here on Alt key up. result = ProcResult::DefWindowProc(wparam); } - } + }, WM_LBUTTONDOWN => { - use crate::event::{ElementState::Pressed, MouseButton::Left, WindowEvent::MouseInput}; + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::Left; + use crate::event::WindowEvent::MouseInput; unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; @@ -1738,19 +1679,15 @@ unsafe fn public_window_callback_inner( userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: MouseInput { - device_id: DEVICE_ID, - state: Pressed, - button: Left, - }, + event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Left }, }); result = ProcResult::Value(0); - } + }, WM_LBUTTONUP => { - use crate::event::{ - ElementState::Released, MouseButton::Left, WindowEvent::MouseInput, - }; + use crate::event::ElementState::Released; + use crate::event::MouseButton::Left; + use crate::event::WindowEvent::MouseInput; unsafe { release_mouse(userdata.window_state_lock()) }; @@ -1758,19 +1695,15 @@ unsafe fn public_window_callback_inner( userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: MouseInput { - device_id: DEVICE_ID, - state: Released, - button: Left, - }, + event: MouseInput { device_id: DEVICE_ID, state: Released, button: Left }, }); result = ProcResult::Value(0); - } + }, WM_RBUTTONDOWN => { - use crate::event::{ - ElementState::Pressed, MouseButton::Right, WindowEvent::MouseInput, - }; + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::Right; + use crate::event::WindowEvent::MouseInput; unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; @@ -1778,19 +1711,15 @@ unsafe fn public_window_callback_inner( userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: MouseInput { - device_id: DEVICE_ID, - state: Pressed, - button: Right, - }, + event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Right }, }); result = ProcResult::Value(0); - } + }, WM_RBUTTONUP => { - use crate::event::{ - ElementState::Released, MouseButton::Right, WindowEvent::MouseInput, - }; + use crate::event::ElementState::Released; + use crate::event::MouseButton::Right; + use crate::event::WindowEvent::MouseInput; unsafe { release_mouse(userdata.window_state_lock()) }; @@ -1798,19 +1727,15 @@ unsafe fn public_window_callback_inner( userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: MouseInput { - device_id: DEVICE_ID, - state: Released, - button: Right, - }, + event: MouseInput { device_id: DEVICE_ID, state: Released, button: Right }, }); result = ProcResult::Value(0); - } + }, WM_MBUTTONDOWN => { - use crate::event::{ - ElementState::Pressed, MouseButton::Middle, WindowEvent::MouseInput, - }; + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::Middle; + use crate::event::WindowEvent::MouseInput; unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; @@ -1818,19 +1743,15 @@ unsafe fn public_window_callback_inner( userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: MouseInput { - device_id: DEVICE_ID, - state: Pressed, - button: Middle, - }, + event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Middle }, }); result = ProcResult::Value(0); - } + }, WM_MBUTTONUP => { - use crate::event::{ - ElementState::Released, MouseButton::Middle, WindowEvent::MouseInput, - }; + use crate::event::ElementState::Released; + use crate::event::MouseButton::Middle; + use crate::event::WindowEvent::MouseInput; unsafe { release_mouse(userdata.window_state_lock()) }; @@ -1838,20 +1759,15 @@ unsafe fn public_window_callback_inner( userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), - event: MouseInput { - device_id: DEVICE_ID, - state: Released, - button: Middle, - }, + event: MouseInput { device_id: DEVICE_ID, state: Released, button: Middle }, }); result = ProcResult::Value(0); - } + }, WM_XBUTTONDOWN => { - use crate::event::{ - ElementState::Pressed, MouseButton::Back, MouseButton::Forward, MouseButton::Other, - WindowEvent::MouseInput, - }; + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::{Back, Forward, Other}; + use crate::event::WindowEvent::MouseInput; let xbutton = super::get_xbutton_wparam(wparam as u32); unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; @@ -1871,13 +1787,12 @@ unsafe fn public_window_callback_inner( }, }); result = ProcResult::Value(0); - } + }, WM_XBUTTONUP => { - use crate::event::{ - ElementState::Released, MouseButton::Back, MouseButton::Forward, - MouseButton::Other, WindowEvent::MouseInput, - }; + use crate::event::ElementState::Released; + use crate::event::MouseButton::{Back, Forward, Other}; + use crate::event::WindowEvent::MouseInput; let xbutton = super::get_xbutton_wparam(wparam as u32); unsafe { release_mouse(userdata.window_state_lock()) }; @@ -1897,7 +1812,7 @@ unsafe fn public_window_callback_inner( }, }); result = ProcResult::Value(0); - } + }, WM_CAPTURECHANGED => { // lparam here is a handle to the window which is gaining mouse capture. @@ -1908,7 +1823,7 @@ unsafe fn public_window_callback_inner( userdata.window_state_lock().mouse.capture_count = 0; } result = ProcResult::Value(0); - } + }, WM_TOUCH => { let pcount = super::loword(wparam as u32) as usize; @@ -1924,10 +1839,7 @@ unsafe fn public_window_callback_inner( } { unsafe { inputs.set_len(pcount) }; for input in &inputs { - let mut location = POINT { - x: input.x / 100, - y: input.y / 100, - }; + let mut location = POINT { x: input.x / 100, y: input.y / 100 }; if unsafe { ScreenToClient(window, &mut location) } == false.into() { continue; @@ -1958,7 +1870,7 @@ unsafe fn public_window_callback_inner( } unsafe { CloseTouchInputHandle(htouch) }; result = ProcResult::Value(0); - } + }, WM_POINTERDOWN | WM_POINTERUPDATE | WM_POINTERUP => { if let ( @@ -2003,8 +1915,8 @@ unsafe fn public_window_callback_inner( unsafe { pointer_infos.set_len(pointer_info_count) }; // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getpointerframeinfohistory - // The information retrieved appears in reverse chronological order, with the most recent entry in the first - // row of the returned array + // The information retrieved appears in reverse chronological order, with the most + // recent entry in the first row of the returned array for pointer_info in pointer_infos.iter().rev() { let mut device_rect = mem::MaybeUninit::uninit(); let mut display_rect = mem::MaybeUninit::uninit(); @@ -2023,25 +1935,23 @@ unsafe fn public_window_callback_inner( let device_rect = unsafe { device_rect.assume_init() }; let display_rect = unsafe { display_rect.assume_init() }; - // For the most precise himetric to pixel conversion we calculate the ratio between the resolution - // of the display device (pixel) and the touch device (himetric). + // For the most precise himetric to pixel conversion we calculate the ratio + // between the resolution of the display device (pixel) and + // the touch device (himetric). let himetric_to_pixel_ratio_x = (display_rect.right - display_rect.left) as f64 / (device_rect.right - device_rect.left) as f64; let himetric_to_pixel_ratio_y = (display_rect.bottom - display_rect.top) as f64 / (device_rect.bottom - device_rect.top) as f64; // ptHimetricLocation's origin is 0,0 even on multi-monitor setups. - // On multi-monitor setups we need to translate the himetric location to the rect of the - // display device it's attached to. + // On multi-monitor setups we need to translate the himetric location to the + // rect of the display device it's attached to. let x = display_rect.left as f64 + pointer_info.ptHimetricLocation.x as f64 * himetric_to_pixel_ratio_x; let y = display_rect.top as f64 + pointer_info.ptHimetricLocation.y as f64 * himetric_to_pixel_ratio_y; - let mut location = POINT { - x: x.floor() as i32, - y: y.floor() as i32, - }; + let mut location = POINT { x: x.floor() as i32, y: y.floor() as i32 }; if unsafe { ScreenToClient(window, &mut location) } == false.into() { continue; @@ -2063,7 +1973,7 @@ unsafe fn public_window_callback_inner( }), } }) - } + }, PT_PEN => { let mut pen_info = mem::MaybeUninit::uninit(); util::GET_POINTER_PEN_INFO.and_then(|GetPointerPenInfo| { @@ -2076,7 +1986,7 @@ unsafe fn public_window_callback_inner( }), } }) - } + }, _ => None, }; @@ -2107,7 +2017,7 @@ unsafe fn public_window_callback_inner( unsafe { SkipPointerFrameMessages(pointer_id) }; } result = ProcResult::Value(0); - } + }, WM_NCACTIVATE => { let is_active = wparam != false.into(); @@ -2120,7 +2030,7 @@ unsafe fn public_window_callback_inner( } } result = ProcResult::DefWindowProc(wparam); - } + }, WM_SETFOCUS => { let active_focus_changed = userdata.window_state_lock().set_focused(true); @@ -2128,7 +2038,7 @@ unsafe fn public_window_callback_inner( unsafe { gain_active_focus(window, userdata) }; } result = ProcResult::Value(0); - } + }, WM_KILLFOCUS => { let active_focus_changed = userdata.window_state_lock().set_focused(false); @@ -2136,7 +2046,7 @@ unsafe fn public_window_callback_inner( unsafe { lose_active_focus(window, userdata) }; } result = ProcResult::Value(0); - } + }, WM_SETCURSOR => { let set_cursor_to = { @@ -2162,10 +2072,10 @@ unsafe fn public_window_callback_inner( }; unsafe { SetCursor(hcursor) }; result = ProcResult::Value(0); - } + }, None => result = ProcResult::DefWindowProc(wparam), } - } + }, WM_GETMINMAXINFO => { let mmi = lparam as *mut MINMAXINFO; @@ -2178,28 +2088,18 @@ unsafe fn public_window_callback_inner( let min_size = min_size.to_physical(window_state.scale_factor); let (width, height): (u32, u32) = window_flags.adjust_size(window, min_size).into(); - unsafe { - (*mmi).ptMinTrackSize = POINT { - x: width as i32, - y: height as i32, - } - }; + unsafe { (*mmi).ptMinTrackSize = POINT { x: width as i32, y: height as i32 } }; } if let Some(max_size) = window_state.max_size { let max_size = max_size.to_physical(window_state.scale_factor); let (width, height): (u32, u32) = window_flags.adjust_size(window, max_size).into(); - unsafe { - (*mmi).ptMaxTrackSize = POINT { - x: width as i32, - y: height as i32, - } - }; + unsafe { (*mmi).ptMaxTrackSize = POINT { x: width as i32, y: height as i32 } }; } } result = ProcResult::Value(0); - } + }, // Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change // DPI, therefore all applications are closed while DPI is changing. @@ -2242,9 +2142,8 @@ unsafe fn public_window_callback_inner( // let margin_right: i32; // let margin_bottom: i32; { - let adjusted_rect = window_flags - .adjust_rect(window, suggested_rect) - .unwrap_or(suggested_rect); + let adjusted_rect = + window_flags.adjust_rect(window, suggested_rect).unwrap_or(suggested_rect); margin_left = suggested_rect.left - adjusted_rect.left; margin_top = suggested_rect.top - adjusted_rect.top; // margin_right = adjusted_rect.right - suggested_rect.right; @@ -2262,8 +2161,8 @@ unsafe fn public_window_callback_inner( // `allow_resize` prevents us from re-applying DPI adjustment to the restored size after // exiting fullscreen (the restored size is already DPI adjusted). let new_physical_inner_size = match allow_resize { - // We calculate our own size because the default suggested rect doesn't do a great job - // of preserving the window's logical size. + // We calculate our own size because the default suggested rect doesn't do a great + // job of preserving the window's logical size. true => old_physical_inner_size .to_logical::(old_scale_factor) .to_physical::(new_scale_factor), @@ -2286,9 +2185,8 @@ unsafe fn public_window_callback_inner( { let window_state = userdata.window_state_lock(); - dragging_window = window_state - .window_flags() - .contains(WindowFlags::MARKER_IN_SIZE_MOVE); + dragging_window = + window_state.window_flags().contains(WindowFlags::MARKER_IN_SIZE_MOVE); // Unset maximized if we're changing the window's size. if new_physical_inner_size != old_physical_inner_size { WindowState::set_window_flags(window_state, window, |f| { @@ -2299,10 +2197,8 @@ unsafe fn public_window_callback_inner( let new_outer_rect: RECT; { - let suggested_ul = ( - suggested_rect.left + margin_left, - suggested_rect.top + margin_top, - ); + let suggested_ul = + (suggested_rect.left + margin_left, suggested_rect.top + margin_top); let mut conservative_rect = RECT { left: suggested_ul.0, @@ -2412,7 +2308,7 @@ unsafe fn public_window_callback_inner( }; result = ProcResult::Value(0); - } + }, WM_SETTINGCHANGE => { use crate::event::WindowEvent::ThemeChanged; @@ -2433,7 +2329,7 @@ unsafe fn public_window_callback_inner( } } result = ProcResult::DefWindowProc(wparam); - } + }, _ => { if msg == DESTROY_MSG_ID.get() { @@ -2452,7 +2348,7 @@ unsafe fn public_window_callback_inner( } else { result = ProcResult::DefWindowProc(wparam); } - } + }, }; userdata @@ -2475,8 +2371,8 @@ unsafe extern "system" fn thread_event_target_callback( let userdata_ptr = unsafe { super::get_window_long(window, GWL_USERDATA) } as *mut ThreadMsgTargetData; if userdata_ptr.is_null() { - // `userdata_ptr` will always be null for the first `WM_GETMINMAXINFO`, as well as `WM_NCCREATE` and - // `WM_CREATE`. + // `userdata_ptr` will always be null for the first `WM_GETMINMAXINFO`, as well as + // `WM_NCCREATE` and `WM_CREATE`. return unsafe { DefWindowProcW(window, msg, wparam, lparam) }; } let userdata = unsafe { Box::from_raw(userdata_ptr) }; @@ -2495,10 +2391,11 @@ unsafe extern "system" fn thread_event_target_callback( unsafe { super::set_window_long(window, GWL_USERDATA, 0) }; userdata_removed = true; 0 - } + }, WM_PAINT => unsafe { ValidateRect(window, ptr::null()); - // Default WM_PAINT behaviour. This makes sure modals and popups are shown immediately when opening them. + // Default WM_PAINT behaviour. This makes sure modals and popups are shown immediately + // when opening them. DefWindowProcW(window, msg, wparam, lparam) }, @@ -2509,13 +2406,11 @@ unsafe extern "system" fn thread_event_target_callback( _ => unreachable!(), }; - userdata.send_event(Event::DeviceEvent { - device_id: wrap_device_id(lparam as u32), - event, - }); + userdata + .send_event(Event::DeviceEvent { device_id: wrap_device_id(lparam as u32), event }); 0 - } + }, WM_INPUT => { if let Some(data) = raw_input::get_raw_input_data(lparam as _) { @@ -2523,7 +2418,7 @@ unsafe extern "system" fn thread_event_target_callback( } unsafe { DefWindowProcW(window, msg, wparam, lparam) } - } + }, _ if msg == USER_EVENT_MSG_ID.get() => { // synthesis a placeholder UserEvent, so that if the callback is @@ -2533,19 +2428,16 @@ unsafe extern "system" fn thread_event_target_callback( // `event_handler` userdata.send_event(Event::UserEvent(UserEventPlaceholder)); 0 - } + }, _ if msg == EXEC_MSG_ID.get() => { let mut function: ThreadExecFn = unsafe { Box::from_raw(wparam as *mut _) }; function(); 0 - } + }, _ => unsafe { DefWindowProcW(window, msg, wparam, lparam) }, }; - let result = userdata - .event_loop_runner - .catch_unwind(callback) - .unwrap_or(-1); + let result = userdata.event_loop_runner.catch_unwind(callback).unwrap_or(-1); if userdata_removed { drop(userdata); } else { @@ -2555,11 +2447,9 @@ unsafe extern "system" fn thread_event_target_callback( } unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) { - use crate::event::{ - DeviceEvent::{Button, Key, Motion, MouseMotion, MouseWheel}, - ElementState::{Pressed, Released}, - MouseScrollDelta::LineDelta, - }; + use crate::event::DeviceEvent::{Button, Key, Motion, MouseMotion, MouseWheel}; + use crate::event::ElementState::{Pressed, Released}; + use crate::event::MouseScrollDelta::LineDelta; let device_id = wrap_device_id(data.header.hDevice as _); @@ -2598,9 +2488,7 @@ unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) { let delta = button_data as f32 / WHEEL_DELTA as f32; userdata.send_event(Event::DeviceEvent { device_id, - event: MouseWheel { - delta: LineDelta(0.0, delta), - }, + event: MouseWheel { delta: LineDelta(0.0, delta) }, }); } if util::has_flag(button_flags as u32, RI_MOUSE_HWHEEL) { @@ -2608,9 +2496,7 @@ unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) { let delta = -button_data as f32 / WHEEL_DELTA as f32; userdata.send_event(Event::DeviceEvent { device_id, - event: MouseWheel { - delta: LineDelta(delta, 0.0), - }, + event: MouseWheel { delta: LineDelta(delta, 0.0) }, }); } @@ -2619,10 +2505,7 @@ unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) { if let Some(state) = *state { userdata.send_event(Event::DeviceEvent { device_id, - event: Button { - button: button as _, - state, - }, + event: Button { button: button as _, state }, }); } } @@ -2641,10 +2524,7 @@ unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) { userdata.send_event(Event::DeviceEvent { device_id, - event: Key(RawKeyEvent { - physical_key, - state, - }), + event: Key(RawKeyEvent { physical_key, state }), }); } } diff --git a/src/platform_impl/windows/event_loop/runner.rs b/src/platform_impl/windows/event_loop/runner.rs index b7130b5790..ad6c801965 100644 --- a/src/platform_impl/windows/event_loop/runner.rs +++ b/src/platform_impl/windows/event_loop/runner.rs @@ -1,24 +1,18 @@ -use std::{ - any::Any, - cell::{Cell, RefCell}, - collections::VecDeque, - mem, panic, - rc::Rc, - sync::{Arc, Mutex}, - time::Instant, -}; +use std::any::Any; +use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use std::{mem, panic}; use windows_sys::Win32::Foundation::HWND; -use crate::{ - dpi::PhysicalSize, - event::{Event, InnerSizeWriter, StartCause, WindowEvent}, - platform_impl::platform::{ - event_loop::{WindowData, GWL_USERDATA}, - get_window_long, - }, - window::WindowId, -}; +use crate::dpi::PhysicalSize; +use crate::event::{Event, InnerSizeWriter, StartCause, WindowEvent}; +use crate::platform_impl::platform::event_loop::{WindowData, GWL_USERDATA}; +use crate::platform_impl::platform::get_window_long; +use crate::window::WindowId; use super::ControlFlow; @@ -187,12 +181,12 @@ impl EventLoopRunner { Err(e) => { self.panic_error.set(Some(e)); None - } + }, }, Some(e) => { self.panic_error.set(Some(e)); None - } + }, } } else { self.panic_error.set(panic_error); @@ -212,22 +206,16 @@ impl EventLoopRunner { } pub(crate) fn send_event(&self, event: Event) { - if let Event::WindowEvent { - event: WindowEvent::RedrawRequested, - .. - } = event - { + if let Event::WindowEvent { event: WindowEvent::RedrawRequested, .. } = event { self.call_event_handler(event); // As a rule, to ensure that `pump_events` can't block an external event loop // for too long, we always guarantee that `pump_events` will return control to // the external loop asap after a `RedrawRequested` event is dispatched. self.interrupt_msg_dispatch.set(true); } else if self.should_buffer() { - // If the runner is already borrowed, we're in the middle of an event loop invocation. Add - // the event to a buffer to be processed later. - self.event_buffer - .borrow_mut() - .push_back(BufferedEvent::from_event(event)) + // If the runner is already borrowed, we're in the middle of an event loop invocation. + // Add the event to a buffer to be processed later. + self.event_buffer.borrow_mut().push_back(BufferedEvent::from_event(event)) } else { self.call_event_handler(event); self.dispatch_buffered_events(); @@ -240,8 +228,10 @@ impl EventLoopRunner { fn call_event_handler(&self, event: Event) { self.catch_unwind(|| { - let mut event_handler = self.event_handler.take() - .expect("either event handler is re-entrant (likely), or no event handler is registered (very unlikely)"); + let mut event_handler = self.event_handler.take().expect( + "either event handler is re-entrant (likely), or no event handler is registered \ + (very unlikely)", + ); event_handler(event); @@ -290,10 +280,7 @@ impl EventLoopRunner { fn move_state_to(&self, new_runner_state: RunnerState) { use RunnerState::{Destroyed, HandlingMainEvents, Idle, Uninitialized}; - match ( - self.runner_state.replace(new_runner_state), - new_runner_state, - ) { + match (self.runner_state.replace(new_runner_state), new_runner_state) { (Uninitialized, Uninitialized) | (Idle, Idle) | (HandlingMainEvents, HandlingMainEvents) @@ -302,38 +289,38 @@ impl EventLoopRunner { // State transitions that initialize the event loop. (Uninitialized, HandlingMainEvents) => { self.call_new_events(true); - } + }, (Uninitialized, Idle) => { self.call_new_events(true); self.call_event_handler(Event::AboutToWait); self.last_events_cleared.set(Instant::now()); - } + }, (Uninitialized, Destroyed) => { self.call_new_events(true); self.call_event_handler(Event::AboutToWait); self.last_events_cleared.set(Instant::now()); self.call_event_handler(Event::LoopExiting); - } + }, (_, Uninitialized) => panic!("cannot move state to Uninitialized"), // State transitions that start the event handling process. (Idle, HandlingMainEvents) => { self.call_new_events(false); - } + }, (Idle, Destroyed) => { self.call_event_handler(Event::LoopExiting); - } + }, (HandlingMainEvents, Idle) => { // This is always the last event we dispatch before waiting for new events self.call_event_handler(Event::AboutToWait); self.last_events_cleared.set(Instant::now()); - } + }, (HandlingMainEvents, Destroyed) => { self.call_event_handler(Event::AboutToWait); self.last_events_cleared.set(Instant::now()); self.call_event_handler(Event::LoopExiting); - } + }, (Destroyed, _) => panic!("cannot move state from Destroyed"), } @@ -341,7 +328,7 @@ impl EventLoopRunner { fn call_new_events(&self, init: bool) { let start_cause = match (init, self.control_flow(), self.exit.get()) { - (true, _, _) => StartCause::Init, + (true, ..) => StartCause::Init, (false, ControlFlow::Poll, None) => StartCause::Poll, (false, _, Some(_)) | (false, ControlFlow::Wait, None) => StartCause::WaitCancelled { requested_resume: None, @@ -359,7 +346,7 @@ impl EventLoopRunner { start: self.last_events_cleared.get(), } } - } + }, }; self.call_event_handler(Event::NewEvents(start_cause)); // NB: For consistency all platforms must emit a 'resumed' event even though Windows @@ -375,21 +362,12 @@ impl BufferedEvent { pub fn from_event(event: Event) -> BufferedEvent { match event { Event::WindowEvent { - event: - WindowEvent::ScaleFactorChanged { - scale_factor, - inner_size_writer, - }, + event: WindowEvent::ScaleFactorChanged { scale_factor, inner_size_writer }, window_id, } => BufferedEvent::ScaleFactorChanged( window_id, scale_factor, - *inner_size_writer - .new_inner_size - .upgrade() - .unwrap() - .lock() - .unwrap(), + *inner_size_writer.new_inner_size.upgrade().unwrap().lock().unwrap(), ), event => BufferedEvent::Event(event), } @@ -422,7 +400,7 @@ impl BufferedEvent { window_flags.set_size((window_id.0).0, inner_size); } - } + }, } } } diff --git a/src/platform_impl/windows/icon.rs b/src/platform_impl/windows/icon.rs index 55a56a9f14..624c8c8279 100644 --- a/src/platform_impl/windows/icon.rs +++ b/src/platform_impl/windows/icon.rs @@ -1,23 +1,22 @@ -use std::{ffi::c_void, fmt, io, mem, path::Path, sync::Arc}; +use std::ffi::c_void; +use std::path::Path; +use std::sync::Arc; +use std::{fmt, io, mem}; use cursor_icon::CursorIcon; -use windows_sys::{ - core::PCWSTR, - Win32::{ - Foundation::HWND, - Graphics::Gdi::{ - CreateBitmap, CreateCompatibleBitmap, DeleteObject, GetDC, ReleaseDC, SetBitmapBits, - }, - UI::WindowsAndMessaging::{ - CreateIcon, CreateIconIndirect, DestroyCursor, DestroyIcon, LoadImageW, SendMessageW, - HCURSOR, HICON, ICONINFO, ICON_BIG, ICON_SMALL, IMAGE_ICON, LR_DEFAULTSIZE, - LR_LOADFROMFILE, WM_SETICON, - }, - }, +use windows_sys::core::PCWSTR; +use windows_sys::Win32::Foundation::HWND; +use windows_sys::Win32::Graphics::Gdi::{ + CreateBitmap, CreateCompatibleBitmap, DeleteObject, GetDC, ReleaseDC, SetBitmapBits, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateIcon, CreateIconIndirect, DestroyCursor, DestroyIcon, LoadImageW, SendMessageW, HCURSOR, + HICON, ICONINFO, ICON_BIG, ICON_SMALL, IMAGE_ICON, LR_DEFAULTSIZE, LR_LOADFROMFILE, WM_SETICON, }; +use crate::cursor::CursorImage; +use crate::dpi::PhysicalSize; use crate::icon::*; -use crate::{cursor::CursorImage, dpi::PhysicalSize}; use super::util; @@ -142,9 +141,7 @@ impl WinIcon { } fn from_handle(handle: HICON) -> Self { - Self { - inner: Arc::new(RaiiIcon { handle }), - } + Self { inner: Arc::new(RaiiIcon { handle }) } } } diff --git a/src/platform_impl/windows/ime.rs b/src/platform_impl/windows/ime.rs index e9ceef606f..6761487351 100644 --- a/src/platform_impl/windows/ime.rs +++ b/src/platform_impl/windows/ime.rs @@ -1,27 +1,19 @@ -use std::{ - ffi::{c_void, OsString}, - os::windows::prelude::OsStringExt, - ptr::null_mut, +use std::ffi::{c_void, OsString}; +use std::os::windows::prelude::OsStringExt; +use std::ptr::null_mut; + +use windows_sys::Win32::Foundation::{POINT, RECT}; +use windows_sys::Win32::Globalization::HIMC; +use windows_sys::Win32::UI::Input::Ime::{ + ImmAssociateContextEx, ImmGetCompositionStringW, ImmGetContext, ImmReleaseContext, + ImmSetCandidateWindow, ImmSetCompositionWindow, ATTR_TARGET_CONVERTED, + ATTR_TARGET_NOTCONVERTED, CANDIDATEFORM, CFS_EXCLUDE, CFS_POINT, COMPOSITIONFORM, GCS_COMPATTR, + GCS_COMPSTR, GCS_CURSORPOS, GCS_RESULTSTR, IACE_CHILDREN, IACE_DEFAULT, }; +use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_IMMENABLED}; -use windows_sys::Win32::{ - Foundation::{POINT, RECT}, - Globalization::HIMC, - UI::{ - Input::Ime::{ - ImmAssociateContextEx, ImmGetCompositionStringW, ImmGetContext, ImmReleaseContext, - ImmSetCandidateWindow, ImmSetCompositionWindow, ATTR_TARGET_CONVERTED, - ATTR_TARGET_NOTCONVERTED, CANDIDATEFORM, CFS_EXCLUDE, CFS_POINT, COMPOSITIONFORM, - GCS_COMPATTR, GCS_COMPSTR, GCS_CURSORPOS, GCS_RESULTSTR, IACE_CHILDREN, IACE_DEFAULT, - }, - WindowsAndMessaging::{GetSystemMetrics, SM_IMMENABLED}, - }, -}; - -use crate::{ - dpi::{Position, Size}, - platform::windows::HWND, -}; +use crate::dpi::{Position, Size}; +use crate::platform::windows::HWND; pub struct ImeContext { hwnd: HWND, @@ -60,7 +52,8 @@ impl ImeContext { if first.is_some() && last.is_none() { last = Some(text.len()); } else if first.is_none() { - // IME haven't split words and select any clause yet, so trying to retrieve normal cursor. + // IME haven't split words and select any clause yet, so trying to retrieve normal + // cursor. let cursor = unsafe { self.get_composition_cursor(&text) }; first = cursor; last = cursor; @@ -120,12 +113,7 @@ impl ImeContext { let (x, y) = spot.to_physical::(scale_factor).into(); let (width, height): (i32, i32) = size.to_physical::(scale_factor).into(); - let rc_area = RECT { - left: x, - top: y, - right: x + width, - bottom: y + height, - }; + let rc_area = RECT { left: x, top: y, right: x + width, bottom: y + height }; let candidate_form = CANDIDATEFORM { dwIndex: 0, dwStyle: CFS_EXCLUDE, diff --git a/src/platform_impl/windows/keyboard.rs b/src/platform_impl/windows/keyboard.rs index 8c101816c7..43dea40db6 100644 --- a/src/platform_impl/windows/keyboard.rs +++ b/src/platform_impl/windows/keyboard.rs @@ -1,50 +1,39 @@ -use std::{ - char, - ffi::OsString, - mem::MaybeUninit, - os::windows::ffi::OsStringExt, - sync::{ - atomic::{AtomicU32, Ordering::Relaxed}, - Mutex, MutexGuard, - }, +use std::char; +use std::ffi::OsString; +use std::mem::MaybeUninit; +use std::os::windows::ffi::OsStringExt; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering::Relaxed; +use std::sync::{Mutex, MutexGuard}; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; +use windows_sys::Win32::System::SystemServices::LANG_KOREAN; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, GetKeyState, GetKeyboardLayout, GetKeyboardState, MapVirtualKeyExW, + MAPVK_VK_TO_VSC_EX, MAPVK_VSC_TO_VK_EX, VIRTUAL_KEY, VK_ABNT_C2, VK_ADD, VK_CAPITAL, VK_CLEAR, + VK_CONTROL, VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_END, VK_F4, VK_HOME, VK_INSERT, + VK_LCONTROL, VK_LEFT, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, VK_MULTIPLY, VK_NEXT, VK_NUMLOCK, + VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, + VK_NUMPAD8, VK_NUMPAD9, VK_PRIOR, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT, + VK_RWIN, VK_SCROLL, VK_SHIFT, VK_SUBTRACT, VK_UP, }; - -use windows_sys::Win32::{ - Foundation::{HWND, LPARAM, WPARAM}, - System::SystemServices::LANG_KOREAN, - UI::{ - Input::KeyboardAndMouse::{ - GetAsyncKeyState, GetKeyState, GetKeyboardLayout, GetKeyboardState, MapVirtualKeyExW, - MAPVK_VK_TO_VSC_EX, MAPVK_VSC_TO_VK_EX, VIRTUAL_KEY, VK_ABNT_C2, VK_ADD, VK_CAPITAL, - VK_CLEAR, VK_CONTROL, VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_END, VK_F4, - VK_HOME, VK_INSERT, VK_LCONTROL, VK_LEFT, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, - VK_MULTIPLY, VK_NEXT, VK_NUMLOCK, VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, - VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_PRIOR, - VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SCROLL, VK_SHIFT, - VK_SUBTRACT, VK_UP, - }, - TextServices::HKL, - WindowsAndMessaging::{ - PeekMessageW, MSG, PM_NOREMOVE, WM_CHAR, WM_DEADCHAR, WM_KEYDOWN, WM_KEYFIRST, - WM_KEYLAST, WM_KEYUP, WM_KILLFOCUS, WM_SETFOCUS, WM_SYSCHAR, WM_SYSDEADCHAR, - WM_SYSKEYDOWN, WM_SYSKEYUP, - }, - }, +use windows_sys::Win32::UI::TextServices::HKL; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + PeekMessageW, MSG, PM_NOREMOVE, WM_CHAR, WM_DEADCHAR, WM_KEYDOWN, WM_KEYFIRST, WM_KEYLAST, + WM_KEYUP, WM_KILLFOCUS, WM_SETFOCUS, WM_SYSCHAR, WM_SYSDEADCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP, }; use smol_str::SmolStr; use tracing::{trace, warn}; use unicode_segmentation::UnicodeSegmentation; -use crate::{ - event::{ElementState, KeyEvent}, - keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey}, - platform_impl::platform::{ - event_loop::ProcResult, - keyboard_layout::{Layout, LayoutCache, WindowsModifiers, LAYOUT_CACHE}, - loword, primarylangid, KeyEventExtra, - }, +use crate::event::{ElementState, KeyEvent}; +use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey}; +use crate::platform_impl::platform::event_loop::ProcResult; +use crate::platform_impl::platform::keyboard_layout::{ + Layout, LayoutCache, WindowsModifiers, LAYOUT_CACHE, }; +use crate::platform_impl::platform::{loword, primarylangid, KeyEventExtra}; pub type ExScancode = u16; @@ -60,16 +49,16 @@ pub struct MessageAsKeyEvent { /// window message. Therefore, this type keeps track of certain information from previous events so /// that a `KeyEvent` can be constructed when the last event related to a keypress is received. /// -/// `PeekMessage` is sometimes used to determine whether the next window message still belongs to the -/// current keypress. If it doesn't and the current state represents a key event waiting to be +/// `PeekMessage` is sometimes used to determine whether the next window message still belongs to +/// the current keypress. If it doesn't and the current state represents a key event waiting to be /// dispatched, then said event is considered complete and is dispatched. /// /// The sequence of window messages for a key press event is the following: /// - Exactly one WM_KEYDOWN / WM_SYSKEYDOWN /// - Zero or one WM_DEADCHAR / WM_SYSDEADCHAR /// - Zero or more WM_CHAR / WM_SYSCHAR. These messages each come with a UTF-16 code unit which when -/// put together in the sequence they arrived in, forms the text which is the result of pressing the -/// key. +/// put together in the sequence they arrived in, forms the text which is the result of pressing +/// the key. /// /// Key release messages are a bit different due to the fact that they don't contribute to /// text input. The "sequence" only consists of one WM_KEYUP / WM_SYSKEYUP event. @@ -79,10 +68,7 @@ pub struct KeyEventBuilder { } impl Default for KeyEventBuilder { fn default() -> Self { - KeyEventBuilder { - event_info: Mutex::new(None), - pending: Default::default(), - } + KeyEventBuilder { event_info: Mutex::new(None), pending: Default::default() } } } impl KeyEventBuilder { @@ -110,13 +96,13 @@ impl KeyEventBuilder { let kbd_state = get_async_kbd_state(); let key_events = Self::synthesize_kbd_state(ElementState::Pressed, &kbd_state); MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events)) - } + }, WM_KILLFOCUS => { // sythesize keyup events let kbd_state = get_kbd_state(); let key_events = Self::synthesize_kbd_state(ElementState::Released, &kbd_state); MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events)) - } + }, WM_KEYDOWN | WM_SYSKEYDOWN => { if msg_kind == WM_SYSKEYDOWN && wparam as VIRTUAL_KEY == VK_F4 { // Don't dispatch Alt+F4 to the application. @@ -162,39 +148,36 @@ impl KeyEventBuilder { let ev = event_info.finalize(); return MatchResult::MessagesToDispatch(self.pending.complete_pending( pending_token, - MessageAsKeyEvent { - event: ev, - is_synthetic: false, - }, + MessageAsKeyEvent { event: ev, is_synthetic: false }, )); } MatchResult::TokenToRemove(pending_token) - } + }, WM_DEADCHAR | WM_SYSDEADCHAR => { let pending_token = self.pending.add_pending(); *result = ProcResult::Value(0); - // At this point, we know that there isn't going to be any more events related to - // this key press + // At this point, we know that there isn't going to be any more events related + // to this key press let event_info = self.event_info.lock().unwrap().take().unwrap(); let ev = event_info.finalize(); MatchResult::MessagesToDispatch(self.pending.complete_pending( pending_token, - MessageAsKeyEvent { - event: ev, - is_synthetic: false, - }, + MessageAsKeyEvent { event: ev, is_synthetic: false }, )) - } + }, WM_CHAR | WM_SYSCHAR => { let mut event_info = self.event_info.lock().unwrap(); if event_info.is_none() { - trace!("Received a CHAR message but no `event_info` was available. The message is probably IME, returning."); + trace!( + "Received a CHAR message but no `event_info` was available. The \ + message is probably IME, returning." + ); return MatchResult::Nothing; } let pending_token = self.pending.add_pending(); *result = ProcResult::Value(0); - let is_high_surrogate = (0xD800..=0xDBFF).contains(&wparam); - let is_low_surrogate = (0xDC00..=0xDFFF).contains(&wparam); + let is_high_surrogate = (0xd800..=0xdbff).contains(&wparam); + let is_low_surrogate = (0xdc00..=0xdfff).contains(&wparam); let is_utf16 = is_high_surrogate || is_low_surrogate; @@ -210,7 +193,7 @@ impl KeyEventBuilder { None => { warn!("The event_info was None when it was expected to be some"); return MatchResult::TokenToRemove(pending_token); - } + }, }; let start_offset = utf16parts.len(); let new_size = utf16parts.len() + 2; @@ -221,16 +204,17 @@ impl KeyEventBuilder { utf16parts.resize(new_size, 0); } } - // It's important that we unlock the mutex, and create the pending event token before - // calling `next_msg` + // It's important that we unlock the mutex, and create the pending event token + // before calling `next_msg` std::mem::drop(event_info); let next_msg = next_kbd_msg(hwnd); let more_char_coming = next_msg .map(|m| matches!(m.message, WM_CHAR | WM_SYSCHAR)) .unwrap_or(false); if more_char_coming { - // No need to produce an event just yet, because there are still more characters that - // need to appended to this keyobard event + // No need to produce an event just yet, because there are still more + // characters that need to appended to this keyobard + // event MatchResult::TokenToRemove(pending_token) } else { let mut event_info = self.event_info.lock().unwrap(); @@ -239,7 +223,7 @@ impl KeyEventBuilder { None => { warn!("The event_info was None when it was expected to be some"); return MatchResult::TokenToRemove(pending_token); - } + }, }; let mut layouts = LAYOUT_CACHE.lock().unwrap(); // It's okay to call `ToUnicode` here, because at this point the dead key @@ -271,13 +255,10 @@ impl KeyEventBuilder { let ev = event_info.finalize(); MatchResult::MessagesToDispatch(self.pending.complete_pending( pending_token, - MessageAsKeyEvent { - event: ev, - is_synthetic: false, - }, + MessageAsKeyEvent { event: ev, is_synthetic: false }, )) } - } + }, WM_KEYUP | WM_SYSKEYUP => { let pending_token = self.pending.add_pending(); *result = ProcResult::Value(0); @@ -289,9 +270,11 @@ impl KeyEventBuilder { ElementState::Released, &mut layouts, ); - // We MUST release the layout lock before calling `next_kbd_msg`, otherwise it may deadlock + // We MUST release the layout lock before calling `next_kbd_msg`, otherwise it + // may deadlock drop(layouts); - // It's important that we create the pending token before reading the next message. + // It's important that we create the pending token before reading the next + // message. let next_msg = next_kbd_msg(hwnd); let mut valid_event_info = Some(event_info); if let Some(next_msg) = next_msg { @@ -309,14 +292,11 @@ impl KeyEventBuilder { let event = event_info.finalize(); return MatchResult::MessagesToDispatch(self.pending.complete_pending( pending_token, - MessageAsKeyEvent { - event, - is_synthetic: false, - }, + MessageAsKeyEvent { event, is_synthetic: false }, )); } MatchResult::TokenToRemove(pending_token) - } + }, _ => MatchResult::Nothing, } }; @@ -352,12 +332,11 @@ impl KeyEventBuilder { let num_lock_on = kbd_state[VK_NUMLOCK as usize] & 1 != 0; // We are synthesizing the press event for caps-lock first for the following reasons: - // 1. If caps-lock is *not* held down but *is* active, then we have to - // synthesize all printable keys, respecting the caps-lock state. - // 2. If caps-lock is held down, we could choose to sythesize its - // keypress after every other key, in which case all other keys *must* - // be sythesized as if the caps-lock state was be the opposite - // of what it currently is. + // 1. If caps-lock is *not* held down but *is* active, then we have to synthesize all + // printable keys, respecting the caps-lock state. + // 2. If caps-lock is held down, we could choose to sythesize its keypress after every other + // key, in which case all other keys *must* be sythesized as if the caps-lock state was + // be the opposite of what it currently is. // -- // For the sake of simplicity we are choosing to always sythesize // caps-lock first, and always use the current caps-lock state @@ -399,14 +378,8 @@ impl KeyEventBuilder { } }; let do_modifier = |key_events: &mut Vec<_>, layouts: &mut _| { - const CLEAR_MODIFIER_VKS: [VIRTUAL_KEY; 6] = [ - VK_LCONTROL, - VK_LSHIFT, - VK_LMENU, - VK_RCONTROL, - VK_RSHIFT, - VK_RMENU, - ]; + const CLEAR_MODIFIER_VKS: [VIRTUAL_KEY; 6] = + [VK_LCONTROL, VK_LSHIFT, VK_LMENU, VK_RCONTROL, VK_RSHIFT, VK_RMENU]; for vk in CLEAR_MODIFIER_VKS.iter() { if is_key_pressed!(*vk) { let event = Self::create_synthetic( @@ -431,11 +404,11 @@ impl KeyEventBuilder { ElementState::Pressed => { do_non_modifier(&mut key_events, &mut layouts); do_modifier(&mut key_events, &mut layouts); - } + }, ElementState::Released => { do_modifier(&mut key_events, &mut layouts); do_non_modifier(&mut key_events, &mut layouts); - } + }, } key_events @@ -455,11 +428,8 @@ impl KeyEventBuilder { } let scancode = scancode as ExScancode; let physical_key = scancode_to_physicalkey(scancode as u32); - let mods = if caps_lock_on { - WindowsModifiers::CAPS_LOCK - } else { - WindowsModifiers::empty() - }; + let mods = + if caps_lock_on { WindowsModifiers::CAPS_LOCK } else { WindowsModifiers::empty() }; let layout = layouts.layouts.get(&(locale_id as u64)).unwrap(); let logical_key = layout.get_key(mods, num_lock_on, vk, &physical_key); let key_without_modifiers = @@ -484,10 +454,7 @@ impl KeyEventBuilder { let mut event = event_info.finalize(); event.logical_key = logical_key; event.platform_specific.text_with_all_modifiers = text; - Some(MessageAsKeyEvent { - event, - is_synthetic: true, - }) + Some(MessageAsKeyEvent { event, is_synthetic: true }) } } @@ -600,7 +567,7 @@ impl PartialKeyEventInfo { } else { Key::Unidentified(NativeKey::Unidentified) } - } + }, key => key, } }; @@ -637,10 +604,10 @@ impl PartialKeyEventInfo { text = Some(SmolStr::new(string)); } } - } + }, PartialText::Text(s) => { text = s.map(SmolStr::new); - } + }, } let logical_key = match self.logical_key { @@ -651,7 +618,7 @@ impl PartialKeyEventInfo { } else { Key::Character(s.clone()) } - } + }, None => Key::Unidentified(NativeKey::Windows(self.vkey)), }, PartialLogicalKey::This(v) => v, @@ -677,7 +644,8 @@ struct KeyLParam { pub scancode: u8, pub extended: bool, - /// This is `previous_state XOR transition_state`. See the lParam for WM_KEYDOWN and WM_KEYUP for further details. + /// This is `previous_state XOR transition_state`. See the lParam for WM_KEYDOWN and WM_KEYUP + /// for further details. pub is_repeat: bool, } @@ -685,7 +653,7 @@ fn destructure_key_lparam(lparam: LPARAM) -> KeyLParam { let previous_state = (lparam >> 30) & 0x01; let transition_state = (lparam >> 31) & 0x01; KeyLParam { - scancode: ((lparam >> 16) & 0xFF) as u8, + scancode: ((lparam >> 16) & 0xff) as u8, extended: ((lparam >> 24) & 0x01) != 0, is_repeat: (previous_state ^ transition_state) != 0, } @@ -693,7 +661,7 @@ fn destructure_key_lparam(lparam: LPARAM) -> KeyLParam { #[inline] fn new_ex_scancode(scancode: u8, extended: bool) -> ExScancode { - (scancode as u16) | (if extended { 0xE000 } else { 0 }) + (scancode as u16) | (if extended { 0xe000 } else { 0 }) } #[inline] @@ -742,13 +710,11 @@ fn get_async_kbd_state() -> [u8; 256] { /// the next event is a right Alt (AltGr) event. If this is the case, the current event must be the /// fake Ctrl event. fn is_current_fake(curr_info: &PartialKeyEventInfo, next_msg: MSG, layout: &Layout) -> bool { - let curr_is_ctrl = matches!( - curr_info.logical_key, - PartialLogicalKey::This(Key::Named(NamedKey::Control)) - ); + let curr_is_ctrl = + matches!(curr_info.logical_key, PartialLogicalKey::This(Key::Named(NamedKey::Control))); if layout.has_alt_graph { let next_code = ex_scancode_from_lparam(next_msg.lParam); - let next_is_altgr = next_code == 0xE038; // 0xE038 is right alt + let next_is_altgr = next_code == 0xe038; // 0xE038 is right alt if curr_is_ctrl && next_is_altgr { return true; } @@ -792,10 +758,7 @@ impl PendingEventQueue { pub fn add_pending(&self) -> PendingMessageToken { let token = self.next_token(); let mut pending = self.pending.lock().unwrap(); - pending.push(IdentifiedPendingMessage { - token, - msg: PendingMessage::Incomplete, - }); + pending.push(IdentifiedPendingMessage { token, msg: PendingMessage::Incomplete }); token } @@ -862,15 +825,20 @@ impl PendingEventQueue { } fn drain_pending(pending: &mut Vec>) -> Vec { - pending.drain(..).map(|m| { - match m.msg { + pending + .drain(..) + .map(|m| match m.msg { PendingMessage::Complete(msg) => msg, PendingMessage::Incomplete => { - panic!("Found an incomplete pending message when collecting messages. This indicates a bug in winit.") - } - } - }).collect() + panic!( + "Found an incomplete pending message when collecting messages. This \ + indicates a bug in winit." + ) + }, + }) + .collect() } + fn next_token(&self) -> PendingMessageToken { // It's okay for the u32 to overflow here. Yes, that could mean // that two different messages have the same token, @@ -884,10 +852,7 @@ impl PendingEventQueue { } impl Default for PendingEventQueue { fn default() -> Self { - PendingEventQueue { - pending: Mutex::new(Vec::new()), - next_id: AtomicU32::new(0), - } + PendingEventQueue { pending: Mutex::new(Vec::new()), next_id: AtomicU32::new(0) } } } @@ -902,13 +867,8 @@ impl Default for PendingEventQueue { pub fn next_kbd_msg(hwnd: HWND) -> Option { unsafe { let mut next_msg = MaybeUninit::uninit(); - let peek_retval = PeekMessageW( - next_msg.as_mut_ptr(), - hwnd, - WM_KEYFIRST, - WM_KEYLAST, - PM_NOREMOVE, - ); + let peek_retval = + PeekMessageW(next_msg.as_mut_ptr(), hwnd, WM_KEYFIRST, WM_KEYLAST, PM_NOREMOVE); (peek_retval != 0).then(|| next_msg.assume_init()) } } @@ -916,7 +876,7 @@ pub fn next_kbd_msg(hwnd: HWND) -> Option { fn get_location(scancode: ExScancode, hkl: HKL) -> KeyLocation { const ABNT_C2: VIRTUAL_KEY = VK_ABNT_C2 as VIRTUAL_KEY; - let extension = 0xE000; + let extension = 0xe000; let extended = (scancode & extension) == extension; let vkey = unsafe { MapVirtualKeyExW(scancode as u32, MAPVK_VSC_TO_VK_EX, hkl) as VIRTUAL_KEY }; @@ -934,7 +894,7 @@ fn get_location(scancode: ExScancode, hkl: HKL) -> KeyLocation { } else { KeyLocation::Numpad } - } + }, VK_NUMPAD0 | VK_NUMPAD1 | VK_NUMPAD2 | VK_NUMPAD3 | VK_NUMPAD4 | VK_NUMPAD5 | VK_NUMPAD6 | VK_NUMPAD7 | VK_NUMPAD8 | VK_NUMPAD9 | VK_DECIMAL | VK_DIVIDE | VK_MULTIPLY | VK_SUBTRACT | VK_ADD | ABNT_C2 => KeyLocation::Numpad, @@ -957,17 +917,17 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option NativeKeyCode::Windows(scancode) => Some(scancode as u32), _ => None, }; - } + }, }; match code { KeyCode::Backquote => Some(0x0029), - KeyCode::Backslash => Some(0x002B), - KeyCode::Backspace => Some(0x000E), - KeyCode::BracketLeft => Some(0x001A), - KeyCode::BracketRight => Some(0x001B), + KeyCode::Backslash => Some(0x002b), + KeyCode::Backspace => Some(0x000e), + KeyCode::BracketLeft => Some(0x001a), + KeyCode::BracketRight => Some(0x001b), KeyCode::Comma => Some(0x0033), - KeyCode::Digit0 => Some(0x000B), + KeyCode::Digit0 => Some(0x000b), KeyCode::Digit1 => Some(0x0002), KeyCode::Digit2 => Some(0x0003), KeyCode::Digit3 => Some(0x0004), @@ -976,14 +936,14 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option KeyCode::Digit6 => Some(0x0007), KeyCode::Digit7 => Some(0x0008), KeyCode::Digit8 => Some(0x0009), - KeyCode::Digit9 => Some(0x000A), - KeyCode::Equal => Some(0x000D), + KeyCode::Digit9 => Some(0x000a), + KeyCode::Equal => Some(0x000d), KeyCode::IntlBackslash => Some(0x0056), KeyCode::IntlRo => Some(0x0073), - KeyCode::IntlYen => Some(0x007D), - KeyCode::KeyA => Some(0x001E), + KeyCode::IntlYen => Some(0x007d), + KeyCode::KeyA => Some(0x001e), KeyCode::KeyB => Some(0x0030), - KeyCode::KeyC => Some(0x002E), + KeyCode::KeyC => Some(0x002e), KeyCode::KeyD => Some(0x0020), KeyCode::KeyE => Some(0x0012), KeyCode::KeyF => Some(0x0021), @@ -999,84 +959,84 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option KeyCode::KeyP => Some(0x0019), KeyCode::KeyQ => Some(0x0010), KeyCode::KeyR => Some(0x0013), - KeyCode::KeyS => Some(0x001F), + KeyCode::KeyS => Some(0x001f), KeyCode::KeyT => Some(0x0014), KeyCode::KeyU => Some(0x0016), - KeyCode::KeyV => Some(0x002F), + KeyCode::KeyV => Some(0x002f), KeyCode::KeyW => Some(0x0011), - KeyCode::KeyX => Some(0x002D), + KeyCode::KeyX => Some(0x002d), KeyCode::KeyY => Some(0x0015), - KeyCode::KeyZ => Some(0x002C), - KeyCode::Minus => Some(0x000C), + KeyCode::KeyZ => Some(0x002c), + KeyCode::Minus => Some(0x000c), KeyCode::Period => Some(0x0034), KeyCode::Quote => Some(0x0028), KeyCode::Semicolon => Some(0x0027), KeyCode::Slash => Some(0x0035), KeyCode::AltLeft => Some(0x0038), - KeyCode::AltRight => Some(0xE038), - KeyCode::CapsLock => Some(0x003A), - KeyCode::ContextMenu => Some(0xE05D), - KeyCode::ControlLeft => Some(0x001D), - KeyCode::ControlRight => Some(0xE01D), - KeyCode::Enter => Some(0x001C), - KeyCode::SuperLeft => Some(0xE05B), - KeyCode::SuperRight => Some(0xE05C), - KeyCode::ShiftLeft => Some(0x002A), + KeyCode::AltRight => Some(0xe038), + KeyCode::CapsLock => Some(0x003a), + KeyCode::ContextMenu => Some(0xe05d), + KeyCode::ControlLeft => Some(0x001d), + KeyCode::ControlRight => Some(0xe01d), + KeyCode::Enter => Some(0x001c), + KeyCode::SuperLeft => Some(0xe05b), + KeyCode::SuperRight => Some(0xe05c), + KeyCode::ShiftLeft => Some(0x002a), KeyCode::ShiftRight => Some(0x0036), KeyCode::Space => Some(0x0039), - KeyCode::Tab => Some(0x000F), + KeyCode::Tab => Some(0x000f), KeyCode::Convert => Some(0x0079), KeyCode::Lang1 => { if is_korean { - Some(0xE0F2) + Some(0xe0f2) } else { Some(0x0072) } - } + }, KeyCode::Lang2 => { if is_korean { - Some(0xE0F1) + Some(0xe0f1) } else { Some(0x0071) } - } + }, KeyCode::KanaMode => Some(0x0070), - KeyCode::NonConvert => Some(0x007B), - KeyCode::Delete => Some(0xE053), - KeyCode::End => Some(0xE04F), - KeyCode::Home => Some(0xE047), - KeyCode::Insert => Some(0xE052), - KeyCode::PageDown => Some(0xE051), - KeyCode::PageUp => Some(0xE049), - KeyCode::ArrowDown => Some(0xE050), - KeyCode::ArrowLeft => Some(0xE04B), - KeyCode::ArrowRight => Some(0xE04D), - KeyCode::ArrowUp => Some(0xE048), - KeyCode::NumLock => Some(0xE045), + KeyCode::NonConvert => Some(0x007b), + KeyCode::Delete => Some(0xe053), + KeyCode::End => Some(0xe04f), + KeyCode::Home => Some(0xe047), + KeyCode::Insert => Some(0xe052), + KeyCode::PageDown => Some(0xe051), + KeyCode::PageUp => Some(0xe049), + KeyCode::ArrowDown => Some(0xe050), + KeyCode::ArrowLeft => Some(0xe04b), + KeyCode::ArrowRight => Some(0xe04d), + KeyCode::ArrowUp => Some(0xe048), + KeyCode::NumLock => Some(0xe045), KeyCode::Numpad0 => Some(0x0052), - KeyCode::Numpad1 => Some(0x004F), + KeyCode::Numpad1 => Some(0x004f), KeyCode::Numpad2 => Some(0x0050), KeyCode::Numpad3 => Some(0x0051), - KeyCode::Numpad4 => Some(0x004B), - KeyCode::Numpad5 => Some(0x004C), - KeyCode::Numpad6 => Some(0x004D), + KeyCode::Numpad4 => Some(0x004b), + KeyCode::Numpad5 => Some(0x004c), + KeyCode::Numpad6 => Some(0x004d), KeyCode::Numpad7 => Some(0x0047), KeyCode::Numpad8 => Some(0x0048), KeyCode::Numpad9 => Some(0x0049), - KeyCode::NumpadAdd => Some(0x004E), - KeyCode::NumpadComma => Some(0x007E), + KeyCode::NumpadAdd => Some(0x004e), + KeyCode::NumpadComma => Some(0x007e), KeyCode::NumpadDecimal => Some(0x0053), - KeyCode::NumpadDivide => Some(0xE035), - KeyCode::NumpadEnter => Some(0xE01C), + KeyCode::NumpadDivide => Some(0xe035), + KeyCode::NumpadEnter => Some(0xe01c), KeyCode::NumpadEqual => Some(0x0059), KeyCode::NumpadMultiply => Some(0x0037), - KeyCode::NumpadSubtract => Some(0x004A), + KeyCode::NumpadSubtract => Some(0x004a), KeyCode::Escape => Some(0x0001), - KeyCode::F1 => Some(0x003B), - KeyCode::F2 => Some(0x003C), - KeyCode::F3 => Some(0x003D), - KeyCode::F4 => Some(0x003E), - KeyCode::F5 => Some(0x003F), + KeyCode::F1 => Some(0x003b), + KeyCode::F2 => Some(0x003c), + KeyCode::F3 => Some(0x003d), + KeyCode::F4 => Some(0x003e), + KeyCode::F5 => Some(0x003f), KeyCode::F6 => Some(0x0040), KeyCode::F7 => Some(0x0041), KeyCode::F8 => Some(0x0042), @@ -1090,36 +1050,36 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option KeyCode::F16 => Some(0x0067), KeyCode::F17 => Some(0x0068), KeyCode::F18 => Some(0x0069), - KeyCode::F19 => Some(0x006A), - KeyCode::F20 => Some(0x006B), - KeyCode::F21 => Some(0x006C), - KeyCode::F22 => Some(0x006D), - KeyCode::F23 => Some(0x006E), + KeyCode::F19 => Some(0x006a), + KeyCode::F20 => Some(0x006b), + KeyCode::F21 => Some(0x006c), + KeyCode::F22 => Some(0x006d), + KeyCode::F23 => Some(0x006e), KeyCode::F24 => Some(0x0076), - KeyCode::PrintScreen => Some(0xE037), - //KeyCode::PrintScreen => Some(0x0054), // Alt + PrintScreen + KeyCode::PrintScreen => Some(0xe037), + // KeyCode::PrintScreen => Some(0x0054), // Alt + PrintScreen KeyCode::ScrollLock => Some(0x0046), KeyCode::Pause => Some(0x0045), - //KeyCode::Pause => Some(0xE046), // Ctrl + Pause - KeyCode::BrowserBack => Some(0xE06A), - KeyCode::BrowserFavorites => Some(0xE066), - KeyCode::BrowserForward => Some(0xE069), - KeyCode::BrowserHome => Some(0xE032), - KeyCode::BrowserRefresh => Some(0xE067), - KeyCode::BrowserSearch => Some(0xE065), - KeyCode::BrowserStop => Some(0xE068), - KeyCode::LaunchApp1 => Some(0xE06B), - KeyCode::LaunchApp2 => Some(0xE021), - KeyCode::LaunchMail => Some(0xE06C), - KeyCode::MediaPlayPause => Some(0xE022), - KeyCode::MediaSelect => Some(0xE06D), - KeyCode::MediaStop => Some(0xE024), - KeyCode::MediaTrackNext => Some(0xE019), - KeyCode::MediaTrackPrevious => Some(0xE010), - KeyCode::Power => Some(0xE05E), - KeyCode::AudioVolumeDown => Some(0xE02E), - KeyCode::AudioVolumeMute => Some(0xE020), - KeyCode::AudioVolumeUp => Some(0xE030), + // KeyCode::Pause => Some(0xE046), // Ctrl + Pause + KeyCode::BrowserBack => Some(0xe06a), + KeyCode::BrowserFavorites => Some(0xe066), + KeyCode::BrowserForward => Some(0xe069), + KeyCode::BrowserHome => Some(0xe032), + KeyCode::BrowserRefresh => Some(0xe067), + KeyCode::BrowserSearch => Some(0xe065), + KeyCode::BrowserStop => Some(0xe068), + KeyCode::LaunchApp1 => Some(0xe06b), + KeyCode::LaunchApp2 => Some(0xe021), + KeyCode::LaunchMail => Some(0xe06c), + KeyCode::MediaPlayPause => Some(0xe022), + KeyCode::MediaSelect => Some(0xe06d), + KeyCode::MediaStop => Some(0xe024), + KeyCode::MediaTrackNext => Some(0xe019), + KeyCode::MediaTrackPrevious => Some(0xe010), + KeyCode::Power => Some(0xe05e), + KeyCode::AudioVolumeDown => Some(0xe02e), + KeyCode::AudioVolumeMute => Some(0xe020), + KeyCode::AudioVolumeUp => Some(0xe030), _ => None, } } @@ -1131,12 +1091,12 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { PhysicalKey::Code(match scancode { 0x0029 => KeyCode::Backquote, - 0x002B => KeyCode::Backslash, - 0x000E => KeyCode::Backspace, - 0x001A => KeyCode::BracketLeft, - 0x001B => KeyCode::BracketRight, + 0x002b => KeyCode::Backslash, + 0x000e => KeyCode::Backspace, + 0x001a => KeyCode::BracketLeft, + 0x001b => KeyCode::BracketRight, 0x0033 => KeyCode::Comma, - 0x000B => KeyCode::Digit0, + 0x000b => KeyCode::Digit0, 0x0002 => KeyCode::Digit1, 0x0003 => KeyCode::Digit2, 0x0004 => KeyCode::Digit3, @@ -1145,14 +1105,14 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x0007 => KeyCode::Digit6, 0x0008 => KeyCode::Digit7, 0x0009 => KeyCode::Digit8, - 0x000A => KeyCode::Digit9, - 0x000D => KeyCode::Equal, + 0x000a => KeyCode::Digit9, + 0x000d => KeyCode::Equal, 0x0056 => KeyCode::IntlBackslash, 0x0073 => KeyCode::IntlRo, - 0x007D => KeyCode::IntlYen, - 0x001E => KeyCode::KeyA, + 0x007d => KeyCode::IntlYen, + 0x001e => KeyCode::KeyA, 0x0030 => KeyCode::KeyB, - 0x002E => KeyCode::KeyC, + 0x002e => KeyCode::KeyC, 0x0020 => KeyCode::KeyD, 0x0012 => KeyCode::KeyE, 0x0021 => KeyCode::KeyF, @@ -1168,74 +1128,74 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x0019 => KeyCode::KeyP, 0x0010 => KeyCode::KeyQ, 0x0013 => KeyCode::KeyR, - 0x001F => KeyCode::KeyS, + 0x001f => KeyCode::KeyS, 0x0014 => KeyCode::KeyT, 0x0016 => KeyCode::KeyU, - 0x002F => KeyCode::KeyV, + 0x002f => KeyCode::KeyV, 0x0011 => KeyCode::KeyW, - 0x002D => KeyCode::KeyX, + 0x002d => KeyCode::KeyX, 0x0015 => KeyCode::KeyY, - 0x002C => KeyCode::KeyZ, - 0x000C => KeyCode::Minus, + 0x002c => KeyCode::KeyZ, + 0x000c => KeyCode::Minus, 0x0034 => KeyCode::Period, 0x0028 => KeyCode::Quote, 0x0027 => KeyCode::Semicolon, 0x0035 => KeyCode::Slash, 0x0038 => KeyCode::AltLeft, - 0xE038 => KeyCode::AltRight, - 0x003A => KeyCode::CapsLock, - 0xE05D => KeyCode::ContextMenu, - 0x001D => KeyCode::ControlLeft, - 0xE01D => KeyCode::ControlRight, - 0x001C => KeyCode::Enter, - 0xE05B => KeyCode::SuperLeft, - 0xE05C => KeyCode::SuperRight, - 0x002A => KeyCode::ShiftLeft, + 0xe038 => KeyCode::AltRight, + 0x003a => KeyCode::CapsLock, + 0xe05d => KeyCode::ContextMenu, + 0x001d => KeyCode::ControlLeft, + 0xe01d => KeyCode::ControlRight, + 0x001c => KeyCode::Enter, + 0xe05b => KeyCode::SuperLeft, + 0xe05c => KeyCode::SuperRight, + 0x002a => KeyCode::ShiftLeft, 0x0036 => KeyCode::ShiftRight, 0x0039 => KeyCode::Space, - 0x000F => KeyCode::Tab, + 0x000f => KeyCode::Tab, 0x0079 => KeyCode::Convert, 0x0072 => KeyCode::Lang1, // for non-Korean layout - 0xE0F2 => KeyCode::Lang1, // for Korean layout + 0xe0f2 => KeyCode::Lang1, // for Korean layout 0x0071 => KeyCode::Lang2, // for non-Korean layout - 0xE0F1 => KeyCode::Lang2, // for Korean layout + 0xe0f1 => KeyCode::Lang2, // for Korean layout 0x0070 => KeyCode::KanaMode, - 0x007B => KeyCode::NonConvert, - 0xE053 => KeyCode::Delete, - 0xE04F => KeyCode::End, - 0xE047 => KeyCode::Home, - 0xE052 => KeyCode::Insert, - 0xE051 => KeyCode::PageDown, - 0xE049 => KeyCode::PageUp, - 0xE050 => KeyCode::ArrowDown, - 0xE04B => KeyCode::ArrowLeft, - 0xE04D => KeyCode::ArrowRight, - 0xE048 => KeyCode::ArrowUp, - 0xE045 => KeyCode::NumLock, + 0x007b => KeyCode::NonConvert, + 0xe053 => KeyCode::Delete, + 0xe04f => KeyCode::End, + 0xe047 => KeyCode::Home, + 0xe052 => KeyCode::Insert, + 0xe051 => KeyCode::PageDown, + 0xe049 => KeyCode::PageUp, + 0xe050 => KeyCode::ArrowDown, + 0xe04b => KeyCode::ArrowLeft, + 0xe04d => KeyCode::ArrowRight, + 0xe048 => KeyCode::ArrowUp, + 0xe045 => KeyCode::NumLock, 0x0052 => KeyCode::Numpad0, - 0x004F => KeyCode::Numpad1, + 0x004f => KeyCode::Numpad1, 0x0050 => KeyCode::Numpad2, 0x0051 => KeyCode::Numpad3, - 0x004B => KeyCode::Numpad4, - 0x004C => KeyCode::Numpad5, - 0x004D => KeyCode::Numpad6, + 0x004b => KeyCode::Numpad4, + 0x004c => KeyCode::Numpad5, + 0x004d => KeyCode::Numpad6, 0x0047 => KeyCode::Numpad7, 0x0048 => KeyCode::Numpad8, 0x0049 => KeyCode::Numpad9, - 0x004E => KeyCode::NumpadAdd, - 0x007E => KeyCode::NumpadComma, + 0x004e => KeyCode::NumpadAdd, + 0x007e => KeyCode::NumpadComma, 0x0053 => KeyCode::NumpadDecimal, - 0xE035 => KeyCode::NumpadDivide, - 0xE01C => KeyCode::NumpadEnter, + 0xe035 => KeyCode::NumpadDivide, + 0xe01c => KeyCode::NumpadEnter, 0x0059 => KeyCode::NumpadEqual, 0x0037 => KeyCode::NumpadMultiply, - 0x004A => KeyCode::NumpadSubtract, + 0x004a => KeyCode::NumpadSubtract, 0x0001 => KeyCode::Escape, - 0x003B => KeyCode::F1, - 0x003C => KeyCode::F2, - 0x003D => KeyCode::F3, - 0x003E => KeyCode::F4, - 0x003F => KeyCode::F5, + 0x003b => KeyCode::F1, + 0x003c => KeyCode::F2, + 0x003d => KeyCode::F3, + 0x003e => KeyCode::F4, + 0x003f => KeyCode::F5, 0x0040 => KeyCode::F6, 0x0041 => KeyCode::F7, 0x0042 => KeyCode::F8, @@ -1249,36 +1209,36 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { 0x0067 => KeyCode::F16, 0x0068 => KeyCode::F17, 0x0069 => KeyCode::F18, - 0x006A => KeyCode::F19, - 0x006B => KeyCode::F20, - 0x006C => KeyCode::F21, - 0x006D => KeyCode::F22, - 0x006E => KeyCode::F23, + 0x006a => KeyCode::F19, + 0x006b => KeyCode::F20, + 0x006c => KeyCode::F21, + 0x006d => KeyCode::F22, + 0x006e => KeyCode::F23, 0x0076 => KeyCode::F24, - 0xE037 => KeyCode::PrintScreen, + 0xe037 => KeyCode::PrintScreen, 0x0054 => KeyCode::PrintScreen, // Alt + PrintScreen 0x0046 => KeyCode::ScrollLock, 0x0045 => KeyCode::Pause, - 0xE046 => KeyCode::Pause, // Ctrl + Pause - 0xE06A => KeyCode::BrowserBack, - 0xE066 => KeyCode::BrowserFavorites, - 0xE069 => KeyCode::BrowserForward, - 0xE032 => KeyCode::BrowserHome, - 0xE067 => KeyCode::BrowserRefresh, - 0xE065 => KeyCode::BrowserSearch, - 0xE068 => KeyCode::BrowserStop, - 0xE06B => KeyCode::LaunchApp1, - 0xE021 => KeyCode::LaunchApp2, - 0xE06C => KeyCode::LaunchMail, - 0xE022 => KeyCode::MediaPlayPause, - 0xE06D => KeyCode::MediaSelect, - 0xE024 => KeyCode::MediaStop, - 0xE019 => KeyCode::MediaTrackNext, - 0xE010 => KeyCode::MediaTrackPrevious, - 0xE05E => KeyCode::Power, - 0xE02E => KeyCode::AudioVolumeDown, - 0xE020 => KeyCode::AudioVolumeMute, - 0xE030 => KeyCode::AudioVolumeUp, + 0xe046 => KeyCode::Pause, // Ctrl + Pause + 0xe06a => KeyCode::BrowserBack, + 0xe066 => KeyCode::BrowserFavorites, + 0xe069 => KeyCode::BrowserForward, + 0xe032 => KeyCode::BrowserHome, + 0xe067 => KeyCode::BrowserRefresh, + 0xe065 => KeyCode::BrowserSearch, + 0xe068 => KeyCode::BrowserStop, + 0xe06b => KeyCode::LaunchApp1, + 0xe021 => KeyCode::LaunchApp2, + 0xe06c => KeyCode::LaunchMail, + 0xe022 => KeyCode::MediaPlayPause, + 0xe06d => KeyCode::MediaSelect, + 0xe024 => KeyCode::MediaStop, + 0xe019 => KeyCode::MediaTrackNext, + 0xe010 => KeyCode::MediaTrackPrevious, + 0xe05e => KeyCode::Power, + 0xe02e => KeyCode::AudioVolumeDown, + 0xe020 => KeyCode::AudioVolumeMute, + 0xe030 => KeyCode::AudioVolumeUp, _ => return PhysicalKey::Unidentified(NativeKeyCode::Windows(scancode as u16)), }) } diff --git a/src/platform_impl/windows/keyboard_layout.rs b/src/platform_impl/windows/keyboard_layout.rs index 31a15e49c5..5340e43d8b 100644 --- a/src/platform_impl/windows/keyboard_layout.rs +++ b/src/platform_impl/windows/keyboard_layout.rs @@ -1,60 +1,49 @@ -use std::{ - collections::{hash_map::Entry, HashMap, HashSet}, - ffi::OsString, - os::windows::ffi::OsStringExt, - sync::Mutex, -}; +use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; +use std::ffi::OsString; +use std::os::windows::ffi::OsStringExt; +use std::sync::Mutex; use crate::utils::Lazy; use smol_str::SmolStr; -use windows_sys::Win32::{ - System::SystemServices::{LANG_JAPANESE, LANG_KOREAN}, - UI::{ - Input::KeyboardAndMouse::{ - GetKeyState, GetKeyboardLayout, MapVirtualKeyExW, ToUnicodeEx, MAPVK_VK_TO_VSC_EX, - VIRTUAL_KEY, VK_ACCEPT, VK_ADD, VK_APPS, VK_ATTN, VK_BACK, VK_BROWSER_BACK, - VK_BROWSER_FAVORITES, VK_BROWSER_FORWARD, VK_BROWSER_HOME, VK_BROWSER_REFRESH, - VK_BROWSER_SEARCH, VK_BROWSER_STOP, VK_CANCEL, VK_CAPITAL, VK_CLEAR, VK_CONTROL, - VK_CONVERT, VK_CRSEL, VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_END, VK_EREOF, - VK_ESCAPE, VK_EXECUTE, VK_EXSEL, VK_F1, VK_F10, VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, - VK_F16, VK_F17, VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, VK_F23, VK_F24, VK_F3, - VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_FINAL, VK_GAMEPAD_A, VK_GAMEPAD_B, - VK_GAMEPAD_DPAD_DOWN, VK_GAMEPAD_DPAD_LEFT, VK_GAMEPAD_DPAD_RIGHT, VK_GAMEPAD_DPAD_UP, - VK_GAMEPAD_LEFT_SHOULDER, VK_GAMEPAD_LEFT_THUMBSTICK_BUTTON, - VK_GAMEPAD_LEFT_THUMBSTICK_DOWN, VK_GAMEPAD_LEFT_THUMBSTICK_LEFT, - VK_GAMEPAD_LEFT_THUMBSTICK_RIGHT, VK_GAMEPAD_LEFT_THUMBSTICK_UP, - VK_GAMEPAD_LEFT_TRIGGER, VK_GAMEPAD_MENU, VK_GAMEPAD_RIGHT_SHOULDER, - VK_GAMEPAD_RIGHT_THUMBSTICK_BUTTON, VK_GAMEPAD_RIGHT_THUMBSTICK_DOWN, - VK_GAMEPAD_RIGHT_THUMBSTICK_LEFT, VK_GAMEPAD_RIGHT_THUMBSTICK_RIGHT, - VK_GAMEPAD_RIGHT_THUMBSTICK_UP, VK_GAMEPAD_RIGHT_TRIGGER, VK_GAMEPAD_VIEW, - VK_GAMEPAD_X, VK_GAMEPAD_Y, VK_HANGUL, VK_HANJA, VK_HELP, VK_HOME, VK_ICO_00, - VK_ICO_CLEAR, VK_ICO_HELP, VK_INSERT, VK_JUNJA, VK_KANA, VK_KANJI, VK_LAUNCH_APP1, - VK_LAUNCH_APP2, VK_LAUNCH_MAIL, VK_LAUNCH_MEDIA_SELECT, VK_LBUTTON, VK_LCONTROL, - VK_LEFT, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MBUTTON, VK_MEDIA_NEXT_TRACK, - VK_MEDIA_PLAY_PAUSE, VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MENU, VK_MODECHANGE, - VK_MULTIPLY, VK_NAVIGATION_ACCEPT, VK_NAVIGATION_CANCEL, VK_NAVIGATION_DOWN, - VK_NAVIGATION_LEFT, VK_NAVIGATION_MENU, VK_NAVIGATION_RIGHT, VK_NAVIGATION_UP, - VK_NAVIGATION_VIEW, VK_NEXT, VK_NONAME, VK_NONCONVERT, VK_NUMLOCK, VK_NUMPAD0, - VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, - VK_NUMPAD8, VK_NUMPAD9, VK_OEM_1, VK_OEM_102, VK_OEM_2, VK_OEM_3, VK_OEM_4, VK_OEM_5, - VK_OEM_6, VK_OEM_7, VK_OEM_8, VK_OEM_ATTN, VK_OEM_AUTO, VK_OEM_AX, VK_OEM_BACKTAB, - VK_OEM_CLEAR, VK_OEM_COMMA, VK_OEM_COPY, VK_OEM_CUSEL, VK_OEM_ENLW, VK_OEM_FINISH, - VK_OEM_FJ_LOYA, VK_OEM_FJ_MASSHOU, VK_OEM_FJ_ROYA, VK_OEM_FJ_TOUROKU, VK_OEM_JUMP, - VK_OEM_MINUS, VK_OEM_NEC_EQUAL, VK_OEM_PA1, VK_OEM_PA2, VK_OEM_PA3, VK_OEM_PERIOD, - VK_OEM_PLUS, VK_OEM_RESET, VK_OEM_WSCTRL, VK_PA1, VK_PACKET, VK_PAUSE, VK_PLAY, - VK_PRINT, VK_PRIOR, VK_PROCESSKEY, VK_RBUTTON, VK_RCONTROL, VK_RETURN, VK_RIGHT, - VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SCROLL, VK_SELECT, VK_SEPARATOR, VK_SHIFT, VK_SLEEP, - VK_SNAPSHOT, VK_SPACE, VK_SUBTRACT, VK_TAB, VK_UP, VK_VOLUME_DOWN, VK_VOLUME_MUTE, - VK_VOLUME_UP, VK_XBUTTON1, VK_XBUTTON2, VK_ZOOM, - }, - TextServices::HKL, - }, +use windows_sys::Win32::System::SystemServices::{LANG_JAPANESE, LANG_KOREAN}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetKeyState, GetKeyboardLayout, MapVirtualKeyExW, ToUnicodeEx, MAPVK_VK_TO_VSC_EX, VIRTUAL_KEY, + VK_ACCEPT, VK_ADD, VK_APPS, VK_ATTN, VK_BACK, VK_BROWSER_BACK, VK_BROWSER_FAVORITES, + VK_BROWSER_FORWARD, VK_BROWSER_HOME, VK_BROWSER_REFRESH, VK_BROWSER_SEARCH, VK_BROWSER_STOP, + VK_CANCEL, VK_CAPITAL, VK_CLEAR, VK_CONTROL, VK_CONVERT, VK_CRSEL, VK_DECIMAL, VK_DELETE, + VK_DIVIDE, VK_DOWN, VK_END, VK_EREOF, VK_ESCAPE, VK_EXECUTE, VK_EXSEL, VK_F1, VK_F10, VK_F11, + VK_F12, VK_F13, VK_F14, VK_F15, VK_F16, VK_F17, VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, + VK_F23, VK_F24, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_FINAL, VK_GAMEPAD_A, + VK_GAMEPAD_B, VK_GAMEPAD_DPAD_DOWN, VK_GAMEPAD_DPAD_LEFT, VK_GAMEPAD_DPAD_RIGHT, + VK_GAMEPAD_DPAD_UP, VK_GAMEPAD_LEFT_SHOULDER, VK_GAMEPAD_LEFT_THUMBSTICK_BUTTON, + VK_GAMEPAD_LEFT_THUMBSTICK_DOWN, VK_GAMEPAD_LEFT_THUMBSTICK_LEFT, + VK_GAMEPAD_LEFT_THUMBSTICK_RIGHT, VK_GAMEPAD_LEFT_THUMBSTICK_UP, VK_GAMEPAD_LEFT_TRIGGER, + VK_GAMEPAD_MENU, VK_GAMEPAD_RIGHT_SHOULDER, VK_GAMEPAD_RIGHT_THUMBSTICK_BUTTON, + VK_GAMEPAD_RIGHT_THUMBSTICK_DOWN, VK_GAMEPAD_RIGHT_THUMBSTICK_LEFT, + VK_GAMEPAD_RIGHT_THUMBSTICK_RIGHT, VK_GAMEPAD_RIGHT_THUMBSTICK_UP, VK_GAMEPAD_RIGHT_TRIGGER, + VK_GAMEPAD_VIEW, VK_GAMEPAD_X, VK_GAMEPAD_Y, VK_HANGUL, VK_HANJA, VK_HELP, VK_HOME, VK_ICO_00, + VK_ICO_CLEAR, VK_ICO_HELP, VK_INSERT, VK_JUNJA, VK_KANA, VK_KANJI, VK_LAUNCH_APP1, + VK_LAUNCH_APP2, VK_LAUNCH_MAIL, VK_LAUNCH_MEDIA_SELECT, VK_LBUTTON, VK_LCONTROL, VK_LEFT, + VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MBUTTON, VK_MEDIA_NEXT_TRACK, VK_MEDIA_PLAY_PAUSE, + VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MENU, VK_MODECHANGE, VK_MULTIPLY, VK_NAVIGATION_ACCEPT, + VK_NAVIGATION_CANCEL, VK_NAVIGATION_DOWN, VK_NAVIGATION_LEFT, VK_NAVIGATION_MENU, + VK_NAVIGATION_RIGHT, VK_NAVIGATION_UP, VK_NAVIGATION_VIEW, VK_NEXT, VK_NONAME, VK_NONCONVERT, + VK_NUMLOCK, VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, + VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_OEM_1, VK_OEM_102, VK_OEM_2, VK_OEM_3, VK_OEM_4, + VK_OEM_5, VK_OEM_6, VK_OEM_7, VK_OEM_8, VK_OEM_ATTN, VK_OEM_AUTO, VK_OEM_AX, VK_OEM_BACKTAB, + VK_OEM_CLEAR, VK_OEM_COMMA, VK_OEM_COPY, VK_OEM_CUSEL, VK_OEM_ENLW, VK_OEM_FINISH, + VK_OEM_FJ_LOYA, VK_OEM_FJ_MASSHOU, VK_OEM_FJ_ROYA, VK_OEM_FJ_TOUROKU, VK_OEM_JUMP, + VK_OEM_MINUS, VK_OEM_NEC_EQUAL, VK_OEM_PA1, VK_OEM_PA2, VK_OEM_PA3, VK_OEM_PERIOD, VK_OEM_PLUS, + VK_OEM_RESET, VK_OEM_WSCTRL, VK_PA1, VK_PACKET, VK_PAUSE, VK_PLAY, VK_PRINT, VK_PRIOR, + VK_PROCESSKEY, VK_RBUTTON, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT, VK_RWIN, + VK_SCROLL, VK_SELECT, VK_SEPARATOR, VK_SHIFT, VK_SLEEP, VK_SNAPSHOT, VK_SPACE, VK_SUBTRACT, + VK_TAB, VK_UP, VK_VOLUME_DOWN, VK_VOLUME_MUTE, VK_VOLUME_UP, VK_XBUTTON1, VK_XBUTTON2, VK_ZOOM, }; +use windows_sys::Win32::UI::TextServices::HKL; -use crate::{ - keyboard::{Key, KeyCode, ModifiersState, NamedKey, NativeKey, PhysicalKey}, - platform_impl::{loword, primarylangid, scancode_to_physicalkey}, -}; +use crate::keyboard::{Key, KeyCode, ModifiersState, NamedKey, NativeKey, PhysicalKey}; +use crate::platform_impl::{loword, primarylangid, scancode_to_physicalkey}; pub(crate) static LAYOUT_CACHE: Lazy> = Lazy::new(|| Mutex::new(LayoutCache::default())); @@ -279,7 +268,7 @@ impl LayoutCache { Entry::Vacant(entry) => { let layout = Self::prepare_layout(locale_id); (locale_id, entry.insert(layout)) - } + }, } } @@ -288,18 +277,9 @@ impl LayoutCache { let filter_out_altgr = layout.has_alt_graph && key_pressed(VK_RMENU); let mut mods = ModifiersState::empty(); mods.set(ModifiersState::SHIFT, key_pressed(VK_SHIFT)); - mods.set( - ModifiersState::CONTROL, - key_pressed(VK_CONTROL) && !filter_out_altgr, - ); - mods.set( - ModifiersState::ALT, - key_pressed(VK_MENU) && !filter_out_altgr, - ); - mods.set( - ModifiersState::SUPER, - key_pressed(VK_LWIN) || key_pressed(VK_RWIN), - ); + mods.set(ModifiersState::CONTROL, key_pressed(VK_CONTROL) && !filter_out_altgr); + mods.set(ModifiersState::ALT, key_pressed(VK_MENU) && !filter_out_altgr); + mods.set(ModifiersState::SUPER, key_pressed(VK_LWIN) || key_pressed(VK_RWIN)); mods } @@ -361,9 +341,7 @@ impl LayoutCache { let scancode = unsafe { MapVirtualKeyExW(vk, MAPVK_VK_TO_VSC_EX, locale_id as HKL) }; let unicode = Self::to_unicode_string(&key_state, vk, scancode, locale_id); if let ToUnicodeResult::Str(s) = unicode { - layout - .numlock_on_keys - .insert(vk as VIRTUAL_KEY, Key::Character(SmolStr::new(s))); + layout.numlock_on_keys.insert(vk as VIRTUAL_KEY, Key::Character(SmolStr::new(s))); } } @@ -403,16 +381,17 @@ impl LayoutCache { _ => { keys_for_this_mod.insert(key_code, preliminary_key); continue; - } + }, } let unicode = Self::to_unicode_string(&key_state, vk, scancode, locale_id); let key = match unicode { ToUnicodeResult::Str(str) => Key::Character(SmolStr::new(str)), ToUnicodeResult::Dead(dead_char) => { - //println!("{:?} - {:?} produced dead {:?}", key_code, mod_state, dead_char); + // println!("{:?} - {:?} produced dead {:?}", key_code, mod_state, + // dead_char); Key::Dead(dead_char) - } + }, ToUnicodeResult::None => { let has_alt = mod_state.contains(WindowsModifiers::ALT); let has_ctrl = mod_state.contains(WindowsModifiers::CONTROL); @@ -424,7 +403,7 @@ impl LayoutCache { // Just use the unidentified key, we got earlier preliminary_key } - } + }, }; // Check for alt graph. @@ -750,10 +729,11 @@ fn keycode_to_vkey(keycode: KeyCode, hkl: u64) -> VIRTUAL_KEY { /// a `Key`, with only the information passed in as arguments, are converted. /// /// In other words: this function does not need to "prepare" the current layout in order to do -/// the conversion, but as such it cannot convert certain keys, like language-specific character keys. +/// the conversion, but as such it cannot convert certain keys, like language-specific character +/// keys. /// -/// The result includes all non-character keys defined within `Key` plus characters from numpad keys. -/// For example, backspace and tab are included. +/// The result includes all non-character keys defined within `Key` plus characters from numpad +/// keys. For example, backspace and tab are included. fn vkey_to_non_char_key( vkey: VIRTUAL_KEY, native_code: NativeKey, @@ -787,7 +767,7 @@ fn vkey_to_non_char_key( VK_PAUSE => Key::Named(NamedKey::Pause), VK_CAPITAL => Key::Named(NamedKey::CapsLock), - //VK_HANGEUL => Key::Named(NamedKey::HangulMode), // Deprecated in favour of VK_HANGUL + // VK_HANGEUL => Key::Named(NamedKey::HangulMode), // Deprecated in favour of VK_HANGUL // VK_HANGUL and VK_KANA are defined as the same constant, therefore // we use appropriate conditions to differentiate between them @@ -881,7 +861,7 @@ fn vkey_to_non_char_key( VK_NUMLOCK => Key::Named(NamedKey::NumLock), VK_SCROLL => Key::Named(NamedKey::ScrollLock), VK_OEM_NEC_EQUAL => Key::Unidentified(native_code), - //VK_OEM_FJ_JISHO => Key::Unidentified(native_code), // Conflicts with `VK_OEM_NEC_EQUAL` + // VK_OEM_FJ_JISHO => Key::Unidentified(native_code), // Conflicts with `VK_OEM_NEC_EQUAL` VK_OEM_FJ_MASSHOU => Key::Unidentified(native_code), VK_OEM_FJ_TOUROKU => Key::Unidentified(native_code), VK_OEM_FJ_LOYA => Key::Unidentified(native_code), @@ -897,7 +877,7 @@ fn vkey_to_non_char_key( } else { Key::Named(NamedKey::Alt) } - } + }, VK_BROWSER_BACK => Key::Named(NamedKey::BrowserBack), VK_BROWSER_FORWARD => Key::Named(NamedKey::BrowserForward), VK_BROWSER_REFRESH => Key::Named(NamedKey::BrowserRefresh), @@ -987,7 +967,7 @@ fn vkey_to_non_char_key( // Also see: https://github.com/pyfisch/keyboard-types/issues/9 Key::Unidentified(native_code) } - } + }, VK_OEM_COPY => Key::Named(NamedKey::Copy), VK_OEM_AUTO => Key::Named(NamedKey::Hankaku), VK_OEM_ENLW => Key::Named(NamedKey::Zenkaku), diff --git a/src/platform_impl/windows/mod.rs b/src/platform_impl/windows/mod.rs index 8b5ad9d7bf..bfb18d81cc 100644 --- a/src/platform_impl/windows/mod.rs +++ b/src/platform_impl/windows/mod.rs @@ -1,21 +1,17 @@ #![cfg(windows_platform)] use smol_str::SmolStr; -use windows_sys::Win32::{ - Foundation::{HANDLE, HWND}, - UI::WindowsAndMessaging::{HMENU, WINDOW_LONG_PTR_INDEX}, -}; +use windows_sys::Win32::Foundation::{HANDLE, HWND}; +use windows_sys::Win32::UI::WindowsAndMessaging::{HMENU, WINDOW_LONG_PTR_INDEX}; -pub(crate) use self::{ - event_loop::{ - ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, - PlatformSpecificEventLoopAttributes, - }, - icon::{SelectedCursor, WinIcon}, - keyboard::{physicalkey_to_scancode, scancode_to_physicalkey}, - monitor::{MonitorHandle, VideoModeHandle}, - window::Window, +pub(crate) use self::event_loop::{ + ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, + PlatformSpecificEventLoopAttributes, }; +pub(crate) use self::icon::{SelectedCursor, WinIcon}; +pub(crate) use self::keyboard::{physicalkey_to_scancode, scancode_to_physicalkey}; +pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle}; +pub(crate) use self::window::Window; pub(crate) use self::icon::WinCursor as PlatformCustomCursor; pub use self::icon::WinIcon as PlatformIcon; @@ -149,17 +145,17 @@ const fn get_y_lparam(x: u32) -> i16 { #[inline(always)] pub(crate) const fn primarylangid(lgid: u16) -> u16 { - lgid & 0x3FF + lgid & 0x3ff } #[inline(always)] pub(crate) const fn loword(x: u32) -> u16 { - (x & 0xFFFF) as u16 + (x & 0xffff) as u16 } #[inline(always)] const fn hiword(x: u32) -> u16 { - ((x >> 16) & 0xFFFF) as u16 + ((x >> 16) & 0xffff) as u16 } #[inline(always)] diff --git a/src/platform_impl/windows/monitor.rs b/src/platform_impl/windows/monitor.rs index b92cf77f4d..9a880db461 100644 --- a/src/platform_impl/windows/monitor.rs +++ b/src/platform_impl/windows/monitor.rs @@ -1,29 +1,21 @@ -use std::{ - collections::{BTreeSet, VecDeque}, - hash::Hash, - io, mem, ptr, -}; - -use windows_sys::Win32::{ - Foundation::{BOOL, HWND, LPARAM, POINT, RECT}, - Graphics::Gdi::{ - EnumDisplayMonitors, EnumDisplaySettingsExW, GetMonitorInfoW, MonitorFromPoint, - MonitorFromWindow, DEVMODEW, DM_BITSPERPEL, DM_DISPLAYFREQUENCY, DM_PELSHEIGHT, - DM_PELSWIDTH, ENUM_CURRENT_SETTINGS, HDC, HMONITOR, MONITORINFO, MONITORINFOEXW, - MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTOPRIMARY, - }, +use std::collections::{BTreeSet, VecDeque}; +use std::hash::Hash; +use std::{io, mem, ptr}; + +use windows_sys::Win32::Foundation::{BOOL, HWND, LPARAM, POINT, RECT}; +use windows_sys::Win32::Graphics::Gdi::{ + EnumDisplayMonitors, EnumDisplaySettingsExW, GetMonitorInfoW, MonitorFromPoint, + MonitorFromWindow, DEVMODEW, DM_BITSPERPEL, DM_DISPLAYFREQUENCY, DM_PELSHEIGHT, DM_PELSWIDTH, + ENUM_CURRENT_SETTINGS, HDC, HMONITOR, MONITORINFO, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST, + MONITOR_DEFAULTTOPRIMARY, }; use super::util::decode_wide; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize}, - monitor::VideoModeHandle as RootVideoModeHandle, - platform_impl::platform::{ - dpi::{dpi_to_scale_factor, get_monitor_dpi}, - util::has_flag, - window::Window, - }, -}; +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::monitor::VideoModeHandle as RootVideoModeHandle; +use crate::platform_impl::platform::dpi::{dpi_to_scale_factor, get_monitor_dpi}; +use crate::platform_impl::platform::util::has_flag; +use crate::platform_impl::platform::window::Window; #[derive(Clone)] pub struct VideoModeHandle { @@ -144,10 +136,7 @@ pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result() as u32; let status = unsafe { - GetMonitorInfoW( - hmonitor, - &mut monitor_info as *mut MONITORINFOEXW as *mut MONITORINFO, - ) + GetMonitorInfoW(hmonitor, &mut monitor_info as *mut MONITORINFOEXW as *mut MONITORINFO) }; if status == false.into() { Err(io::Error::last_os_error()) @@ -164,11 +153,7 @@ impl MonitorHandle { #[inline] pub fn name(&self) -> Option { let monitor_info = get_monitor_info(self.0).unwrap(); - Some( - decode_wide(&monitor_info.szDevice) - .to_string_lossy() - .to_string(), - ) + Some(decode_wide(&monitor_info.szDevice).to_string_lossy().to_string()) } #[inline] @@ -212,10 +197,7 @@ impl MonitorHandle { get_monitor_info(self.0) .map(|info| { let rc_monitor = info.monitorInfo.rcMonitor; - PhysicalPosition { - x: rc_monitor.left, - y: rc_monitor.top, - } + PhysicalPosition { x: rc_monitor.left, y: rc_monitor.top } }) .unwrap_or(PhysicalPosition { x: 0, y: 0 }) } @@ -238,7 +220,7 @@ impl MonitorHandle { Err(error) => { tracing::warn!("Error from get_monitor_info: {error}"); return modes.into_iter().map(mod_map); - } + }, }; let device_name = monitor_info.szDevice.as_ptr(); diff --git a/src/platform_impl/windows/raw_input.rs b/src/platform_impl/windows/raw_input.rs index a53a9b67f6..44c7c95a73 100644 --- a/src/platform_impl/windows/raw_input.rs +++ b/src/platform_impl/windows/raw_input.rs @@ -1,39 +1,31 @@ -use std::{ - mem::{self, size_of}, - ptr, -}; +use std::mem::{self, size_of}; +use std::ptr; -use windows_sys::Win32::{ - Devices::HumanInterfaceDevice::{ - HID_USAGE_GENERIC_KEYBOARD, HID_USAGE_GENERIC_MOUSE, HID_USAGE_PAGE_GENERIC, - }, - Foundation::{HANDLE, HWND}, - UI::{ - Input::{ - GetRawInputData, GetRawInputDeviceInfoW, GetRawInputDeviceList, - KeyboardAndMouse::{MapVirtualKeyW, MAPVK_VK_TO_VSC_EX, VK_NUMLOCK, VK_SHIFT}, - RegisterRawInputDevices, HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTDEVICELIST, - RAWINPUTHEADER, RAWKEYBOARD, RIDEV_DEVNOTIFY, RIDEV_INPUTSINK, RIDEV_REMOVE, - RIDI_DEVICEINFO, RIDI_DEVICENAME, RID_DEVICE_INFO, RID_DEVICE_INFO_HID, - RID_DEVICE_INFO_KEYBOARD, RID_DEVICE_INFO_MOUSE, RID_INPUT, RIM_TYPEHID, - RIM_TYPEKEYBOARD, RIM_TYPEMOUSE, - }, - WindowsAndMessaging::{ - RI_KEY_E0, RI_KEY_E1, RI_MOUSE_BUTTON_1_DOWN, RI_MOUSE_BUTTON_1_UP, - RI_MOUSE_BUTTON_2_DOWN, RI_MOUSE_BUTTON_2_UP, RI_MOUSE_BUTTON_3_DOWN, - RI_MOUSE_BUTTON_3_UP, RI_MOUSE_BUTTON_4_DOWN, RI_MOUSE_BUTTON_4_UP, - RI_MOUSE_BUTTON_5_DOWN, RI_MOUSE_BUTTON_5_UP, - }, - }, +use windows_sys::Win32::Devices::HumanInterfaceDevice::{ + HID_USAGE_GENERIC_KEYBOARD, HID_USAGE_GENERIC_MOUSE, HID_USAGE_PAGE_GENERIC, +}; +use windows_sys::Win32::Foundation::{HANDLE, HWND}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + MapVirtualKeyW, MAPVK_VK_TO_VSC_EX, VK_NUMLOCK, VK_SHIFT, +}; +use windows_sys::Win32::UI::Input::{ + GetRawInputData, GetRawInputDeviceInfoW, GetRawInputDeviceList, RegisterRawInputDevices, + HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTDEVICELIST, RAWINPUTHEADER, RAWKEYBOARD, + RIDEV_DEVNOTIFY, RIDEV_INPUTSINK, RIDEV_REMOVE, RIDI_DEVICEINFO, RIDI_DEVICENAME, + RID_DEVICE_INFO, RID_DEVICE_INFO_HID, RID_DEVICE_INFO_KEYBOARD, RID_DEVICE_INFO_MOUSE, + RID_INPUT, RIM_TYPEHID, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + RI_KEY_E0, RI_KEY_E1, RI_MOUSE_BUTTON_1_DOWN, RI_MOUSE_BUTTON_1_UP, RI_MOUSE_BUTTON_2_DOWN, + RI_MOUSE_BUTTON_2_UP, RI_MOUSE_BUTTON_3_DOWN, RI_MOUSE_BUTTON_3_UP, RI_MOUSE_BUTTON_4_DOWN, + RI_MOUSE_BUTTON_4_UP, RI_MOUSE_BUTTON_5_DOWN, RI_MOUSE_BUTTON_5_UP, }; use super::scancode_to_physicalkey; -use crate::{ - event::ElementState, - event_loop::DeviceEvents, - keyboard::{KeyCode, PhysicalKey}, - platform_impl::platform::util, -}; +use crate::event::ElementState; +use crate::event_loop::DeviceEvents; +use crate::keyboard::{KeyCode, PhysicalKey}; +use crate::platform_impl::platform::util; #[allow(dead_code)] pub fn get_raw_input_device_list() -> Option> { @@ -91,12 +83,7 @@ pub fn get_raw_input_device_info(handle: HANDLE) -> Option { let mut minimum_size = 0; let status = unsafe { - GetRawInputDeviceInfoW( - handle, - RIDI_DEVICEINFO, - &mut info as *mut _ as _, - &mut minimum_size, - ) + GetRawInputDeviceInfoW(handle, RIDI_DEVICEINFO, &mut info as *mut _ as _, &mut minimum_size) }; if status == u32::MAX || status == 0 { @@ -121,12 +108,7 @@ pub fn get_raw_input_device_name(handle: HANDLE) -> Option { let mut name: Vec = Vec::with_capacity(minimum_size as _); let status = unsafe { - GetRawInputDeviceInfoW( - handle, - RIDI_DEVICENAME, - name.as_ptr() as _, - &mut minimum_size, - ) + GetRawInputDeviceInfoW(handle, RIDI_DEVICENAME, name.as_ptr() as _, &mut minimum_size) }; if status == u32::MAX || status == 0 { @@ -159,7 +141,7 @@ pub fn register_all_mice_and_keyboards_for_raw_input( DeviceEvents::Never => { window_handle = 0; RIDEV_REMOVE - } + }, DeviceEvents::WhenFocused => RIDEV_DEVNOTIFY, DeviceEvents::Always => RIDEV_DEVNOTIFY | RIDEV_INPUTSINK, }; @@ -188,13 +170,7 @@ pub fn get_raw_input_data(handle: HRAWINPUT) -> Option { let header_size = size_of::() as u32; let status = unsafe { - GetRawInputData( - handle, - RID_INPUT, - &mut data as *mut _ as _, - &mut data_size, - header_size, - ) + GetRawInputData(handle, RID_INPUT, &mut data as *mut _ as _, &mut data_size, header_size) }; if status == u32::MAX || status == 0 { @@ -232,9 +208,9 @@ pub fn get_raw_mouse_button_state(button_flags: u32) -> [Option; 5 pub fn get_keyboard_physical_key(keyboard: RAWKEYBOARD) -> Option { let extension = { if util::has_flag(keyboard.Flags, RI_KEY_E0 as _) { - 0xE000 + 0xe000 } else if util::has_flag(keyboard.Flags, RI_KEY_E1 as _) { - 0xE100 + 0xe100 } else { 0x0000 } @@ -246,7 +222,7 @@ pub fn get_keyboard_physical_key(keyboard: RAWKEYBOARD) -> Option { } else { keyboard.MakeCode | extension }; - if scancode == 0xE11D || scancode == 0xE02A { + if scancode == 0xe11d || scancode == 0xe02a { // At the hardware (or driver?) level, pressing the Pause key is equivalent to pressing // Ctrl+NumLock. // This equvalence means that if the user presses Pause, the keyboard will emit two @@ -307,16 +283,17 @@ pub fn get_keyboard_physical_key(keyboard: RAWKEYBOARD) -> Option { // as well. // // The issue is that in the raw device event (here), the fake shift release - // event reports the numpad key as the scancode. Unfortunately, the event doesn't - // have any information to tell whether it's the left shift or the right shift - // that needs to get the fake release (or press) event so we don't forward this + // event reports the numpad key as the scancode. Unfortunately, the event + // doesn't have any information to tell whether it's the + // left shift or the right shift that needs to get the fake + // release (or press) event so we don't forward this // event to the application at all. // // For more on this, read the article by Raymond Chen, titled: // "The shift key overrides NumLock" // https://devblogs.microsoft.com/oldnewthing/20040906-00/?p=37953 return None; - } + }, _ => (), } } diff --git a/src/platform_impl/windows/util.rs b/src/platform_impl/windows/util.rs index 165242c11c..87bcbd4256 100644 --- a/src/platform_impl/windows/util.rs +++ b/src/platform_impl/windows/util.rs @@ -1,39 +1,27 @@ -use std::{ - ffi::{c_void, OsStr, OsString}, - io, - iter::once, - mem, - ops::BitAnd, - os::windows::prelude::{OsStrExt, OsStringExt}, - ptr, - sync::atomic::{AtomicBool, Ordering}, -}; +use std::ffi::{c_void, OsStr, OsString}; +use std::iter::once; +use std::ops::BitAnd; +use std::os::windows::prelude::{OsStrExt, OsStringExt}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::{io, mem, ptr}; use crate::utils::Lazy; -use windows_sys::{ - core::{HRESULT, PCWSTR}, - Win32::{ - Foundation::{BOOL, HANDLE, HMODULE, HWND, RECT}, - Graphics::Gdi::{ClientToScreen, HMONITOR}, - System::{ - LibraryLoader::{GetProcAddress, LoadLibraryA}, - SystemServices::IMAGE_DOS_HEADER, - }, - UI::{ - HiDpi::{DPI_AWARENESS_CONTEXT, MONITOR_DPI_TYPE, PROCESS_DPI_AWARENESS}, - Input::{ - KeyboardAndMouse::GetActiveWindow, - Pointer::{POINTER_INFO, POINTER_PEN_INFO, POINTER_TOUCH_INFO}, - }, - WindowsAndMessaging::{ - ClipCursor, GetClientRect, GetClipCursor, GetSystemMetrics, GetWindowPlacement, - GetWindowRect, IsIconic, ShowCursor, IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, - IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, - IDC_SIZENWSE, IDC_SIZEWE, IDC_WAIT, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, - SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_MAXIMIZE, WINDOWPLACEMENT, - }, - }, - }, +use windows_sys::core::{HRESULT, PCWSTR}; +use windows_sys::Win32::Foundation::{BOOL, HANDLE, HMODULE, HWND, RECT}; +use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, HMONITOR}; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; +use windows_sys::Win32::System::SystemServices::IMAGE_DOS_HEADER; +use windows_sys::Win32::UI::HiDpi::{ + DPI_AWARENESS_CONTEXT, MONITOR_DPI_TYPE, PROCESS_DPI_AWARENESS, +}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow; +use windows_sys::Win32::UI::Input::Pointer::{POINTER_INFO, POINTER_PEN_INFO, POINTER_TOUCH_INFO}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + ClipCursor, GetClientRect, GetClipCursor, GetSystemMetrics, GetWindowPlacement, GetWindowRect, + IsIconic, ShowCursor, IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, + IDC_NO, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_WAIT, + SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_MAXIMIZE, + WINDOWPLACEMENT, }; use crate::window::CursorIcon; @@ -77,7 +65,7 @@ impl WindowArea { match self { WindowArea::Outer => { win_to_err(unsafe { GetWindowRect(hwnd, &mut rect) })?; - } + }, WindowArea::Inner => unsafe { let mut top_left = mem::zeroed(); @@ -123,10 +111,7 @@ pub fn get_cursor_clip() -> Result { /// Note that calling this will automatically dispatch a `WM_MOUSEMOVE` event. pub fn set_cursor_clip(rect: Option) -> Result<(), io::Error> { unsafe { - let rect_ptr = rect - .as_ref() - .map(|r| r as *const RECT) - .unwrap_or(ptr::null()); + let rect_ptr = rect.as_ref().map(|r| r as *const RECT).unwrap_or(ptr::null()); win_to_err(ClipCursor(rect_ptr)) } } @@ -176,7 +161,7 @@ pub(crate) fn to_windows_cursor(cursor: CursorIcon) -> PCWSTR { CursorIcon::NotAllowed | CursorIcon::NoDrop => IDC_NO, CursorIcon::Grab | CursorIcon::Grabbing | CursorIcon::Move | CursorIcon::AllScroll => { IDC_SIZEALL - } + }, CursorIcon::EResize | CursorIcon::WResize | CursorIcon::EwResize diff --git a/src/platform_impl/windows/window.rs b/src/platform_impl/windows/window.rs index f0cbdf84b6..01589bef71 100644 --- a/src/platform_impl/windows/window.rs +++ b/src/platform_impl/windows/window.rs @@ -1,92 +1,76 @@ #![cfg(windows_platform)] -use std::{ - cell::Cell, - ffi::c_void, - io, - mem::{self, MaybeUninit}, - panic, ptr, - sync::{mpsc::channel, Arc, Mutex, MutexGuard}, +use std::cell::Cell; +use std::ffi::c_void; +use std::mem::{self, MaybeUninit}; +use std::sync::mpsc::channel; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::{io, panic, ptr}; + +use windows_sys::Win32::Foundation::{ + HWND, LPARAM, OLE_E_WRONGCOMPOBJ, POINT, POINTS, RECT, RPC_E_CHANGED_MODE, S_OK, WPARAM, }; - -use windows_sys::Win32::{ - Foundation::{ - HWND, LPARAM, OLE_E_WRONGCOMPOBJ, POINT, POINTS, RECT, RPC_E_CHANGED_MODE, S_OK, WPARAM, - }, - Graphics::{ - Dwm::{ - DwmEnableBlurBehindWindow, DwmSetWindowAttribute, DWMWA_BORDER_COLOR, - DWMWA_CAPTION_COLOR, DWMWA_SYSTEMBACKDROP_TYPE, DWMWA_TEXT_COLOR, - DWMWA_WINDOW_CORNER_PREFERENCE, DWM_BB_BLURREGION, DWM_BB_ENABLE, DWM_BLURBEHIND, - DWM_SYSTEMBACKDROP_TYPE, DWM_WINDOW_CORNER_PREFERENCE, - }, - Gdi::{ - ChangeDisplaySettingsExW, ClientToScreen, CreateRectRgn, DeleteObject, InvalidateRgn, - RedrawWindow, CDS_FULLSCREEN, DISP_CHANGE_BADFLAGS, DISP_CHANGE_BADMODE, - DISP_CHANGE_BADPARAM, DISP_CHANGE_FAILED, DISP_CHANGE_SUCCESSFUL, RDW_INTERNALPAINT, - }, - }, - System::{ - Com::{ - CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED, - }, - Ole::{OleInitialize, RegisterDragDrop}, - }, - UI::{ - Input::{ - KeyboardAndMouse::{ - EnableWindow, GetActiveWindow, MapVirtualKeyW, ReleaseCapture, SendInput, - ToUnicode, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_EXTENDEDKEY, - KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC, VIRTUAL_KEY, VK_LMENU, VK_MENU, VK_SPACE, - }, - Touch::{RegisterTouchWindow, TWF_WANTPALM}, - }, - WindowsAndMessaging::{ - CreateWindowExW, EnableMenuItem, FlashWindowEx, GetClientRect, GetCursorPos, - GetForegroundWindow, GetSystemMenu, GetSystemMetrics, GetWindowPlacement, - GetWindowTextLengthW, GetWindowTextW, IsWindowVisible, LoadCursorW, PeekMessageW, - PostMessageW, RegisterClassExW, SetCursor, SetCursorPos, SetForegroundWindow, - SetMenuDefaultItem, SetWindowDisplayAffinity, SetWindowPlacement, SetWindowPos, - SetWindowTextW, TrackPopupMenu, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, FLASHWINFO, - FLASHW_ALL, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, GWLP_HINSTANCE, HTBOTTOM, - HTBOTTOMLEFT, HTBOTTOMRIGHT, HTCAPTION, HTLEFT, HTRIGHT, HTTOP, HTTOPLEFT, HTTOPRIGHT, - MENU_ITEM_STATE, MFS_DISABLED, MFS_ENABLED, MF_BYCOMMAND, NID_READY, PM_NOREMOVE, - SC_CLOSE, SC_MAXIMIZE, SC_MINIMIZE, SC_MOVE, SC_RESTORE, SC_SIZE, SM_DIGITIZER, - SWP_ASYNCWINDOWPOS, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, TPM_LEFTALIGN, - TPM_RETURNCMD, WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_NCLBUTTONDOWN, WM_SYSCOMMAND, - WNDCLASSEXW, - }, - }, +use windows_sys::Win32::Graphics::Dwm::{ + DwmEnableBlurBehindWindow, DwmSetWindowAttribute, DWMWA_BORDER_COLOR, DWMWA_CAPTION_COLOR, + DWMWA_SYSTEMBACKDROP_TYPE, DWMWA_TEXT_COLOR, DWMWA_WINDOW_CORNER_PREFERENCE, DWM_BB_BLURREGION, + DWM_BB_ENABLE, DWM_BLURBEHIND, DWM_SYSTEMBACKDROP_TYPE, DWM_WINDOW_CORNER_PREFERENCE, +}; +use windows_sys::Win32::Graphics::Gdi::{ + ChangeDisplaySettingsExW, ClientToScreen, CreateRectRgn, DeleteObject, InvalidateRgn, + RedrawWindow, CDS_FULLSCREEN, DISP_CHANGE_BADFLAGS, DISP_CHANGE_BADMODE, DISP_CHANGE_BADPARAM, + DISP_CHANGE_FAILED, DISP_CHANGE_SUCCESSFUL, RDW_INTERNALPAINT, +}; +use windows_sys::Win32::System::Com::{ + CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED, +}; +use windows_sys::Win32::System::Ole::{OleInitialize, RegisterDragDrop}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + EnableWindow, GetActiveWindow, MapVirtualKeyW, ReleaseCapture, SendInput, ToUnicode, INPUT, + INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_EXTENDEDKEY, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC, + VIRTUAL_KEY, VK_LMENU, VK_MENU, VK_SPACE, +}; +use windows_sys::Win32::UI::Input::Touch::{RegisterTouchWindow, TWF_WANTPALM}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, EnableMenuItem, FlashWindowEx, GetClientRect, GetCursorPos, + GetForegroundWindow, GetSystemMenu, GetSystemMetrics, GetWindowPlacement, GetWindowTextLengthW, + GetWindowTextW, IsWindowVisible, LoadCursorW, PeekMessageW, PostMessageW, RegisterClassExW, + SetCursor, SetCursorPos, SetForegroundWindow, SetMenuDefaultItem, SetWindowDisplayAffinity, + SetWindowPlacement, SetWindowPos, SetWindowTextW, TrackPopupMenu, CS_HREDRAW, CS_VREDRAW, + CW_USEDEFAULT, FLASHWINFO, FLASHW_ALL, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, + GWLP_HINSTANCE, HTBOTTOM, HTBOTTOMLEFT, HTBOTTOMRIGHT, HTCAPTION, HTLEFT, HTRIGHT, HTTOP, + HTTOPLEFT, HTTOPRIGHT, MENU_ITEM_STATE, MFS_DISABLED, MFS_ENABLED, MF_BYCOMMAND, NID_READY, + PM_NOREMOVE, SC_CLOSE, SC_MAXIMIZE, SC_MINIMIZE, SC_MOVE, SC_RESTORE, SC_SIZE, SM_DIGITIZER, + SWP_ASYNCWINDOWPOS, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, TPM_LEFTALIGN, TPM_RETURNCMD, + WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_NCLBUTTONDOWN, WM_SYSCOMMAND, WNDCLASSEXW, }; use tracing::warn; -use crate::{ - cursor::Cursor, - dpi::{PhysicalPosition, PhysicalSize, Position, Size}, - error::{ExternalError, NotSupportedError, OsError as RootOsError}, - icon::Icon, - platform::windows::{BackdropType, Color, CornerPreference}, - platform_impl::platform::{ - dark_mode::try_theme, - definitions::{ - CLSID_TaskbarList, IID_ITaskbarList, IID_ITaskbarList2, ITaskbarList, ITaskbarList2, - }, - dpi::{dpi_to_scale_factor, enable_non_client_dpi_scaling, hwnd_dpi}, - drop_handler::FileDropHandler, - event_loop::{self, ActiveEventLoop, DESTROY_MSG_ID}, - icon::{self, IconType, WinCursor}, - ime::ImeContext, - keyboard::KeyEventBuilder, - monitor::{self, MonitorHandle}, - util, - window_state::{CursorFlags, SavedWindow, WindowFlags, WindowState}, - Fullscreen, SelectedCursor, WindowId, - }, - window::{ - CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, - WindowButtons, WindowLevel, - }, +use crate::cursor::Cursor; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::icon::Icon; +use crate::platform::windows::{BackdropType, Color, CornerPreference}; +use crate::platform_impl::platform::dark_mode::try_theme; +use crate::platform_impl::platform::definitions::{ + CLSID_TaskbarList, IID_ITaskbarList, IID_ITaskbarList2, ITaskbarList, ITaskbarList2, +}; +use crate::platform_impl::platform::dpi::{ + dpi_to_scale_factor, enable_non_client_dpi_scaling, hwnd_dpi, +}; +use crate::platform_impl::platform::drop_handler::FileDropHandler; +use crate::platform_impl::platform::event_loop::{self, ActiveEventLoop, DESTROY_MSG_ID}; +use crate::platform_impl::platform::icon::{self, IconType, WinCursor}; +use crate::platform_impl::platform::ime::ImeContext; +use crate::platform_impl::platform::keyboard::KeyEventBuilder; +use crate::platform_impl::platform::monitor::{self, MonitorHandle}; +use crate::platform_impl::platform::window_state::{ + CursorFlags, SavedWindow, WindowFlags, WindowState, +}; +use crate::platform_impl::platform::{util, Fullscreen, SelectedCursor, WindowId}; +use crate::window::{ + CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, + WindowButtons, WindowLevel, }; /// The Win32 implementation of the main `Window` object. @@ -178,16 +162,23 @@ impl Window { #[inline] pub fn outer_position(&self) -> Result, NotSupportedError> { - util::WindowArea::Outer.get_rect(self.hwnd()) + util::WindowArea::Outer + .get_rect(self.hwnd()) .map(|rect| Ok(PhysicalPosition::new(rect.left, rect.top))) - .expect("Unexpected GetWindowRect failure; please report this error to rust-windowing/winit") + .expect( + "Unexpected GetWindowRect failure; please report this error to \ + rust-windowing/winit", + ) } #[inline] pub fn inner_position(&self) -> Result, NotSupportedError> { let mut position: POINT = unsafe { mem::zeroed() }; if unsafe { ClientToScreen(self.hwnd(), &mut position) } == false.into() { - panic!("Unexpected ClientToScreen failure: please report this error to rust-windowing/winit") + panic!( + "Unexpected ClientToScreen failure: please report this error to \ + rust-windowing/winit" + ) } Ok(PhysicalPosition::new(position.x, position.y)) } @@ -223,12 +214,12 @@ impl Window { pub fn inner_size(&self) -> PhysicalSize { let mut rect: RECT = unsafe { mem::zeroed() }; if unsafe { GetClientRect(self.hwnd(), &mut rect) } == false.into() { - panic!("Unexpected GetClientRect failure: please report this error to rust-windowing/winit") + panic!( + "Unexpected GetClientRect failure: please report this error to \ + rust-windowing/winit" + ) } - PhysicalSize::new( - (rect.right - rect.left) as u32, - (rect.bottom - rect.top) as u32, - ) + PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32) } #[inline] @@ -236,10 +227,7 @@ impl Window { util::WindowArea::Outer .get_rect(self.hwnd()) .map(|rect| { - PhysicalSize::new( - (rect.right - rect.left) as u32, - (rect.bottom - rect.top) as u32, - ) + PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32) }) .unwrap() } @@ -286,8 +274,7 @@ impl Window { pub fn resize_increments(&self) -> Option> { let w = self.window_state_lock(); let scale_factor = w.scale_factor; - w.resize_increments - .map(|size| size.to_physical(scale_factor)) + w.resize_increments.map(|size| size.to_physical(scale_factor)) } #[inline] @@ -322,18 +309,9 @@ impl Window { self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { - f.set( - WindowFlags::MINIMIZABLE, - buttons.contains(WindowButtons::MINIMIZE), - ); - f.set( - WindowFlags::MAXIMIZABLE, - buttons.contains(WindowButtons::MAXIMIZE), - ); - f.set( - WindowFlags::CLOSABLE, - buttons.contains(WindowButtons::CLOSE), - ) + f.set(WindowFlags::MINIMIZABLE, buttons.contains(WindowButtons::MINIMIZE)); + f.set(WindowFlags::MAXIMIZABLE, buttons.contains(WindowButtons::MAXIMIZE)); + f.set(WindowFlags::CLOSABLE, buttons.contains(WindowButtons::CLOSE)) }); }); } @@ -352,6 +330,7 @@ impl Window { } buttons } + /// Returns the `hwnd` of this window. #[inline] pub fn hwnd(&self) -> HWND { @@ -401,9 +380,7 @@ impl Window { pub fn raw_display_handle_rwh_06( &self, ) -> Result { - Ok(rwh_06::RawDisplayHandle::Windows( - rwh_06::WindowsDisplayHandle::new(), - )) + Ok(rwh_06::RawDisplayHandle::Windows(rwh_06::WindowsDisplayHandle::new())) } #[inline] @@ -415,21 +392,21 @@ impl Window { let cursor = LoadCursorW(0, util::to_windows_cursor(icon)); SetCursor(cursor); }); - } + }, Cursor::Custom(cursor) => { let new_cursor = match cursor.inner { WinCursor::Cursor(cursor) => cursor, WinCursor::Failed => { warn!("Requested to apply failed cursor"); return; - } + }, }; self.window_state_lock().mouse.selected_cursor = SelectedCursor::Custom(new_cursor.clone()); self.thread_executor.execute_in_thread(move || unsafe { SetCursor(new_cursor.as_raw_handle()); }); - } + }, } } @@ -440,7 +417,7 @@ impl Window { CursorGrabMode::Confined => true, CursorGrabMode::Locked => { return Err(ExternalError::NotSupported(NotSupportedError::new())) - } + }, }; let window = self.window; @@ -520,21 +497,13 @@ impl Window { unsafe { GetCursorPos(&mut pos) }; pos }; - let points = POINTS { - x: points.x as i16, - y: points.y as i16, - }; + let points = POINTS { x: points.x as i16, y: points.y as i16 }; // ReleaseCapture needs to execute on the main thread unsafe { ReleaseCapture() }; unsafe { - PostMessageW( - window, - WM_NCLBUTTONDOWN, - wparam, - &points as *const _ as LPARAM, - ) + PostMessageW(window, WM_NCLBUTTONDOWN, wparam, &points as *const _ as LPARAM) }; }); } @@ -575,7 +544,10 @@ impl Window { point.x = x; point.y = y; if ClientToScreen(self.hwnd(), &mut point) == false.into() { - warn!("Can't convert client-area coordinates to screen coordinates when showing window menu."); + warn!( + "Can't convert client-area coordinates to screen coordinates when showing \ + window menu." + ); return; } point @@ -585,7 +557,8 @@ impl Window { let h_menu = GetSystemMenu(self.hwnd(), 0); if h_menu == 0 { warn!("The corresponding window doesn't have a system menu"); - // This situation should not be treated as an error so just return without showing menu. + // This situation should not be treated as an error so just return without showing + // menu. return; } @@ -616,7 +589,8 @@ impl Window { // Popup the system menu at the position. let result = TrackPopupMenu( h_menu, - TPM_RETURNCMD | TPM_LEFTALIGN, // for now im using LTR, but we have to use user layout direction + TPM_RETURNCMD | TPM_LEFTALIGN, /* for now im using LTR, but we have to use user + * layout direction */ point.x, point.y, 0, @@ -720,13 +694,14 @@ impl Window { match (&old_fullscreen, &fullscreen) { // Return if we already are in the same fullscreen mode _ if old_fullscreen == fullscreen => return, - // Return if saved Borderless(monitor) is the same as current monitor when requested fullscreen is Borderless(None) + // Return if saved Borderless(monitor) is the same as current monitor when requested + // fullscreen is Borderless(None) (Some(Fullscreen::Borderless(Some(monitor))), Some(Fullscreen::Borderless(None))) if *monitor == monitor::current_monitor(window) => { return - } - _ => {} + }, + _ => {}, } window_state_lock.fullscreen.clone_from(&fullscreen); @@ -756,7 +731,7 @@ impl Window { debug_assert!(res != DISP_CHANGE_BADPARAM); debug_assert!(res != DISP_CHANGE_FAILED); assert_eq!(res, DISP_CHANGE_SUCCESSFUL); - } + }, (Some(Fullscreen::Exclusive(_)), _) => { let res = unsafe { ChangeDisplaySettingsExW( @@ -773,7 +748,7 @@ impl Window { debug_assert!(res != DISP_CHANGE_BADPARAM); debug_assert!(res != DISP_CHANGE_FAILED); assert_eq!(res, DISP_CHANGE_SUCCESSFUL); - } + }, _ => (), } @@ -805,7 +780,8 @@ impl Window { // Mark as fullscreen window wrt to z-order // // this needs to be called before the below fullscreen SetWindowPos as this itself - // will generate WM_SIZE messages of the old window size that can race with what we set below + // will generate WM_SIZE messages of the old window size that can race with what we set + // below unsafe { taskbar_mark_fullscreen(window, fullscreen.is_some()); } @@ -843,7 +819,7 @@ impl Window { ); InvalidateRgn(window, 0, false.into()); } - } + }, None => { let mut window_state_lock = window_state.lock().unwrap(); if let Some(SavedWindow { placement }) = window_state_lock.saved_window.take() { @@ -853,7 +829,7 @@ impl Window { InvalidateRgn(window, 0, false.into()); } } - } + }, } }); } @@ -874,9 +850,7 @@ impl Window { #[inline] pub fn is_decorated(&self) -> bool { let window_state = self.window_state_lock(); - window_state - .window_flags - .contains(WindowFlags::MARKER_DECORATIONS) + window_state.window_flags.contains(WindowFlags::MARKER_DECORATIONS) } #[inline] @@ -887,14 +861,8 @@ impl Window { self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { - f.set( - WindowFlags::ALWAYS_ON_TOP, - level == WindowLevel::AlwaysOnTop, - ); - f.set( - WindowFlags::ALWAYS_ON_BOTTOM, - level == WindowLevel::AlwaysOnBottom, - ); + f.set(WindowFlags::ALWAYS_ON_TOP, level == WindowLevel::AlwaysOnTop); + f.set(WindowFlags::ALWAYS_ON_BOTTOM, level == WindowLevel::AlwaysOnBottom); }); }); } @@ -907,9 +875,7 @@ impl Window { #[inline] pub fn set_window_icon(&self, window_icon: Option) { if let Some(ref window_icon) = window_icon { - window_icon - .inner - .set_for_window(self.hwnd(), IconType::Small); + window_icon.inner.set_for_window(self.hwnd(), IconType::Small); } else { icon::unset_for_window(self.hwnd(), IconType::Small); } @@ -924,9 +890,7 @@ impl Window { #[inline] pub fn set_taskbar_icon(&self, taskbar_icon: Option) { if let Some(ref taskbar_icon) = taskbar_icon { - taskbar_icon - .inner - .set_for_window(self.hwnd(), IconType::Big); + taskbar_icon.inner.set_for_window(self.hwnd(), IconType::Big); } else { icon::unset_for_window(self.hwnd(), IconType::Big); } @@ -1055,11 +1019,7 @@ impl Window { unsafe { SetWindowDisplayAffinity( self.hwnd(), - if protected { - WDA_EXCLUDEFROMCAPTURE - } else { - WDA_NONE - }, + if protected { WDA_EXCLUDEFROMCAPTURE } else { WDA_NONE }, ) }; } @@ -1189,11 +1149,7 @@ impl<'a> InitData<'a> { unsafe { ImeContext::set_ime_allowed(window, false) }; - Window { - window, - window_state, - thread_executor: self.event_loop.create_thread_executor(), - } + Window { window, window_state, thread_executor: self.event_loop.create_thread_executor() } } unsafe fn create_window_data(&self, win: &Window) -> event_loop::WindowData { @@ -1205,9 +1161,9 @@ impl<'a> InitData<'a> { panic!("OleInitialize failed! Result was: `OLE_E_WRONGCOMPOBJ`"); } else if ole_init_result == RPC_E_CHANGED_MODE { panic!( - "OleInitialize failed! Result was: `RPC_E_CHANGED_MODE`. \ - Make sure other crates are not using multithreaded COM library \ - on the same thread or disable drag and drop support." + "OleInitialize failed! Result was: `RPC_E_CHANGED_MODE`. Make sure other \ + crates are not using multithreaded COM library on the same thread or disable \ + drag and drop support." ); } @@ -1224,10 +1180,7 @@ impl<'a> InitData<'a> { let handler_interface_ptr = unsafe { &mut (*file_drop_handler.data).interface as *mut _ as *mut c_void }; - assert_eq!( - unsafe { RegisterDragDrop(win.window, handler_interface_ptr) }, - S_OK - ); + assert_eq!(unsafe { RegisterDragDrop(win.window, handler_interface_ptr) }, S_OK); Some(file_drop_handler) } else { None @@ -1244,7 +1197,8 @@ impl<'a> InitData<'a> { } // Returns a pointer to window user data on success. - // The user data will be registered for the window and can be accessed within the window event callback. + // The user data will be registered for the window and can be accessed within the window event + // callback. pub unsafe fn on_nccreate(&mut self, window: HWND) -> Option { let runner = self.event_loop.runner_shared.clone(); let result = runner.catch_unwind(|| { @@ -1276,10 +1230,7 @@ impl<'a> InitData<'a> { }; let hr = unsafe { DwmEnableBlurBehindWindow(win.hwnd(), &bb) }; if hr < 0 { - warn!( - "Setting transparent window is failed. HRESULT Code: 0x{:X}", - hr - ); + warn!("Setting transparent window is failed. HRESULT Code: 0x{:X}", hr); } unsafe { DeleteObject(region) }; } @@ -1302,15 +1253,11 @@ impl<'a> InitData<'a> { win.set_enabled_buttons(attributes.enabled_buttons); - let size = attributes - .inner_size - .unwrap_or_else(|| PhysicalSize::new(800, 600).into()); + let size = attributes.inner_size.unwrap_or_else(|| PhysicalSize::new(800, 600).into()); let max_size = attributes .max_inner_size .unwrap_or_else(|| PhysicalSize::new(f64::MAX, f64::MAX).into()); - let min_size = attributes - .min_inner_size - .unwrap_or_else(|| PhysicalSize::new(0, 0).into()); + let min_size = attributes.min_inner_size.unwrap_or_else(|| PhysicalSize::new(0, 0).into()); let clamped_size = Size::clamp(size, min_size, max_size, win.scale_factor()); win.request_inner_size(clamped_size); @@ -1357,18 +1304,12 @@ unsafe fn init( WindowFlags::MARKER_UNDECORATED_SHADOW, attributes.platform_specific.decoration_shadow, ); - window_flags.set( - WindowFlags::ALWAYS_ON_TOP, - attributes.window_level == WindowLevel::AlwaysOnTop, - ); - window_flags.set( - WindowFlags::ALWAYS_ON_BOTTOM, - attributes.window_level == WindowLevel::AlwaysOnBottom, - ); - window_flags.set( - WindowFlags::NO_BACK_BUFFER, - attributes.platform_specific.no_redirection_bitmap, - ); + window_flags + .set(WindowFlags::ALWAYS_ON_TOP, attributes.window_level == WindowLevel::AlwaysOnTop); + window_flags + .set(WindowFlags::ALWAYS_ON_BOTTOM, attributes.window_level == WindowLevel::AlwaysOnBottom); + window_flags + .set(WindowFlags::NO_BACK_BUFFER, attributes.platform_specific.no_redirection_bitmap); window_flags.set(WindowFlags::MARKER_ACTIVATE, attributes.active); window_flags.set(WindowFlags::TRANSPARENT, attributes.transparent); // WindowFlags::VISIBLE and MAXIMIZED are set down below after the window has been configured. @@ -1376,20 +1317,17 @@ unsafe fn init( // Will be changed later using `window.set_enabled_buttons` but we need to set a default here // so the diffing later can work. window_flags.set(WindowFlags::CLOSABLE, true); - window_flags.set( - WindowFlags::CLIP_CHILDREN, - attributes.platform_specific.clip_children, - ); + window_flags.set(WindowFlags::CLIP_CHILDREN, attributes.platform_specific.clip_children); let mut fallback_parent = || match attributes.platform_specific.owner { Some(parent) => { window_flags.set(WindowFlags::POPUP, true); Some(parent) - } + }, None => { window_flags.set(WindowFlags::ON_TASKBAR, true); None - } + }, }; #[cfg(feature = "rwh_06")] @@ -1400,7 +1338,7 @@ unsafe fn init( warn!("Setting a menu on a child window is unsupported"); } Some(handle.hwnd.get() as HWND) - } + }, Some(raw) => unreachable!("Invalid raw window handle {raw:?} on Windows"), None => fallback_parent(), }; @@ -1411,12 +1349,7 @@ unsafe fn init( let menu = attributes.platform_specific.menu; let fullscreen = attributes.fullscreen.clone(); let maximized = attributes.maximized; - let mut initdata = InitData { - event_loop, - attributes, - window_flags, - window: None, - }; + let mut initdata = InitData { event_loop, attributes, window_flags, window: None }; let (style, ex_style) = window_flags.to_window_styles(); let handle = unsafe { @@ -1450,7 +1383,8 @@ unsafe fn init( let win = initdata.window.unwrap(); // Need to set FULLSCREEN or MAXIMIZED after CreateWindowEx - // This is because if the size is changed in WM_CREATE, the restored size will be stored in that size. + // This is because if the size is changed in WM_CREATE, the restored size will be stored in that + // size. if fullscreen.is_some() { win.set_fullscreen(fullscreen.map(Into::into)); unsafe { force_window_active(win.window) }; @@ -1624,13 +1558,7 @@ unsafe fn force_window_active(handle: HWND) { ]; // Simulate a key press and release - unsafe { - SendInput( - inputs.len() as u32, - inputs.as_ptr(), - mem::size_of::() as i32, - ) - }; + unsafe { SendInput(inputs.len() as u32, inputs.as_ptr(), mem::size_of::() as i32) }; unsafe { SetForegroundWindow(handle) }; } diff --git a/src/platform_impl/windows/window_state.rs b/src/platform_impl/windows/window_state.rs index ab0b484c63..911467b4c7 100644 --- a/src/platform_impl/windows/window_state.rs +++ b/src/platform_impl/windows/window_state.rs @@ -1,28 +1,23 @@ -use crate::{ - dpi::{PhysicalPosition, PhysicalSize, Size}, - icon::Icon, - keyboard::ModifiersState, - platform_impl::platform::{event_loop, util, Fullscreen, SelectedCursor}, - window::{Theme, WindowAttributes}, -}; +use crate::dpi::{PhysicalPosition, PhysicalSize, Size}; +use crate::icon::Icon; +use crate::keyboard::ModifiersState; +use crate::platform_impl::platform::{event_loop, util, Fullscreen, SelectedCursor}; +use crate::window::{Theme, WindowAttributes}; use bitflags::bitflags; use std::io; use std::sync::MutexGuard; -use windows_sys::Win32::{ - Foundation::{HWND, RECT}, - Graphics::Gdi::InvalidateRgn, - UI::WindowsAndMessaging::{ - AdjustWindowRectEx, EnableMenuItem, GetMenu, GetSystemMenu, GetWindowLongW, SendMessageW, - SetWindowLongW, SetWindowPos, ShowWindow, GWL_EXSTYLE, GWL_STYLE, HWND_BOTTOM, - HWND_NOTOPMOST, HWND_TOPMOST, MF_BYCOMMAND, MF_DISABLED, MF_ENABLED, SC_CLOSE, - SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOREPOSITION, - SWP_NOSIZE, SWP_NOZORDER, SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, - SW_SHOWNOACTIVATE, WINDOWPLACEMENT, WINDOW_EX_STYLE, WINDOW_STYLE, WS_BORDER, WS_CAPTION, - WS_CHILD, WS_CLIPCHILDREN, WS_CLIPSIBLINGS, WS_EX_ACCEPTFILES, WS_EX_APPWINDOW, - WS_EX_LAYERED, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOPMOST, WS_EX_TRANSPARENT, - WS_EX_WINDOWEDGE, WS_MAXIMIZE, WS_MAXIMIZEBOX, WS_MINIMIZE, WS_MINIMIZEBOX, - WS_OVERLAPPEDWINDOW, WS_POPUP, WS_SIZEBOX, WS_SYSMENU, WS_VISIBLE, - }, +use windows_sys::Win32::Foundation::{HWND, RECT}; +use windows_sys::Win32::Graphics::Gdi::InvalidateRgn; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + AdjustWindowRectEx, EnableMenuItem, GetMenu, GetSystemMenu, GetWindowLongW, SendMessageW, + SetWindowLongW, SetWindowPos, ShowWindow, GWL_EXSTYLE, GWL_STYLE, HWND_BOTTOM, HWND_NOTOPMOST, + HWND_TOPMOST, MF_BYCOMMAND, MF_DISABLED, MF_ENABLED, SC_CLOSE, SWP_ASYNCWINDOWPOS, + SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOREPOSITION, SWP_NOSIZE, SWP_NOZORDER, + SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, SW_SHOWNOACTIVATE, WINDOWPLACEMENT, + WINDOW_EX_STYLE, WINDOW_STYLE, WS_BORDER, WS_CAPTION, WS_CHILD, WS_CLIPCHILDREN, + WS_CLIPSIBLINGS, WS_EX_ACCEPTFILES, WS_EX_APPWINDOW, WS_EX_LAYERED, WS_EX_NOREDIRECTIONBITMAP, + WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_EX_WINDOWEDGE, WS_MAXIMIZE, WS_MAXIMIZEBOX, WS_MINIMIZE, + WS_MINIMIZEBOX, WS_OVERLAPPEDWINDOW, WS_POPUP, WS_SIZEBOX, WS_SYSMENU, WS_VISIBLE, }; /// Contains information about states and the window that the callback is going to use. @@ -242,7 +237,7 @@ impl MouseProperties { Err(e) => { self.cursor_flags = old_flags; return Err(e); - } + }, } Ok(()) @@ -365,26 +360,20 @@ impl WindowFlags { if diff.contains(WindowFlags::MAXIMIZED) || new.contains(WindowFlags::MAXIMIZED) { unsafe { - ShowWindow( - window, - match new.contains(WindowFlags::MAXIMIZED) { - true => SW_MAXIMIZE, - false => SW_RESTORE, - }, - ); + ShowWindow(window, match new.contains(WindowFlags::MAXIMIZED) { + true => SW_MAXIMIZE, + false => SW_RESTORE, + }); } } // Minimize operations should execute after maximize for proper window animations if diff.contains(WindowFlags::MINIMIZED) { unsafe { - ShowWindow( - window, - match new.contains(WindowFlags::MINIMIZED) { - true => SW_MINIMIZE, - false => SW_RESTORE, - }, - ); + ShowWindow(window, match new.contains(WindowFlags::MINIMIZED) { + true => SW_MINIMIZE, + false => SW_RESTORE, + }); } diff.remove(WindowFlags::MINIMIZED); @@ -392,11 +381,7 @@ impl WindowFlags { if diff.contains(WindowFlags::CLOSABLE) || new.contains(WindowFlags::CLOSABLE) { let flags = MF_BYCOMMAND - | if new.contains(WindowFlags::CLOSABLE) { - MF_ENABLED - } else { - MF_DISABLED - }; + | if new.contains(WindowFlags::CLOSABLE) { MF_ENABLED } else { MF_DISABLED }; unsafe { EnableMenuItem(GetSystemMenu(window, 0), SC_CLOSE, flags); @@ -413,12 +398,7 @@ impl WindowFlags { let (style, style_ex) = new.to_window_styles(); unsafe { - SendMessageW( - window, - event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), - 1, - 0, - ); + SendMessageW(window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 1, 0); // This condition is necessary to avoid having an unrestorable window if !new.contains(WindowFlags::MINIMIZED) { @@ -439,12 +419,7 @@ impl WindowFlags { // Refresh the window frame SetWindowPos(window, 0, 0, 0, 0, 0, flags); - SendMessageW( - window, - event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), - 0, - 0, - ); + SendMessageW(window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 0, 0); } } } @@ -454,17 +429,17 @@ impl WindowFlags { let mut style = GetWindowLongW(hwnd, GWL_STYLE) as u32; let style_ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32; - // Frameless style implemented by manually overriding the non-client area in `WM_NCCALCSIZE`. + // Frameless style implemented by manually overriding the non-client area in + // `WM_NCCALCSIZE`. if !self.contains(WindowFlags::MARKER_DECORATIONS) { style &= !(WS_CAPTION | WS_SIZEBOX); } util::win_to_err({ let b_menu = GetMenu(hwnd) != 0; - if let (Some(get_dpi_for_window), Some(adjust_window_rect_ex_for_dpi)) = ( - *util::GET_DPI_FOR_WINDOW, - *util::ADJUST_WINDOW_RECT_EX_FOR_DPI, - ) { + if let (Some(get_dpi_for_window), Some(adjust_window_rect_ex_for_dpi)) = + (*util::GET_DPI_FOR_WINDOW, *util::ADJUST_WINDOW_RECT_EX_FOR_DPI) + { let dpi = get_dpi_for_window(hwnd); adjust_window_rect_ex_for_dpi(&mut rect, style, b_menu.into(), style_ex, dpi) } else { @@ -477,12 +452,7 @@ impl WindowFlags { pub fn adjust_size(self, hwnd: HWND, size: PhysicalSize) -> PhysicalSize { let (width, height): (u32, u32) = size.into(); - let rect = RECT { - left: 0, - right: width as i32, - top: 0, - bottom: height as i32, - }; + let rect = RECT { left: 0, right: width as i32, top: 0, bottom: height as i32 }; let rect = self.adjust_rect(hwnd, rect).unwrap_or(rect); let outer_x = (rect.right - rect.left).abs(); @@ -516,20 +486,16 @@ impl CursorFlags { let cursor_clip = match self.contains(CursorFlags::GRABBED) { true => { if self.contains(CursorFlags::HIDDEN) { - // Confine the cursor to the center of the window if the cursor is hidden. This avoids - // problems with the cursor activating the taskbar if the window borders or overlaps that. + // Confine the cursor to the center of the window if the cursor is hidden. + // This avoids problems with the cursor activating + // the taskbar if the window borders or overlaps that. let cx = (client_rect.left + client_rect.right) / 2; let cy = (client_rect.top + client_rect.bottom) / 2; - Some(RECT { - left: cx, - right: cx + 1, - top: cy, - bottom: cy + 1, - }) + Some(RECT { left: cx, right: cx + 1, top: cy, bottom: cy + 1 }) } else { Some(client_rect) } - } + }, false => None, }; @@ -543,8 +509,9 @@ impl CursorFlags { }; // We do this check because calling `set_cursor_clip` incessantly will flood the event - // loop with `WM_MOUSEMOVE` events, and `refresh_os_cursor` is called by `set_cursor_flags` - // which at times gets called once every iteration of the eventloop. + // loop with `WM_MOUSEMOVE` events, and `refresh_os_cursor` is called by + // `set_cursor_flags` which at times gets called once every iteration of the + // eventloop. if active_cursor_clip != cursor_clip.map(rect_to_tuple) { util::set_cursor_clip(cursor_clip)?; } diff --git a/src/utils.rs b/src/utils.rs index 5bb52a4af2..16f5a4c549 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -14,15 +14,13 @@ pub(crate) struct Lazy { impl Lazy { pub const fn new(f: fn() -> T) -> Self { - Self { - cell: OnceLock::new(), - init: f, - } + Self { cell: OnceLock::new(), init: f } } } impl Deref for Lazy { type Target = T; + #[inline] fn deref(&self) -> &'_ T { self.cell.get_or_init(self.init) diff --git a/src/window.rs b/src/window.rs index cddef0469a..0a3ede02d2 100644 --- a/src/window.rs +++ b/src/window.rs @@ -1,12 +1,10 @@ //! The [`Window`] struct and associated types. use std::fmt; -use crate::{ - dpi::{PhysicalPosition, PhysicalSize, Position, Size}, - error::{ExternalError, NotSupportedError}, - monitor::{MonitorHandle, VideoModeHandle}, - platform_impl::{self, PlatformSpecificWindowAttributes}, -}; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError}; +use crate::monitor::{MonitorHandle, VideoModeHandle}; +use crate::platform_impl::{self, PlatformSpecificWindowAttributes}; pub use crate::cursor::{BadImage, Cursor, CustomCursor, CustomCursorSource, MAX_CURSOR_SIZE}; pub use crate::icon::{BadIcon, Icon}; @@ -239,19 +237,15 @@ impl WindowAttributes { /// /// ## Platform-specific /// - /// - **macOS:** The top left corner position of the window content, the - /// window's "inner" position. The window title bar will be placed above - /// it. The window will be positioned such that it fits on screen, - /// maintaining set `inner_size` if any. - /// If you need to precisely position the top left corner of the whole - /// window you have to use [`Window::set_outer_position`] after creating - /// the window. - /// - **Windows:** The top left corner position of the window title bar, - /// the window's "outer" position. - /// There may be a small gap between this position and the window due to - /// the specifics of the Window Manager. - /// - **X11:** The top left corner of the window, the window's "outer" - /// position. + /// - **macOS:** The top left corner position of the window content, the window's "inner" + /// position. The window title bar will be placed above it. The window will be positioned such + /// that it fits on screen, maintaining set `inner_size` if any. If you need to precisely + /// position the top left corner of the whole window you have to use + /// [`Window::set_outer_position`] after creating the window. + /// - **Windows:** The top left corner position of the window title bar, the window's "outer" + /// position. There may be a small gap between this position and the window due to the + /// specifics of the Window Manager. + /// - **X11:** The top left corner of the window, the window's "outer" position. /// - **Others:** Ignored. #[inline] pub fn with_position>(mut self, position: P) -> Self { @@ -523,26 +517,29 @@ impl Window { /// /// The scale factor is calculated differently on different platforms: /// - /// - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the - /// display settings. While users are free to select any option they want, they're only given a - /// selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale factor is - /// global and changing it requires logging out. See [this article][windows_1] for technical - /// details. + /// - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from + /// the display settings. While users are free to select any option they want, they're only + /// given a selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale + /// factor is global and changing it requires logging out. See [this article][windows_1] for + /// technical details. /// - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific /// displays. When available, the user may pick a per-monitor scaling factor from a set of /// pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default, /// but the specific value varies across devices. - /// - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. Winit - /// currently uses a three-pronged approach: + /// - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. + /// Winit currently uses a three-pronged approach: /// + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present. /// + If not present, use the value set in `Xft.dpi` in Xresources. - /// + Otherwise, calculate the scale factor based on the millimeter monitor dimensions provided by XRandR. + /// + Otherwise, calculate the scale factor based on the millimeter monitor dimensions + /// provided by XRandR. /// - /// If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use the - /// XRandR scaling method. Generally speaking, you should try to configure the standard system - /// variables to do what you want before resorting to `WINIT_X11_SCALE_FACTOR`. - /// - **Wayland:** The scale factor is suggested by the compositor for each window individually by - /// using the wp-fractional-scale protocol if available. Falls back to integer-scale factors otherwise. + /// If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use + /// the XRandR scaling method. Generally speaking, you should try to configure the + /// standard system variables to do what you want before resorting to + /// `WINIT_X11_SCALE_FACTOR`. + /// - **Wayland:** The scale factor is suggested by the compositor for each window individually + /// by using the wp-fractional-scale protocol if available. Falls back to integer-scale + /// factors otherwise. /// /// The monitor scale factor may differ from the window scale factor. /// - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range @@ -591,12 +588,13 @@ impl Window { /// /// ## Platform-specific /// - /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and `RedrawRequested` - /// is emitted in sync with any `WM_PAINT` messages. + /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and + /// `RedrawRequested` is emitted in sync with any `WM_PAINT` messages. /// - **iOS:** Can only be called on the main thread. - /// - **Wayland:** The events are aligned with the frame callbacks when [`Window::pre_present_notify`] - /// is used. - /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the `requestAnimationFrame`. + /// - **Wayland:** The events are aligned with the frame callbacks when + /// [`Window::pre_present_notify`] is used. + /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the + /// `requestAnimationFrame`. /// /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested #[inline] @@ -674,8 +672,8 @@ impl Window { /// /// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the /// window's [safe area] in the screen space coordinate system. - /// - **Web:** Returns the top-left coordinates relative to the viewport. _Note: this returns the - /// same value as [`Window::outer_position`]._ + /// - **Web:** Returns the top-left coordinates relative to the viewport. _Note: this returns + /// the same value as [`Window::outer_position`]._ /// - **Android / Wayland:** Always returns [`NotSupportedError`]. /// /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc @@ -744,8 +742,7 @@ impl Window { ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_outer_position(position)) + self.window.maybe_queue_on_main(move |w| w.set_outer_position(position)) } /// Returns the physical size of the window's client area. @@ -810,19 +807,18 @@ impl Window { size = ?size ) .entered(); - self.window - .maybe_wait_on_main(|w| w.request_inner_size(size)) + self.window.maybe_wait_on_main(|w| w.request_inner_size(size)) } /// Returns the physical size of the entire window. /// - /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), - /// use [`Window::inner_size`] instead. + /// These dimensions include the title bar and borders. If you don't want that (and you usually + /// don't), use [`Window::inner_size`] instead. /// /// ## Platform-specific /// - /// - **iOS:** Can only be called on the main thread. Returns the [`PhysicalSize`] of the window in - /// screen space coordinates. + /// - **iOS:** Can only be called on the main thread. Returns the [`PhysicalSize`] of the window + /// in screen space coordinates. /// - **Web:** Returns the size of the canvas element. _Note: this returns the same value as /// [`Window::inner_size`]._ #[inline] @@ -856,8 +852,7 @@ impl Window { min_size = ?min_size ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_min_inner_size(min_size)) + self.window.maybe_queue_on_main(move |w| w.set_min_inner_size(min_size)) } /// Sets a maximum dimension size for the window. @@ -885,8 +880,7 @@ impl Window { max_size = ?max_size ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_max_inner_size(max_size)) + self.window.maybe_queue_on_main(move |w| w.set_max_inner_size(max_size)) } /// Returns window resize increments if any were set. @@ -907,7 +901,8 @@ impl Window { /// /// ## Platform-specific /// - /// - **macOS:** Increments are converted to logical size and then macOS rounds them to whole numbers. + /// - **macOS:** Increments are converted to logical size and then macOS rounds them to whole + /// numbers. /// - **Wayland:** Not implemented. /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] @@ -918,8 +913,7 @@ impl Window { increments = ?increments ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_resize_increments(increments)) + self.window.maybe_queue_on_main(move |w| w.set_resize_increments(increments)) } } @@ -948,12 +942,12 @@ impl Window { /// ## Platform-specific /// /// - **Web / iOS / Android:** Unsupported. - /// - **X11:** Can only be set while building the window, with [`WindowAttributes::with_transparent`]. + /// - **X11:** Can only be set while building the window, with + /// [`WindowAttributes::with_transparent`]. #[inline] pub fn set_transparent(&self, transparent: bool) { let _span = tracing::debug_span!("winit::Window::set_transparent", transparent).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_transparent(transparent)) + self.window.maybe_queue_on_main(move |w| w.set_transparent(transparent)) } /// Change the window blur state. @@ -981,13 +975,13 @@ impl Window { #[inline] pub fn set_visible(&self, visible: bool) { let _span = tracing::debug_span!("winit::Window::set_visible", visible).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_visible(visible)) + self.window.maybe_queue_on_main(move |w| w.set_visible(visible)) } /// Gets the window's current visibility state. /// - /// `None` means it couldn't be determined, so it is not recommended to use this to drive your rendering backend. + /// `None` means it couldn't be determined, so it is not recommended to use this to drive your + /// rendering backend. /// /// ## Platform-specific /// @@ -1001,9 +995,10 @@ impl Window { /// Sets whether the window is resizable or not. /// - /// Note that making the window unresizable doesn't exempt you from handling [`WindowEvent::Resized`], as that - /// event can still be triggered by DPI scaling, entering fullscreen mode, etc. Also, the - /// window could still be resized by calling [`Window::request_inner_size`]. + /// Note that making the window unresizable doesn't exempt you from handling + /// [`WindowEvent::Resized`], as that event can still be triggered by DPI scaling, entering + /// fullscreen mode, etc. Also, the window could still be resized by calling + /// [`Window::request_inner_size`]. /// /// ## Platform-specific /// @@ -1016,8 +1011,7 @@ impl Window { #[inline] pub fn set_resizable(&self, resizable: bool) { let _span = tracing::debug_span!("winit::Window::set_resizable", resizable).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_resizable(resizable)) + self.window.maybe_queue_on_main(move |w| w.set_resizable(resizable)) } /// Gets the window's current resizable state. @@ -1044,8 +1038,7 @@ impl Window { buttons = ?buttons ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_enabled_buttons(buttons)) + self.window.maybe_queue_on_main(move |w| w.set_enabled_buttons(buttons)) } /// Gets the enabled window buttons. @@ -1068,8 +1061,7 @@ impl Window { #[inline] pub fn set_minimized(&self, minimized: bool) { let _span = tracing::debug_span!("winit::Window::set_minimized", minimized).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_minimized(minimized)) + self.window.maybe_queue_on_main(move |w| w.set_minimized(minimized)) } /// Gets the window's current minimized state. @@ -1098,8 +1090,7 @@ impl Window { #[inline] pub fn set_maximized(&self, maximized: bool) { let _span = tracing::debug_span!("winit::Window::set_maximized", maximized).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_maximized(maximized)) + self.window.maybe_queue_on_main(move |w| w.set_maximized(maximized)) } /// Gets the window's current maximized state. @@ -1117,11 +1108,10 @@ impl Window { /// /// ## Platform-specific /// - /// - **macOS:** [`Fullscreen::Exclusive`] provides true exclusive mode with a - /// video mode change. *Caveat!* macOS doesn't provide task switching (or - /// spaces!) while in exclusive fullscreen mode. This mode should be used - /// when a video mode change is desired, but for a better user experience, - /// borderless fullscreen might be preferred. + /// - **macOS:** [`Fullscreen::Exclusive`] provides true exclusive mode with a video mode + /// change. *Caveat!* macOS doesn't provide task switching (or spaces!) while in exclusive + /// fullscreen mode. This mode should be used when a video mode change is desired, but for a + /// better user experience, borderless fullscreen might be preferred. /// /// [`Fullscreen::Borderless`] provides a borderless fullscreen window on a /// separate space. This is the idiomatic way for fullscreen games to work @@ -1143,8 +1133,7 @@ impl Window { fullscreen = ?fullscreen ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_fullscreen(fullscreen.map(|f| f.into()))) + self.window.maybe_queue_on_main(move |w| w.set_fullscreen(fullscreen.map(|f| f.into()))) } /// Gets the window's current fullscreen state. @@ -1158,8 +1147,7 @@ impl Window { #[inline] pub fn fullscreen(&self) -> Option { let _span = tracing::debug_span!("winit::Window::fullscreen",).entered(); - self.window - .maybe_wait_on_main(|w| w.fullscreen().map(|f| f.into())) + self.window.maybe_wait_on_main(|w| w.fullscreen().map(|f| f.into())) } /// Turn window decorations on or off. @@ -1174,8 +1162,7 @@ impl Window { #[inline] pub fn set_decorations(&self, decorations: bool) { let _span = tracing::debug_span!("winit::Window::set_decorations", decorations).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_decorations(decorations)) + self.window.maybe_queue_on_main(move |w| w.set_decorations(decorations)) } /// Gets the window's current decorations state. @@ -1203,8 +1190,7 @@ impl Window { level = ?level ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_window_level(level)) + self.window.maybe_queue_on_main(move |w| w.set_window_level(level)) } /// Sets the window icon. @@ -1219,13 +1205,12 @@ impl Window { /// - **Windows:** Sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's /// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32. /// - /// - **X11:** Has no universal guidelines for icon sizes, so you're at the whims of the WM. That - /// said, it's usually in the same ballpark as on Windows. + /// - **X11:** Has no universal guidelines for icon sizes, so you're at the whims of the WM. + /// That said, it's usually in the same ballpark as on Windows. #[inline] pub fn set_window_icon(&self, window_icon: Option) { let _span = tracing::debug_span!("winit::Window::set_window_icon",).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_window_icon(window_icon)) + self.window.maybe_queue_on_main(move |w| w.set_window_icon(window_icon)) } /// Set the IME cursor editing area, where the `position` is the top left corner of that area @@ -1272,8 +1257,7 @@ impl Window { size = ?size, ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_ime_cursor_area(position, size)) + self.window.maybe_queue_on_main(move |w| w.set_ime_cursor_area(position, size)) } /// Sets whether the window should get IME events @@ -1290,7 +1274,8 @@ impl Window { /// /// ## Platform-specific /// - /// - **macOS:** IME must be enabled to receive text-input where dead-key sequences are combined. + /// - **macOS:** IME must be enabled to receive text-input where dead-key sequences are + /// combined. /// - **iOS / Android / Web / Orbital:** Unsupported. /// - **X11**: Enabling IME will disable dead keys reporting during compose. /// @@ -1299,8 +1284,7 @@ impl Window { #[inline] pub fn set_ime_allowed(&self, allowed: bool) { let _span = tracing::debug_span!("winit::Window::set_ime_allowed", allowed).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_ime_allowed(allowed)) + self.window.maybe_queue_on_main(move |w| w.set_ime_allowed(allowed)) } /// Sets the IME purpose for the window using [`ImePurpose`]. @@ -1315,8 +1299,7 @@ impl Window { purpose = ?purpose ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.set_ime_purpose(purpose)) + self.window.maybe_queue_on_main(move |w| w.set_ime_purpose(purpose)) } /// Brings the window to the front and sets input focus. Has no effect if the window is @@ -1366,8 +1349,7 @@ impl Window { request_type = ?request_type ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.request_user_attention(request_type)) + self.window.maybe_queue_on_main(move |w| w.request_user_attention(request_type)) } /// Sets the current window theme. Use `None` to fallback to system default. @@ -1375,9 +1357,10 @@ impl Window { /// ## Platform-specific /// /// - **macOS:** This is an app-wide setting. - /// - **Wayland:** Sets the theme for the client side decorations. Using `None` will use dbus - /// to get the system preference. - /// - **X11:** Sets `_GTK_THEME_VARIANT` hint to `dark` or `light` and if `None` is used, it will default to [`Theme::Dark`]. + /// - **Wayland:** Sets the theme for the client side decorations. Using `None` will use dbus to + /// get the system preference. + /// - **X11:** Sets `_GTK_THEME_VARIANT` hint to `dark` or `light` and if `None` is used, it + /// will default to [`Theme::Dark`]. /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] pub fn set_theme(&self, theme: Option) { @@ -1413,8 +1396,7 @@ impl Window { pub fn set_content_protected(&self, protected: bool) { let _span = tracing::debug_span!("winit::Window::set_content_protected", protected).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_content_protected(protected)) + self.window.maybe_queue_on_main(move |w| w.set_content_protected(protected)) } /// Gets the current title of the window. @@ -1436,14 +1418,13 @@ impl Window { /// ## Platform-specific /// /// - **iOS / Android / Orbital:** Unsupported. - /// - **Web:** Custom cursors have to be loaded and decoded first, until - /// then the previous cursor is shown. + /// - **Web:** Custom cursors have to be loaded and decoded first, until then the previous + /// cursor is shown. #[inline] pub fn set_cursor(&self, cursor: impl Into) { let cursor = cursor.into(); let _span = tracing::debug_span!("winit::Window::set_cursor",).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_cursor(cursor)) + self.window.maybe_queue_on_main(move |w| w.set_cursor(cursor)) } /// Deprecated! Use [`Window::set_cursor()`] instead. @@ -1479,8 +1460,7 @@ impl Window { position = ?position ) .entered(); - self.window - .maybe_wait_on_main(|w| w.set_cursor_position(position)) + self.window.maybe_wait_on_main(|w| w.set_cursor_position(position)) } /// Set grabbing [mode][CursorGrabMode] on the cursor preventing it from leaving the window. @@ -1492,9 +1472,10 @@ impl Window { /// ```no_run /// # use winit::window::{CursorGrabMode, Window}; /// # fn scope(window: &Window) { - /// window.set_cursor_grab(CursorGrabMode::Confined) - /// .or_else(|_e| window.set_cursor_grab(CursorGrabMode::Locked)) - /// .unwrap(); + /// window + /// .set_cursor_grab(CursorGrabMode::Confined) + /// .or_else(|_e| window.set_cursor_grab(CursorGrabMode::Locked)) + /// .unwrap(); /// # } /// ``` #[inline] @@ -1516,14 +1497,13 @@ impl Window { /// - **Windows:** The cursor is only hidden within the confines of the window. /// - **X11:** The cursor is only hidden within the confines of the window. /// - **Wayland:** The cursor is only hidden within the confines of the window. - /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is - /// outside of the window. + /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor + /// is outside of the window. /// - **iOS / Android:** Unsupported. #[inline] pub fn set_cursor_visible(&self, visible: bool) { let _span = tracing::debug_span!("winit::Window::set_cursor_visible", visible).entered(); - self.window - .maybe_queue_on_main(move |w| w.set_cursor_visible(visible)) + self.window.maybe_queue_on_main(move |w| w.set_cursor_visible(visible)) } /// Moves the window with the left mouse button until the button is released. @@ -1559,8 +1539,7 @@ impl Window { direction = ?direction ) .entered(); - self.window - .maybe_wait_on_main(|w| w.drag_resize_window(direction)) + self.window.maybe_wait_on_main(|w| w.drag_resize_window(direction)) } /// Show [window menu] at a specified position . @@ -1579,14 +1558,14 @@ impl Window { position = ?position ) .entered(); - self.window - .maybe_queue_on_main(move |w| w.show_window_menu(position)) + self.window.maybe_queue_on_main(move |w| w.show_window_menu(position)) } /// Modifies whether the window catches cursor events. /// /// If `true`, the window will catch the cursor events. If `false`, events are passed through - /// the window such that any other window behind it receives them. By default hittest is enabled. + /// the window such that any other window behind it receives them. By default hittest is + /// enabled. /// /// ## Platform-specific /// @@ -1594,8 +1573,7 @@ impl Window { #[inline] pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { let _span = tracing::debug_span!("winit::Window::set_cursor_hittest", hittest).entered(); - self.window - .maybe_wait_on_main(|w| w.set_cursor_hittest(hittest)) + self.window.maybe_wait_on_main(|w| w.set_cursor_hittest(hittest)) } } @@ -1607,22 +1585,20 @@ impl Window { #[inline] pub fn current_monitor(&self) -> Option { let _span = tracing::debug_span!("winit::Window::current_monitor",).entered(); - self.window - .maybe_wait_on_main(|w| w.current_monitor().map(|inner| MonitorHandle { inner })) + self.window.maybe_wait_on_main(|w| w.current_monitor().map(|inner| MonitorHandle { inner })) } /// Returns the list of all the monitors available on the system. /// - /// This is the same as [`ActiveEventLoop::available_monitors`], and is provided for convenience. + /// This is the same as [`ActiveEventLoop::available_monitors`], and is provided for + /// convenience. /// /// [`ActiveEventLoop::available_monitors`]: crate::event_loop::ActiveEventLoop::available_monitors #[inline] pub fn available_monitors(&self) -> impl Iterator { let _span = tracing::debug_span!("winit::Window::available_monitors",).entered(); self.window.maybe_wait_on_main(|w| { - w.available_monitors() - .into_iter() - .map(|inner| MonitorHandle { inner }) + w.available_monitors().into_iter().map(|inner| MonitorHandle { inner }) }) } @@ -1640,8 +1616,7 @@ impl Window { #[inline] pub fn primary_monitor(&self) -> Option { let _span = tracing::debug_span!("winit::Window::primary_monitor",).entered(); - self.window - .maybe_wait_on_main(|w| w.primary_monitor().map(|inner| MonitorHandle { inner })) + self.window.maybe_wait_on_main(|w| w.primary_monitor().map(|inner| MonitorHandle { inner })) } } @@ -1681,9 +1656,7 @@ unsafe impl Send for UnsafeSendWrapper {} #[cfg(feature = "rwh_05")] unsafe impl rwh_05::HasRawWindowHandle for Window { fn raw_window_handle(&self) -> rwh_05::RawWindowHandle { - self.window - .maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_window_handle_rwh_05())) - .0 + self.window.maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_window_handle_rwh_05())).0 } } @@ -1694,18 +1667,14 @@ unsafe impl rwh_05::HasRawDisplayHandle for Window { /// /// [`EventLoop`]: crate::event_loop::EventLoop fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle { - self.window - .maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_display_handle_rwh_05())) - .0 + self.window.maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_display_handle_rwh_05())).0 } } #[cfg(feature = "rwh_04")] unsafe impl rwh_04::HasRawWindowHandle for Window { fn raw_window_handle(&self) -> rwh_04::RawWindowHandle { - self.window - .maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_window_handle_rwh_04())) - .0 + self.window.maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_window_handle_rwh_04())).0 } } @@ -1736,7 +1705,8 @@ pub enum CursorGrabMode { /// /// ## Platform-specific /// - /// - **X11 / Windows:** Not implemented. Always returns [`ExternalError::NotSupported`] for now. + /// - **X11 / Windows:** Not implemented. Always returns [`ExternalError::NotSupported`] for + /// now. /// - **iOS / Android:** Always returns an [`ExternalError::NotSupported`]. Locked, } @@ -1792,7 +1762,8 @@ pub enum Theme { /// ## 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`]. /// /// [`Critical`]: Self::Critical /// [`Informational`]: Self::Informational @@ -1801,7 +1772,8 @@ pub enum UserAttentionType { /// ## Platform-specific /// /// - **macOS:** Bounces the dock icon until the application is in focus. - /// - **Windows:** Flashes both the window and the taskbar button until the application is in focus. + /// - **Windows:** Flashes both the window and the taskbar button until the application is in + /// focus. Critical, /// ## Platform-specific diff --git a/tests/serde_objects.rs b/tests/serde_objects.rs index 02b249b555..c427373f01 100644 --- a/tests/serde_objects.rs +++ b/tests/serde_objects.rs @@ -1,12 +1,10 @@ #![cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -use winit::{ - dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}, - event::{ElementState, MouseButton, MouseScrollDelta, TouchPhase}, - keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey, PhysicalKey}, - window::CursorIcon, -}; +use winit::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; +use winit::event::{ElementState, MouseButton, MouseScrollDelta, TouchPhase}; +use winit::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey, PhysicalKey}; +use winit::window::CursorIcon; #[allow(dead_code)] fn needs_serde>() {}