diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 28c1f75c..ecf78fcf 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 06dcdd06..942d40a5 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
{
#[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 f3ff496c..715996eb 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 76032db2..13cc9477 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 c7c64990..ad198cfa 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 33488c1f..5a277de1 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 5b5d9b46..31540c02 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 f5c8f374..bab7ced7 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 437d90ec..83a31e13 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 9e77694c..9db55e5c 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 a069b434..e10d6b00 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 024c0e03..1d318d21 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 cdd001a5..ee86b84a 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 b36eadd1..7bcac54d 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::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::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 fdeb3c50..d15bb9e7 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 e1975c65..bc7c18a5 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 48455e30..c0f64d9e 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 d01098d0..b013d2f0 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 94f6863a..49d55c1e 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.
///
/// 
///
@@ -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 78801217..cef9106e 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 5c522b10..ed987e25 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 1d0a9d93..5d13364b 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 2e8d4548..500cf3db 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 dafbd59b..74d400f3 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 da6c7aa8..4f59303e 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 651ba7f3..b1db7345 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 37a31ea6..7eedda28 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 886ff49d..ecb22395 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 c175e5b8..0d783135 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 24301ee0..68362192 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 1209b50c..25765ae8 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 9857e9e9..16ff8eab 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 1b0f661c..80262fe8 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 a1cbf4ce..207d549f 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 f10016d9..31285b63 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 ecc02553..99ddf1e3 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 4ab33685..15dd25f3 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 3064a086..40293d9f 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 a6f30e67..c90a21c5 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 d109401b..d85fe20e 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 7afe759f..9092471a 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 719b7c4d..abd9bc53 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 79a1eb95..8531a60d 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