From 40aea29fd2f982f8ebdadf1892ed4bdcaec7b2ee Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Wed, 28 May 2025 15:25:56 -0400 Subject: [PATCH 01/18] initial definition of Surface trait --- winit-core/src/lib.rs | 1 + winit-core/src/surface.rs | 251 ++++++++++++++++++++++++++++++++++++++ winit-core/src/window.rs | 18 +-- 3 files changed, 261 insertions(+), 9 deletions(-) create mode 100644 winit-core/src/surface.rs diff --git a/winit-core/src/lib.rs b/winit-core/src/lib.rs index 89bc682164..6a209fe292 100644 --- a/winit-core/src/lib.rs +++ b/winit-core/src/lib.rs @@ -18,6 +18,7 @@ pub mod event_loop; pub mod icon; pub mod keyboard; pub mod monitor; +pub mod surface; pub mod window; // `Instant` is not actually available on `wasm32-unknown-unknown`, the `std` implementation there diff --git a/winit-core/src/surface.rs b/winit-core/src/surface.rs new file mode 100644 index 0000000000..0c4458f4d8 --- /dev/null +++ b/winit-core/src/surface.rs @@ -0,0 +1,251 @@ +//! The [`Window`] trait and associated types. +use std::fmt; + +use cursor_icon::CursorIcon; +use dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size}; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +use crate::as_any::AsAny; +use crate::cursor::Cursor; +use crate::error::RequestError; +use crate::icon::Icon; +use crate::monitor::{Fullscreen, MonitorHandle}; + +/// Represents a surface that has a window handle. +/// +/// The surface is closed when dropped. +pub trait Surface: AsAny + Send + Sync + fmt::Debug { + /// Returns an identifier unique to the window. + fn id(&self) -> SurfaceId; + + /// Returns the scale factor that can be used to map logical pixels to physical pixels, and + /// vice versa. + /// + /// Note that this value can change depending on user action (for example if the window is + /// moved to another screen); as such, tracking [`WindowEvent::ScaleFactorChanged`] events is + /// the most robust way to track the DPI you need to use to draw. + /// + /// This value may differ from [`MonitorHandleProvider::scale_factor`]. + /// + /// See the [`dpi`] crate for more information. + /// + /// ## Platform-specific + /// + /// The scale factor is calculated differently on different platforms: + /// + /// - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from + /// the display settings. While users are free to select any option they want, they're only + /// given a selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale + /// factor is global and changing it requires logging out. See [this article][windows_1] for + /// technical details. + /// - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific + /// displays. When available, the user may pick a per-monitor scaling factor from a set of + /// pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default, + /// but the specific value varies across devices. + /// - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. + /// Winit currently uses a three-pronged approach: + /// + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present. + /// + If not present, use the value set in `Xft.dpi` in Xresources. + /// + Otherwise, calculate the scale factor based on the millimeter monitor dimensions + /// provided by XRandR. + /// + /// If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use + /// the XRandR scaling method. Generally speaking, you should try to configure the + /// standard system variables to do what you want before resorting to + /// `WINIT_X11_SCALE_FACTOR`. + /// - **Wayland:** The scale factor is suggested by the compositor for each window individually + /// by using the wp-fractional-scale protocol if available. Falls back to integer-scale + /// factors otherwise. + /// + /// The monitor scale factor may differ from the window scale factor. + /// - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range + /// from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more + /// information. + /// + /// This uses the underlying `UIView`'s [`contentScaleFactor`]. + /// - **Android:** Scale factors are set by the manufacturer to the value that best suits the + /// device, and range from `1.0` to `4.0`. See [this article][android_1] for more information. + /// + /// This is currently unimplemented, and this function always returns 1.0. + /// - **Web:** The scale factor is the ratio between CSS pixels and the physical device pixels. + /// In other words, it is the value of [`window.devicePixelRatio`][web_1]. It is affected by + /// both the screen scaling and the browser zoom level and can go below `1.0`. + /// - **Orbital:** This is currently unimplemented, and this function always returns 1.0. + /// + /// [`WindowEvent::ScaleFactorChanged`]: crate::event::WindowEvent::ScaleFactorChanged + /// [windows_1]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows + /// [apple_1]: https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html + /// [apple_2]: https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/ + /// [android_1]: https://developer.android.com/training/multiscreen/screendensities + /// [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + /// [`MonitorHandleProvider::scale_factor`]: crate::monitor::MonitorHandleProvider::scale_factor. + fn scale_factor(&self) -> f64; + + /// Queues a [`WindowEvent::RedrawRequested`] event to be emitted that aligns with the windowing + /// system drawing loop. + /// + /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with + /// OS-requested redraws (e.g. when a window gets resized). To improve the event delivery + /// consider using [`Window::pre_present_notify`] as described in docs. + /// + /// Applications should always aim to redraw whenever they receive a `RedrawRequested` event. + /// + /// There are no strong guarantees about when exactly a `RedrawRequest` event will be emitted + /// with respect to other events, since the requirements can vary significantly between + /// windowing systems. + /// + /// However as the event aligns with the windowing system drawing loop, it may not arrive in + /// same or even next event loop iteration. + /// + /// ## Platform-specific + /// + /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and + /// `RedrawRequested` is emitted in sync with any `WM_PAINT` messages. + /// - **Wayland:** The events are aligned with the frame callbacks when + /// [`Window::pre_present_notify`] is used. + /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the + /// `requestAnimationFrame`. + /// + /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested + fn request_redraw(&self); + + /// Notify the windowing system before presenting to the window. + /// + /// You should call this event after your drawing operations, but before you submit + /// the buffer to the display or commit your drawings. Doing so will help winit to properly + /// schedule and make assumptions about its internal state. For example, it could properly + /// throttle [`WindowEvent::RedrawRequested`]. + /// + /// ## Example + /// + /// This example illustrates how it looks with OpenGL, but it applies to other graphics + /// APIs and software rendering. + /// + /// ```no_run + /// # use winit_core::window::Window; + /// # fn swap_buffers() {} + /// # fn scope(window: &dyn Window) { + /// // Do the actual drawing with OpenGL. + /// + /// // Notify winit that we're about to submit buffer to the windowing system. + /// window.pre_present_notify(); + /// + /// // Submit buffer to the windowing system. + /// swap_buffers(); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Android / iOS / X11 / Web / Windows / macOS / Orbital:** Unsupported. + /// - **Wayland:** Schedules a frame callback to throttle [`WindowEvent::RedrawRequested`]. + /// + /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested + fn pre_present_notify(&self); + + /// Returns the size of the window's render-able surface. + /// + /// This is the dimensions you should pass to things like Wgpu or Glutin when configuring the + /// surface for drawing. See [`WindowEvent::SurfaceResized`] for listening to changes to this + /// field. + /// + /// Note that to ensure that your content is not obscured by things such as notches or the title + /// bar, you will likely want to only draw important content inside a specific area of the + /// surface, see [`safe_area()`] for details. + /// + /// ## Platform-specific + /// + /// - **Web:** Returns the size of the canvas element. Doesn't account for CSS [`transform`]. + /// + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized + /// [`safe_area()`]: Window::safe_area + fn surface_size(&self) -> PhysicalSize; + + /// Request the new size for the surface. + /// + /// On platforms where the size is entirely controlled by the user the + /// applied size will be returned immediately, resize event in such case + /// may not be generated. + /// + /// On platforms where resizing is disallowed by the windowing system, the current surface size + /// is returned immediately, and the user one is ignored. + /// + /// When `None` is returned, it means that the request went to the display system, + /// and the actual size will be delivered later with the [`WindowEvent::SurfaceResized`]. + /// + /// See [`Window::surface_size`] for more information about the values. + /// + /// The request could automatically un-maximize the window if it's maximized. + /// + /// ```no_run + /// # use dpi::{LogicalSize, PhysicalSize}; + /// # use winit_core::window::Window; + /// # fn scope(window: &dyn Window) { + /// // Specify the size in logical dimensions like this: + /// let _ = window.request_surface_size(LogicalSize::new(400.0, 200.0).into()); + /// + /// // Or specify the size in physical dimensions like this: + /// let _ = window.request_surface_size(PhysicalSize::new(400, 200).into()); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Web:** Sets the size of the canvas element. Doesn't account for CSS [`trkansform`]. + /// + /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + #[must_use] + fn request_surface_size(&self, size: Size) -> Option>; + + /// Change the window transparency state. + /// + /// This is just a hint that may not change anything about + /// the window transparency, however doing a mismatch between + /// the content of your window and this hint may result in + /// visual artifacts. + /// + /// The default value follows the [`WindowAttributes::with_transparent`]. + /// + /// ## Platform-specific + /// + /// - **macOS:** This will reset the window's background color. + /// - **Web / iOS / Android:** Unsupported. + /// - **X11:** Can only be set while building the window, with + /// [`WindowAttributes::with_transparent`]. + fn set_transparent(&self, transparent: bool); +} + +/// Identifier of a window. Unique for each window. +/// +/// Can be obtained with [`window.id()`][`Window::id`]. +/// +/// Whenever you receive an event specific to a window, this event contains a `WindowId` which you +/// can then compare to the ids of your windows. +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct SurfaceId(usize); + +impl SurfaceId { + /// Convert the `WindowId` into the underlying integer. + /// + /// This is useful if you need to pass the ID across an FFI boundary, or store it in an atomic. + pub const fn into_raw(self) -> usize { + self.0 + } + + /// Construct a `WindowId` from the underlying integer. + /// + /// This should only be called with integers returned from [`WindowId::into_raw`]. + pub const fn from_raw(id: usize) -> Self { + Self(id) + } +} + +impl fmt::Debug for SurfaceId { + fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(fmtr) + } +} \ No newline at end of file diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index bea235eeb0..197b8c6582 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -457,7 +457,7 @@ pub trait PlatformWindowAttributes: AsAny + std::fmt::Debug + Send + Sync { impl_dyn_casting!(PlatformWindowAttributes); -/// Represents a window. +/// Represents a toplevel window. /// /// The window is closed when dropped. /// @@ -477,7 +477,7 @@ impl_dyn_casting!(PlatformWindowAttributes); /// not be closed by dropping the [`Window`]. pub trait Window: AsAny + Send + Sync + fmt::Debug { /// Returns an identifier unique to the window. - fn id(&self) -> WindowId; + fn id(&self) -> WindowId; // * /// Returns the scale factor that can be used to map logical pixels to physical pixels, and /// vice versa. @@ -541,7 +541,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc /// [`MonitorHandleProvider::scale_factor`]: crate::monitor::MonitorHandleProvider::scale_factor. - fn scale_factor(&self) -> f64; + fn scale_factor(&self) -> f64; // * /// Queues a [`WindowEvent::RedrawRequested`] event to be emitted that aligns with the windowing /// system drawing loop. @@ -569,7 +569,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// `requestAnimationFrame`. /// /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested - fn request_redraw(&self); + fn request_redraw(&self); // * /// Notify the windowing system before presenting to the window. /// @@ -603,7 +603,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// - **Wayland:** Schedules a frame callback to throttle [`WindowEvent::RedrawRequested`]. /// /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested - fn pre_present_notify(&self); + fn pre_present_notify(&self); // * /// Reset the dead key state of the keyboard. /// @@ -636,7 +636,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// as the window itself, this simply returns `(0, 0)`. /// /// [`outer_position`]: Self::outer_position - fn surface_position(&self) -> PhysicalPosition; + fn surface_position(&self) -> PhysicalPosition; // * /// The position of the top-left hand corner of the window relative to the top-left hand corner /// of the desktop. @@ -699,7 +699,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized /// [`safe_area()`]: Window::safe_area - fn surface_size(&self) -> PhysicalSize; + fn surface_size(&self) -> PhysicalSize; // * /// Request the new size for the surface. /// @@ -736,7 +736,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform #[must_use] - fn request_surface_size(&self, size: Size) -> Option>; + fn request_surface_size(&self, size: Size) -> Option>; // * /// Returns the size of the entire window. /// @@ -872,7 +872,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// - **Web / iOS / Android:** Unsupported. /// - **X11:** Can only be set while building the window, with /// [`WindowAttributes::with_transparent`]. - fn set_transparent(&self, transparent: bool); + fn set_transparent(&self, transparent: bool); // * /// Change the window blur state. /// From dba4f4d0eceb1bdb24762d203c675207d4ac50a8 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Wed, 28 May 2025 18:12:51 -0400 Subject: [PATCH 02/18] move Surface into window module --- examples/application.rs | 12 +- examples/child_window.rs | 8 +- examples/control_flow.rs | 4 +- examples/dnd.rs | 4 +- examples/pump_events.rs | 4 +- examples/run_on_demand.rs | 6 +- examples/util/fill.rs | 4 +- examples/window.rs | 4 +- examples/x11_embed.rs | 4 +- winit-core/src/application/macos.rs | 4 +- winit-core/src/application/mod.rs | 8 +- winit-core/src/surface.rs | 251 --------------- winit-core/src/window.rs | 354 +++++++++++++++++++++- winit-orbital/src/event_loop.rs | 14 +- winit-orbital/src/window.rs | 10 +- winit-wayland/src/event_loop/mod.rs | 6 +- winit-wayland/src/event_loop/sink.rs | 4 +- winit-wayland/src/lib.rs | 6 +- winit-wayland/src/seat/keyboard/mod.rs | 4 +- winit-wayland/src/seat/pointer/mod.rs | 6 +- winit-wayland/src/state.rs | 12 +- winit-wayland/src/types/xdg_activation.rs | 4 +- winit-wayland/src/window/mod.rs | 6 +- winit-wayland/src/window/state.rs | 4 +- winit-web/src/event_loop/runner.rs | 18 +- winit-web/src/event_loop/window_target.rs | 8 +- winit-web/src/web_sys/canvas.rs | 8 +- winit-web/src/window.rs | 6 +- winit-x11/src/event_loop.rs | 14 +- winit-x11/src/event_processor.rs | 16 +- winit-x11/src/window.rs | 12 +- winit/tests/send_objects.rs | 2 +- 32 files changed, 457 insertions(+), 370 deletions(-) delete mode 100644 winit-core/src/surface.rs diff --git a/examples/application.rs b/examples/application.rs index 75d936e505..a6ce9beeb2 100644 --- a/examples/application.rs +++ b/examples/application.rs @@ -41,7 +41,7 @@ use winit::platform::web::{ActiveEventLoopExtWeb, WindowAttributesWeb}; use winit::platform::x11::{ActiveEventLoopExtX11, WindowAttributesX11}; use winit::window::{ CursorGrabMode, ImeCapabilities, ImeEnableRequest, ImePurpose, ImeRequestData, ResizeDirection, - Theme, Window, WindowAttributes, WindowId, + Theme, Window, WindowAttributes, SurfaceId, }; use winit_core::application::macos::ApplicationHandlerExtMacOS; use winit_core::window::ImeRequest; @@ -95,7 +95,7 @@ struct Application { custom_cursors: Result, RequestError>, /// Application icon. icon: Icon, - windows: HashMap, + windows: HashMap, /// Drawing context. /// /// With OpenGL it could be EGLDisplay. @@ -147,7 +147,7 @@ impl Application { &mut self, event_loop: &dyn ActiveEventLoop, _tab_id: Option, - ) -> Result> { + ) -> Result> { // TODO read-out activation token. #[allow(unused_mut)] @@ -213,7 +213,7 @@ impl Application { fn handle_action_with_window( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, action: Action, ) { // let cursor_position = self.cursor_position; @@ -415,7 +415,7 @@ impl ApplicationHandler for Application { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, event: WindowEvent, ) { let window = match self.windows.get_mut(&window_id) { @@ -601,7 +601,7 @@ impl ApplicationHandlerExtMacOS for Application { fn standard_key_binding( &mut self, _event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, action: &str, ) { info!(?window_id, ?action, "macOS standard key binding"); diff --git a/examples/child_window.rs b/examples/child_window.rs index e87207828b..29807e5a59 100644 --- a/examples/child_window.rs +++ b/examples/child_window.rs @@ -8,7 +8,7 @@ fn main() -> Result<(), impl std::error::Error> { use winit::event::{ElementState, KeyEvent, WindowEvent}; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::raw_window_handle::HasRawWindowHandle; - use winit::window::{Window, WindowAttributes, WindowId}; + use winit::window::{Window, WindowAttributes, SurfaceId}; #[path = "util/fill.rs"] mod fill; @@ -27,8 +27,8 @@ fn main() -> Result<(), impl std::error::Error> { #[derive(Default, Debug)] struct Application { - parent_window_id: Option, - windows: HashMap, + parent_window_id: Option, + windows: HashMap, } impl ApplicationHandler for Application { @@ -47,7 +47,7 @@ fn main() -> Result<(), impl std::error::Error> { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: winit::window::WindowId, + window_id: winit::window::SurfaceId, event: WindowEvent, ) { match event { diff --git a/examples/control_flow.rs b/examples/control_flow.rs index 8fb09bb3f0..bd9f875658 100644 --- a/examples/control_flow.rs +++ b/examples/control_flow.rs @@ -11,7 +11,7 @@ use winit::application::ApplicationHandler; use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent}; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; use winit::keyboard::{Key, NamedKey}; -use winit::window::{Window, WindowAttributes, WindowId}; +use winit::window::{Window, WindowAttributes, SurfaceId}; #[path = "util/fill.rs"] mod fill; @@ -75,7 +75,7 @@ impl ApplicationHandler for ControlFlowDemo { fn window_event( &mut self, _event_loop: &dyn ActiveEventLoop, - _window_id: WindowId, + _window_id: SurfaceId, event: WindowEvent, ) { info!("{event:?}"); diff --git a/examples/dnd.rs b/examples/dnd.rs index 8b21743bb1..e05399a2f7 100644 --- a/examples/dnd.rs +++ b/examples/dnd.rs @@ -3,7 +3,7 @@ use std::error::Error; use winit::application::ApplicationHandler; use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; -use winit::window::{Window, WindowAttributes, WindowId}; +use winit::window::{Window, WindowAttributes, SurfaceId}; #[path = "util/fill.rs"] mod fill; @@ -41,7 +41,7 @@ impl ApplicationHandler for Application { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - _window_id: WindowId, + _window_id: SurfaceId, event: WindowEvent, ) { match event { diff --git a/examples/pump_events.rs b/examples/pump_events.rs index 4de531ac80..3332c6f2c1 100644 --- a/examples/pump_events.rs +++ b/examples/pump_events.rs @@ -11,7 +11,7 @@ fn main() -> std::process::ExitCode { use winit::event::WindowEvent; use winit::event_loop::pump_events::{EventLoopExtPumpEvents, PumpStatus}; use winit::event_loop::{ActiveEventLoop, EventLoop}; - use winit::window::{Window, WindowAttributes, WindowId}; + use winit::window::{Window, WindowAttributes, SurfaceId}; #[path = "util/fill.rs"] mod fill; @@ -30,7 +30,7 @@ fn main() -> std::process::ExitCode { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - _window_id: WindowId, + _window_id: SurfaceId, event: WindowEvent, ) { println!("{event:?}"); diff --git a/examples/run_on_demand.rs b/examples/run_on_demand.rs index f076b43b87..570fd2d6be 100644 --- a/examples/run_on_demand.rs +++ b/examples/run_on_demand.rs @@ -9,7 +9,7 @@ fn main() -> Result<(), Box> { use winit::event::WindowEvent; use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand; use winit::event_loop::{ActiveEventLoop, EventLoop}; - use winit::window::{Window, WindowAttributes, WindowId}; + use winit::window::{Window, WindowAttributes, SurfaceId}; #[path = "util/fill.rs"] mod fill; @@ -17,7 +17,7 @@ fn main() -> Result<(), Box> { #[derive(Default, Debug)] struct App { idx: usize, - window_id: Option, + window_id: Option, window: Option>, } @@ -40,7 +40,7 @@ fn main() -> Result<(), Box> { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, event: WindowEvent, ) { if event == WindowEvent::Destroyed && self.window_id == Some(window_id) { diff --git a/examples/util/fill.rs b/examples/util/fill.rs index 0b1a4fb06a..f8280eb313 100644 --- a/examples/util/fill.rs +++ b/examples/util/fill.rs @@ -29,7 +29,7 @@ mod platform { use softbuffer::{Context, Surface}; #[cfg(all(web_platform, not(android_platform)))] use web_time::Instant; - use winit::window::{Window, WindowId}; + use winit::window::{Window, SurfaceId}; thread_local! { // NOTE: You should never do things like that, create context and drop it before @@ -46,7 +46,7 @@ mod platform { context: RefCell>, /// The hash map of window IDs to surfaces. - surfaces: HashMap>, + surfaces: HashMap>, } impl GraphicsContext { diff --git a/examples/window.rs b/examples/window.rs index 76c60c39e8..d8d938f93e 100644 --- a/examples/window.rs +++ b/examples/window.rs @@ -7,7 +7,7 @@ use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; #[cfg(web_platform)] use winit::platform::web::WindowAttributesWeb; -use winit::window::{Window, WindowAttributes, WindowId}; +use winit::window::{Window, WindowAttributes, SurfaceId}; #[path = "util/fill.rs"] mod fill; @@ -36,7 +36,7 @@ impl ApplicationHandler for App { } } - fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _: WindowId, event: WindowEvent) { + fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _: SurfaceId, event: WindowEvent) { println!("{event:?}"); match event { WindowEvent::CloseRequested => { diff --git a/examples/x11_embed.rs b/examples/x11_embed.rs index c047f71ef4..6f486dfdb6 100644 --- a/examples/x11_embed.rs +++ b/examples/x11_embed.rs @@ -7,7 +7,7 @@ fn main() -> Result<(), Box> { use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::platform::x11::WindowAttributesX11; - use winit::window::{Window, WindowAttributes, WindowId}; + use winit::window::{Window, WindowAttributes, SurfaceId}; #[path = "util/fill.rs"] mod fill; @@ -33,7 +33,7 @@ fn main() -> Result<(), Box> { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - _window_id: WindowId, + _window_id: SurfaceId, event: WindowEvent, ) { let window = self.window.as_ref().unwrap(); diff --git a/winit-core/src/application/macos.rs b/winit-core/src/application/macos.rs index d18b4090e5..1dbf878887 100644 --- a/winit-core/src/application/macos.rs +++ b/winit-core/src/application/macos.rs @@ -1,6 +1,6 @@ use crate::application::ApplicationHandler; use crate::event_loop::ActiveEventLoop; -use crate::window::WindowId; +use crate::window::SurfaceId; /// Additional events on [`ApplicationHandler`] that are specific to macOS. /// @@ -42,7 +42,7 @@ pub trait ApplicationHandlerExtMacOS: ApplicationHandler { fn standard_key_binding( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, action: &str, ) { let _ = event_loop; diff --git a/winit-core/src/application/mod.rs b/winit-core/src/application/mod.rs index b9fd34bff1..7f5ec5ac35 100644 --- a/winit-core/src/application/mod.rs +++ b/winit-core/src/application/mod.rs @@ -2,7 +2,7 @@ use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent}; use crate::event_loop::ActiveEventLoop; -use crate::window::WindowId; +use crate::window::SurfaceId; pub mod macos; @@ -195,7 +195,7 @@ pub trait ApplicationHandler { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, event: WindowEvent, ); @@ -371,7 +371,7 @@ impl ApplicationHandler for &mut A { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, event: WindowEvent, ) { (**self).window_event(event_loop, window_id, event); @@ -439,7 +439,7 @@ impl ApplicationHandler for Box { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: WindowId, + window_id: SurfaceId, event: WindowEvent, ) { (**self).window_event(event_loop, window_id, event); diff --git a/winit-core/src/surface.rs b/winit-core/src/surface.rs deleted file mode 100644 index 0c4458f4d8..0000000000 --- a/winit-core/src/surface.rs +++ /dev/null @@ -1,251 +0,0 @@ -//! The [`Window`] trait and associated types. -use std::fmt; - -use cursor_icon::CursorIcon; -use dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size}; -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; - -use crate::as_any::AsAny; -use crate::cursor::Cursor; -use crate::error::RequestError; -use crate::icon::Icon; -use crate::monitor::{Fullscreen, MonitorHandle}; - -/// Represents a surface that has a window handle. -/// -/// The surface is closed when dropped. -pub trait Surface: AsAny + Send + Sync + fmt::Debug { - /// Returns an identifier unique to the window. - fn id(&self) -> SurfaceId; - - /// Returns the scale factor that can be used to map logical pixels to physical pixels, and - /// vice versa. - /// - /// Note that this value can change depending on user action (for example if the window is - /// moved to another screen); as such, tracking [`WindowEvent::ScaleFactorChanged`] events is - /// the most robust way to track the DPI you need to use to draw. - /// - /// This value may differ from [`MonitorHandleProvider::scale_factor`]. - /// - /// See the [`dpi`] crate for more information. - /// - /// ## Platform-specific - /// - /// The scale factor is calculated differently on different platforms: - /// - /// - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from - /// the display settings. While users are free to select any option they want, they're only - /// given a selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale - /// factor is global and changing it requires logging out. See [this article][windows_1] for - /// technical details. - /// - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific - /// displays. When available, the user may pick a per-monitor scaling factor from a set of - /// pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default, - /// but the specific value varies across devices. - /// - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. - /// Winit currently uses a three-pronged approach: - /// + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present. - /// + If not present, use the value set in `Xft.dpi` in Xresources. - /// + Otherwise, calculate the scale factor based on the millimeter monitor dimensions - /// provided by XRandR. - /// - /// If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use - /// the XRandR scaling method. Generally speaking, you should try to configure the - /// standard system variables to do what you want before resorting to - /// `WINIT_X11_SCALE_FACTOR`. - /// - **Wayland:** The scale factor is suggested by the compositor for each window individually - /// by using the wp-fractional-scale protocol if available. Falls back to integer-scale - /// factors otherwise. - /// - /// The monitor scale factor may differ from the window scale factor. - /// - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range - /// from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more - /// information. - /// - /// This uses the underlying `UIView`'s [`contentScaleFactor`]. - /// - **Android:** Scale factors are set by the manufacturer to the value that best suits the - /// device, and range from `1.0` to `4.0`. See [this article][android_1] for more information. - /// - /// This is currently unimplemented, and this function always returns 1.0. - /// - **Web:** The scale factor is the ratio between CSS pixels and the physical device pixels. - /// In other words, it is the value of [`window.devicePixelRatio`][web_1]. It is affected by - /// both the screen scaling and the browser zoom level and can go below `1.0`. - /// - **Orbital:** This is currently unimplemented, and this function always returns 1.0. - /// - /// [`WindowEvent::ScaleFactorChanged`]: crate::event::WindowEvent::ScaleFactorChanged - /// [windows_1]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows - /// [apple_1]: https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html - /// [apple_2]: https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/ - /// [android_1]: https://developer.android.com/training/multiscreen/screendensities - /// [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio - /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc - /// [`MonitorHandleProvider::scale_factor`]: crate::monitor::MonitorHandleProvider::scale_factor. - fn scale_factor(&self) -> f64; - - /// Queues a [`WindowEvent::RedrawRequested`] event to be emitted that aligns with the windowing - /// system drawing loop. - /// - /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with - /// OS-requested redraws (e.g. when a window gets resized). To improve the event delivery - /// consider using [`Window::pre_present_notify`] as described in docs. - /// - /// Applications should always aim to redraw whenever they receive a `RedrawRequested` event. - /// - /// There are no strong guarantees about when exactly a `RedrawRequest` event will be emitted - /// with respect to other events, since the requirements can vary significantly between - /// windowing systems. - /// - /// However as the event aligns with the windowing system drawing loop, it may not arrive in - /// same or even next event loop iteration. - /// - /// ## Platform-specific - /// - /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and - /// `RedrawRequested` is emitted in sync with any `WM_PAINT` messages. - /// - **Wayland:** The events are aligned with the frame callbacks when - /// [`Window::pre_present_notify`] is used. - /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the - /// `requestAnimationFrame`. - /// - /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested - fn request_redraw(&self); - - /// Notify the windowing system before presenting to the window. - /// - /// You should call this event after your drawing operations, but before you submit - /// the buffer to the display or commit your drawings. Doing so will help winit to properly - /// schedule and make assumptions about its internal state. For example, it could properly - /// throttle [`WindowEvent::RedrawRequested`]. - /// - /// ## Example - /// - /// This example illustrates how it looks with OpenGL, but it applies to other graphics - /// APIs and software rendering. - /// - /// ```no_run - /// # use winit_core::window::Window; - /// # fn swap_buffers() {} - /// # fn scope(window: &dyn Window) { - /// // Do the actual drawing with OpenGL. - /// - /// // Notify winit that we're about to submit buffer to the windowing system. - /// window.pre_present_notify(); - /// - /// // Submit buffer to the windowing system. - /// swap_buffers(); - /// # } - /// ``` - /// - /// ## Platform-specific - /// - /// - **Android / iOS / X11 / Web / Windows / macOS / Orbital:** Unsupported. - /// - **Wayland:** Schedules a frame callback to throttle [`WindowEvent::RedrawRequested`]. - /// - /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested - fn pre_present_notify(&self); - - /// Returns the size of the window's render-able surface. - /// - /// This is the dimensions you should pass to things like Wgpu or Glutin when configuring the - /// surface for drawing. See [`WindowEvent::SurfaceResized`] for listening to changes to this - /// field. - /// - /// Note that to ensure that your content is not obscured by things such as notches or the title - /// bar, you will likely want to only draw important content inside a specific area of the - /// surface, see [`safe_area()`] for details. - /// - /// ## Platform-specific - /// - /// - **Web:** Returns the size of the canvas element. Doesn't account for CSS [`transform`]. - /// - /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform - /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized - /// [`safe_area()`]: Window::safe_area - fn surface_size(&self) -> PhysicalSize; - - /// Request the new size for the surface. - /// - /// On platforms where the size is entirely controlled by the user the - /// applied size will be returned immediately, resize event in such case - /// may not be generated. - /// - /// On platforms where resizing is disallowed by the windowing system, the current surface size - /// is returned immediately, and the user one is ignored. - /// - /// When `None` is returned, it means that the request went to the display system, - /// and the actual size will be delivered later with the [`WindowEvent::SurfaceResized`]. - /// - /// See [`Window::surface_size`] for more information about the values. - /// - /// The request could automatically un-maximize the window if it's maximized. - /// - /// ```no_run - /// # use dpi::{LogicalSize, PhysicalSize}; - /// # use winit_core::window::Window; - /// # fn scope(window: &dyn Window) { - /// // Specify the size in logical dimensions like this: - /// let _ = window.request_surface_size(LogicalSize::new(400.0, 200.0).into()); - /// - /// // Or specify the size in physical dimensions like this: - /// let _ = window.request_surface_size(PhysicalSize::new(400, 200).into()); - /// # } - /// ``` - /// - /// ## Platform-specific - /// - /// - **Web:** Sets the size of the canvas element. Doesn't account for CSS [`trkansform`]. - /// - /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized - /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform - #[must_use] - fn request_surface_size(&self, size: Size) -> Option>; - - /// Change the window transparency state. - /// - /// This is just a hint that may not change anything about - /// the window transparency, however doing a mismatch between - /// the content of your window and this hint may result in - /// visual artifacts. - /// - /// The default value follows the [`WindowAttributes::with_transparent`]. - /// - /// ## Platform-specific - /// - /// - **macOS:** This will reset the window's background color. - /// - **Web / iOS / Android:** Unsupported. - /// - **X11:** Can only be set while building the window, with - /// [`WindowAttributes::with_transparent`]. - fn set_transparent(&self, transparent: bool); -} - -/// Identifier of a window. Unique for each window. -/// -/// Can be obtained with [`window.id()`][`Window::id`]. -/// -/// Whenever you receive an event specific to a window, this event contains a `WindowId` which you -/// can then compare to the ids of your windows. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct SurfaceId(usize); - -impl SurfaceId { - /// Convert the `WindowId` into the underlying integer. - /// - /// This is useful if you need to pass the ID across an FFI boundary, or store it in an atomic. - pub const fn into_raw(self) -> usize { - self.0 - } - - /// Construct a `WindowId` from the underlying integer. - /// - /// This should only be called with integers returned from [`WindowId::into_raw`]. - pub const fn from_raw(id: usize) -> Self { - Self(id) - } -} - -impl fmt::Debug for SurfaceId { - fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(fmtr) - } -} \ No newline at end of file diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index 197b8c6582..86ab4c3e35 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -22,9 +22,9 @@ use crate::monitor::{Fullscreen, MonitorHandle}; /// Whenever you receive an event specific to a window, this event contains a `WindowId` which you /// can then compare to the ids of your windows. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct WindowId(usize); +pub struct SurfaceId(usize); -impl WindowId { +impl SurfaceId { /// Convert the `WindowId` into the underlying integer. /// /// This is useful if you need to pass the ID across an FFI boundary, or store it in an atomic. @@ -40,7 +40,7 @@ impl WindowId { } } -impl fmt::Debug for WindowId { +impl fmt::Debug for SurfaceId { fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(fmtr) } @@ -457,6 +457,344 @@ pub trait PlatformWindowAttributes: AsAny + std::fmt::Debug + Send + Sync { impl_dyn_casting!(PlatformWindowAttributes); +/// Represents a drawable, resizable surface that is visible on-screen. +/// +/// The surface is closed when dropped. +pub trait Surface: AsAny + Send + Sync + fmt::Debug { + /// Returns an identifier unique to the window. + fn id(&self) -> SurfaceId; + + /// Returns the scale factor that can be used to map logical pixels to physical pixels, and + /// vice versa. + /// + /// Note that this value can change depending on user action (for example if the window is + /// moved to another screen); as such, tracking [`WindowEvent::ScaleFactorChanged`] events is + /// the most robust way to track the DPI you need to use to draw. + /// + /// This value may differ from [`MonitorHandleProvider::scale_factor`]. + /// + /// See the [`dpi`] crate for more information. + /// + /// ## Platform-specific + /// + /// The scale factor is calculated differently on different platforms: + /// + /// - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from + /// the display settings. While users are free to select any option they want, they're only + /// given a selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale + /// factor is global and changing it requires logging out. See [this article][windows_1] for + /// technical details. + /// - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific + /// displays. When available, the user may pick a per-monitor scaling factor from a set of + /// pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default, + /// but the specific value varies across devices. + /// - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. + /// Winit currently uses a three-pronged approach: + /// + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present. + /// + If not present, use the value set in `Xft.dpi` in Xresources. + /// + Otherwise, calculate the scale factor based on the millimeter monitor dimensions + /// provided by XRandR. + /// + /// If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use + /// the XRandR scaling method. Generally speaking, you should try to configure the + /// standard system variables to do what you want before resorting to + /// `WINIT_X11_SCALE_FACTOR`. + /// - **Wayland:** The scale factor is suggested by the compositor for each window individually + /// by using the wp-fractional-scale protocol if available. Falls back to integer-scale + /// factors otherwise. + /// + /// The monitor scale factor may differ from the window scale factor. + /// - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range + /// from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more + /// information. + /// + /// This uses the underlying `UIView`'s [`contentScaleFactor`]. + /// - **Android:** Scale factors are set by the manufacturer to the value that best suits the + /// device, and range from `1.0` to `4.0`. See [this article][android_1] for more information. + /// + /// This is currently unimplemented, and this function always returns 1.0. + /// - **Web:** The scale factor is the ratio between CSS pixels and the physical device pixels. + /// In other words, it is the value of [`window.devicePixelRatio`][web_1]. It is affected by + /// both the screen scaling and the browser zoom level and can go below `1.0`. + /// - **Orbital:** This is currently unimplemented, and this function always returns 1.0. + /// + /// [`WindowEvent::ScaleFactorChanged`]: crate::event::WindowEvent::ScaleFactorChanged + /// [windows_1]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows + /// [apple_1]: https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html + /// [apple_2]: https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/ + /// [android_1]: https://developer.android.com/training/multiscreen/screendensities + /// [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + /// [`MonitorHandleProvider::scale_factor`]: crate::monitor::MonitorHandleProvider::scale_factor. + fn scale_factor(&self) -> f64; + + /// Queues a [`WindowEvent::RedrawRequested`] event to be emitted that aligns with the windowing + /// system drawing loop. + /// + /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with + /// OS-requested redraws (e.g. when a window gets resized). To improve the event delivery + /// consider using [`Window::pre_present_notify`] as described in docs. + /// + /// Applications should always aim to redraw whenever they receive a `RedrawRequested` event. + /// + /// There are no strong guarantees about when exactly a `RedrawRequest` event will be emitted + /// with respect to other events, since the requirements can vary significantly between + /// windowing systems. + /// + /// However as the event aligns with the windowing system drawing loop, it may not arrive in + /// same or even next event loop iteration. + /// + /// ## Platform-specific + /// + /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and + /// `RedrawRequested` is emitted in sync with any `WM_PAINT` messages. + /// - **Wayland:** The events are aligned with the frame callbacks when + /// [`Window::pre_present_notify`] is used. + /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the + /// `requestAnimationFrame`. + /// + /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested + fn request_redraw(&self); + + /// Notify the windowing system before presenting to the window. + /// + /// You should call this event after your drawing operations, but before you submit + /// the buffer to the display or commit your drawings. Doing so will help winit to properly + /// schedule and make assumptions about its internal state. For example, it could properly + /// throttle [`WindowEvent::RedrawRequested`]. + /// + /// ## Example + /// + /// This example illustrates how it looks with OpenGL, but it applies to other graphics + /// APIs and software rendering. + /// + /// ```no_run + /// # use winit_core::window::Window; + /// # fn swap_buffers() {} + /// # fn scope(window: &dyn Window) { + /// // Do the actual drawing with OpenGL. + /// + /// // Notify winit that we're about to submit buffer to the windowing system. + /// window.pre_present_notify(); + /// + /// // Submit buffer to the windowing system. + /// swap_buffers(); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Android / iOS / X11 / Web / Windows / macOS / Orbital:** Unsupported. + /// - **Wayland:** Schedules a frame callback to throttle [`WindowEvent::RedrawRequested`]. + /// + /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested + fn pre_present_notify(&self); + + /// Returns the size of the window's render-able surface. + /// + /// This is the dimensions you should pass to things like Wgpu or Glutin when configuring the + /// surface for drawing. See [`WindowEvent::SurfaceResized`] for listening to changes to this + /// field. + /// + /// Note that to ensure that your content is not obscured by things such as notches or the title + /// bar, you will likely want to only draw important content inside a specific area of the + /// surface, see [`safe_area()`] for details. + /// + /// ## Platform-specific + /// + /// - **Web:** Returns the size of the canvas element. Doesn't account for CSS [`transform`]. + /// + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized + /// [`safe_area()`]: Window::safe_area + fn surface_size(&self) -> PhysicalSize; + + /// Request the new size for the surface. + /// + /// On platforms where the size is entirely controlled by the user the + /// applied size will be returned immediately, resize event in such case + /// may not be generated. + /// + /// On platforms where resizing is disallowed by the windowing system, the current surface size + /// is returned immediately, and the user one is ignored. + /// + /// When `None` is returned, it means that the request went to the display system, + /// and the actual size will be delivered later with the [`WindowEvent::SurfaceResized`]. + /// + /// See [`Window::surface_size`] for more information about the values. + /// + /// The request could automatically un-maximize the window if it's maximized. + /// + /// ```no_run + /// # use dpi::{LogicalSize, PhysicalSize}; + /// # use winit_core::window::Window; + /// # fn scope(window: &dyn Window) { + /// // Specify the size in logical dimensions like this: + /// let _ = window.request_surface_size(LogicalSize::new(400.0, 200.0).into()); + /// + /// // Or specify the size in physical dimensions like this: + /// let _ = window.request_surface_size(PhysicalSize::new(400, 200).into()); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Web:** Sets the size of the canvas element. Doesn't account for CSS [`trkansform`]. + /// + /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + #[must_use] + fn request_surface_size(&self, size: Size) -> Option>; + + /// Change the window transparency state. + /// + /// This is just a hint that may not change anything about + /// the window transparency, however doing a mismatch between + /// the content of your window and this hint may result in + /// visual artifacts. + /// + /// The default value follows the [`WindowAttributes::with_transparent`]. + /// + /// ## Platform-specific + /// + /// - **macOS:** This will reset the window's background color. + /// - **Web / iOS / Android:** Unsupported. + /// - **X11:** Can only be set while building the window, with + /// [`WindowAttributes::with_transparent`]. + fn set_transparent(&self, transparent: bool); + + /// Modifies the cursor icon of the window. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Orbital:** Unsupported. + /// - **Web:** Custom cursors have to be loaded and decoded first, until then the previous + /// cursor is shown. + fn set_cursor(&self, cursor: Cursor); // * + + /// Changes the position of the cursor in window coordinates. + /// + /// ```no_run + /// # use dpi::{LogicalPosition, PhysicalPosition}; + /// # use winit_core::window::Window; + /// # fn scope(window: &dyn Window) { + /// // Specify the position in logical dimensions like this: + /// window.set_cursor_position(LogicalPosition::new(400.0, 200.0).into()); + /// + /// // Or specify the position in physical dimensions like this: + /// window.set_cursor_position(PhysicalPosition::new(400, 200).into()); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Wayland**: Cursor must be in [`CursorGrabMode::Locked`]. + /// - **iOS / Android / Web / Orbital:** Always returns an [`RequestError::NotSupported`]. + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError>; // * + + /// Set grabbing [mode][CursorGrabMode] on the cursor preventing it from leaving the window. + /// + /// # Example + /// + /// First try confining the cursor, and if that fails, try locking it instead. + /// + /// ```no_run + /// # use winit_core::window::{CursorGrabMode, Window}; + /// # fn scope(window: &dyn Window) { + /// window + /// .set_cursor_grab(CursorGrabMode::Confined) + /// .or_else(|_e| window.set_cursor_grab(CursorGrabMode::Locked)) + /// .unwrap(); + /// # } + /// ``` + fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError>; // * + + /// Modifies the cursor's visibility. + /// + /// If `false`, this will hide the cursor. If `true`, this will show the cursor. + /// + /// ## Platform-specific + /// + /// - **Windows:** The cursor is only hidden within the confines of the window. + /// - **X11:** The cursor is only hidden within the confines of the window. + /// - **Wayland:** The cursor is only hidden within the confines of the window. + /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor + /// is outside of the window. + /// - **iOS / Android:** Unsupported. + fn set_cursor_visible(&self, visible: bool); // * + + /// Modifies whether the window catches cursor events. + /// + /// If `true`, the window will catch the cursor events. If `false`, events are passed through + /// the window such that any other window behind it receives them. By default hittest is + /// enabled. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Orbital:** Always returns an [`RequestError::NotSupported`]. + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError>; + + /// Returns the monitor on which the window currently resides. + /// + /// Returns `None` if current monitor can't be detected. + fn current_monitor(&self) -> Option; + + /// Returns the list of all the monitors available on the system. + /// + /// This is the same as [`ActiveEventLoop::available_monitors`], and is provided for + /// convenience. + /// + /// [`ActiveEventLoop::available_monitors`]: crate::event_loop::ActiveEventLoop::available_monitors + fn available_monitors(&self) -> Box>; + + /// Returns the primary monitor of the system. + /// + /// Returns `None` if it can't identify any monitor as a primary one. + /// + /// This is the same as [`ActiveEventLoop::primary_monitor`], and is provided for convenience. + /// + /// ## Platform-specific + /// + /// - **Wayland:** Always returns `None`. + /// + /// [`ActiveEventLoop::primary_monitor`]: crate::event_loop::ActiveEventLoop::primary_monitor + fn primary_monitor(&self) -> Option; + + /// Get the raw-window-handle v0.6 display handle. + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle; + + /// Get the raw-window-handle v0.6 window handle. + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle; +} + +impl_dyn_casting!(Surface); + +impl PartialEq for dyn Surface + '_ { + fn eq(&self, other: &dyn Surface) -> bool { + self.id().eq(&other.id()) + } +} + +impl Eq for dyn Surface + '_ {} + +impl std::hash::Hash for dyn Surface + '_ { + fn hash(&self, state: &mut H) { + self.id().hash(state); + } +} + +impl rwh_06::HasDisplayHandle for dyn Surface + '_ { + fn display_handle(&self) -> Result, rwh_06::HandleError> { + self.rwh_06_display_handle().display_handle() + } +} + +impl rwh_06::HasWindowHandle for dyn Surface + '_ { + fn window_handle(&self) -> Result, rwh_06::HandleError> { + self.rwh_06_window_handle().window_handle() + } +} + /// Represents a toplevel window. /// /// The window is closed when dropped. @@ -477,7 +815,7 @@ impl_dyn_casting!(PlatformWindowAttributes); /// not be closed by dropping the [`Window`]. pub trait Window: AsAny + Send + Sync + fmt::Debug { /// Returns an identifier unique to the window. - fn id(&self) -> WindowId; // * + fn id(&self) -> SurfaceId; // * /// Returns the scale factor that can be used to map logical pixels to physical pixels, and /// vice versa. @@ -1304,7 +1642,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// - **iOS / Android / Orbital:** Unsupported. /// - **Web:** Custom cursors have to be loaded and decoded first, until then the previous /// cursor is shown. - fn set_cursor(&self, cursor: Cursor); + fn set_cursor(&self, cursor: Cursor); // * /// Changes the position of the cursor in window coordinates. /// @@ -1324,7 +1662,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// /// - **Wayland**: Cursor must be in [`CursorGrabMode::Locked`]. /// - **iOS / Android / Web / Orbital:** Always returns an [`RequestError::NotSupported`]. - fn set_cursor_position(&self, position: Position) -> Result<(), RequestError>; + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError>; // * /// Set grabbing [mode][CursorGrabMode] on the cursor preventing it from leaving the window. /// @@ -1341,7 +1679,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// .unwrap(); /// # } /// ``` - fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError>; + fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError>; // * /// Modifies the cursor's visibility. /// @@ -1355,7 +1693,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor /// is outside of the window. /// - **iOS / Android:** Unsupported. - fn set_cursor_visible(&self, visible: bool); + fn set_cursor_visible(&self, visible: bool); // * /// Moves the window with the left mouse button until the button is released. /// diff --git a/winit-orbital/src/event_loop.rs b/winit-orbital/src/event_loop.rs index 77f1aaeaa3..663ad9e046 100644 --- a/winit-orbital/src/event_loop.rs +++ b/winit-orbital/src/event_loop.rs @@ -24,7 +24,7 @@ use winit_core::keyboard::{ Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, PhysicalKey, }; -use winit_core::window::{Theme, Window as CoreWindow, WindowId}; +use winit_core::window::{Theme, Window as CoreWindow, SurfaceId}; use crate::window::Window; use crate::{RedoxSocket, TimeSocket, WindowProperties}; @@ -320,7 +320,7 @@ impl EventLoop { } fn process_event( - window_id: WindowId, + window_id: SurfaceId, event_option: EventOption, event_state: &mut EventState, window_target: &ActiveEventLoop, @@ -499,7 +499,7 @@ impl EventLoop { let mut creates = self.window_target.creates.lock().unwrap(); creates.pop_front() } { - let window_id = WindowId::from_raw(window.fd); + let window_id = SurfaceId::from_raw(window.fd); let mut buf: [u8; 4096] = [0; 4096]; let path = window.fpath(&mut buf).expect("failed to read properties"); @@ -523,14 +523,14 @@ impl EventLoop { } { app.window_event(&self.window_target, destroy_id, event::WindowEvent::Destroyed); self.windows - .retain(|(window, _event_state)| WindowId::from_raw(window.fd) != destroy_id); + .retain(|(window, _event_state)| SurfaceId::from_raw(window.fd) != destroy_id); } // Handle window events. let mut i = 0; // While loop is used here because the same window may be processed more than once. while let Some((window, event_state)) = self.windows.get_mut(i) { - let window_id = WindowId::from_raw(window.fd); + let window_id = SurfaceId::from_raw(window.fd); let mut event_buf = [0u8; 16 * mem::size_of::()]; let count = @@ -687,8 +687,8 @@ pub struct ActiveEventLoop { control_flow: Cell, exit: Cell, pub(super) creates: Mutex>>, - pub(super) redraws: Arc>>, - pub(super) destroys: Arc>>, + pub(super) redraws: Arc>>, + pub(super) destroys: Arc>>, pub(super) event_socket: Arc, pub(super) event_loop_proxy: Arc, } diff --git a/winit-orbital/src/window.rs b/winit-orbital/src/window.rs index 7f3918f7a9..b9299a816d 100644 --- a/winit-orbital/src/window.rs +++ b/winit-orbital/src/window.rs @@ -6,7 +6,7 @@ use dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size}; use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; -use winit_core::window::{self, Window as CoreWindow, WindowId}; +use winit_core::window::{self, Window as CoreWindow, SurfaceId}; use crate::event_loop::{ActiveEventLoop, EventLoopProxy}; use crate::{RedoxSocket, WindowProperties}; @@ -25,8 +25,8 @@ const ORBITAL_FLAG_TRANSPARENT: char = 't'; #[derive(Debug)] pub struct Window { window_socket: Arc, - redraws: Arc>>, - destroys: Arc>>, + redraws: Arc>>, + destroys: Arc>>, event_loop_proxy: Arc, } @@ -157,8 +157,8 @@ impl Window { } impl CoreWindow for Window { - fn id(&self) -> WindowId { - WindowId::from_raw(self.window_socket.fd) + fn id(&self) -> SurfaceId { + SurfaceId::from_raw(self.window_socket.fd) } fn ime_capabilities(&self) -> Option { diff --git a/winit-wayland/src/event_loop/mod.rs b/winit-wayland/src/event_loop/mod.rs index ee6b4e8e92..6e30f51001 100644 --- a/winit-wayland/src/event_loop/mod.rs +++ b/winit-wayland/src/event_loop/mod.rs @@ -41,13 +41,13 @@ pub use winit_core::event_loop::EventLoopProxy as CoreEventLoopProxy; use super::output::MonitorHandle; use super::state::{WindowCompositorUpdate, WinitState}; use super::window::state::FrameCallbackState; -use super::{logical_to_physical_rounded, WindowId}; +use super::{logical_to_physical_rounded, SurfaceId}; type WaylandDispatcher = calloop::Dispatcher<'static, WaylandSource, WinitState>; #[derive(Debug)] pub(crate) enum Event { - WindowEvent { window_id: WindowId, event: WindowEvent }, + WindowEvent { window_id: SurfaceId, event: WindowEvent }, DeviceEvent { event: DeviceEvent }, } @@ -59,7 +59,7 @@ pub struct EventLoop { buffer_sink: EventSink, compositor_updates: Vec, - window_ids: Vec, + window_ids: Vec, /// The Wayland dispatcher to has raw access to the queue when needed, such as /// when creating a new window. diff --git a/winit-wayland/src/event_loop/sink.rs b/winit-wayland/src/event_loop/sink.rs index c67463d2e4..92ab5e893c 100644 --- a/winit-wayland/src/event_loop/sink.rs +++ b/winit-wayland/src/event_loop/sink.rs @@ -3,7 +3,7 @@ use std::vec::Drain; use winit_core::event::{DeviceEvent, WindowEvent}; -use winit_core::window::WindowId; +use winit_core::window::SurfaceId; use super::Event; @@ -33,7 +33,7 @@ impl EventSink { /// Add new window event to a queue. #[inline] - pub fn push_window_event(&mut self, event: WindowEvent, window_id: WindowId) { + pub fn push_window_event(&mut self, event: WindowEvent, window_id: SurfaceId) { self.window_events.push(Event::WindowEvent { event, window_id }); } diff --git a/winit-wayland/src/lib.rs b/winit-wayland/src/lib.rs index 1a35a3de22..e3b36d6f68 100644 --- a/winit-wayland/src/lib.rs +++ b/winit-wayland/src/lib.rs @@ -23,7 +23,7 @@ use sctk::shm::slot::{Buffer, CreateBufferError, SlotPool}; use wayland_client::protocol::wl_shm::Format; use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop; use winit_core::window::{ - ActivationToken, PlatformWindowAttributes, Window as CoreWindow, WindowId, + ActivationToken, PlatformWindowAttributes, Window as CoreWindow, SurfaceId, }; macro_rules! os_error { @@ -130,8 +130,8 @@ impl PlatformWindowAttributes for WindowAttributesWayland { /// Get the WindowId out of the surface. #[inline] -fn make_wid(surface: &WlSurface) -> WindowId { - WindowId::from_raw(surface.id().as_ptr() as usize) +fn make_wid(surface: &WlSurface) -> SurfaceId { + SurfaceId::from_raw(surface.id().as_ptr() as usize) } /// The default routine does floor, but we need round on Wayland. diff --git a/winit-wayland/src/seat/keyboard/mod.rs b/winit-wayland/src/seat/keyboard/mod.rs index 227006857b..a40e0a4daf 100644 --- a/winit-wayland/src/seat/keyboard/mod.rs +++ b/winit-wayland/src/seat/keyboard/mod.rs @@ -17,7 +17,7 @@ use winit_core::keyboard::ModifiersState; use crate::event_loop::sink::EventSink; use crate::state::WinitState; -use crate::WindowId; +use crate::SurfaceId; impl Dispatch for WinitState { fn event( @@ -344,7 +344,7 @@ impl Default for RepeatInfo { #[derive(Debug)] pub struct KeyboardData { /// The currently focused window surface. Could be `None` on bugged compositors, like mutter. - window_id: Mutex>, + window_id: Mutex>, /// The seat used to create this keyboard. seat: WlSeat, diff --git a/winit-wayland/src/seat/pointer/mod.rs b/winit-wayland/src/seat/pointer/mod.rs index 9dea4b7ff6..9f4da547b6 100644 --- a/winit-wayland/src/seat/pointer/mod.rs +++ b/winit-wayland/src/seat/pointer/mod.rs @@ -34,7 +34,7 @@ use winit_core::event::{ }; use crate::state::WinitState; -use crate::WindowId; +use crate::SurfaceId; pub mod relative_pointer; @@ -318,7 +318,7 @@ impl WinitPointerData { } /// Active window. - pub fn focused_window(&self) -> Option { + pub fn focused_window(&self) -> Option { self.inner.lock().unwrap().surface } @@ -370,7 +370,7 @@ pub struct WinitPointerDataInner { latest_button_serial: u32, /// Currently focused window. - surface: Option, + surface: Option, /// Current axis phase. phase: TouchPhase, diff --git a/winit-wayland/src/state.rs b/winit-wayland/src/state.rs index 9f8a4f490a..1bccf9f3e2 100644 --- a/winit-wayland/src/state.rs +++ b/winit-wayland/src/state.rs @@ -34,7 +34,7 @@ use crate::types::wp_viewporter::ViewporterState; use crate::types::xdg_activation::XdgActivationState; use crate::types::xdg_toplevel_icon_manager::XdgToplevelIconManagerState; use crate::window::{WindowRequests, WindowState}; -use crate::WindowId; +use crate::SurfaceId; /// Winit's Wayland state. #[derive(Debug)] @@ -61,10 +61,10 @@ pub struct WinitState { pub xdg_shell: XdgShell, /// The currently present windows. - pub windows: RefCell>>>, + pub windows: RefCell>>>, /// The requests from the `Window` to EventLoop, such as close operations and redraw requests. - pub window_requests: RefCell>>, + pub window_requests: RefCell>>, /// The events that were generated directly from the window. pub window_events_sink: Arc>, @@ -248,7 +248,7 @@ impl WinitState { } } - pub fn queue_close(updates: &mut Vec, window_id: WindowId) { + pub fn queue_close(updates: &mut Vec, window_id: SurfaceId) { let pos = if let Some(pos) = updates.iter().position(|update| update.window_id == window_id) { pos @@ -418,7 +418,7 @@ impl ProvidesRegistryState for WinitState { #[derive(Debug, Clone, Copy)] pub struct WindowCompositorUpdate { /// The id of the window this updates belongs to. - pub window_id: WindowId, + pub window_id: SurfaceId, /// New window size. pub resized: bool, @@ -431,7 +431,7 @@ pub struct WindowCompositorUpdate { } impl WindowCompositorUpdate { - fn new(window_id: WindowId) -> Self { + fn new(window_id: SurfaceId) -> Self { Self { window_id, resized: false, scale_changed: false, close_window: false } } } diff --git a/winit-wayland/src/types/xdg_activation.rs b/winit-wayland/src/types/xdg_activation.rs index 9e9998cb42..070aa6e442 100644 --- a/winit-wayland/src/types/xdg_activation.rs +++ b/winit-wayland/src/types/xdg_activation.rs @@ -12,7 +12,7 @@ use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_toke }; use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1; use winit_core::event_loop::AsyncRequestSerial; -use winit_core::window::{ActivationToken, WindowId}; +use winit_core::window::{ActivationToken, SurfaceId}; use crate::state::WinitState; @@ -95,7 +95,7 @@ pub enum XdgActivationTokenData { /// Request user attention for the given surface. Attention((WlSurface, Weak)), /// Get a token to be passed outside of the winit. - Obtain((WindowId, AsyncRequestSerial)), + Obtain((SurfaceId, AsyncRequestSerial)), } delegate_dispatch!(WinitState: [ XdgActivationV1: GlobalData] => XdgActivationState); diff --git a/winit-wayland/src/window/mod.rs b/winit-wayland/src/window/mod.rs index fb5f22fea8..66f9559813 100644 --- a/winit-wayland/src/window/mod.rs +++ b/winit-wayland/src/window/mod.rs @@ -21,7 +21,7 @@ use winit_core::event_loop::AsyncRequestSerial; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, - UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons, WindowId, + UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons, SurfaceId, WindowLevel, }; @@ -43,7 +43,7 @@ pub struct Window { window: SctkWindow, /// Window id. - window_id: WindowId, + window_id: SurfaceId, /// The state of the window. window_state: Arc>, @@ -283,7 +283,7 @@ impl rwh_06::HasDisplayHandle for Window { } impl CoreWindow for Window { - fn id(&self) -> WindowId { + fn id(&self) -> SurfaceId { self.window_id } diff --git a/winit-wayland/src/window/state.rs b/winit-wayland/src/window/state.rs index 899b0e0174..2a62ae528d 100644 --- a/winit-wayland/src/window/state.rs +++ b/winit-wayland/src/window/state.rs @@ -33,7 +33,7 @@ use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur; use winit_core::cursor::{CursorIcon, CustomCursor as CoreCustomCursor}; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::window::{ - CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, WindowId, + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, SurfaceId, }; use crate::event_loop::OwnedDisplayHandle; @@ -442,7 +442,7 @@ impl WindowState { seat: &WlSeat, serial: u32, timestamp: Duration, - window_id: WindowId, + window_id: SurfaceId, updates: &mut Vec, ) -> Option { match self.frame.as_mut()?.on_click(timestamp, click, pressed)? { diff --git a/winit-web/src/event_loop/runner.rs b/winit-web/src/event_loop/runner.rs index 4aeaf383e1..7359cca3fb 100644 --- a/winit-web/src/event_loop/runner.rs +++ b/winit-web/src/event_loop/runner.rs @@ -15,7 +15,7 @@ use winit_core::event::{ DeviceEvent, DeviceId, ElementState, RawKeyEvent, StartCause, WindowEvent, }; use winit_core::event_loop::{ControlFlow, DeviceEvents}; -use winit_core::window::WindowId; +use winit_core::window::SurfaceId; use super::proxy::EventLoopProxy; use super::state::State; @@ -55,9 +55,9 @@ struct Execution { navigator: Navigator, document: Document, #[allow(clippy::type_complexity)] - all_canvases: RefCell, DispatchRunner)>>, - redraw_pending: RefCell>, - destroy_pending: RefCell>, + all_canvases: RefCell, DispatchRunner)>>, + redraw_pending: RefCell>, + destroy_pending: RefCell>, pub(crate) monitor: Rc, safe_area: Rc, page_transition_event_handle: RefCell>, @@ -237,14 +237,14 @@ impl Shared { pub fn add_canvas( &self, - id: WindowId, + id: SurfaceId, canvas: Weak, runner: DispatchRunner, ) { self.0.all_canvases.borrow_mut().push((id, canvas, runner)); } - pub fn notify_destroy_window(&self, id: WindowId) { + pub fn notify_destroy_window(&self, id: SurfaceId) { self.0.destroy_pending.borrow_mut().push_back(id); } @@ -478,7 +478,7 @@ impl Shared { id } - pub fn request_redraw(&self, id: WindowId) { + pub fn request_redraw(&self, id: SurfaceId) { self.0.redraw_pending.borrow_mut().insert(id); self.send_events([]); } @@ -620,7 +620,7 @@ impl Shared { self.process_destroy_pending_windows(); // Collect all of the redraw events to avoid double-locking the RefCell - let redraw_events: Vec = self.0.redraw_pending.borrow_mut().drain().collect(); + let redraw_events: Vec = self.0.redraw_pending.borrow_mut().drain().collect(); for window_id in redraw_events { self.handle_event(Event::WindowEvent { window_id, @@ -877,7 +877,7 @@ impl WeakShared { #[allow(clippy::enum_variant_names)] pub(crate) enum Event { NewEvents(StartCause), - WindowEvent { window_id: WindowId, event: WindowEvent }, + WindowEvent { window_id: SurfaceId, event: WindowEvent }, ScaleChange { canvas: Weak, size: PhysicalSize, scale: f64 }, DeviceEvent { device_id: Option, event: DeviceEvent }, Suspended, diff --git a/winit-web/src/event_loop/window_target.rs b/winit-web/src/event_loop/window_target.rs index 84c080e8d1..7423c1fd60 100644 --- a/winit-web/src/event_loop/window_target.rs +++ b/winit-web/src/event_loop/window_target.rs @@ -15,7 +15,7 @@ use winit_core::event_loop::{ }; use winit_core::keyboard::ModifiersState; use winit_core::monitor::MonitorHandle as CoremMonitorHandle; -use winit_core::window::{Theme, WindowId}; +use winit_core::window::{Theme, SurfaceId}; use super::super::lock; use super::super::monitor::MonitorPermissionFuture; @@ -61,15 +61,15 @@ impl ActiveEventLoop { self.runner.start(app, self.clone()); } - pub fn generate_id(&self) -> WindowId { - WindowId::from_raw(self.runner.generate_id()) + pub fn generate_id(&self) -> SurfaceId { + SurfaceId::from_raw(self.runner.generate_id()) } pub fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture { CustomCursorFuture(CustomCursor::new_async(self, source)) } - pub fn register(&self, canvas: &Rc, window_id: WindowId) { + pub fn register(&self, canvas: &Rc, window_id: SurfaceId) { let canvas_clone = canvas.clone(); canvas.on_touch_start(); diff --git a/winit-web/src/web_sys/canvas.rs b/winit-web/src/web_sys/canvas.rs index 3a9f8ae546..4df3a63c82 100644 --- a/winit-web/src/web_sys/canvas.rs +++ b/winit-web/src/web_sys/canvas.rs @@ -18,7 +18,7 @@ use winit_core::event::{ }; use winit_core::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey}; use winit_core::monitor::Fullscreen; -use winit_core::window::{WindowAttributes, WindowId}; +use winit_core::window::{WindowAttributes, SurfaceId}; use super::super::cursor::CursorHandler; use super::super::event_loop::runner; @@ -35,7 +35,7 @@ use crate::WindowAttributesWeb; pub struct Canvas { main_thread: MainThreadMarker, common: Common, - id: WindowId, + id: SurfaceId, pub has_focus: Rc>, pub prevent_default: Rc>, pub is_intersecting: Cell>, @@ -81,7 +81,7 @@ pub struct Style { impl Canvas { pub(crate) fn create( main_thread: MainThreadMarker, - id: WindowId, + id: SurfaceId, window: web_sys::Window, navigator: Navigator, document: Document, @@ -489,7 +489,7 @@ impl Canvas { pub(crate) fn handle_scale_change( &self, runner: &super::super::event_loop::runner::Shared, - event_handler: impl FnOnce(WindowId, WindowEvent), + event_handler: impl FnOnce(SurfaceId, WindowEvent), current_size: PhysicalSize, scale: f64, ) { diff --git a/winit-web/src/window.rs b/winit-web/src/window.rs index a3579a33bf..2fdae63b53 100644 --- a/winit-web/src/window.rs +++ b/winit-web/src/window.rs @@ -13,7 +13,7 @@ use winit_core::icon::Icon; use winit_core::monitor::{Fullscreen, MonitorHandle as CoremMonitorHandle}; use winit_core::window::{ CursorGrabMode, ImeRequestError, ResizeDirection, Theme, UserAttentionType, - Window as RootWindow, WindowAttributes, WindowButtons, WindowId, WindowLevel, + Window as RootWindow, WindowAttributes, WindowButtons, SurfaceId, WindowLevel, }; use crate::event_loop::ActiveEventLoop; @@ -33,7 +33,7 @@ impl fmt::Debug for Window { } pub struct Inner { - id: WindowId, + id: SurfaceId, pub window: web_sys::Window, monitor: Rc, safe_area: Rc, @@ -103,7 +103,7 @@ impl Window { } impl RootWindow for Window { - fn id(&self) -> WindowId { + fn id(&self) -> SurfaceId { self.inner.queue(|inner| inner.id) } diff --git a/winit-x11/src/event_loop.rs b/winit-x11/src/event_loop.rs index b1b309ecb5..cb66383405 100644 --- a/winit-x11/src/event_loop.rs +++ b/winit-x11/src/event_loop.rs @@ -28,7 +28,7 @@ use winit_core::event_loop::{ OwnedDisplayHandle as CoreOwnedDisplayHandle, }; use winit_core::monitor::MonitorHandle as CoreMonitorHandle; -use winit_core::window::{Theme, Window as CoreWindow, WindowAttributes, WindowId}; +use winit_core::window::{Theme, Window as CoreWindow, WindowAttributes, SurfaceId}; use x11rb::connection::RequestConnection; use x11rb::errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError}; use x11rb::protocol::xinput::{self, ConnectionExt as _}; @@ -176,8 +176,8 @@ pub struct ActiveEventLoop { exit: Cell>, pub(crate) root: xproto::Window, pub(crate) ime: Option>, - pub(crate) windows: RefCell>>, - pub(crate) redraw_sender: WakeSender, + pub(crate) windows: RefCell>>, + pub(crate) redraw_sender: WakeSender, pub(crate) activation_sender: WakeSender, event_loop_proxy: CoreEventLoopProxy, device_events: Cell, @@ -188,14 +188,14 @@ pub struct EventLoop { loop_running: bool, event_loop: Loop<'static, EventLoopState>, event_processor: EventProcessor, - redraw_receiver: PeekableReceiver, + redraw_receiver: PeekableReceiver, activation_receiver: PeekableReceiver, /// The current state of the event loop. state: EventLoopState, } -pub(crate) type ActivationItem = (WindowId, winit_core::event_loop::AsyncRequestSerial); +pub(crate) type ActivationItem = (SurfaceId, winit_core::event_loop::AsyncRequestSerial); #[derive(Debug)] struct EventLoopState { @@ -991,8 +991,8 @@ impl CookieResultExt for Result, E> { } } -pub(crate) fn mkwid(w: xproto::Window) -> winit_core::window::WindowId { - winit_core::window::WindowId::from_raw(w as _) +pub(crate) fn mkwid(w: xproto::Window) -> winit_core::window::SurfaceId { + winit_core::window::SurfaceId::from_raw(w as _) } pub(crate) fn mkdid(w: xinput::DeviceId) -> DeviceId { diff --git a/winit-x11/src/event_processor.rs b/winit-x11/src/event_processor.rs index eaf50260e4..e782495736 100644 --- a/winit-x11/src/event_processor.rs +++ b/winit-x11/src/event_processor.rs @@ -13,7 +13,7 @@ use winit_core::event::{ WindowEvent, }; use winit_core::keyboard::ModifiersState; -use winit_core::window::WindowId; +use winit_core::window::SurfaceId; use x11_dl::xinput2::{ self, XIDeviceEvent, XIEnterEvent, XIFocusInEvent, XIFocusOutEvent, XIHierarchyEvent, XILeaveEvent, XIModifierState, XIRawEvent, @@ -334,7 +334,7 @@ impl EventProcessor { F: Fn(&Arc) -> Ret, { let mut deleted = false; - let window_id = WindowId::from_raw(window_id as _); + let window_id = SurfaceId::from_raw(window_id as _); let result = self .target .windows @@ -784,7 +784,7 @@ impl EventProcessor { // In the event that the window's been destroyed without being dropped first, we // cleanup again here. - self.target.windows.borrow_mut().remove(&WindowId::from_raw(window as _)); + self.target.windows.borrow_mut().remove(&SurfaceId::from_raw(window as _)); // Since all XIM stuff needs to happen from the same thread, we destroy the input // context here instead of when dropping the window. @@ -936,7 +936,7 @@ impl EventProcessor { fn send_synthic_modifier_from_core( &mut self, - window_id: winit_core::window::WindowId, + window_id: winit_core::window::SurfaceId, state: u16, app: &mut dyn ApplicationHandler, ) { @@ -1553,7 +1553,7 @@ impl EventProcessor { fn update_mods_from_query( &mut self, - window_id: winit_core::window::WindowId, + window_id: winit_core::window::SurfaceId, app: &mut dyn ApplicationHandler, ) { let xkb_state = match self.xkb_context.state_mut() { @@ -1586,7 +1586,7 @@ impl EventProcessor { pub(crate) fn update_mods_from_core_event( &mut self, - window_id: winit_core::window::WindowId, + window_id: winit_core::window::SurfaceId, state: u16, app: &mut dyn ApplicationHandler, ) { @@ -1663,7 +1663,7 @@ impl EventProcessor { /// unless `force` is passed. The `force` should be passed when the active window changes. fn send_modifiers( &self, - window_id: winit_core::window::WindowId, + window_id: winit_core::window::SurfaceId, modifiers: ModifiersState, force: bool, app: &mut dyn ApplicationHandler, @@ -1678,7 +1678,7 @@ impl EventProcessor { fn handle_pressed_keys( target: &ActiveEventLoop, - window_id: winit_core::window::WindowId, + window_id: winit_core::window::SurfaceId, state: ElementState, xkb_context: &mut Context, app: &mut dyn ApplicationHandler, diff --git a/winit-x11/src/window.rs b/winit-x11/src/window.rs index 7dacfcd665..8427072b0b 100644 --- a/winit-x11/src/window.rs +++ b/winit-x11/src/window.rs @@ -22,7 +22,7 @@ use winit_core::monitor::{ use winit_core::window::{ CursorGrabMode, ImeCapabilities, ImeRequest as CoreImeRequest, ImeRequestError, ResizeDirection, Theme, UserAttentionType, Window as CoreWindow, WindowAttributes, - WindowButtons, WindowId, WindowLevel, + WindowButtons, SurfaceId, WindowLevel, }; use x11rb::connection::{Connection, RequestConnection}; use x11rb::properties::{WmHints, WmSizeHints, WmSizeHintsSpecification}; @@ -67,7 +67,7 @@ impl Window { } impl CoreWindow for Window { - fn id(&self) -> WindowId { + fn id(&self) -> SurfaceId { self.0.id() } @@ -427,7 +427,7 @@ pub struct UnownedWindow { cursor_visible: Mutex, ime_sender: Mutex, pub shared_state: Mutex, - redraw_sender: WakeSender, + redraw_sender: WakeSender, activation_sender: WakeSender, } macro_rules! leap { @@ -2211,8 +2211,8 @@ impl UnownedWindow { } #[inline] - pub fn id(&self) -> WindowId { - WindowId::from_raw(self.xwindow as _) + pub fn id(&self) -> SurfaceId { + SurfaceId::from_raw(self.xwindow as _) } pub(super) fn sync_counter_id(&self) -> Option { @@ -2221,7 +2221,7 @@ impl UnownedWindow { #[inline] pub fn request_redraw(&self) { - self.redraw_sender.send(WindowId::from_raw(self.xwindow as _)); + self.redraw_sender.send(SurfaceId::from_raw(self.xwindow as _)); } #[inline] diff --git a/winit/tests/send_objects.rs b/winit/tests/send_objects.rs index 48bfa3b94f..dbb0023929 100644 --- a/winit/tests/send_objects.rs +++ b/winit/tests/send_objects.rs @@ -18,7 +18,7 @@ fn window_builder_send() { #[test] fn ids_send() { - needs_send::(); + needs_send::(); needs_send::(); needs_send::(); } From fc7708023e5eaaacdc4612fd2c5125317d032e67 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Wed, 28 May 2025 18:37:02 -0400 Subject: [PATCH 03/18] reorganize orbital, wayland, and web backends --- winit-core/src/lib.rs | 1 - winit-core/src/window.rs | 309 +------------------------------- winit-orbital/src/window.rs | 139 +++++++------- winit-wayland/src/window/mod.rs | 213 +++++++++++----------- winit-web/src/window.rs | 164 ++++++++--------- 5 files changed, 264 insertions(+), 562 deletions(-) diff --git a/winit-core/src/lib.rs b/winit-core/src/lib.rs index 6a209fe292..89bc682164 100644 --- a/winit-core/src/lib.rs +++ b/winit-core/src/lib.rs @@ -18,7 +18,6 @@ pub mod event_loop; pub mod icon; pub mod keyboard; pub mod monitor; -pub mod surface; pub mod window; // `Instant` is not actually available on `wasm32-unknown-unknown`, the `std` implementation there diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index 86ab4c3e35..051cfd037a 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -813,136 +813,7 @@ impl rwh_06::HasWindowHandle for dyn Surface + '_ { /// /// **Web:** The [`Window`], which is represented by a `HTMLElementCanvas`, can /// not be closed by dropping the [`Window`]. -pub trait Window: AsAny + Send + Sync + fmt::Debug { - /// Returns an identifier unique to the window. - fn id(&self) -> SurfaceId; // * - - /// Returns the scale factor that can be used to map logical pixels to physical pixels, and - /// vice versa. - /// - /// Note that this value can change depending on user action (for example if the window is - /// moved to another screen); as such, tracking [`WindowEvent::ScaleFactorChanged`] events is - /// the most robust way to track the DPI you need to use to draw. - /// - /// This value may differ from [`MonitorHandleProvider::scale_factor`]. - /// - /// See the [`dpi`] crate for more information. - /// - /// ## Platform-specific - /// - /// The scale factor is calculated differently on different platforms: - /// - /// - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from - /// the display settings. While users are free to select any option they want, they're only - /// given a selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale - /// factor is global and changing it requires logging out. See [this article][windows_1] for - /// technical details. - /// - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific - /// displays. When available, the user may pick a per-monitor scaling factor from a set of - /// pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default, - /// but the specific value varies across devices. - /// - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. - /// Winit currently uses a three-pronged approach: - /// + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present. - /// + If not present, use the value set in `Xft.dpi` in Xresources. - /// + Otherwise, calculate the scale factor based on the millimeter monitor dimensions - /// provided by XRandR. - /// - /// If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use - /// the XRandR scaling method. Generally speaking, you should try to configure the - /// standard system variables to do what you want before resorting to - /// `WINIT_X11_SCALE_FACTOR`. - /// - **Wayland:** The scale factor is suggested by the compositor for each window individually - /// by using the wp-fractional-scale protocol if available. Falls back to integer-scale - /// factors otherwise. - /// - /// The monitor scale factor may differ from the window scale factor. - /// - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range - /// from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more - /// information. - /// - /// This uses the underlying `UIView`'s [`contentScaleFactor`]. - /// - **Android:** Scale factors are set by the manufacturer to the value that best suits the - /// device, and range from `1.0` to `4.0`. See [this article][android_1] for more information. - /// - /// This is currently unimplemented, and this function always returns 1.0. - /// - **Web:** The scale factor is the ratio between CSS pixels and the physical device pixels. - /// In other words, it is the value of [`window.devicePixelRatio`][web_1]. It is affected by - /// both the screen scaling and the browser zoom level and can go below `1.0`. - /// - **Orbital:** This is currently unimplemented, and this function always returns 1.0. - /// - /// [`WindowEvent::ScaleFactorChanged`]: crate::event::WindowEvent::ScaleFactorChanged - /// [windows_1]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows - /// [apple_1]: https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html - /// [apple_2]: https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/ - /// [android_1]: https://developer.android.com/training/multiscreen/screendensities - /// [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio - /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc - /// [`MonitorHandleProvider::scale_factor`]: crate::monitor::MonitorHandleProvider::scale_factor. - fn scale_factor(&self) -> f64; // * - - /// Queues a [`WindowEvent::RedrawRequested`] event to be emitted that aligns with the windowing - /// system drawing loop. - /// - /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with - /// OS-requested redraws (e.g. when a window gets resized). To improve the event delivery - /// consider using [`Window::pre_present_notify`] as described in docs. - /// - /// Applications should always aim to redraw whenever they receive a `RedrawRequested` event. - /// - /// There are no strong guarantees about when exactly a `RedrawRequest` event will be emitted - /// with respect to other events, since the requirements can vary significantly between - /// windowing systems. - /// - /// However as the event aligns with the windowing system drawing loop, it may not arrive in - /// same or even next event loop iteration. - /// - /// ## Platform-specific - /// - /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and - /// `RedrawRequested` is emitted in sync with any `WM_PAINT` messages. - /// - **Wayland:** The events are aligned with the frame callbacks when - /// [`Window::pre_present_notify`] is used. - /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the - /// `requestAnimationFrame`. - /// - /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested - fn request_redraw(&self); // * - - /// Notify the windowing system before presenting to the window. - /// - /// You should call this event after your drawing operations, but before you submit - /// the buffer to the display or commit your drawings. Doing so will help winit to properly - /// schedule and make assumptions about its internal state. For example, it could properly - /// throttle [`WindowEvent::RedrawRequested`]. - /// - /// ## Example - /// - /// This example illustrates how it looks with OpenGL, but it applies to other graphics - /// APIs and software rendering. - /// - /// ```no_run - /// # use winit_core::window::Window; - /// # fn swap_buffers() {} - /// # fn scope(window: &dyn Window) { - /// // Do the actual drawing with OpenGL. - /// - /// // Notify winit that we're about to submit buffer to the windowing system. - /// window.pre_present_notify(); - /// - /// // Submit buffer to the windowing system. - /// swap_buffers(); - /// # } - /// ``` - /// - /// ## Platform-specific - /// - /// - **Android / iOS / X11 / Web / Windows / macOS / Orbital:** Unsupported. - /// - **Wayland:** Schedules a frame callback to throttle [`WindowEvent::RedrawRequested`]. - /// - /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested - fn pre_present_notify(&self); // * - +pub trait Window: Surface { /// Reset the dead key state of the keyboard. /// /// This is useful when a dead key is bound to trigger an action. Then @@ -974,7 +845,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// as the window itself, this simply returns `(0, 0)`. /// /// [`outer_position`]: Self::outer_position - fn surface_position(&self) -> PhysicalPosition; // * + fn surface_position(&self) -> PhysicalPosition; /// The position of the top-left hand corner of the window relative to the top-left hand corner /// of the desktop. @@ -1020,62 +891,6 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform fn set_outer_position(&self, position: Position); - /// Returns the size of the window's render-able surface. - /// - /// This is the dimensions you should pass to things like Wgpu or Glutin when configuring the - /// surface for drawing. See [`WindowEvent::SurfaceResized`] for listening to changes to this - /// field. - /// - /// Note that to ensure that your content is not obscured by things such as notches or the title - /// bar, you will likely want to only draw important content inside a specific area of the - /// surface, see [`safe_area()`] for details. - /// - /// ## Platform-specific - /// - /// - **Web:** Returns the size of the canvas element. Doesn't account for CSS [`transform`]. - /// - /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform - /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized - /// [`safe_area()`]: Window::safe_area - fn surface_size(&self) -> PhysicalSize; // * - - /// Request the new size for the surface. - /// - /// On platforms where the size is entirely controlled by the user the - /// applied size will be returned immediately, resize event in such case - /// may not be generated. - /// - /// On platforms where resizing is disallowed by the windowing system, the current surface size - /// is returned immediately, and the user one is ignored. - /// - /// When `None` is returned, it means that the request went to the display system, - /// and the actual size will be delivered later with the [`WindowEvent::SurfaceResized`]. - /// - /// See [`Window::surface_size`] for more information about the values. - /// - /// The request could automatically un-maximize the window if it's maximized. - /// - /// ```no_run - /// # use dpi::{LogicalSize, PhysicalSize}; - /// # use winit_core::window::Window; - /// # fn scope(window: &dyn Window) { - /// // Specify the size in logical dimensions like this: - /// let _ = window.request_surface_size(LogicalSize::new(400.0, 200.0).into()); - /// - /// // Or specify the size in physical dimensions like this: - /// let _ = window.request_surface_size(PhysicalSize::new(400, 200).into()); - /// # } - /// ``` - /// - /// ## Platform-specific - /// - /// - **Web:** Sets the size of the canvas element. Doesn't account for CSS [`transform`]. - /// - /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized - /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform - #[must_use] - fn request_surface_size(&self, size: Size) -> Option>; // * - /// Returns the size of the entire window. /// /// These dimensions include window decorations like the title bar and borders. If you don't @@ -1195,23 +1010,6 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// - **iOS / Android:** Unsupported. fn set_title(&self, title: &str); - /// Change the window transparency state. - /// - /// This is just a hint that may not change anything about - /// the window transparency, however doing a mismatch between - /// the content of your window and this hint may result in - /// visual artifacts. - /// - /// The default value follows the [`WindowAttributes::with_transparent`]. - /// - /// ## Platform-specific - /// - /// - **macOS:** This will reset the window's background color. - /// - **Web / iOS / Android:** Unsupported. - /// - **X11:** Can only be set while building the window, with - /// [`WindowAttributes::with_transparent`]. - fn set_transparent(&self, transparent: bool); // * - /// Change the window blur state. /// /// If `true`, this will make the transparent window background blurry. @@ -1635,66 +1433,6 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// - **iOS / Android / x11 / Wayland / Web:** Unsupported. Always returns an empty string. fn title(&self) -> String; - /// Modifies the cursor icon of the window. - /// - /// ## Platform-specific - /// - /// - **iOS / Android / Orbital:** Unsupported. - /// - **Web:** Custom cursors have to be loaded and decoded first, until then the previous - /// cursor is shown. - fn set_cursor(&self, cursor: Cursor); // * - - /// Changes the position of the cursor in window coordinates. - /// - /// ```no_run - /// # use dpi::{LogicalPosition, PhysicalPosition}; - /// # use winit_core::window::Window; - /// # fn scope(window: &dyn Window) { - /// // Specify the position in logical dimensions like this: - /// window.set_cursor_position(LogicalPosition::new(400.0, 200.0).into()); - /// - /// // Or specify the position in physical dimensions like this: - /// window.set_cursor_position(PhysicalPosition::new(400, 200).into()); - /// # } - /// ``` - /// - /// ## Platform-specific - /// - /// - **Wayland**: Cursor must be in [`CursorGrabMode::Locked`]. - /// - **iOS / Android / Web / Orbital:** Always returns an [`RequestError::NotSupported`]. - fn set_cursor_position(&self, position: Position) -> Result<(), RequestError>; // * - - /// Set grabbing [mode][CursorGrabMode] on the cursor preventing it from leaving the window. - /// - /// ## Example - /// - /// First try confining the cursor, and if that fails, try locking it instead. - /// - /// ```no_run - /// # use winit_core::window::{CursorGrabMode, Window}; - /// # fn scope(window: &dyn Window) { - /// window - /// .set_cursor_grab(CursorGrabMode::Confined) - /// .or_else(|_e| window.set_cursor_grab(CursorGrabMode::Locked)) - /// .unwrap(); - /// # } - /// ``` - fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError>; // * - - /// Modifies the cursor's visibility. - /// - /// If `false`, this will hide the cursor. If `true`, this will show the cursor. - /// - /// ## Platform-specific - /// - /// - **Windows:** The cursor is only hidden within the confines of the window. - /// - **X11:** The cursor is only hidden within the confines of the window. - /// - **Wayland:** The cursor is only hidden within the confines of the window. - /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor - /// is outside of the window. - /// - **iOS / Android:** Unsupported. - fn set_cursor_visible(&self, visible: bool); // * - /// Moves the window with the left mouse button until the button is released. /// /// There's no guarantee that this will work unless the left mouse button was pressed @@ -1729,49 +1467,6 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug { /// /// [window menu]: https://en.wikipedia.org/wiki/Common_menus_in_Microsoft_Windows#System_menu fn show_window_menu(&self, position: Position); - - /// Modifies whether the window catches cursor events. - /// - /// If `true`, the window will catch the cursor events. If `false`, events are passed through - /// the window such that any other window behind it receives them. By default hittest is - /// enabled. - /// - /// ## Platform-specific - /// - /// - **iOS / Android / Web / Orbital:** Always returns an [`RequestError::NotSupported`]. - fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError>; - - /// Returns the monitor on which the window currently resides. - /// - /// Returns `None` if current monitor can't be detected. - fn current_monitor(&self) -> Option; - - /// Returns the list of all the monitors available on the system. - /// - /// This is the same as [`ActiveEventLoop::available_monitors`], and is provided for - /// convenience. - /// - /// [`ActiveEventLoop::available_monitors`]: crate::event_loop::ActiveEventLoop::available_monitors - fn available_monitors(&self) -> Box>; - - /// Returns the primary monitor of the system. - /// - /// Returns `None` if it can't identify any monitor as a primary one. - /// - /// This is the same as [`ActiveEventLoop::primary_monitor`], and is provided for convenience. - /// - /// ## Platform-specific - /// - /// - **Wayland:** Always returns `None`. - /// - /// [`ActiveEventLoop::primary_monitor`]: crate::event_loop::ActiveEventLoop::primary_monitor - fn primary_monitor(&self) -> Option; - - /// Get the raw-window-handle v0.6 display handle. - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle; - - /// Get the raw-window-handle v0.6 window handle. - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle; } impl_dyn_casting!(Window); diff --git a/winit-orbital/src/window.rs b/winit-orbital/src/window.rs index b9299a816d..6ffab64651 100644 --- a/winit-orbital/src/window.rs +++ b/winit-orbital/src/window.rs @@ -6,7 +6,7 @@ use dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size}; use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; -use winit_core::window::{self, Window as CoreWindow, SurfaceId}; +use winit_core::window::{self, Window as CoreWindow, Surface as CoreSurface, SurfaceId}; use crate::event_loop::{ActiveEventLoop, EventLoopProxy}; use crate::{RedoxSocket, WindowProperties}; @@ -156,15 +156,11 @@ impl Window { } } -impl CoreWindow for Window { +impl CoreSurface for Window { fn id(&self) -> SurfaceId { SurfaceId::from_raw(self.window_socket.fd) } - fn ime_capabilities(&self) -> Option { - None - } - #[inline] fn primary_monitor(&self) -> Option { None @@ -199,11 +195,80 @@ impl CoreWindow for Window { #[inline] fn pre_present_notify(&self) {} + #[inline] + fn surface_size(&self) -> PhysicalSize { + let mut buf: [u8; 4096] = [0; 4096]; + let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); + let properties = WindowProperties::new(path); + (properties.w, properties.h).into() + } + + #[inline] + fn request_surface_size(&self, size: Size) -> Option> { + let (w, h): (u32, u32) = size.to_physical::(self.scale_factor()).into(); + self.window_socket.write(format!("S,{w},{h}").as_bytes()).expect("failed to set size"); + None + } + + #[inline] + fn set_transparent(&self, transparent: bool) { + let _ = self.set_flag(ORBITAL_FLAG_TRANSPARENT, transparent); + } + + #[inline] + fn set_cursor(&self, _: Cursor) {} + + #[inline] + fn set_cursor_position(&self, _: Position) -> Result<(), RequestError> { + Err(NotSupportedError::new("set_cursor_position is not supported").into()) + } + + #[inline] + fn set_cursor_grab(&self, mode: window::CursorGrabMode) -> Result<(), RequestError> { + let (grab, relative) = match mode { + window::CursorGrabMode::None => (false, false), + window::CursorGrabMode::Confined => (true, false), + window::CursorGrabMode::Locked => (true, true), + }; + self.window_socket + .write(format!("M,G,{}", if grab { 1 } else { 0 }).as_bytes()) + .map_err(|err| os_error!(format!("{err}")))?; + self.window_socket + .write(format!("M,R,{}", if relative { 1 } else { 0 }).as_bytes()) + .map_err(|err| os_error!(format!("{err}")))?; + Ok(()) + } + + #[inline] + fn set_cursor_visible(&self, visible: bool) { + let _ = self.window_socket.write(format!("M,C,{}", if visible { 1 } else { 0 }).as_bytes()); + } + + #[inline] + fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), RequestError> { + Err(NotSupportedError::new("set_cursor_hittest is not supported").into()) + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } +} + +impl CoreWindow for Window { + #[inline] fn reset_dead_keys(&self) { // TODO? } + fn ime_capabilities(&self) -> Option { + None + } + #[inline] fn surface_position(&self) -> PhysicalPosition { // TODO: adjust for window decorations @@ -225,21 +290,6 @@ impl CoreWindow for Window { self.window_socket.write(format!("P,{x},{y}").as_bytes()).expect("failed to set position"); } - #[inline] - fn surface_size(&self) -> PhysicalSize { - let mut buf: [u8; 4096] = [0; 4096]; - let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); - let properties = WindowProperties::new(path); - (properties.w, properties.h).into() - } - - #[inline] - fn request_surface_size(&self, size: Size) -> Option> { - let (w, h): (u32, u32) = size.to_physical::(self.scale_factor()).into(); - self.window_socket.write(format!("S,{w},{h}").as_bytes()).expect("failed to set size"); - None - } - #[inline] fn outer_size(&self) -> PhysicalSize { // TODO: adjust for window decorations @@ -269,11 +319,6 @@ impl CoreWindow for Window { self.window_socket.write(format!("T,{title}").as_bytes()).expect("failed to set title"); } - #[inline] - fn set_transparent(&self, transparent: bool) { - let _ = self.set_flag(ORBITAL_FLAG_TRANSPARENT, transparent); - } - #[inline] fn set_blur(&self, _blur: bool) {} @@ -368,35 +413,6 @@ impl CoreWindow for Window { #[inline] fn request_user_attention(&self, _request_type: Option) {} - #[inline] - fn set_cursor(&self, _: Cursor) {} - - #[inline] - fn set_cursor_position(&self, _: Position) -> Result<(), RequestError> { - Err(NotSupportedError::new("set_cursor_position is not supported").into()) - } - - #[inline] - fn set_cursor_grab(&self, mode: window::CursorGrabMode) -> Result<(), RequestError> { - let (grab, relative) = match mode { - window::CursorGrabMode::None => (false, false), - window::CursorGrabMode::Confined => (true, false), - window::CursorGrabMode::Locked => (true, true), - }; - self.window_socket - .write(format!("M,G,{}", if grab { 1 } else { 0 }).as_bytes()) - .map_err(|err| os_error!(format!("{err}")))?; - self.window_socket - .write(format!("M,R,{}", if relative { 1 } else { 0 }).as_bytes()) - .map_err(|err| os_error!(format!("{err}")))?; - Ok(()) - } - - #[inline] - fn set_cursor_visible(&self, visible: bool) { - let _ = self.window_socket.write(format!("M,C,{}", if visible { 1 } else { 0 }).as_bytes()); - } - #[inline] fn drag_window(&self) -> Result<(), RequestError> { self.window_socket.write(b"D").map_err(|err| os_error!(format!("{err}")))?; @@ -424,11 +440,6 @@ impl CoreWindow for Window { #[inline] fn show_window_menu(&self, _position: Position) {} - #[inline] - fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), RequestError> { - Err(NotSupportedError::new("set_cursor_hittest is not supported").into()) - } - #[inline] fn set_enabled_buttons(&self, _buttons: window::WindowButtons) {} @@ -451,14 +462,6 @@ impl CoreWindow for Window { fn set_theme(&self, _theme: Option) {} fn set_content_protected(&self, _protected: bool) {} - - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } - - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } } impl rwh_06::HasWindowHandle for Window { diff --git a/winit-wayland/src/window/mod.rs b/winit-wayland/src/window/mod.rs index 66f9559813..b8d1f1101b 100644 --- a/winit-wayland/src/window/mod.rs +++ b/winit-wayland/src/window/mod.rs @@ -21,7 +21,7 @@ use winit_core::event_loop::AsyncRequestSerial; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, - UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons, SurfaceId, + UserAttentionType, Window as CoreWindow, Surface as CoreSurface, WindowAttributes, WindowButtons, SurfaceId, WindowLevel, }; @@ -282,7 +282,7 @@ impl rwh_06::HasDisplayHandle for Window { } } -impl CoreWindow for Window { +impl CoreSurface for Window { fn id(&self) -> SurfaceId { self.window_id } @@ -302,13 +302,115 @@ impl CoreWindow for Window { } } + fn pre_present_notify(&self) { + self.window_state.lock().unwrap().request_frame_callback(); + } + + fn surface_size(&self) -> PhysicalSize { + let window_state = self.window_state.lock().unwrap(); + let scale_factor = window_state.scale_factor(); + super::logical_to_physical_rounded(window_state.surface_size(), scale_factor) + } + + fn request_surface_size(&self, size: Size) -> Option> { + let mut window_state = self.window_state.lock().unwrap(); + let new_size = window_state.request_surface_size(size); + self.request_redraw(); + Some(new_size) + } + #[inline] - fn title(&self) -> String { - self.window_state.lock().unwrap().title().to_owned() + fn set_transparent(&self, transparent: bool) { + self.window_state.lock().unwrap().set_transparent(transparent); } - fn pre_present_notify(&self) { - self.window_state.lock().unwrap().request_frame_callback(); + #[inline] + fn scale_factor(&self) -> f64 { + self.window_state.lock().unwrap().scale_factor() + } + + fn set_cursor(&self, cursor: Cursor) { + let window_state = &mut self.window_state.lock().unwrap(); + + match cursor { + Cursor::Icon(icon) => window_state.set_cursor(icon), + Cursor::Custom(cursor) => window_state.set_custom_cursor(cursor), + } + } + + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { + let scale_factor = self.scale_factor(); + let position = position.to_logical(scale_factor); + self.window_state + .lock() + .unwrap() + .set_cursor_position(position) + // Request redraw on success, since the state is double buffered. + .map(|_| self.request_redraw()) + } + + fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { + self.window_state.lock().unwrap().set_cursor_grab(mode) + } + + fn set_cursor_visible(&self, visible: bool) { + self.window_state.lock().unwrap().set_cursor_visible(visible); + } + + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { + let surface = self.window.wl_surface(); + + if hittest { + surface.set_input_region(None); + Ok(()) + } else { + let region = Region::new(&*self.compositor).map_err(|err| os_error!(err))?; + region.add(0, 0, 0, 0); + surface.set_input_region(Some(region.wl_region())); + Ok(()) + } + } + + fn current_monitor(&self) -> Option { + let data = self.window.wl_surface().data::()?; + data.outputs() + .next() + .map(MonitorHandle::new) + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + } + + fn available_monitors(&self) -> Box> { + Box::new( + self.monitors + .lock() + .unwrap() + .clone() + .into_iter() + .map(|inner| CoreMonitorHandle(Arc::new(inner))), + ) + } + + fn primary_monitor(&self) -> Option { + // NOTE: There's no such concept on Wayland. + None + } + + /// Get the raw-window-handle v0.6 display handle. + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + /// Get the raw-window-handle v0.6 window handle. + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +impl CoreWindow for Window { + + #[inline] + fn title(&self) -> String { + self.window_state.lock().unwrap().title().to_owned() } fn reset_dead_keys(&self) { @@ -328,19 +430,6 @@ impl CoreWindow for Window { // Not possible. } - fn surface_size(&self) -> PhysicalSize { - let window_state = self.window_state.lock().unwrap(); - let scale_factor = window_state.scale_factor(); - super::logical_to_physical_rounded(window_state.surface_size(), scale_factor) - } - - fn request_surface_size(&self, size: Size) -> Option> { - let mut window_state = self.window_state.lock().unwrap(); - let new_size = window_state.request_surface_size(size); - self.request_redraw(); - Some(new_size) - } - fn outer_size(&self) -> PhysicalSize { let window_state = self.window_state.lock().unwrap(); let scale_factor = window_state.scale_factor(); @@ -382,11 +471,6 @@ impl CoreWindow for Window { self.window_state.lock().unwrap().set_title(new_title); } - #[inline] - fn set_transparent(&self, transparent: bool) { - self.window_state.lock().unwrap().set_transparent(transparent); - } - fn set_visible(&self, _visible: bool) { // Not possible on Wayland. } @@ -482,11 +566,6 @@ impl CoreWindow for Window { } } - #[inline] - fn scale_factor(&self) -> f64 { - self.window_state.lock().unwrap().scale_factor() - } - #[inline] fn set_blur(&self, blur: bool) { self.window_state.lock().unwrap().set_blur(blur); @@ -568,34 +647,6 @@ impl CoreWindow for Window { fn set_content_protected(&self, _protected: bool) {} - fn set_cursor(&self, cursor: Cursor) { - let window_state = &mut self.window_state.lock().unwrap(); - - match cursor { - Cursor::Icon(icon) => window_state.set_cursor(icon), - Cursor::Custom(cursor) => window_state.set_custom_cursor(cursor), - } - } - - fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { - let scale_factor = self.scale_factor(); - let position = position.to_logical(scale_factor); - self.window_state - .lock() - .unwrap() - .set_cursor_position(position) - // Request redraw on success, since the state is double buffered. - .map(|_| self.request_redraw()) - } - - fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { - self.window_state.lock().unwrap().set_cursor_grab(mode) - } - - fn set_cursor_visible(&self, visible: bool) { - self.window_state.lock().unwrap().set_cursor_visible(visible); - } - fn drag_window(&self) -> Result<(), RequestError> { self.window_state.lock().unwrap().drag_window() } @@ -609,54 +660,6 @@ impl CoreWindow for Window { let position = position.to_logical(scale_factor); self.window_state.lock().unwrap().show_window_menu(position); } - - fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { - let surface = self.window.wl_surface(); - - if hittest { - surface.set_input_region(None); - Ok(()) - } else { - let region = Region::new(&*self.compositor).map_err(|err| os_error!(err))?; - region.add(0, 0, 0, 0); - surface.set_input_region(Some(region.wl_region())); - Ok(()) - } - } - - fn current_monitor(&self) -> Option { - let data = self.window.wl_surface().data::()?; - data.outputs() - .next() - .map(MonitorHandle::new) - .map(|monitor| CoreMonitorHandle(Arc::new(monitor))) - } - - fn available_monitors(&self) -> Box> { - Box::new( - self.monitors - .lock() - .unwrap() - .clone() - .into_iter() - .map(|inner| CoreMonitorHandle(Arc::new(inner))), - ) - } - - fn primary_monitor(&self) -> Option { - // NOTE: There's no such concept on Wayland. - None - } - - /// Get the raw-window-handle v0.6 display handle. - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } - - /// Get the raw-window-handle v0.6 window handle. - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } } /// The request from the window to the event loop. diff --git a/winit-web/src/window.rs b/winit-web/src/window.rs index 2fdae63b53..6f1cd4006b 100644 --- a/winit-web/src/window.rs +++ b/winit-web/src/window.rs @@ -12,8 +12,8 @@ use winit_core::error::{NotSupportedError, RequestError}; use winit_core::icon::Icon; use winit_core::monitor::{Fullscreen, MonitorHandle as CoremMonitorHandle}; use winit_core::window::{ - CursorGrabMode, ImeRequestError, ResizeDirection, Theme, UserAttentionType, - Window as RootWindow, WindowAttributes, WindowButtons, SurfaceId, WindowLevel, + CursorGrabMode, ImeRequestError, ResizeDirection, Surface as RootSurface, SurfaceId, Theme, + UserAttentionType, Window as RootWindow, WindowAttributes, WindowButtons, WindowLevel, }; use crate::event_loop::ActiveEventLoop; @@ -102,7 +102,7 @@ impl Window { } } -impl RootWindow for Window { +impl RootSurface for Window { fn id(&self) -> SurfaceId { self.inner.queue(|inner| inner.id) } @@ -117,6 +117,86 @@ impl RootWindow for Window { fn pre_present_notify(&self) {} + fn surface_size(&self) -> PhysicalSize { + self.inner.queue(|inner| inner.canvas.surface_size()) + } + + fn request_surface_size(&self, size: Size) -> Option> { + self.inner.queue(|inner| { + let size = size.to_logical(self.scale_factor()); + backend::set_canvas_size( + inner.canvas.document(), + inner.canvas.raw(), + inner.canvas.style(), + size, + ); + None + }) + } + + fn set_transparent(&self, _: bool) {} + + fn set_cursor(&self, cursor: Cursor) { + self.inner.dispatch(move |inner| inner.canvas.cursor.set_cursor(cursor)) + } + + fn set_cursor_position(&self, _: Position) -> Result<(), RequestError> { + Err(NotSupportedError::new("set_cursor_position is not supported").into()) + } + + fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { + Ok(self.inner.queue(|inner| { + match mode { + CursorGrabMode::None => inner.canvas.document().exit_pointer_lock(), + CursorGrabMode::Locked => lock::request_pointer_lock( + inner.canvas.navigator(), + inner.canvas.document(), + inner.canvas.raw(), + ), + CursorGrabMode::Confined => { + return Err(NotSupportedError::new("confined cursor mode is not supported")) + }, + } + + Ok(()) + })?) + } + + fn set_cursor_visible(&self, visible: bool) { + self.inner.dispatch(move |inner| inner.canvas.cursor.set_cursor_visible(visible)) + } + + fn set_cursor_hittest(&self, _: bool) -> Result<(), RequestError> { + Err(NotSupportedError::new("set_cursor_hittest is not supported").into()) + } + + fn current_monitor(&self) -> Option { + Some(self.inner.queue(|inner| inner.monitor.current_monitor()).into()) + } + + fn available_monitors(&self) -> Box> { + Box::new( + self.inner + .queue(|inner| inner.monitor.available_monitors()) + .into_iter() + .map(CoremMonitorHandle::from), + ) + } + + fn primary_monitor(&self) -> Option { + self.inner.queue(|inner| inner.monitor.primary_monitor()).map(CoremMonitorHandle::from) + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +impl RootWindow for Window { fn reset_dead_keys(&self) { // Not supported } @@ -142,23 +222,6 @@ impl RootWindow for Window { }) } - fn surface_size(&self) -> PhysicalSize { - self.inner.queue(|inner| inner.canvas.surface_size()) - } - - fn request_surface_size(&self, size: Size) -> Option> { - self.inner.queue(|inner| { - let size = size.to_logical(self.scale_factor()); - backend::set_canvas_size( - inner.canvas.document(), - inner.canvas.raw(), - inner.canvas.style(), - size, - ); - None - }) - } - fn outer_size(&self) -> PhysicalSize { // Note: the canvas element has no window decorations, so this is equal to `surface_size`. self.surface_size() @@ -228,8 +291,6 @@ impl RootWindow for Window { self.inner.queue(|inner| inner.canvas.set_attribute("alt", title)) } - fn set_transparent(&self, _: bool) {} - fn set_blur(&self, _: bool) {} fn set_visible(&self, _: bool) { @@ -350,36 +411,6 @@ impl RootWindow for Window { String::new() } - fn set_cursor(&self, cursor: Cursor) { - self.inner.dispatch(move |inner| inner.canvas.cursor.set_cursor(cursor)) - } - - fn set_cursor_position(&self, _: Position) -> Result<(), RequestError> { - Err(NotSupportedError::new("set_cursor_position is not supported").into()) - } - - fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { - Ok(self.inner.queue(|inner| { - match mode { - CursorGrabMode::None => inner.canvas.document().exit_pointer_lock(), - CursorGrabMode::Locked => lock::request_pointer_lock( - inner.canvas.navigator(), - inner.canvas.document(), - inner.canvas.raw(), - ), - CursorGrabMode::Confined => { - return Err(NotSupportedError::new("confined cursor mode is not supported")) - }, - } - - Ok(()) - })?) - } - - fn set_cursor_visible(&self, visible: bool) { - self.inner.dispatch(move |inner| inner.canvas.cursor.set_cursor_visible(visible)) - } - fn drag_window(&self) -> Result<(), RequestError> { Err(NotSupportedError::new("drag_window is not supported").into()) } @@ -389,35 +420,6 @@ impl RootWindow for Window { } fn show_window_menu(&self, _: Position) {} - - fn set_cursor_hittest(&self, _: bool) -> Result<(), RequestError> { - Err(NotSupportedError::new("set_cursor_hittest is not supported").into()) - } - - fn current_monitor(&self) -> Option { - Some(self.inner.queue(|inner| inner.monitor.current_monitor()).into()) - } - - fn available_monitors(&self) -> Box> { - Box::new( - self.inner - .queue(|inner| inner.monitor.available_monitors()) - .into_iter() - .map(CoremMonitorHandle::from), - ) - } - - fn primary_monitor(&self) -> Option { - self.inner.queue(|inner| inner.monitor.primary_monitor()).map(CoremMonitorHandle::from) - } - - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } - - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } } impl rwh_06::HasWindowHandle for Window { From 0cc4d9955d6c8e4a1d79b1c2fc92af5c5e74519d Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Wed, 28 May 2025 18:54:29 -0400 Subject: [PATCH 04/18] reorganize X11 --- winit-x11/src/window.rs | 134 +++++++++++++++++++++------------------- 1 file changed, 70 insertions(+), 64 deletions(-) diff --git a/winit-x11/src/window.rs b/winit-x11/src/window.rs index 8427072b0b..c9d8c215d4 100644 --- a/winit-x11/src/window.rs +++ b/winit-x11/src/window.rs @@ -21,8 +21,8 @@ use winit_core::monitor::{ }; use winit_core::window::{ CursorGrabMode, ImeCapabilities, ImeRequest as CoreImeRequest, ImeRequestError, - ResizeDirection, Theme, UserAttentionType, Window as CoreWindow, WindowAttributes, - WindowButtons, SurfaceId, WindowLevel, + ResizeDirection, Surface as CoreSurface, SurfaceId, Theme, UserAttentionType, + Window as CoreWindow, WindowAttributes, WindowButtons, WindowLevel, }; use x11rb::connection::{Connection, RequestConnection}; use x11rb::properties::{WmHints, WmSizeHints, WmSizeHintsSpecification}; @@ -66,7 +66,7 @@ impl Window { } } -impl CoreWindow for Window { +impl CoreSurface for Window { fn id(&self) -> SurfaceId { self.0.id() } @@ -83,6 +83,65 @@ impl CoreWindow for Window { self.0.pre_present_notify() } + fn surface_size(&self) -> PhysicalSize { + self.0.surface_size() + } + + fn request_surface_size(&self, size: Size) -> Option> { + self.0.request_surface_size(size) + } + + fn set_transparent(&self, transparent: bool) { + self.0.set_transparent(transparent); + } + + fn set_cursor(&self, cursor: Cursor) { + self.0.set_cursor(cursor); + } + + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { + self.0.set_cursor_position(position) + } + + fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { + self.0.set_cursor_grab(mode) + } + + fn set_cursor_visible(&self, visible: bool) { + self.0.set_cursor_visible(visible); + } + + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { + self.0.set_cursor_hittest(hittest) + } + + fn current_monitor(&self) -> Option { + self.0.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + } + + fn available_monitors(&self) -> Box> { + Box::new( + self.0 + .available_monitors() + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + } + + fn primary_monitor(&self) -> Option { + self.0.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +impl CoreWindow for Window { fn reset_dead_keys(&self) { winit_common::xkb::reset_dead_keys(); } @@ -99,14 +158,6 @@ impl CoreWindow for Window { self.0.set_outer_position(position) } - fn surface_size(&self) -> PhysicalSize { - self.0.surface_size() - } - - fn request_surface_size(&self, size: Size) -> Option> { - self.0.request_surface_size(size) - } - fn outer_size(&self) -> PhysicalSize { self.0.outer_size() } @@ -135,10 +186,6 @@ impl CoreWindow for Window { self.0.set_title(title); } - fn set_transparent(&self, transparent: bool) { - self.0.set_transparent(transparent); - } - fn set_blur(&self, blur: bool) { self.0.set_blur(blur); } @@ -247,22 +294,6 @@ impl CoreWindow for Window { self.0.title() } - fn set_cursor(&self, cursor: Cursor) { - self.0.set_cursor(cursor); - } - - fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { - self.0.set_cursor_position(position) - } - - fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { - self.0.set_cursor_grab(mode) - } - - fn set_cursor_visible(&self, visible: bool) { - self.0.set_cursor_visible(visible); - } - fn drag_window(&self) -> Result<(), RequestError> { self.0.drag_window() } @@ -274,35 +305,6 @@ impl CoreWindow for Window { fn show_window_menu(&self, position: Position) { self.0.show_window_menu(position); } - - fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { - self.0.set_cursor_hittest(hittest) - } - - fn current_monitor(&self) -> Option { - self.0.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) - } - - fn available_monitors(&self) -> Box> { - Box::new( - self.0 - .available_monitors() - .into_iter() - .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), - ) - } - - fn primary_monitor(&self) -> Option { - self.0.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) - } - - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } - - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } } impl rwh_06::HasDisplayHandle for Window { @@ -1238,10 +1240,14 @@ impl UnownedWindow { let old_surface_size = PhysicalSize::new(width, height); let surface_size = Arc::new(Mutex::new(PhysicalSize::new(new_width, new_height))); - app.window_event(event_loop, self.id(), WindowEvent::ScaleFactorChanged { - scale_factor: new_monitor.scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), - }); + app.window_event( + event_loop, + self.id(), + WindowEvent::ScaleFactorChanged { + scale_factor: new_monitor.scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), + }, + ); let new_surface_size = *surface_size.lock().unwrap(); drop(surface_size); From be8bb9157b638a15d2ebcac56b896e01b7d345de Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Wed, 28 May 2025 19:39:32 -0400 Subject: [PATCH 05/18] Implement downcasting function from `Surface` to `Window` et al. --- winit-core/src/lib.rs | 1 + winit-core/src/window.rs | 50 +++++++++++++++++++++++++++++++++ winit-orbital/src/window.rs | 3 ++ winit-wayland/src/window/mod.rs | 3 ++ winit-web/src/window.rs | 3 ++ winit-x11/src/window.rs | 3 ++ 6 files changed, 63 insertions(+) diff --git a/winit-core/src/lib.rs b/winit-core/src/lib.rs index 89bc682164..1136b97bc2 100644 --- a/winit-core/src/lib.rs +++ b/winit-core/src/lib.rs @@ -18,6 +18,7 @@ pub mod event_loop; pub mod icon; pub mod keyboard; pub mod monitor; +#[macro_use] pub mod window; // `Instant` is not actually available on `wasm32-unknown-unknown`, the `std` implementation there diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index 051cfd037a..b5366198e3 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -461,6 +461,12 @@ impl_dyn_casting!(PlatformWindowAttributes); /// /// The surface is closed when dropped. pub trait Surface: AsAny + Send + Sync + fmt::Debug { + /// Attempts to downcast this surface to a core surface type, e.g. [`Window`]. + fn try_downcast(&self) -> Option>; + + /// Attempts to downcast this surface mutably to a core surface type, e.g. [`Window`]. + fn try_downcast_mut(&mut self) -> Option>; + /// Returns an identifier unique to the window. fn id(&self) -> SurfaceId; @@ -1965,3 +1971,47 @@ mod tests { .is_some()); } } +/// Dynamic reference to one of the common surface traits. +pub enum SurfaceDowncastRef<'a> { + /// A toplevel window, see [`Window`] for details. + Window(&'a dyn Window), +} + +/// Dynamic mutable reference to one of the common surface traits. +pub enum SurfaceDowncastMut<'a> { + /// A toplevel window, see [`Window`] for details. + Window(&'a mut dyn Window), +} + +/// Helper macro for implementing [`Surface::try_downcast`] and [`Surface::try_downcast_mut`]. +/// ## Syntax +/// Use the names of variants of [`SurfaceDowncastRef`] or [`SurfaceDowncastMut`] to return that type: +/// ```ignore +/// impl_surface_downcast!(Window); +/// ``` +/// You may also use the special identifier `None` to cause the downcast to fail. +/// ```ignore +/// impl_surface_downcast!(None); +/// ``` +#[macro_export] +macro_rules! impl_surface_downcast { + (None) => { + fn try_downcast(&self) -> Option<$crate::window::SurfaceDowncastRef<'_>> { + None + } + + fn try_downcast_mut(&mut self) -> Option<$crate::window::SurfaceDowncastMut<'_>> { + None + } + }; + ($variant:ident) => { + fn try_downcast(&self) -> Option<$crate::window::SurfaceDowncastRef<'_>> { + Some($crate::window::SurfaceDowncastRef::$variant(self)) + } + + fn try_downcast_mut(&mut self) -> Option<$crate::window::SurfaceDowncastMut<'_>> { + Some($crate::window::SurfaceDowncastMut::$variant(self)) + + } + }; +} diff --git a/winit-orbital/src/window.rs b/winit-orbital/src/window.rs index 6ffab64651..dbac7a6835 100644 --- a/winit-orbital/src/window.rs +++ b/winit-orbital/src/window.rs @@ -5,6 +5,7 @@ use std::sync::{Arc, Mutex}; use dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size}; use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; +use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{self, Window as CoreWindow, Surface as CoreSurface, SurfaceId}; @@ -157,6 +158,8 @@ impl Window { } impl CoreSurface for Window { + impl_surface_downcast!(Window); + fn id(&self) -> SurfaceId { SurfaceId::from_raw(self.window_socket.fd) } diff --git a/winit-wayland/src/window/mod.rs b/winit-wayland/src/window/mod.rs index b8d1f1101b..27073cb247 100644 --- a/winit-wayland/src/window/mod.rs +++ b/winit-wayland/src/window/mod.rs @@ -18,6 +18,7 @@ use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::event::{Ime, WindowEvent}; use winit_core::event_loop::AsyncRequestSerial; +use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, @@ -283,6 +284,8 @@ impl rwh_06::HasDisplayHandle for Window { } impl CoreSurface for Window { + impl_surface_downcast!(Window); + fn id(&self) -> SurfaceId { self.window_id } diff --git a/winit-web/src/window.rs b/winit-web/src/window.rs index 6f1cd4006b..f30074ea0f 100644 --- a/winit-web/src/window.rs +++ b/winit-web/src/window.rs @@ -10,6 +10,7 @@ use web_sys::HtmlCanvasElement; use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::icon::Icon; +use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoremMonitorHandle}; use winit_core::window::{ CursorGrabMode, ImeRequestError, ResizeDirection, Surface as RootSurface, SurfaceId, Theme, @@ -103,6 +104,8 @@ impl Window { } impl RootSurface for Window { + impl_surface_downcast!(Window); + fn id(&self) -> SurfaceId { self.inner.queue(|inner| inner.id) } diff --git a/winit-x11/src/window.rs b/winit-x11/src/window.rs index c9d8c215d4..c09176ad00 100644 --- a/winit-x11/src/window.rs +++ b/winit-x11/src/window.rs @@ -16,6 +16,7 @@ use winit_core::error::{NotSupportedError, RequestError}; use winit_core::event::{SurfaceSizeWriter, WindowEvent}; use winit_core::event_loop::AsyncRequestSerial; use winit_core::icon::RgbaIcon; +use winit_core::impl_surface_downcast; use winit_core::monitor::{ Fullscreen, MonitorHandle as CoreMonitorHandle, MonitorHandleProvider, VideoMode, }; @@ -67,6 +68,8 @@ impl Window { } impl CoreSurface for Window { + impl_surface_downcast!(Window); + fn id(&self) -> SurfaceId { self.0.id() } From f39377d897d490e86d31fa7792fe2b03a01035c4 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Wed, 28 May 2025 20:55:24 -0400 Subject: [PATCH 06/18] Implement upcasting using a similar mechanism to AsAny --- winit-core/src/window.rs | 49 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index b5366198e3..93d7cb0d44 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -819,7 +819,7 @@ impl rwh_06::HasWindowHandle for dyn Surface + '_ { /// /// **Web:** The [`Window`], which is represented by a `HTMLElementCanvas`, can /// not be closed by dropping the [`Window`]. -pub trait Window: Surface { +pub trait Window: AsSurface { /// Reset the dead key state of the keyboard. /// /// This is useful when a dead key is bound to trigger an action. Then @@ -1971,18 +1971,65 @@ mod tests { .is_some()); } } +// Implementation trait to allow upcasting to [`Surface`]. +// This trait can be safely removed once MSRV hits Rust 1.86, similar to `AsAny`. +#[doc(hidden)] +pub trait AsSurface: Surface { + #[doc(hidden)] + fn __as_surface(&self) -> &dyn Surface; + #[doc(hidden)] + fn __as_surface_mut(&mut self) -> &mut dyn Surface; + #[doc(hidden)] + fn __into_surface(self: Box) -> Box; +} + +impl AsSurface for T { + fn __as_surface(&self) -> &dyn Surface { + self + } + + fn __as_surface_mut(&mut self) -> &mut dyn Surface { + self + } + + fn __into_surface(self: Box) -> Box { + self + } +} + /// Dynamic reference to one of the common surface traits. +#[non_exhaustive] pub enum SurfaceDowncastRef<'a> { /// A toplevel window, see [`Window`] for details. Window(&'a dyn Window), } +impl SurfaceDowncastRef<'_> { + /// Tries to cast this reference into a [`Window`]. + pub fn as_window(&self) -> Option<&'_ dyn Window> { + match self { + Self::Window(window) => Some(*window), + _ => None, + } + } +} + /// Dynamic mutable reference to one of the common surface traits. pub enum SurfaceDowncastMut<'a> { /// A toplevel window, see [`Window`] for details. Window(&'a mut dyn Window), } +impl SurfaceDowncastMut<'_> { + /// Tries to cast this reference into a [`Window`]. + pub fn as_window(&mut self) -> Option<&'_ mut dyn Window> { + match self { + Self::Window(window) => Some(*window), + _ => None, + } + } +} + /// Helper macro for implementing [`Surface::try_downcast`] and [`Surface::try_downcast_mut`]. /// ## Syntax /// Use the names of variants of [`SurfaceDowncastRef`] or [`SurfaceDowncastMut`] to return that type: From 9b49b5b054d71f30e35b2e0921ba852cee16ab93 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Thu, 3 Jul 2025 21:00:16 -0400 Subject: [PATCH 07/18] hopefully fixes CI --- winit-core/src/window.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index 93d7cb0d44..f61c7affb3 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -15,15 +15,17 @@ use crate::error::RequestError; use crate::icon::Icon; use crate::monitor::{Fullscreen, MonitorHandle}; -/// Identifier of a window. Unique for each window. +/// Identifier of a surface. Unique for each surface. /// -/// Can be obtained with [`window.id()`][`Window::id`]. +/// Can be obtained with [`surface.id()`][`Window::id`]. /// -/// Whenever you receive an event specific to a window, this event contains a `WindowId` which you +/// Whenever you receive an event specific to a surface, this event contains a `SurfaceId` which you /// can then compare to the ids of your windows. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SurfaceId(usize); +pub type WindowId = SurfaceId; + impl SurfaceId { /// Convert the `WindowId` into the underlying integer. /// @@ -2009,7 +2011,7 @@ impl SurfaceDowncastRef<'_> { pub fn as_window(&self) -> Option<&'_ dyn Window> { match self { Self::Window(window) => Some(*window), - _ => None, + // _ => None, } } } @@ -2025,7 +2027,7 @@ impl SurfaceDowncastMut<'_> { pub fn as_window(&mut self) -> Option<&'_ mut dyn Window> { match self { Self::Window(window) => Some(*window), - _ => None, + // _ => None, } } } From 2850fb9923b430c319cd66328974509033c20fa1 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Mon, 7 Jul 2025 10:18:01 -0400 Subject: [PATCH 08/18] fix docs --- winit-core/src/event.rs | 6 +++--- winit-core/src/window.rs | 8 ++++---- winit/src/lib.rs | 10 +++++----- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/winit-core/src/event.rs b/winit-core/src/event.rs index 42c37c8d1c..cd10a8eb56 100644 --- a/winit-core/src/event.rs +++ b/winit-core/src/event.rs @@ -53,7 +53,7 @@ pub enum WindowEvent { /// This event will not necessarily be emitted upon window creation, query /// [`Window::surface_size`] if you need to determine the surface's initial size. /// - /// [`Window::surface_size`]: crate::window::Window::surface_size + /// [`Surface::surface_size`]: crate::window::Surface::surface_size SurfaceResized(PhysicalSize), /// The position of the window has changed. @@ -352,11 +352,11 @@ pub enum WindowEvent { /// window is resized to the value suggested by the OS, but it can be changed to any value. /// /// This event will not necessarily be emitted upon window creation, query - /// [`Window::scale_factor`] if you need to determine the window's initial scale factor. + /// [`Surface::scale_factor`] if you need to determine the window's initial scale factor. /// /// For more information about DPI in general, see the [`dpi`] crate. /// - /// [`Window::scale_factor`]: crate::window::Window::scale_factor + /// [`Surface::scale_factor`]: crate::window::Surface::scale_factor ScaleFactorChanged { scale_factor: f64, /// Handle to update surface size during scale changes. diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index f61c7affb3..c0b2bd60f7 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -24,17 +24,18 @@ use crate::monitor::{Fullscreen, MonitorHandle}; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SurfaceId(usize); +/// Alias to `SurfaceId` for compatibility with older versions of `winit`. pub type WindowId = SurfaceId; impl SurfaceId { - /// Convert the `WindowId` into the underlying integer. + /// Convert the `SurfaceId` into the underlying integer. /// /// This is useful if you need to pass the ID across an FFI boundary, or store it in an atomic. pub const fn into_raw(self) -> usize { self.0 } - /// Construct a `WindowId` from the underlying integer. + /// Construct a `SurfaceId` from the underlying integer. /// /// This should only be called with integers returned from [`WindowId::into_raw`]. pub const fn from_raw(id: usize) -> Self { @@ -460,7 +461,7 @@ pub trait PlatformWindowAttributes: AsAny + std::fmt::Debug + Send + Sync { impl_dyn_casting!(PlatformWindowAttributes); /// Represents a drawable, resizable surface that is visible on-screen. -/// +/// /// The surface is closed when dropped. pub trait Surface: AsAny + Send + Sync + fmt::Debug { /// Attempts to downcast this surface to a core surface type, e.g. [`Window`]. @@ -2060,7 +2061,6 @@ macro_rules! impl_surface_downcast { fn try_downcast_mut(&mut self) -> Option<$crate::window::SurfaceDowncastMut<'_>> { Some($crate::window::SurfaceDowncastMut::$variant(self)) - } }; } diff --git a/winit/src/lib.rs b/winit/src/lib.rs index a10da9addb..7ab8b4fa02 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -112,7 +112,7 @@ //! ``` //! //! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be -//! compared to the value returned by [`Window::id()`] to determine which [`Window`] +//! compared to the value returned by [`Surface::id()`] to determine which [`Window`] //! dispatched the event. //! //! # Drawing on the window @@ -147,7 +147,7 @@ //! //! Most of the functionality in Winit works with surface coordinates, so usually you only need to //! concern yourself with those. In case you need to convert to some other coordinate system, Winit -//! provides [`Window::surface_position`] and [`Window::surface_size`] to describe the surface's +//! provides [`Window::surface_position`] and [`Surface::surface_size`] to describe the surface's //! location in window coordinates, and Winit provides [`Window::outer_position`] and //! [`Window::outer_size`] to describe the window's location in desktop coordinates. Using these //! methods, you should be able to convert a position in one coordinate system to another. @@ -163,7 +163,7 @@ //! mobile. #![doc = concat!("\n\n", include_str!("../docs/res/coordinate-systems-mobile.svg"), "\n\n")] // Rustfmt removes \n, adding them like this works around that. //! [`Window::surface_position`]: crate::window::Window::surface_position -//! [`Window::surface_size`]: crate::window::Window::surface_size +//! [`Surface::surface_size`]: crate::window::Surface::surface_size //! [`Window::outer_position`]: crate::window::Window::outer_position //! [`Window::outer_size`]: crate::window::Window::outer_size //! @@ -184,7 +184,7 @@ //! can be found by calling [`window.scale_factor()`]. //! //! [`ScaleFactorChanged`]: event::WindowEvent::ScaleFactorChanged -//! [`window.scale_factor()`]: window::Window::scale_factor +//! [`window.scale_factor()`]: window::Surface::scale_factor //! //! # Cargo Features //! @@ -263,7 +263,7 @@ //! [`WindowId`]: window::WindowId //! [`WindowAttributes`]: window::WindowAttributes //! [`create_window`]: event_loop::ActiveEventLoop::create_window -//! [`Window::id()`]: window::Window::id +//! [`Surface::id()`]: window::Surface::id //! [`WindowEvent`]: event::WindowEvent //! [`DeviceEvent`]: event::DeviceEvent //! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle From 9415609312e66c0d194ac915978b6cce280e5731 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Mon, 7 Jul 2025 10:40:44 -0400 Subject: [PATCH 09/18] reorganize win32 --- winit-win32/src/window.rs | 356 +++++++++++++++++++------------------- 1 file changed, 181 insertions(+), 175 deletions(-) diff --git a/winit-win32/src/window.rs b/winit-win32/src/window.rs index 4b1d455139..985f32663c 100644 --- a/winit-win32/src/window.rs +++ b/winit-win32/src/window.rs @@ -49,11 +49,12 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{ use winit_core::cursor::Cursor; use winit_core::error::RequestError; use winit_core::icon::{Icon, RgbaIcon}; +use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle, MonitorHandleProvider}; use winit_core::window::{ - CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, - UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons, WindowId, - WindowLevel, + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, + Surface as CoreSurface, Theme, UserAttentionType, Window as CoreWindow, WindowAttributes, + WindowButtons, WindowId, WindowLevel, }; use crate::dark_mode::try_theme; @@ -413,23 +414,194 @@ impl rwh_06::HasWindowHandle for Window { } } -impl CoreWindow for Window { - fn set_title(&self, text: &str) { - let wide_text = util::encode_wide(text); +impl CoreSurface for Window { + impl_surface_downcast!(Window); + + fn set_transparent(&self, transparent: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window.hwnd(), |f| { + f.set(WindowFlags::TRANSPARENT, transparent) + }); + }); + } + + fn request_redraw(&self) { + // NOTE: mark that we requested a redraw to handle requests during `WM_PAINT` handling. + self.window_state.lock().unwrap().redraw_requested = true; unsafe { - SetWindowTextW(self.hwnd(), wide_text.as_ptr()); + RedrawWindow(self.hwnd(), ptr::null(), ptr::null_mut(), RDW_INTERNALPAINT); } } - fn set_transparent(&self, transparent: bool) { + fn pre_present_notify(&self) {} + + fn surface_size(&self) -> PhysicalSize { + let mut rect: RECT = unsafe { mem::zeroed() }; + if unsafe { GetClientRect(self.hwnd(), &mut rect) } == false.into() { + panic!( + "Unexpected GetClientRect failure: please report this error to \ + rust-windowing/winit" + ) + } + PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32) + } + + fn request_surface_size(&self, size: Size) -> Option> { + let scale_factor = self.scale_factor(); + let physical_size = size.to_physical::(scale_factor); + + let window_flags = self.window_state_lock().window_flags; + window_flags.set_size(self.hwnd(), physical_size); + + if physical_size != self.surface_size() { + let window_state = Arc::clone(&self.window_state); + let window = self.window; + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window.hwnd(), |f| { + f.set(WindowFlags::MAXIMIZED, false) + }); + }); + } + + None + } + + fn set_cursor(&self, cursor: Cursor) { + match cursor { + Cursor::Icon(icon) => { + self.window_state_lock().mouse.selected_cursor = SelectedCursor::Named(icon); + self.thread_executor.execute_in_thread(move || unsafe { + let cursor = LoadCursorW(ptr::null_mut(), util::to_windows_cursor(icon)); + SetCursor(cursor); + }); + }, + Cursor::Custom(cursor) => { + let cursor = match cursor.cast_ref::() { + Some(cursor) => cursor, + None => return, + }; + self.window_state_lock().mouse.selected_cursor = + SelectedCursor::Custom(cursor.0.clone()); + let handle = cursor.0.clone(); + self.thread_executor.execute_in_thread(move || unsafe { + SetCursor(handle.as_raw_handle()); + }); + }, + } + } + + fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + let (tx, rx) = channel(); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + let result = window_state + .lock() + .unwrap() + .mouse + .set_cursor_flags(window.hwnd(), |f| { + f.set(CursorFlags::GRABBED, mode != CursorGrabMode::None); + f.set(CursorFlags::LOCKED, mode == CursorGrabMode::Locked); + }) + .map_err(|err| os_error!(err).into()); + let _ = tx.send(result); + }); + + rx.recv().unwrap() + } + + fn set_cursor_visible(&self, visible: bool) { let window = self.window; let window_state = Arc::clone(&self.window_state); + let (tx, rx) = channel(); + self.thread_executor.execute_in_thread(move || { let _ = &window; + let result = window_state + .lock() + .unwrap() + .mouse + .set_cursor_flags(window.hwnd(), |f| f.set(CursorFlags::HIDDEN, !visible)) + .map_err(|e| e.to_string()); + let _ = tx.send(result); + }); + rx.recv().unwrap().ok(); + } + + fn scale_factor(&self) -> f64 { + self.window_state_lock().scale_factor + } + + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { + let scale_factor = self.scale_factor(); + let (x, y) = position.to_physical::(scale_factor).into(); + + let mut point = POINT { x, y }; + unsafe { + if ClientToScreen(self.hwnd(), &mut point) == false.into() { + return Err(os_error!(io::Error::last_os_error()).into()); + } + if SetCursorPos(point.x, point.y) == false.into() { + return Err(os_error!(io::Error::last_os_error()).into()); + } + } + Ok(()) + } + + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + self.thread_executor.execute_in_thread(move || { WindowState::set_window_flags(window_state.lock().unwrap(), window.hwnd(), |f| { - f.set(WindowFlags::TRANSPARENT, transparent) + f.set(WindowFlags::IGNORE_CURSOR_EVENT, !hittest) }); }); + + Ok(()) + } + + fn id(&self) -> WindowId { + WindowId::from_raw(self.hwnd() as usize) + } + + + fn current_monitor(&self) -> Option { + Some(CoreMonitorHandle(Arc::new(monitor::current_monitor(self.hwnd())))) + } + + fn available_monitors(&self) -> Box> { + Box::new( + monitor::available_monitors() + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + } + + fn primary_monitor(&self) -> Option { + Some(CoreMonitorHandle(Arc::new(monitor::primary_monitor()))) + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } +} + +impl CoreWindow for Window { + fn set_title(&self, text: &str) { + let wide_text = util::encode_wide(text); + unsafe { + SetWindowTextW(self.hwnd(), wide_text.as_ptr()); + } } fn set_blur(&self, _blur: bool) {} @@ -449,16 +621,6 @@ impl CoreWindow for Window { Some(unsafe { IsWindowVisible(self.window.hwnd()) == 1 }) } - fn request_redraw(&self) { - // NOTE: mark that we requested a redraw to handle requests during `WM_PAINT` handling. - self.window_state.lock().unwrap().redraw_requested = true; - unsafe { - RedrawWindow(self.hwnd(), ptr::null(), ptr::null_mut(), RDW_INTERNALPAINT); - } - } - - fn pre_present_notify(&self) {} - fn outer_position(&self) -> Result, RequestError> { util::WindowArea::Outer .get_rect(self.hwnd()) @@ -506,17 +668,6 @@ impl CoreWindow for Window { } } - fn surface_size(&self) -> PhysicalSize { - let mut rect: RECT = unsafe { mem::zeroed() }; - if unsafe { GetClientRect(self.hwnd(), &mut rect) } == false.into() { - panic!( - "Unexpected GetClientRect failure: please report this error to \ - rust-windowing/winit" - ) - } - PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32) - } - fn outer_size(&self) -> PhysicalSize { util::WindowArea::Outer .get_rect(self.hwnd()) @@ -526,27 +677,6 @@ impl CoreWindow for Window { .unwrap() } - fn request_surface_size(&self, size: Size) -> Option> { - let scale_factor = self.scale_factor(); - let physical_size = size.to_physical::(scale_factor); - - let window_flags = self.window_state_lock().window_flags; - window_flags.set_size(self.hwnd(), physical_size); - - if physical_size != self.surface_size() { - let window_state = Arc::clone(&self.window_state); - let window = self.window; - self.thread_executor.execute_in_thread(move || { - let _ = &window; - WindowState::set_window_flags(window_state.lock().unwrap(), window.hwnd(), |f| { - f.set(WindowFlags::MAXIMIZED, false) - }); - }); - } - - None - } - fn safe_area(&self) -> PhysicalInsets { PhysicalInsets::new(0, 0, 0, 0) } @@ -621,90 +751,6 @@ impl CoreWindow for Window { buttons } - fn set_cursor(&self, cursor: Cursor) { - match cursor { - Cursor::Icon(icon) => { - self.window_state_lock().mouse.selected_cursor = SelectedCursor::Named(icon); - self.thread_executor.execute_in_thread(move || unsafe { - let cursor = LoadCursorW(ptr::null_mut(), util::to_windows_cursor(icon)); - SetCursor(cursor); - }); - }, - Cursor::Custom(cursor) => { - let cursor = match cursor.cast_ref::() { - Some(cursor) => cursor, - None => return, - }; - self.window_state_lock().mouse.selected_cursor = - SelectedCursor::Custom(cursor.0.clone()); - let handle = cursor.0.clone(); - self.thread_executor.execute_in_thread(move || unsafe { - SetCursor(handle.as_raw_handle()); - }); - }, - } - } - - fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), RequestError> { - let window = self.window; - let window_state = Arc::clone(&self.window_state); - let (tx, rx) = channel(); - - self.thread_executor.execute_in_thread(move || { - let _ = &window; - let result = window_state - .lock() - .unwrap() - .mouse - .set_cursor_flags(window.hwnd(), |f| { - f.set(CursorFlags::GRABBED, mode != CursorGrabMode::None); - f.set(CursorFlags::LOCKED, mode == CursorGrabMode::Locked); - }) - .map_err(|err| os_error!(err).into()); - let _ = tx.send(result); - }); - - rx.recv().unwrap() - } - - fn set_cursor_visible(&self, visible: bool) { - let window = self.window; - let window_state = Arc::clone(&self.window_state); - let (tx, rx) = channel(); - - self.thread_executor.execute_in_thread(move || { - let _ = &window; - let result = window_state - .lock() - .unwrap() - .mouse - .set_cursor_flags(window.hwnd(), |f| f.set(CursorFlags::HIDDEN, !visible)) - .map_err(|e| e.to_string()); - let _ = tx.send(result); - }); - rx.recv().unwrap().ok(); - } - - fn scale_factor(&self) -> f64 { - self.window_state_lock().scale_factor - } - - fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { - let scale_factor = self.scale_factor(); - let (x, y) = position.to_physical::(scale_factor).into(); - - let mut point = POINT { x, y }; - unsafe { - if ClientToScreen(self.hwnd(), &mut point) == false.into() { - return Err(os_error!(io::Error::last_os_error()).into()); - } - if SetCursorPos(point.x, point.y) == false.into() { - return Err(os_error!(io::Error::last_os_error()).into()); - } - } - Ok(()) - } - fn drag_window(&self) -> Result<(), RequestError> { unsafe { self.handle_os_dragging(HTCAPTION as WPARAM); @@ -736,22 +782,6 @@ impl CoreWindow for Window { } } - fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { - let window = self.window; - let window_state = Arc::clone(&self.window_state); - self.thread_executor.execute_in_thread(move || { - WindowState::set_window_flags(window_state.lock().unwrap(), window.hwnd(), |f| { - f.set(WindowFlags::IGNORE_CURSOR_EVENT, !hittest) - }); - }); - - Ok(()) - } - - fn id(&self) -> WindowId { - WindowId::from_raw(self.hwnd() as usize) - } - fn set_minimized(&self, minimized: bool) { let window = self.window; let window_state = Arc::clone(&self.window_state); @@ -985,22 +1015,6 @@ impl CoreWindow for Window { }); } - fn current_monitor(&self) -> Option { - Some(CoreMonitorHandle(Arc::new(monitor::current_monitor(self.hwnd())))) - } - - fn available_monitors(&self) -> Box> { - Box::new( - monitor::available_monitors() - .into_iter() - .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), - ) - } - - fn primary_monitor(&self) -> Option { - Some(CoreMonitorHandle(Arc::new(monitor::primary_monitor()))) - } - fn set_window_icon(&self, window_icon: Option) { if let Some(window_icon) = window_icon { self.set_icon(window_icon, IconType::Small); @@ -1155,14 +1169,6 @@ impl CoreWindow for Window { ); } } - - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } - - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } } pub(super) struct InitData<'a> { From a35cfb189cd41c15aa0bded1eef316b02f061853 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Mon, 7 Jul 2025 10:55:18 -0400 Subject: [PATCH 10/18] reorganize apple platforms --- winit-appkit/src/window.rs | 144 +++++++++++++++++---------------- winit-uikit/src/window.rs | 162 +++++++++++++++++++------------------ 2 files changed, 159 insertions(+), 147 deletions(-) diff --git a/winit-appkit/src/window.rs b/winit-appkit/src/window.rs index 515ac55f78..048227d585 100644 --- a/winit-appkit/src/window.rs +++ b/winit-appkit/src/window.rs @@ -11,10 +11,11 @@ use objc2_foundation::NSObject; use winit_core::cursor::Cursor; use winit_core::error::RequestError; use winit_core::icon::Icon; +use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ ImeCapabilities, ImeRequest, ImeRequestError, Theme, UserAttentionType, Window as CoreWindow, - WindowAttributes, WindowButtons, WindowId, WindowLevel, + Surface as CoreSurface, WindowAttributes, WindowButtons, WindowId, WindowLevel, }; use super::event_loop::ActiveEventLoop; @@ -92,7 +93,9 @@ impl rwh_06::HasWindowHandle for Window { } } -impl CoreWindow for Window { +impl CoreSurface for Window { + impl_surface_downcast!(Window); + fn id(&self) -> winit_core::window::WindowId { self.maybe_wait_on_main(|delegate| delegate.id()) } @@ -109,6 +112,76 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.pre_present_notify()); } + fn surface_size(&self) -> dpi::PhysicalSize { + self.maybe_wait_on_main(|delegate| delegate.surface_size()) + } + + fn request_surface_size(&self, size: Size) -> Option> { + self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size)) + } + + fn set_transparent(&self, transparent: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent)); + } + + fn set_cursor(&self, cursor: Cursor) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor)); + } + + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position)) + } + + fn set_cursor_grab( + &self, + mode: winit_core::window::CursorGrabMode, + ) -> Result<(), RequestError> { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode)) + } + + fn set_cursor_visible(&self, visible: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible)) + } + + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest)); + Ok(()) + } + + fn current_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn available_monitors(&self) -> Box> { + self.maybe_wait_on_main(|delegate| { + Box::new( + delegate + .available_monitors() + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + }) + } + + fn primary_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +impl CoreWindow for Window { + fn reset_dead_keys(&self) { self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys()); } @@ -125,14 +198,6 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.set_outer_position(position)); } - fn surface_size(&self) -> dpi::PhysicalSize { - self.maybe_wait_on_main(|delegate| delegate.surface_size()) - } - - fn request_surface_size(&self, size: Size) -> Option> { - self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size)) - } - fn outer_size(&self) -> dpi::PhysicalSize { self.maybe_wait_on_main(|delegate| delegate.outer_size()) } @@ -161,10 +226,6 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.set_title(title)); } - fn set_transparent(&self, transparent: bool) { - self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent)); - } - fn set_blur(&self, blur: bool) { self.maybe_wait_on_main(|delegate| delegate.set_blur(blur)); } @@ -269,25 +330,6 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.title()) } - fn set_cursor(&self, cursor: Cursor) { - self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor)); - } - - fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { - self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position)) - } - - fn set_cursor_grab( - &self, - mode: winit_core::window::CursorGrabMode, - ) -> Result<(), RequestError> { - self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode)) - } - - fn set_cursor_visible(&self, visible: bool) { - self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible)) - } - fn drag_window(&self) -> Result<(), RequestError> { self.maybe_wait_on_main(|delegate| delegate.drag_window()) } @@ -302,42 +344,6 @@ impl CoreWindow for Window { fn show_window_menu(&self, position: Position) { self.maybe_wait_on_main(|delegate| delegate.show_window_menu(position)) } - - fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { - self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest)); - Ok(()) - } - - fn current_monitor(&self) -> Option { - self.maybe_wait_on_main(|delegate| { - delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) - }) - } - - fn available_monitors(&self) -> Box> { - self.maybe_wait_on_main(|delegate| { - Box::new( - delegate - .available_monitors() - .into_iter() - .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), - ) - }) - } - - fn primary_monitor(&self) -> Option { - self.maybe_wait_on_main(|delegate| { - delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) - }) - } - - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } - - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } } define_class!( diff --git a/winit-uikit/src/window.rs b/winit-uikit/src/window.rs index 52acb038f1..3d596b5a9b 100644 --- a/winit-uikit/src/window.rs +++ b/winit-uikit/src/window.rs @@ -21,11 +21,12 @@ use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::event::WindowEvent; use winit_core::icon::Icon; +use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ - CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, - UserAttentionType, Window as CoreWindow, WindowAttributes, WindowButtons, WindowId, - WindowLevel, + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, + Surface as CoreSurface, Theme, UserAttentionType, Window as CoreWindow, WindowAttributes, + WindowButtons, WindowId, WindowLevel, }; use super::app_state::EventWrapper; @@ -47,20 +48,20 @@ define_class!( #[unsafe(method(becomeKeyWindow))] fn become_key_window(&self) { let mtm = MainThreadMarker::new().unwrap(); - app_state::handle_nonuser_event(mtm, EventWrapper::Window { - window_id: self.id(), - event: WindowEvent::Focused(true), - }); + app_state::handle_nonuser_event( + mtm, + EventWrapper::Window { window_id: self.id(), event: WindowEvent::Focused(true) }, + ); let _: () = unsafe { msg_send![super(self), becomeKeyWindow] }; } #[unsafe(method(resignKeyWindow))] fn resign_key_window(&self) { let mtm = MainThreadMarker::new().unwrap(); - app_state::handle_nonuser_event(mtm, EventWrapper::Window { - window_id: self.id(), - event: WindowEvent::Focused(false), - }); + app_state::handle_nonuser_event( + mtm, + EventWrapper::Window { window_id: self.id(), event: WindowEvent::Focused(false) }, + ); let _: () = unsafe { msg_send![super(self), resignKeyWindow] }; } } @@ -592,7 +593,9 @@ impl rwh_06::HasWindowHandle for Window { } } -impl CoreWindow for Window { +impl CoreSurface for Window { + impl_surface_downcast!(Window); + fn id(&self) -> winit_core::window::WindowId { self.maybe_wait_on_main(|delegate| delegate.id()) } @@ -609,6 +612,75 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.pre_present_notify()); } + fn surface_size(&self) -> PhysicalSize { + self.maybe_wait_on_main(|delegate| delegate.surface_size()) + } + + fn request_surface_size(&self, size: Size) -> Option> { + self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size)) + } + + fn set_transparent(&self, transparent: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent)); + } + + fn set_cursor(&self, cursor: Cursor) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor)); + } + + fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position))?) + } + + fn set_cursor_grab( + &self, + mode: winit_core::window::CursorGrabMode, + ) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode))?) + } + + fn set_cursor_visible(&self, visible: bool) { + self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible)) + } + + fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { + Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest))?) + } + + fn current_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn available_monitors(&self) -> Box> { + self.maybe_wait_on_main(|delegate| { + Box::new( + delegate + .available_monitors() + .into_iter() + .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), + ) + }) + } + + fn primary_monitor(&self) -> Option { + self.maybe_wait_on_main(|delegate| { + delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) + }) + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +impl CoreWindow for Window { + fn reset_dead_keys(&self) { self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys()); } @@ -625,14 +697,6 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.set_outer_position(position)); } - fn surface_size(&self) -> PhysicalSize { - self.maybe_wait_on_main(|delegate| delegate.surface_size()) - } - - fn request_surface_size(&self, size: Size) -> Option> { - self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size)) - } - fn outer_size(&self) -> PhysicalSize { self.maybe_wait_on_main(|delegate| delegate.outer_size()) } @@ -661,10 +725,6 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.set_title(title)); } - fn set_transparent(&self, transparent: bool) { - self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent)); - } - fn set_blur(&self, blur: bool) { self.maybe_wait_on_main(|delegate| delegate.set_blur(blur)); } @@ -769,25 +829,6 @@ impl CoreWindow for Window { self.maybe_wait_on_main(|delegate| delegate.title()) } - fn set_cursor(&self, cursor: Cursor) { - self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor)); - } - - fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> { - Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position))?) - } - - fn set_cursor_grab( - &self, - mode: winit_core::window::CursorGrabMode, - ) -> Result<(), RequestError> { - Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode))?) - } - - fn set_cursor_visible(&self, visible: bool) { - self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible)) - } - fn drag_window(&self) -> Result<(), RequestError> { Ok(self.maybe_wait_on_main(|delegate| delegate.drag_window())?) } @@ -802,41 +843,6 @@ impl CoreWindow for Window { fn show_window_menu(&self, position: Position) { self.maybe_wait_on_main(|delegate| delegate.show_window_menu(position)) } - - fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> { - Ok(self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest))?) - } - - fn current_monitor(&self) -> Option { - self.maybe_wait_on_main(|delegate| { - delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) - }) - } - - fn available_monitors(&self) -> Box> { - self.maybe_wait_on_main(|delegate| { - Box::new( - delegate - .available_monitors() - .into_iter() - .map(|monitor| CoreMonitorHandle(Arc::new(monitor))), - ) - }) - } - - fn primary_monitor(&self) -> Option { - self.maybe_wait_on_main(|delegate| { - delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor))) - }) - } - - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } - - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } } // WindowExtIOS From 770c478ea663d8e90c16fa83ab710cc01c0f2f39 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Mon, 7 Jul 2025 10:59:35 -0400 Subject: [PATCH 11/18] reorganize android --- winit-android/src/event_loop.rs | 81 +++++++++++++++++---------------- 1 file changed, 43 insertions(+), 38 deletions(-) diff --git a/winit-android/src/event_loop.rs b/winit-android/src/event_loop.rs index 1396574cbc..4a4b973de8 100644 --- a/winit-android/src/event_loop.rs +++ b/winit-android/src/event_loop.rs @@ -21,11 +21,12 @@ use winit_core::event_loop::{ EventLoopProxy as CoreEventLoopProxy, EventLoopProxyProvider, OwnedDisplayHandle as CoreOwnedDisplayHandle, }; +use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ self, CursorGrabMode, ImeCapabilities, ImePurpose, ImeRequest, ImeRequestError, - ResizeDirection, Theme, Window as CoreWindow, WindowAttributes, WindowButtons, WindowId, - WindowLevel, + ResizeDirection, Surface as CoreSurface, Theme, Window as CoreWindow, WindowAttributes, + WindowButtons, WindowId, WindowLevel, }; use crate::keycodes; @@ -821,7 +822,9 @@ impl rwh_06::HasWindowHandle for Window { } } -impl CoreWindow for Window { +impl CoreSurface for Window { + impl_surface_downcast!(Window); + fn id(&self) -> WindowId { GLOBAL_WINDOW } @@ -848,6 +851,43 @@ impl CoreWindow for Window { fn pre_present_notify(&self) {} + fn surface_size(&self) -> PhysicalSize { + self.outer_size() + } + + fn request_surface_size(&self, _size: Size) -> Option> { + Some(self.surface_size()) + } + + fn set_transparent(&self, _transparent: bool) {} + + fn set_cursor(&self, _: Cursor) {} + + fn set_cursor_position(&self, _: Position) -> Result<(), RequestError> { + Err(NotSupportedError::new("set_cursor_position is not supported").into()) + } + + fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), RequestError> { + Err(NotSupportedError::new("set_cursor_grab is not supported").into()) + } + + fn set_cursor_visible(&self, _: bool) {} + + fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), RequestError> { + Err(NotSupportedError::new("set_cursor_hittest is not supported").into()) + } + + fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { + self + } + + fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { + self + } +} + +impl CoreWindow for Window { + fn surface_position(&self) -> PhysicalPosition { (0, 0).into() } @@ -859,15 +899,6 @@ impl CoreWindow for Window { fn set_outer_position(&self, _position: Position) { // no effect } - - fn surface_size(&self) -> PhysicalSize { - self.outer_size() - } - - fn request_surface_size(&self, _size: Size) -> Option> { - Some(self.surface_size()) - } - fn outer_size(&self) -> PhysicalSize { screen_size(&self.app) } @@ -888,8 +919,6 @@ impl CoreWindow for Window { fn set_title(&self, _title: &str) {} - fn set_transparent(&self, _transparent: bool) {} - fn set_blur(&self, _blur: bool) {} fn set_visible(&self, _visibility: bool) {} @@ -977,18 +1006,6 @@ impl CoreWindow for Window { fn request_user_attention(&self, _request_type: Option) {} - fn set_cursor(&self, _: Cursor) {} - - fn set_cursor_position(&self, _: Position) -> Result<(), RequestError> { - Err(NotSupportedError::new("set_cursor_position is not supported").into()) - } - - fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), RequestError> { - Err(NotSupportedError::new("set_cursor_grab is not supported").into()) - } - - fn set_cursor_visible(&self, _: bool) {} - fn drag_window(&self) -> Result<(), RequestError> { Err(NotSupportedError::new("drag_window is not supported").into()) } @@ -1000,10 +1017,6 @@ impl CoreWindow for Window { #[inline] fn show_window_menu(&self, _position: Position) {} - fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), RequestError> { - Err(NotSupportedError::new("set_cursor_hittest is not supported").into()) - } - fn set_theme(&self, _theme: Option) {} fn theme(&self) -> Option { @@ -1021,14 +1034,6 @@ impl CoreWindow for Window { } fn reset_dead_keys(&self) {} - - fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle { - self - } - - fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle { - self - } } fn screen_size(app: &AndroidApp) -> PhysicalSize { From 79a7286a771b7afc957cb0373b1d4221fb766ad0 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Mon, 7 Jul 2025 11:12:28 -0400 Subject: [PATCH 12/18] cargo fmt --- examples/application.rs | 2 +- examples/child_window.rs | 2 +- examples/control_flow.rs | 2 +- examples/dnd.rs | 2 +- examples/pump_events.rs | 2 +- examples/run_on_demand.rs | 2 +- examples/util/fill.rs | 2 +- examples/window.rs | 2 +- examples/x11_embed.rs | 2 +- winit-android/src/event_loop.rs | 1 - winit-appkit/src/app.rs | 26 +- winit-appkit/src/view.rs | 19 +- winit-appkit/src/window.rs | 5 +- winit-orbital/src/event_loop.rs | 58 ++- winit-orbital/src/window.rs | 5 +- winit-uikit/src/app_state.rs | 12 +- winit-uikit/src/view.rs | 30 +- winit-uikit/src/window.rs | 1 - winit-wayland/src/lib.rs | 2 +- .../src/seat/pointer/relative_pointer.rs | 2 +- winit-wayland/src/window/mod.rs | 7 +- winit-wayland/src/window/state.rs | 2 +- winit-web/src/event_loop/window_target.rs | 2 +- winit-web/src/web_sys/canvas.rs | 13 +- winit-web/src/window.rs | 2 +- winit-win32/src/event_loop.rs | 449 ++++++++++-------- winit-win32/src/window.rs | 1 - winit-win32/src/window_state.rs | 22 +- winit-x11/src/dnd.rs | 28 +- winit-x11/src/event_loop.rs | 21 +- winit-x11/src/event_processor.rs | 12 +- winit-x11/src/util/input.rs | 8 +- 32 files changed, 428 insertions(+), 318 deletions(-) diff --git a/examples/application.rs b/examples/application.rs index a6ce9beeb2..0e6c2dbe24 100644 --- a/examples/application.rs +++ b/examples/application.rs @@ -41,7 +41,7 @@ use winit::platform::web::{ActiveEventLoopExtWeb, WindowAttributesWeb}; use winit::platform::x11::{ActiveEventLoopExtX11, WindowAttributesX11}; use winit::window::{ CursorGrabMode, ImeCapabilities, ImeEnableRequest, ImePurpose, ImeRequestData, ResizeDirection, - Theme, Window, WindowAttributes, SurfaceId, + SurfaceId, Theme, Window, WindowAttributes, }; use winit_core::application::macos::ApplicationHandlerExtMacOS; use winit_core::window::ImeRequest; diff --git a/examples/child_window.rs b/examples/child_window.rs index 29807e5a59..7f359b74ee 100644 --- a/examples/child_window.rs +++ b/examples/child_window.rs @@ -8,7 +8,7 @@ fn main() -> Result<(), impl std::error::Error> { use winit::event::{ElementState, KeyEvent, WindowEvent}; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::raw_window_handle::HasRawWindowHandle; - use winit::window::{Window, WindowAttributes, SurfaceId}; + use winit::window::{SurfaceId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; diff --git a/examples/control_flow.rs b/examples/control_flow.rs index bd9f875658..6a7a9f0f0f 100644 --- a/examples/control_flow.rs +++ b/examples/control_flow.rs @@ -11,7 +11,7 @@ use winit::application::ApplicationHandler; use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent}; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; use winit::keyboard::{Key, NamedKey}; -use winit::window::{Window, WindowAttributes, SurfaceId}; +use winit::window::{SurfaceId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; diff --git a/examples/dnd.rs b/examples/dnd.rs index e05399a2f7..71e198e9b3 100644 --- a/examples/dnd.rs +++ b/examples/dnd.rs @@ -3,7 +3,7 @@ use std::error::Error; use winit::application::ApplicationHandler; use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; -use winit::window::{Window, WindowAttributes, SurfaceId}; +use winit::window::{SurfaceId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; diff --git a/examples/pump_events.rs b/examples/pump_events.rs index 3332c6f2c1..8af60a0a6a 100644 --- a/examples/pump_events.rs +++ b/examples/pump_events.rs @@ -11,7 +11,7 @@ fn main() -> std::process::ExitCode { use winit::event::WindowEvent; use winit::event_loop::pump_events::{EventLoopExtPumpEvents, PumpStatus}; use winit::event_loop::{ActiveEventLoop, EventLoop}; - use winit::window::{Window, WindowAttributes, SurfaceId}; + use winit::window::{SurfaceId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; diff --git a/examples/run_on_demand.rs b/examples/run_on_demand.rs index 570fd2d6be..6b48988130 100644 --- a/examples/run_on_demand.rs +++ b/examples/run_on_demand.rs @@ -9,7 +9,7 @@ fn main() -> Result<(), Box> { use winit::event::WindowEvent; use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand; use winit::event_loop::{ActiveEventLoop, EventLoop}; - use winit::window::{Window, WindowAttributes, SurfaceId}; + use winit::window::{SurfaceId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; diff --git a/examples/util/fill.rs b/examples/util/fill.rs index f8280eb313..a77bbac7ef 100644 --- a/examples/util/fill.rs +++ b/examples/util/fill.rs @@ -29,7 +29,7 @@ mod platform { use softbuffer::{Context, Surface}; #[cfg(all(web_platform, not(android_platform)))] use web_time::Instant; - use winit::window::{Window, SurfaceId}; + use winit::window::{SurfaceId, Window}; thread_local! { // NOTE: You should never do things like that, create context and drop it before diff --git a/examples/window.rs b/examples/window.rs index d8d938f93e..f9a7383980 100644 --- a/examples/window.rs +++ b/examples/window.rs @@ -7,7 +7,7 @@ use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; #[cfg(web_platform)] use winit::platform::web::WindowAttributesWeb; -use winit::window::{Window, WindowAttributes, SurfaceId}; +use winit::window::{SurfaceId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; diff --git a/examples/x11_embed.rs b/examples/x11_embed.rs index 6f486dfdb6..ded67b3332 100644 --- a/examples/x11_embed.rs +++ b/examples/x11_embed.rs @@ -7,7 +7,7 @@ fn main() -> Result<(), Box> { use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::platform::x11::WindowAttributesX11; - use winit::window::{Window, WindowAttributes, SurfaceId}; + use winit::window::{SurfaceId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; diff --git a/winit-android/src/event_loop.rs b/winit-android/src/event_loop.rs index 4a4b973de8..54ce00b403 100644 --- a/winit-android/src/event_loop.rs +++ b/winit-android/src/event_loop.rs @@ -887,7 +887,6 @@ impl CoreSurface for Window { } impl CoreWindow for Window { - fn surface_position(&self) -> PhysicalPosition { (0, 0).into() } diff --git a/winit-appkit/src/app.rs b/winit-appkit/src/app.rs index 281b38d272..6149bc9b9a 100644 --- a/winit-appkit/src/app.rs +++ b/winit-appkit/src/app.rs @@ -110,28 +110,32 @@ fn maybe_dispatch_device_event(app_state: &Rc, event: &NSEvent) { if delta_x != 0.0 || delta_y != 0.0 { app_state.maybe_queue_with_handler(move |app, event_loop| { - app.device_event(event_loop, None, DeviceEvent::PointerMotion { - delta: (delta_x, delta_y), - }); + app.device_event( + event_loop, + None, + DeviceEvent::PointerMotion { delta: (delta_x, delta_y) }, + ); }); } }, NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => { let button = unsafe { event.buttonNumber() } as u32; app_state.maybe_queue_with_handler(move |app, event_loop| { - app.device_event(event_loop, None, DeviceEvent::Button { - button, - state: ElementState::Pressed, - }); + app.device_event( + event_loop, + None, + DeviceEvent::Button { button, state: ElementState::Pressed }, + ); }); }, NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => { let button = unsafe { event.buttonNumber() } as u32; app_state.maybe_queue_with_handler(move |app, event_loop| { - app.device_event(event_loop, None, DeviceEvent::Button { - button, - state: ElementState::Released, - }); + app.device_event( + event_loop, + None, + DeviceEvent::Button { button, state: ElementState::Released }, + ); }); }, _ => (), diff --git a/winit-appkit/src/view.rs b/winit-appkit/src/view.rs index 8f8976e9c6..02b85647a8 100644 --- a/winit-appkit/src/view.rs +++ b/winit-appkit/src/view.rs @@ -271,16 +271,15 @@ define_class!( // TODO: Use _replacement_range, requires changing the event to report surrounding text. trace_scope!("setMarkedText:selectedRange:replacementRange:"); - let (marked_text, string) = if let Some(string) = - string.downcast_ref::() - { - (NSMutableAttributedString::from_attributed_nsstring(string), string.string()) - } else if let Some(string) = string.downcast_ref::() { - (NSMutableAttributedString::from_nsstring(string), string.copy()) - } else { - // This method is guaranteed to get either a `NSString` or a `NSAttributedString`. - panic!("unexpected text {string:?}") - }; + let (marked_text, string) = + if let Some(string) = string.downcast_ref::() { + (NSMutableAttributedString::from_attributed_nsstring(string), string.string()) + } else if let Some(string) = string.downcast_ref::() { + (NSMutableAttributedString::from_nsstring(string), string.copy()) + } else { + // This method is guaranteed to get either a `NSString` or a `NSAttributedString`. + panic!("unexpected text {string:?}") + }; // Update marked text. *self.ivars().marked_text.borrow_mut() = marked_text; diff --git a/winit-appkit/src/window.rs b/winit-appkit/src/window.rs index 048227d585..54cdab5226 100644 --- a/winit-appkit/src/window.rs +++ b/winit-appkit/src/window.rs @@ -14,8 +14,8 @@ use winit_core::icon::Icon; use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ - ImeCapabilities, ImeRequest, ImeRequestError, Theme, UserAttentionType, Window as CoreWindow, - Surface as CoreSurface, WindowAttributes, WindowButtons, WindowId, WindowLevel, + ImeCapabilities, ImeRequest, ImeRequestError, Surface as CoreSurface, Theme, UserAttentionType, + Window as CoreWindow, WindowAttributes, WindowButtons, WindowId, WindowLevel, }; use super::event_loop::ActiveEventLoop; @@ -181,7 +181,6 @@ impl CoreSurface for Window { } impl CoreWindow for Window { - fn reset_dead_keys(&self) { self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys()); } diff --git a/winit-orbital/src/event_loop.rs b/winit-orbital/src/event_loop.rs index 663ad9e046..df9d62a3ed 100644 --- a/winit-orbital/src/event_loop.rs +++ b/winit-orbital/src/event_loop.rs @@ -24,7 +24,7 @@ use winit_core::keyboard::{ Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, PhysicalKey, }; -use winit_core::window::{Theme, Window as CoreWindow, SurfaceId}; +use winit_core::window::{SurfaceId, Theme, Window as CoreWindow}; use crate::window::Window; use crate::{RedoxSocket, TimeSocket, WindowProperties}; @@ -406,35 +406,49 @@ impl EventLoop { ); }, EventOption::Mouse(MouseEvent { x, y }) => { - app.window_event(window_target, window_id, event::WindowEvent::PointerMoved { - device_id: None, - primary: true, - position: (x, y).into(), - source: event::PointerSource::Mouse, - }); + app.window_event( + window_target, + window_id, + event::WindowEvent::PointerMoved { + device_id: None, + primary: true, + position: (x, y).into(), + source: event::PointerSource::Mouse, + }, + ); }, EventOption::MouseRelative(MouseRelativeEvent { dx, dy }) => { - app.device_event(window_target, None, event::DeviceEvent::PointerMotion { - delta: (dx as f64, dy as f64), - }); + app.device_event( + window_target, + None, + event::DeviceEvent::PointerMotion { delta: (dx as f64, dy as f64) }, + ); }, EventOption::Button(ButtonEvent { left, middle, right }) => { while let Some((button, state)) = event_state.mouse(left, middle, right) { - app.window_event(window_target, window_id, event::WindowEvent::PointerButton { - device_id: None, - primary: true, - state, - position: dpi::PhysicalPosition::default(), - button: button.into(), - }); + app.window_event( + window_target, + window_id, + event::WindowEvent::PointerButton { + device_id: None, + primary: true, + state, + position: dpi::PhysicalPosition::default(), + button: button.into(), + }, + ); } }, EventOption::Scroll(ScrollEvent { x, y }) => { - app.window_event(window_target, window_id, event::WindowEvent::MouseWheel { - device_id: None, - delta: event::MouseScrollDelta::LineDelta(x as f32, y as f32), - phase: event::TouchPhase::Moved, - }); + app.window_event( + window_target, + window_id, + event::WindowEvent::MouseWheel { + device_id: None, + delta: event::MouseScrollDelta::LineDelta(x as f32, y as f32), + phase: event::TouchPhase::Moved, + }, + ); }, EventOption::Quit(QuitEvent {}) => { app.window_event(window_target, window_id, event::WindowEvent::CloseRequested); diff --git a/winit-orbital/src/window.rs b/winit-orbital/src/window.rs index dbac7a6835..995263e39e 100644 --- a/winit-orbital/src/window.rs +++ b/winit-orbital/src/window.rs @@ -7,7 +7,7 @@ use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; -use winit_core::window::{self, Window as CoreWindow, Surface as CoreSurface, SurfaceId}; +use winit_core::window::{self, Surface as CoreSurface, SurfaceId, Window as CoreWindow}; use crate::event_loop::{ActiveEventLoop, EventLoopProxy}; use crate::{RedoxSocket, WindowProperties}; @@ -159,7 +159,7 @@ impl Window { impl CoreSurface for Window { impl_surface_downcast!(Window); - + fn id(&self) -> SurfaceId { SurfaceId::from_raw(self.window_socket.fd) } @@ -262,7 +262,6 @@ impl CoreSurface for Window { } impl CoreWindow for Window { - #[inline] fn reset_dead_keys(&self) { // TODO? diff --git a/winit-uikit/src/app_state.rs b/winit-uikit/src/app_state.rs index 52ad2346cc..d071fbb83c 100644 --- a/winit-uikit/src/app_state.rs +++ b/winit-uikit/src/app_state.rs @@ -451,10 +451,14 @@ fn handle_hidpi_proxy(mtm: MainThreadMarker, event: ScaleFactorChanged) { let ScaleFactorChanged { suggested_size, scale_factor, window } = event; let new_surface_size = Arc::new(Mutex::new(suggested_size)); get_handler(mtm).handle(|app| { - app.window_event(&ActiveEventLoop { mtm }, window.id(), WindowEvent::ScaleFactorChanged { - scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), - }); + app.window_event( + &ActiveEventLoop { mtm }, + window.id(), + WindowEvent::ScaleFactorChanged { + scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), + }, + ); }); let (view, screen_frame) = get_view_and_screen_frame(&window); let physical_size = *new_surface_size.lock().unwrap(); diff --git a/winit-uikit/src/view.rs b/winit-uikit/src/view.rs index 194bf03475..286e19dcfd 100644 --- a/winit-uikit/src/view.rs +++ b/winit-uikit/src/view.rs @@ -50,10 +50,13 @@ define_class!( fn draw_rect(&self, rect: CGRect) { let mtm = MainThreadMarker::new().unwrap(); let window = self.window().unwrap(); - app_state::handle_nonuser_event(mtm, EventWrapper::Window { - window_id: window.id(), - event: WindowEvent::RedrawRequested, - }); + app_state::handle_nonuser_event( + mtm, + EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::RedrawRequested, + }, + ); let _: () = unsafe { msg_send![super(self), drawRect: rect] }; } @@ -71,10 +74,13 @@ define_class!( .to_physical(scale_factor); let window = self.window().unwrap(); - app_state::handle_nonuser_event(mtm, EventWrapper::Window { - window_id: window.id(), - event: WindowEvent::SurfaceResized(size), - }); + app_state::handle_nonuser_event( + mtm, + EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::SurfaceResized(size), + }, + ); } #[unsafe(method(setContentScaleFactor:))] @@ -550,10 +556,10 @@ impl WinitView { let (primary, source) = if let UITouchType::Pencil = touch_type { (true, PointerSource::Unknown) } else { - (ivars.primary_finger.get().unwrap() == finger_id, PointerSource::Touch { - finger_id, - force, - }) + ( + ivars.primary_finger.get().unwrap() == finger_id, + PointerSource::Touch { finger_id, force }, + ) }; touch_events.push(EventWrapper::Window { diff --git a/winit-uikit/src/window.rs b/winit-uikit/src/window.rs index 3d596b5a9b..78b177c3d6 100644 --- a/winit-uikit/src/window.rs +++ b/winit-uikit/src/window.rs @@ -680,7 +680,6 @@ impl CoreSurface for Window { } impl CoreWindow for Window { - fn reset_dead_keys(&self) { self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys()); } diff --git a/winit-wayland/src/lib.rs b/winit-wayland/src/lib.rs index e3b36d6f68..c805cee3b1 100644 --- a/winit-wayland/src/lib.rs +++ b/winit-wayland/src/lib.rs @@ -23,7 +23,7 @@ use sctk::shm::slot::{Buffer, CreateBufferError, SlotPool}; use wayland_client::protocol::wl_shm::Format; use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop; use winit_core::window::{ - ActivationToken, PlatformWindowAttributes, Window as CoreWindow, SurfaceId, + ActivationToken, PlatformWindowAttributes, SurfaceId, Window as CoreWindow, }; macro_rules! os_error { diff --git a/winit-wayland/src/seat/pointer/relative_pointer.rs b/winit-wayland/src/seat/pointer/relative_pointer.rs index 8465b720d6..1b3135ea85 100644 --- a/winit-wayland/src/seat/pointer/relative_pointer.rs +++ b/winit-wayland/src/seat/pointer/relative_pointer.rs @@ -12,8 +12,8 @@ use sctk::reexports::protocols::wp::relative_pointer::zv1::{ use sctk::globals::GlobalData; -use winit_core::event::DeviceEvent; use crate::state::WinitState; +use winit_core::event::DeviceEvent; /// Wrapper around the relative pointer. #[derive(Debug)] diff --git a/winit-wayland/src/window/mod.rs b/winit-wayland/src/window/mod.rs index 27073cb247..6cc9cd39d1 100644 --- a/winit-wayland/src/window/mod.rs +++ b/winit-wayland/src/window/mod.rs @@ -21,9 +21,9 @@ use winit_core::event_loop::AsyncRequestSerial; use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ - CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, - UserAttentionType, Window as CoreWindow, Surface as CoreSurface, WindowAttributes, WindowButtons, SurfaceId, - WindowLevel, + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, + Surface as CoreSurface, SurfaceId, Theme, UserAttentionType, Window as CoreWindow, + WindowAttributes, WindowButtons, WindowLevel, }; use super::event_loop::sink::EventSink; @@ -410,7 +410,6 @@ impl CoreSurface for Window { } impl CoreWindow for Window { - #[inline] fn title(&self) -> String { self.window_state.lock().unwrap().title().to_owned() diff --git a/winit-wayland/src/window/state.rs b/winit-wayland/src/window/state.rs index 2a62ae528d..32b6fa9910 100644 --- a/winit-wayland/src/window/state.rs +++ b/winit-wayland/src/window/state.rs @@ -33,7 +33,7 @@ use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur; use winit_core::cursor::{CursorIcon, CustomCursor as CoreCustomCursor}; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::window::{ - CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, SurfaceId, + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, SurfaceId, Theme, }; use crate::event_loop::OwnedDisplayHandle; diff --git a/winit-web/src/event_loop/window_target.rs b/winit-web/src/event_loop/window_target.rs index 7423c1fd60..1fd14b765c 100644 --- a/winit-web/src/event_loop/window_target.rs +++ b/winit-web/src/event_loop/window_target.rs @@ -15,7 +15,7 @@ use winit_core::event_loop::{ }; use winit_core::keyboard::ModifiersState; use winit_core::monitor::MonitorHandle as CoremMonitorHandle; -use winit_core::window::{Theme, SurfaceId}; +use winit_core::window::{SurfaceId, Theme}; use super::super::lock; use super::super::monitor::MonitorPermissionFuture; diff --git a/winit-web/src/web_sys/canvas.rs b/winit-web/src/web_sys/canvas.rs index 4df3a63c82..082cccf98a 100644 --- a/winit-web/src/web_sys/canvas.rs +++ b/winit-web/src/web_sys/canvas.rs @@ -18,7 +18,7 @@ use winit_core::event::{ }; use winit_core::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey}; use winit_core::monitor::Fullscreen; -use winit_core::window::{WindowAttributes, SurfaceId}; +use winit_core::window::{SurfaceId, WindowAttributes}; use super::super::cursor::CursorHandler; use super::super::event_loop::runner; @@ -497,10 +497,13 @@ impl Canvas { self.set_current_size(current_size); let new_size = { let new_size = Arc::new(Mutex::new(current_size)); - event_handler(self.id, WindowEvent::ScaleFactorChanged { - scale_factor: scale, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_size)), - }); + event_handler( + self.id, + WindowEvent::ScaleFactorChanged { + scale_factor: scale, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_size)), + }, + ); let new_size = *new_size.lock().unwrap(); new_size diff --git a/winit-web/src/window.rs b/winit-web/src/window.rs index f30074ea0f..5988a5e888 100644 --- a/winit-web/src/window.rs +++ b/winit-web/src/window.rs @@ -105,7 +105,7 @@ impl Window { impl RootSurface for Window { impl_surface_downcast!(Window); - + fn id(&self) -> SurfaceId { self.inner.queue(|inner| inner.id) } diff --git a/winit-win32/src/event_loop.rs b/winit-win32/src/event_loop.rs index a14023f0cd..490dc8f944 100644 --- a/winit-win32/src/event_loop.rs +++ b/winit-win32/src/event_loop.rs @@ -1061,11 +1061,14 @@ unsafe fn public_window_callback_inner( let events = userdata.key_event_builder.process_message(window, msg, wparam, lparam, &mut result); for event in events { - userdata.send_window_event(window, KeyboardInput { - device_id: None, - event: event.event, - is_synthetic: event.is_synthetic, - }); + userdata.send_window_event( + window, + KeyboardInput { + device_id: None, + event: event.event, + is_synthetic: event.is_synthetic, + }, + ); } }; userdata @@ -1554,12 +1557,15 @@ unsafe fn public_window_callback_inner( .ok(); drop(w); - userdata.send_window_event(window, PointerEntered { - device_id: None, - primary: true, - position, - kind: PointerKind::Mouse, - }); + userdata.send_window_event( + window, + PointerEntered { + device_id: None, + primary: true, + position, + kind: PointerKind::Mouse, + }, + ); // Calling TrackMouseEvent in order to receive mouse leave events. unsafe { @@ -1577,12 +1583,15 @@ unsafe fn public_window_callback_inner( .ok(); drop(w); - userdata.send_window_event(window, PointerLeft { - device_id: None, - primary: true, - position: Some(position), - kind: PointerKind::Mouse, - }); + userdata.send_window_event( + window, + PointerLeft { + device_id: None, + primary: true, + position: Some(position), + kind: PointerKind::Mouse, + }, + ); }, PointerMoveKind::None => drop(w), } @@ -1598,12 +1607,15 @@ unsafe fn public_window_callback_inner( if cursor_moved { update_modifiers(window, userdata); - userdata.send_window_event(window, PointerMoved { - device_id: None, - primary: true, - position, - source: PointerSource::Mouse, - }); + userdata.send_window_event( + window, + PointerMoved { + device_id: None, + primary: true, + position, + source: PointerSource::Mouse, + }, + ); } result = ProcResult::Value(0); @@ -1618,12 +1630,10 @@ unsafe fn public_window_callback_inner( w.mouse.set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)).ok(); } - userdata.send_window_event(window, PointerLeft { - device_id: None, - primary: true, - position: None, - kind: Mouse, - }); + userdata.send_window_event( + window, + PointerLeft { device_id: None, primary: true, position: None, kind: Mouse }, + ); result = ProcResult::Value(0); }, @@ -1636,11 +1646,14 @@ unsafe fn public_window_callback_inner( update_modifiers(window, userdata); - userdata.send_window_event(window, WindowEvent::MouseWheel { - device_id: None, - delta: LineDelta(0.0, value), - phase: TouchPhase::Moved, - }); + userdata.send_window_event( + window, + WindowEvent::MouseWheel { + device_id: None, + delta: LineDelta(0.0, value), + phase: TouchPhase::Moved, + }, + ); result = ProcResult::Value(0); }, @@ -1653,11 +1666,14 @@ unsafe fn public_window_callback_inner( update_modifiers(window, userdata); - userdata.send_window_event(window, WindowEvent::MouseWheel { - device_id: None, - delta: LineDelta(value, 0.0), - phase: TouchPhase::Moved, - }); + userdata.send_window_event( + window, + WindowEvent::MouseWheel { + device_id: None, + delta: LineDelta(value, 0.0), + phase: TouchPhase::Moved, + }, + ); result = ProcResult::Value(0); }, @@ -1689,13 +1705,16 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: Left.into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: Left.into(), + }, + ); result = ProcResult::Value(0); }, @@ -1712,13 +1731,16 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: Left.into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: Left.into(), + }, + ); result = ProcResult::Value(0); }, @@ -1735,13 +1757,16 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: Right.into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: Right.into(), + }, + ); result = ProcResult::Value(0); }, @@ -1758,13 +1783,16 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: Right.into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: Right.into(), + }, + ); result = ProcResult::Value(0); }, @@ -1781,13 +1809,16 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: Middle.into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: Middle.into(), + }, + ); result = ProcResult::Value(0); }, @@ -1804,13 +1835,16 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: Middle.into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: Middle.into(), + }, + ); result = ProcResult::Value(0); }, @@ -1828,18 +1862,21 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: match xbutton { - 1 => Back, - 2 => Forward, - _ => Other(xbutton), - } - .into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: match xbutton { + 1 => Back, + 2 => Forward, + _ => Other(xbutton), + } + .into(), + }, + ); result = ProcResult::Value(0); }, @@ -1857,18 +1894,21 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event(window, PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: match xbutton { - 1 => Back, - 2 => Forward, - _ => Other(xbutton), - } - .into(), - }); + userdata.send_window_event( + window, + PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: match xbutton { + 1 => Back, + 2 => Forward, + _ => Other(xbutton), + } + .into(), + }, + ); result = ProcResult::Value(0); }, @@ -1915,40 +1955,55 @@ unsafe fn public_window_callback_inner( let primary = util::has_flag(input.dwFlags, TOUCHEVENTF_PRIMARY); if util::has_flag(input.dwFlags, TOUCHEVENTF_DOWN) { - userdata.send_window_event(window, WindowEvent::PointerEntered { - device_id: None, - primary, - position, - kind: PointerKind::Touch(finger_id), - }); - userdata.send_window_event(window, WindowEvent::PointerButton { - device_id: None, - primary, - state: Pressed, - position, - button: Touch { finger_id, force: None }, - }); + userdata.send_window_event( + window, + WindowEvent::PointerEntered { + device_id: None, + primary, + position, + kind: PointerKind::Touch(finger_id), + }, + ); + userdata.send_window_event( + window, + WindowEvent::PointerButton { + device_id: None, + primary, + state: Pressed, + position, + button: Touch { finger_id, force: None }, + }, + ); } else if util::has_flag(input.dwFlags, TOUCHEVENTF_UP) { - userdata.send_window_event(window, WindowEvent::PointerButton { - device_id: None, - primary, - state: Released, - position, - button: Touch { finger_id, force: None }, - }); - userdata.send_window_event(window, WindowEvent::PointerLeft { - device_id: None, - primary, - position: Some(position), - kind: PointerKind::Touch(finger_id), - }); + userdata.send_window_event( + window, + WindowEvent::PointerButton { + device_id: None, + primary, + state: Released, + position, + button: Touch { finger_id, force: None }, + }, + ); + userdata.send_window_event( + window, + WindowEvent::PointerLeft { + device_id: None, + primary, + position: Some(position), + kind: PointerKind::Touch(finger_id), + }, + ); } else if util::has_flag(input.dwFlags, TOUCHEVENTF_MOVE) { - userdata.send_window_event(window, WindowEvent::PointerMoved { - device_id: None, - primary, - position, - source: PointerSource::Touch { finger_id, force: None }, - }); + userdata.send_window_event( + window, + WindowEvent::PointerMoved { + device_id: None, + primary, + position, + source: PointerSource::Touch { finger_id, force: None }, + }, + ); } else { continue; } @@ -2070,60 +2125,75 @@ unsafe fn public_window_callback_inner( let primary = util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_PRIMARY); if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_DOWN) { - userdata.send_window_event(window, WindowEvent::PointerEntered { - device_id: None, - primary, - position, - kind: if let PT_TOUCH = pointer_info.pointerType { - PointerKind::Touch(finger_id) - } else { - PointerKind::Unknown + userdata.send_window_event( + window, + WindowEvent::PointerEntered { + device_id: None, + primary, + position, + kind: if let PT_TOUCH = pointer_info.pointerType { + PointerKind::Touch(finger_id) + } else { + PointerKind::Unknown + }, }, - }); - userdata.send_window_event(window, WindowEvent::PointerButton { - device_id: None, - primary, - state: Pressed, - position, - button: if let PT_TOUCH = pointer_info.pointerType { - ButtonSource::Touch { finger_id, force } - } else { - ButtonSource::Unknown(0) + ); + userdata.send_window_event( + window, + WindowEvent::PointerButton { + device_id: None, + primary, + state: Pressed, + position, + button: if let PT_TOUCH = pointer_info.pointerType { + ButtonSource::Touch { finger_id, force } + } else { + ButtonSource::Unknown(0) + }, }, - }); + ); } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UP) { - userdata.send_window_event(window, WindowEvent::PointerButton { - device_id: None, - primary, - state: Released, - position, - button: if let PT_TOUCH = pointer_info.pointerType { - ButtonSource::Touch { finger_id, force } - } else { - ButtonSource::Unknown(0) + userdata.send_window_event( + window, + WindowEvent::PointerButton { + device_id: None, + primary, + state: Released, + position, + button: if let PT_TOUCH = pointer_info.pointerType { + ButtonSource::Touch { finger_id, force } + } else { + ButtonSource::Unknown(0) + }, }, - }); - userdata.send_window_event(window, WindowEvent::PointerLeft { - device_id: None, - primary, - position: Some(position), - kind: if let PT_TOUCH = pointer_info.pointerType { - PointerKind::Touch(finger_id) - } else { - PointerKind::Unknown + ); + userdata.send_window_event( + window, + WindowEvent::PointerLeft { + device_id: None, + primary, + position: Some(position), + kind: if let PT_TOUCH = pointer_info.pointerType { + PointerKind::Touch(finger_id) + } else { + PointerKind::Unknown + }, }, - }); + ); } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UPDATE) { - userdata.send_window_event(window, WindowEvent::PointerMoved { - device_id: None, - primary, - position, - source: if let PT_TOUCH = pointer_info.pointerType { - PointerSource::Touch { finger_id, force } - } else { - PointerSource::Unknown + userdata.send_window_event( + window, + WindowEvent::PointerMoved { + device_id: None, + primary, + position, + source: if let PT_TOUCH = pointer_info.pointerType { + PointerSource::Touch { finger_id, force } + } else { + PointerSource::Unknown + }, }, - }); + ); } else { continue; } @@ -2285,10 +2355,13 @@ unsafe fn public_window_callback_inner( }; let new_surface_size = Arc::new(Mutex::new(new_physical_surface_size)); - userdata.send_window_event(window, ScaleFactorChanged { - scale_factor: new_scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), - }); + userdata.send_window_event( + window, + ScaleFactorChanged { + scale_factor: new_scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), + }, + ); let new_physical_surface_size = *new_surface_size.lock().unwrap(); drop(new_surface_size); diff --git a/winit-win32/src/window.rs b/winit-win32/src/window.rs index 985f32663c..eb11b1ba17 100644 --- a/winit-win32/src/window.rs +++ b/winit-win32/src/window.rs @@ -570,7 +570,6 @@ impl CoreSurface for Window { WindowId::from_raw(self.hwnd() as usize) } - fn current_monitor(&self) -> Option { Some(CoreMonitorHandle(Arc::new(monitor::current_monitor(self.hwnd())))) } diff --git a/winit-win32/src/window_state.rs b/winit-win32/src/window_state.rs index 08dfe84e24..60ac71fe3a 100644 --- a/winit-win32/src/window_state.rs +++ b/winit-win32/src/window_state.rs @@ -371,20 +371,26 @@ impl WindowFlags { if diff.contains(WindowFlags::MAXIMIZED) || new.contains(WindowFlags::MAXIMIZED) { unsafe { - ShowWindow(window, match new.contains(WindowFlags::MAXIMIZED) { - true => SW_MAXIMIZE, - false => SW_RESTORE, - }); + ShowWindow( + window, + match new.contains(WindowFlags::MAXIMIZED) { + true => SW_MAXIMIZE, + false => SW_RESTORE, + }, + ); } } // Minimize operations should execute after maximize for proper window animations if diff.contains(WindowFlags::MINIMIZED) { unsafe { - ShowWindow(window, match new.contains(WindowFlags::MINIMIZED) { - true => SW_MINIMIZE, - false => SW_RESTORE, - }); + ShowWindow( + window, + match new.contains(WindowFlags::MINIMIZED) { + true => SW_MINIMIZE, + false => SW_RESTORE, + }, + ); } diff.remove(WindowFlags::MINIMIZED); diff --git a/winit-x11/src/dnd.rs b/winit-x11/src/dnd.rs index 3c85e4fe2e..2e56ad96f7 100644 --- a/winit-x11/src/dnd.rs +++ b/winit-x11/src/dnd.rs @@ -90,13 +90,13 @@ impl Dnd { DndState::Rejected => (0, atoms[DndNone]), }; self.xconn - .send_client_msg(target_window, target_window, atoms[XdndStatus] as _, None, [ - this_window, - accepted, - 0, - 0, - action as _, - ])? + .send_client_msg( + target_window, + target_window, + atoms[XdndStatus] as _, + None, + [this_window, accepted, 0, 0, action as _], + )? .ignore_error(); Ok(()) @@ -114,13 +114,13 @@ impl Dnd { DndState::Rejected => (0, atoms[DndNone]), }; self.xconn - .send_client_msg(target_window, target_window, atoms[XdndFinished] as _, None, [ - this_window, - accepted, - action as _, - 0, - 0, - ])? + .send_client_msg( + target_window, + target_window, + atoms[XdndFinished] as _, + None, + [this_window, accepted, action as _, 0, 0], + )? .ignore_error(); Ok(()) diff --git a/winit-x11/src/event_loop.rs b/winit-x11/src/event_loop.rs index cb66383405..7543ca0469 100644 --- a/winit-x11/src/event_loop.rs +++ b/winit-x11/src/event_loop.rs @@ -28,7 +28,7 @@ use winit_core::event_loop::{ OwnedDisplayHandle as CoreOwnedDisplayHandle, }; use winit_core::monitor::MonitorHandle as CoreMonitorHandle; -use winit_core::window::{Theme, Window as CoreWindow, WindowAttributes, SurfaceId}; +use winit_core::window::{SurfaceId, Theme, Window as CoreWindow, WindowAttributes}; use x11rb::connection::RequestConnection; use x11rb::errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError}; use x11rb::protocol::xinput::{self, ConnectionExt as _}; @@ -1032,15 +1032,18 @@ impl Device { let ty = unsafe { (*class_ptr)._type }; if ty == ffi::XIScrollClass { let info = unsafe { &*(class_ptr as *const ffi::XIScrollClassInfo) }; - scroll_axes.push((info.number, ScrollAxis { - increment: info.increment, - orientation: match info.scroll_type { - ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, - ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, - _ => unreachable!(), + scroll_axes.push(( + info.number, + ScrollAxis { + increment: info.increment, + orientation: match info.scroll_type { + ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, + ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, + _ => unreachable!(), + }, + position: 0.0, }, - position: 0.0, - })); + )); } } } diff --git a/winit-x11/src/event_processor.rs b/winit-x11/src/event_processor.rs index e782495736..80a4cdd641 100644 --- a/winit-x11/src/event_processor.rs +++ b/winit-x11/src/event_processor.rs @@ -694,10 +694,14 @@ impl EventProcessor { drop(shared_state_lock); let surface_size = Arc::new(Mutex::new(new_surface_size)); - app.window_event(&self.target, window_id, WindowEvent::ScaleFactorChanged { - scale_factor: new_scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), - }); + app.window_event( + &self.target, + window_id, + WindowEvent::ScaleFactorChanged { + scale_factor: new_scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), + }, + ); let new_surface_size = *surface_size.lock().unwrap(); drop(surface_size); diff --git a/winit-x11/src/util/input.rs b/winit-x11/src/util/input.rs index 12a69bd0c7..b4f441436b 100644 --- a/winit-x11/src/util/input.rs +++ b/winit-x11/src/util/input.rs @@ -20,10 +20,10 @@ impl XConnection { mask: xinput::XIEventMask, ) -> Result, X11Error> { self.xcb_connection() - .xinput_xi_select_events(window, &[xinput::EventMask { - deviceid: device_id, - mask: vec![mask], - }]) + .xinput_xi_select_events( + window, + &[xinput::EventMask { deviceid: device_id, mask: vec![mask] }], + ) .map_err(Into::into) } From 7243fe981cfe2b524ee14cca2ef216913c608359 Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Mon, 7 Jul 2025 11:15:00 -0400 Subject: [PATCH 13/18] use nightly cargo fmt --- winit-appkit/src/app.rs | 26 +- winit-appkit/src/view.rs | 19 +- winit-core/src/window.rs | 4 +- winit-orbital/src/event_loop.rs | 56 ++-- winit-uikit/src/app_state.rs | 12 +- winit-uikit/src/view.rs | 30 +-- winit-uikit/src/window.rs | 16 +- winit-web/src/web_sys/canvas.rs | 11 +- winit-win32/src/event_loop.rs | 449 +++++++++++++------------------ winit-win32/src/window_state.rs | 22 +- winit-x11/src/dnd.rs | 28 +- winit-x11/src/event_loop.rs | 19 +- winit-x11/src/event_processor.rs | 12 +- winit-x11/src/util/input.rs | 8 +- winit-x11/src/window.rs | 12 +- 15 files changed, 302 insertions(+), 422 deletions(-) diff --git a/winit-appkit/src/app.rs b/winit-appkit/src/app.rs index 6149bc9b9a..281b38d272 100644 --- a/winit-appkit/src/app.rs +++ b/winit-appkit/src/app.rs @@ -110,32 +110,28 @@ fn maybe_dispatch_device_event(app_state: &Rc, event: &NSEvent) { if delta_x != 0.0 || delta_y != 0.0 { app_state.maybe_queue_with_handler(move |app, event_loop| { - app.device_event( - event_loop, - None, - DeviceEvent::PointerMotion { delta: (delta_x, delta_y) }, - ); + app.device_event(event_loop, None, DeviceEvent::PointerMotion { + delta: (delta_x, delta_y), + }); }); } }, NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => { let button = unsafe { event.buttonNumber() } as u32; app_state.maybe_queue_with_handler(move |app, event_loop| { - app.device_event( - event_loop, - None, - DeviceEvent::Button { button, state: ElementState::Pressed }, - ); + app.device_event(event_loop, None, DeviceEvent::Button { + button, + state: ElementState::Pressed, + }); }); }, NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => { let button = unsafe { event.buttonNumber() } as u32; app_state.maybe_queue_with_handler(move |app, event_loop| { - app.device_event( - event_loop, - None, - DeviceEvent::Button { button, state: ElementState::Released }, - ); + app.device_event(event_loop, None, DeviceEvent::Button { + button, + state: ElementState::Released, + }); }); }, _ => (), diff --git a/winit-appkit/src/view.rs b/winit-appkit/src/view.rs index 02b85647a8..8f8976e9c6 100644 --- a/winit-appkit/src/view.rs +++ b/winit-appkit/src/view.rs @@ -271,15 +271,16 @@ define_class!( // TODO: Use _replacement_range, requires changing the event to report surrounding text. trace_scope!("setMarkedText:selectedRange:replacementRange:"); - let (marked_text, string) = - if let Some(string) = string.downcast_ref::() { - (NSMutableAttributedString::from_attributed_nsstring(string), string.string()) - } else if let Some(string) = string.downcast_ref::() { - (NSMutableAttributedString::from_nsstring(string), string.copy()) - } else { - // This method is guaranteed to get either a `NSString` or a `NSAttributedString`. - panic!("unexpected text {string:?}") - }; + let (marked_text, string) = if let Some(string) = + string.downcast_ref::() + { + (NSMutableAttributedString::from_attributed_nsstring(string), string.string()) + } else if let Some(string) = string.downcast_ref::() { + (NSMutableAttributedString::from_nsstring(string), string.copy()) + } else { + // This method is guaranteed to get either a `NSString` or a `NSAttributedString`. + panic!("unexpected text {string:?}") + }; // Update marked text. *self.ivars().marked_text.borrow_mut() = marked_text; diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index c0b2bd60f7..97a6c46533 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -2035,8 +2035,8 @@ impl SurfaceDowncastMut<'_> { /// Helper macro for implementing [`Surface::try_downcast`] and [`Surface::try_downcast_mut`]. /// ## Syntax -/// Use the names of variants of [`SurfaceDowncastRef`] or [`SurfaceDowncastMut`] to return that type: -/// ```ignore +/// Use the names of variants of [`SurfaceDowncastRef`] or [`SurfaceDowncastMut`] to return that +/// type: ```ignore /// impl_surface_downcast!(Window); /// ``` /// You may also use the special identifier `None` to cause the downcast to fail. diff --git a/winit-orbital/src/event_loop.rs b/winit-orbital/src/event_loop.rs index df9d62a3ed..277691b8eb 100644 --- a/winit-orbital/src/event_loop.rs +++ b/winit-orbital/src/event_loop.rs @@ -406,49 +406,35 @@ impl EventLoop { ); }, EventOption::Mouse(MouseEvent { x, y }) => { - app.window_event( - window_target, - window_id, - event::WindowEvent::PointerMoved { - device_id: None, - primary: true, - position: (x, y).into(), - source: event::PointerSource::Mouse, - }, - ); + app.window_event(window_target, window_id, event::WindowEvent::PointerMoved { + device_id: None, + primary: true, + position: (x, y).into(), + source: event::PointerSource::Mouse, + }); }, EventOption::MouseRelative(MouseRelativeEvent { dx, dy }) => { - app.device_event( - window_target, - None, - event::DeviceEvent::PointerMotion { delta: (dx as f64, dy as f64) }, - ); + app.device_event(window_target, None, event::DeviceEvent::PointerMotion { + delta: (dx as f64, dy as f64), + }); }, EventOption::Button(ButtonEvent { left, middle, right }) => { while let Some((button, state)) = event_state.mouse(left, middle, right) { - app.window_event( - window_target, - window_id, - event::WindowEvent::PointerButton { - device_id: None, - primary: true, - state, - position: dpi::PhysicalPosition::default(), - button: button.into(), - }, - ); + app.window_event(window_target, window_id, event::WindowEvent::PointerButton { + device_id: None, + primary: true, + state, + position: dpi::PhysicalPosition::default(), + button: button.into(), + }); } }, EventOption::Scroll(ScrollEvent { x, y }) => { - app.window_event( - window_target, - window_id, - event::WindowEvent::MouseWheel { - device_id: None, - delta: event::MouseScrollDelta::LineDelta(x as f32, y as f32), - phase: event::TouchPhase::Moved, - }, - ); + app.window_event(window_target, window_id, event::WindowEvent::MouseWheel { + device_id: None, + delta: event::MouseScrollDelta::LineDelta(x as f32, y as f32), + phase: event::TouchPhase::Moved, + }); }, EventOption::Quit(QuitEvent {}) => { app.window_event(window_target, window_id, event::WindowEvent::CloseRequested); diff --git a/winit-uikit/src/app_state.rs b/winit-uikit/src/app_state.rs index d071fbb83c..52ad2346cc 100644 --- a/winit-uikit/src/app_state.rs +++ b/winit-uikit/src/app_state.rs @@ -451,14 +451,10 @@ fn handle_hidpi_proxy(mtm: MainThreadMarker, event: ScaleFactorChanged) { let ScaleFactorChanged { suggested_size, scale_factor, window } = event; let new_surface_size = Arc::new(Mutex::new(suggested_size)); get_handler(mtm).handle(|app| { - app.window_event( - &ActiveEventLoop { mtm }, - window.id(), - WindowEvent::ScaleFactorChanged { - scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), - }, - ); + app.window_event(&ActiveEventLoop { mtm }, window.id(), WindowEvent::ScaleFactorChanged { + scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), + }); }); let (view, screen_frame) = get_view_and_screen_frame(&window); let physical_size = *new_surface_size.lock().unwrap(); diff --git a/winit-uikit/src/view.rs b/winit-uikit/src/view.rs index 286e19dcfd..194bf03475 100644 --- a/winit-uikit/src/view.rs +++ b/winit-uikit/src/view.rs @@ -50,13 +50,10 @@ define_class!( fn draw_rect(&self, rect: CGRect) { let mtm = MainThreadMarker::new().unwrap(); let window = self.window().unwrap(); - app_state::handle_nonuser_event( - mtm, - EventWrapper::Window { - window_id: window.id(), - event: WindowEvent::RedrawRequested, - }, - ); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::RedrawRequested, + }); let _: () = unsafe { msg_send![super(self), drawRect: rect] }; } @@ -74,13 +71,10 @@ define_class!( .to_physical(scale_factor); let window = self.window().unwrap(); - app_state::handle_nonuser_event( - mtm, - EventWrapper::Window { - window_id: window.id(), - event: WindowEvent::SurfaceResized(size), - }, - ); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: window.id(), + event: WindowEvent::SurfaceResized(size), + }); } #[unsafe(method(setContentScaleFactor:))] @@ -556,10 +550,10 @@ impl WinitView { let (primary, source) = if let UITouchType::Pencil = touch_type { (true, PointerSource::Unknown) } else { - ( - ivars.primary_finger.get().unwrap() == finger_id, - PointerSource::Touch { finger_id, force }, - ) + (ivars.primary_finger.get().unwrap() == finger_id, PointerSource::Touch { + finger_id, + force, + }) }; touch_events.push(EventWrapper::Window { diff --git a/winit-uikit/src/window.rs b/winit-uikit/src/window.rs index 78b177c3d6..0adcc56cef 100644 --- a/winit-uikit/src/window.rs +++ b/winit-uikit/src/window.rs @@ -48,20 +48,20 @@ define_class!( #[unsafe(method(becomeKeyWindow))] fn become_key_window(&self) { let mtm = MainThreadMarker::new().unwrap(); - app_state::handle_nonuser_event( - mtm, - EventWrapper::Window { window_id: self.id(), event: WindowEvent::Focused(true) }, - ); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: self.id(), + event: WindowEvent::Focused(true), + }); let _: () = unsafe { msg_send![super(self), becomeKeyWindow] }; } #[unsafe(method(resignKeyWindow))] fn resign_key_window(&self) { let mtm = MainThreadMarker::new().unwrap(); - app_state::handle_nonuser_event( - mtm, - EventWrapper::Window { window_id: self.id(), event: WindowEvent::Focused(false) }, - ); + app_state::handle_nonuser_event(mtm, EventWrapper::Window { + window_id: self.id(), + event: WindowEvent::Focused(false), + }); let _: () = unsafe { msg_send![super(self), resignKeyWindow] }; } } diff --git a/winit-web/src/web_sys/canvas.rs b/winit-web/src/web_sys/canvas.rs index 082cccf98a..1e32f81e85 100644 --- a/winit-web/src/web_sys/canvas.rs +++ b/winit-web/src/web_sys/canvas.rs @@ -497,13 +497,10 @@ impl Canvas { self.set_current_size(current_size); let new_size = { let new_size = Arc::new(Mutex::new(current_size)); - event_handler( - self.id, - WindowEvent::ScaleFactorChanged { - scale_factor: scale, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_size)), - }, - ); + event_handler(self.id, WindowEvent::ScaleFactorChanged { + scale_factor: scale, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_size)), + }); let new_size = *new_size.lock().unwrap(); new_size diff --git a/winit-win32/src/event_loop.rs b/winit-win32/src/event_loop.rs index 490dc8f944..a14023f0cd 100644 --- a/winit-win32/src/event_loop.rs +++ b/winit-win32/src/event_loop.rs @@ -1061,14 +1061,11 @@ unsafe fn public_window_callback_inner( let events = userdata.key_event_builder.process_message(window, msg, wparam, lparam, &mut result); for event in events { - userdata.send_window_event( - window, - KeyboardInput { - device_id: None, - event: event.event, - is_synthetic: event.is_synthetic, - }, - ); + userdata.send_window_event(window, KeyboardInput { + device_id: None, + event: event.event, + is_synthetic: event.is_synthetic, + }); } }; userdata @@ -1557,15 +1554,12 @@ unsafe fn public_window_callback_inner( .ok(); drop(w); - userdata.send_window_event( - window, - PointerEntered { - device_id: None, - primary: true, - position, - kind: PointerKind::Mouse, - }, - ); + userdata.send_window_event(window, PointerEntered { + device_id: None, + primary: true, + position, + kind: PointerKind::Mouse, + }); // Calling TrackMouseEvent in order to receive mouse leave events. unsafe { @@ -1583,15 +1577,12 @@ unsafe fn public_window_callback_inner( .ok(); drop(w); - userdata.send_window_event( - window, - PointerLeft { - device_id: None, - primary: true, - position: Some(position), - kind: PointerKind::Mouse, - }, - ); + userdata.send_window_event(window, PointerLeft { + device_id: None, + primary: true, + position: Some(position), + kind: PointerKind::Mouse, + }); }, PointerMoveKind::None => drop(w), } @@ -1607,15 +1598,12 @@ unsafe fn public_window_callback_inner( if cursor_moved { update_modifiers(window, userdata); - userdata.send_window_event( - window, - PointerMoved { - device_id: None, - primary: true, - position, - source: PointerSource::Mouse, - }, - ); + userdata.send_window_event(window, PointerMoved { + device_id: None, + primary: true, + position, + source: PointerSource::Mouse, + }); } result = ProcResult::Value(0); @@ -1630,10 +1618,12 @@ unsafe fn public_window_callback_inner( w.mouse.set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)).ok(); } - userdata.send_window_event( - window, - PointerLeft { device_id: None, primary: true, position: None, kind: Mouse }, - ); + userdata.send_window_event(window, PointerLeft { + device_id: None, + primary: true, + position: None, + kind: Mouse, + }); result = ProcResult::Value(0); }, @@ -1646,14 +1636,11 @@ unsafe fn public_window_callback_inner( update_modifiers(window, userdata); - userdata.send_window_event( - window, - WindowEvent::MouseWheel { - device_id: None, - delta: LineDelta(0.0, value), - phase: TouchPhase::Moved, - }, - ); + userdata.send_window_event(window, WindowEvent::MouseWheel { + device_id: None, + delta: LineDelta(0.0, value), + phase: TouchPhase::Moved, + }); result = ProcResult::Value(0); }, @@ -1666,14 +1653,11 @@ unsafe fn public_window_callback_inner( update_modifiers(window, userdata); - userdata.send_window_event( - window, - WindowEvent::MouseWheel { - device_id: None, - delta: LineDelta(value, 0.0), - phase: TouchPhase::Moved, - }, - ); + userdata.send_window_event(window, WindowEvent::MouseWheel { + device_id: None, + delta: LineDelta(value, 0.0), + phase: TouchPhase::Moved, + }); result = ProcResult::Value(0); }, @@ -1705,16 +1689,13 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: Left.into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: Left.into(), + }); result = ProcResult::Value(0); }, @@ -1731,16 +1712,13 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: Left.into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: Left.into(), + }); result = ProcResult::Value(0); }, @@ -1757,16 +1735,13 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: Right.into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: Right.into(), + }); result = ProcResult::Value(0); }, @@ -1783,16 +1758,13 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: Right.into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: Right.into(), + }); result = ProcResult::Value(0); }, @@ -1809,16 +1781,13 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: Middle.into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: Middle.into(), + }); result = ProcResult::Value(0); }, @@ -1835,16 +1804,13 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: Middle.into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: Middle.into(), + }); result = ProcResult::Value(0); }, @@ -1862,21 +1828,18 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Pressed, - position, - button: match xbutton { - 1 => Back, - 2 => Forward, - _ => Other(xbutton), - } - .into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Pressed, + position, + button: match xbutton { + 1 => Back, + 2 => Forward, + _ => Other(xbutton), + } + .into(), + }); result = ProcResult::Value(0); }, @@ -1894,21 +1857,18 @@ unsafe fn public_window_callback_inner( let y = util::get_y_lparam(lparam as u32) as i32; let position = PhysicalPosition::new(x as f64, y as f64); - userdata.send_window_event( - window, - PointerButton { - device_id: None, - primary: true, - state: Released, - position, - button: match xbutton { - 1 => Back, - 2 => Forward, - _ => Other(xbutton), - } - .into(), - }, - ); + userdata.send_window_event(window, PointerButton { + device_id: None, + primary: true, + state: Released, + position, + button: match xbutton { + 1 => Back, + 2 => Forward, + _ => Other(xbutton), + } + .into(), + }); result = ProcResult::Value(0); }, @@ -1955,55 +1915,40 @@ unsafe fn public_window_callback_inner( let primary = util::has_flag(input.dwFlags, TOUCHEVENTF_PRIMARY); if util::has_flag(input.dwFlags, TOUCHEVENTF_DOWN) { - userdata.send_window_event( - window, - WindowEvent::PointerEntered { - device_id: None, - primary, - position, - kind: PointerKind::Touch(finger_id), - }, - ); - userdata.send_window_event( - window, - WindowEvent::PointerButton { - device_id: None, - primary, - state: Pressed, - position, - button: Touch { finger_id, force: None }, - }, - ); + userdata.send_window_event(window, WindowEvent::PointerEntered { + device_id: None, + primary, + position, + kind: PointerKind::Touch(finger_id), + }); + userdata.send_window_event(window, WindowEvent::PointerButton { + device_id: None, + primary, + state: Pressed, + position, + button: Touch { finger_id, force: None }, + }); } else if util::has_flag(input.dwFlags, TOUCHEVENTF_UP) { - userdata.send_window_event( - window, - WindowEvent::PointerButton { - device_id: None, - primary, - state: Released, - position, - button: Touch { finger_id, force: None }, - }, - ); - userdata.send_window_event( - window, - WindowEvent::PointerLeft { - device_id: None, - primary, - position: Some(position), - kind: PointerKind::Touch(finger_id), - }, - ); + userdata.send_window_event(window, WindowEvent::PointerButton { + device_id: None, + primary, + state: Released, + position, + button: Touch { finger_id, force: None }, + }); + userdata.send_window_event(window, WindowEvent::PointerLeft { + device_id: None, + primary, + position: Some(position), + kind: PointerKind::Touch(finger_id), + }); } else if util::has_flag(input.dwFlags, TOUCHEVENTF_MOVE) { - userdata.send_window_event( - window, - WindowEvent::PointerMoved { - device_id: None, - primary, - position, - source: PointerSource::Touch { finger_id, force: None }, - }, - ); + userdata.send_window_event(window, WindowEvent::PointerMoved { + device_id: None, + primary, + position, + source: PointerSource::Touch { finger_id, force: None }, + }); } else { continue; } @@ -2125,75 +2070,60 @@ unsafe fn public_window_callback_inner( let primary = util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_PRIMARY); if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_DOWN) { - userdata.send_window_event( - window, - WindowEvent::PointerEntered { - device_id: None, - primary, - position, - kind: if let PT_TOUCH = pointer_info.pointerType { - PointerKind::Touch(finger_id) - } else { - PointerKind::Unknown - }, + userdata.send_window_event(window, WindowEvent::PointerEntered { + device_id: None, + primary, + position, + kind: if let PT_TOUCH = pointer_info.pointerType { + PointerKind::Touch(finger_id) + } else { + PointerKind::Unknown }, - ); - userdata.send_window_event( - window, - WindowEvent::PointerButton { - device_id: None, - primary, - state: Pressed, - position, - button: if let PT_TOUCH = pointer_info.pointerType { - ButtonSource::Touch { finger_id, force } - } else { - ButtonSource::Unknown(0) - }, + }); + userdata.send_window_event(window, WindowEvent::PointerButton { + device_id: None, + primary, + state: Pressed, + position, + button: if let PT_TOUCH = pointer_info.pointerType { + ButtonSource::Touch { finger_id, force } + } else { + ButtonSource::Unknown(0) }, - ); + }); } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UP) { - userdata.send_window_event( - window, - WindowEvent::PointerButton { - device_id: None, - primary, - state: Released, - position, - button: if let PT_TOUCH = pointer_info.pointerType { - ButtonSource::Touch { finger_id, force } - } else { - ButtonSource::Unknown(0) - }, + userdata.send_window_event(window, WindowEvent::PointerButton { + device_id: None, + primary, + state: Released, + position, + button: if let PT_TOUCH = pointer_info.pointerType { + ButtonSource::Touch { finger_id, force } + } else { + ButtonSource::Unknown(0) }, - ); - userdata.send_window_event( - window, - WindowEvent::PointerLeft { - device_id: None, - primary, - position: Some(position), - kind: if let PT_TOUCH = pointer_info.pointerType { - PointerKind::Touch(finger_id) - } else { - PointerKind::Unknown - }, + }); + userdata.send_window_event(window, WindowEvent::PointerLeft { + device_id: None, + primary, + position: Some(position), + kind: if let PT_TOUCH = pointer_info.pointerType { + PointerKind::Touch(finger_id) + } else { + PointerKind::Unknown }, - ); + }); } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UPDATE) { - userdata.send_window_event( - window, - WindowEvent::PointerMoved { - device_id: None, - primary, - position, - source: if let PT_TOUCH = pointer_info.pointerType { - PointerSource::Touch { finger_id, force } - } else { - PointerSource::Unknown - }, + userdata.send_window_event(window, WindowEvent::PointerMoved { + device_id: None, + primary, + position, + source: if let PT_TOUCH = pointer_info.pointerType { + PointerSource::Touch { finger_id, force } + } else { + PointerSource::Unknown }, - ); + }); } else { continue; } @@ -2355,13 +2285,10 @@ unsafe fn public_window_callback_inner( }; let new_surface_size = Arc::new(Mutex::new(new_physical_surface_size)); - userdata.send_window_event( - window, - ScaleFactorChanged { - scale_factor: new_scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), - }, - ); + userdata.send_window_event(window, ScaleFactorChanged { + scale_factor: new_scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)), + }); let new_physical_surface_size = *new_surface_size.lock().unwrap(); drop(new_surface_size); diff --git a/winit-win32/src/window_state.rs b/winit-win32/src/window_state.rs index 60ac71fe3a..08dfe84e24 100644 --- a/winit-win32/src/window_state.rs +++ b/winit-win32/src/window_state.rs @@ -371,26 +371,20 @@ impl WindowFlags { if diff.contains(WindowFlags::MAXIMIZED) || new.contains(WindowFlags::MAXIMIZED) { unsafe { - ShowWindow( - window, - match new.contains(WindowFlags::MAXIMIZED) { - true => SW_MAXIMIZE, - false => SW_RESTORE, - }, - ); + ShowWindow(window, match new.contains(WindowFlags::MAXIMIZED) { + true => SW_MAXIMIZE, + false => SW_RESTORE, + }); } } // Minimize operations should execute after maximize for proper window animations if diff.contains(WindowFlags::MINIMIZED) { unsafe { - ShowWindow( - window, - match new.contains(WindowFlags::MINIMIZED) { - true => SW_MINIMIZE, - false => SW_RESTORE, - }, - ); + ShowWindow(window, match new.contains(WindowFlags::MINIMIZED) { + true => SW_MINIMIZE, + false => SW_RESTORE, + }); } diff.remove(WindowFlags::MINIMIZED); diff --git a/winit-x11/src/dnd.rs b/winit-x11/src/dnd.rs index 2e56ad96f7..3c85e4fe2e 100644 --- a/winit-x11/src/dnd.rs +++ b/winit-x11/src/dnd.rs @@ -90,13 +90,13 @@ impl Dnd { DndState::Rejected => (0, atoms[DndNone]), }; self.xconn - .send_client_msg( - target_window, - target_window, - atoms[XdndStatus] as _, - None, - [this_window, accepted, 0, 0, action as _], - )? + .send_client_msg(target_window, target_window, atoms[XdndStatus] as _, None, [ + this_window, + accepted, + 0, + 0, + action as _, + ])? .ignore_error(); Ok(()) @@ -114,13 +114,13 @@ impl Dnd { DndState::Rejected => (0, atoms[DndNone]), }; self.xconn - .send_client_msg( - target_window, - target_window, - atoms[XdndFinished] as _, - None, - [this_window, accepted, action as _, 0, 0], - )? + .send_client_msg(target_window, target_window, atoms[XdndFinished] as _, None, [ + this_window, + accepted, + action as _, + 0, + 0, + ])? .ignore_error(); Ok(()) diff --git a/winit-x11/src/event_loop.rs b/winit-x11/src/event_loop.rs index 7543ca0469..57da2b51c9 100644 --- a/winit-x11/src/event_loop.rs +++ b/winit-x11/src/event_loop.rs @@ -1032,18 +1032,15 @@ impl Device { let ty = unsafe { (*class_ptr)._type }; if ty == ffi::XIScrollClass { let info = unsafe { &*(class_ptr as *const ffi::XIScrollClassInfo) }; - scroll_axes.push(( - info.number, - ScrollAxis { - increment: info.increment, - orientation: match info.scroll_type { - ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, - ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, - _ => unreachable!(), - }, - position: 0.0, + scroll_axes.push((info.number, ScrollAxis { + increment: info.increment, + orientation: match info.scroll_type { + ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, + ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, + _ => unreachable!(), }, - )); + position: 0.0, + })); } } } diff --git a/winit-x11/src/event_processor.rs b/winit-x11/src/event_processor.rs index 80a4cdd641..e782495736 100644 --- a/winit-x11/src/event_processor.rs +++ b/winit-x11/src/event_processor.rs @@ -694,14 +694,10 @@ impl EventProcessor { drop(shared_state_lock); let surface_size = Arc::new(Mutex::new(new_surface_size)); - app.window_event( - &self.target, - window_id, - WindowEvent::ScaleFactorChanged { - scale_factor: new_scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), - }, - ); + app.window_event(&self.target, window_id, WindowEvent::ScaleFactorChanged { + scale_factor: new_scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), + }); let new_surface_size = *surface_size.lock().unwrap(); drop(surface_size); diff --git a/winit-x11/src/util/input.rs b/winit-x11/src/util/input.rs index b4f441436b..12a69bd0c7 100644 --- a/winit-x11/src/util/input.rs +++ b/winit-x11/src/util/input.rs @@ -20,10 +20,10 @@ impl XConnection { mask: xinput::XIEventMask, ) -> Result, X11Error> { self.xcb_connection() - .xinput_xi_select_events( - window, - &[xinput::EventMask { deviceid: device_id, mask: vec![mask] }], - ) + .xinput_xi_select_events(window, &[xinput::EventMask { + deviceid: device_id, + mask: vec![mask], + }]) .map_err(Into::into) } diff --git a/winit-x11/src/window.rs b/winit-x11/src/window.rs index c09176ad00..7fa42f34ef 100644 --- a/winit-x11/src/window.rs +++ b/winit-x11/src/window.rs @@ -1243,14 +1243,10 @@ impl UnownedWindow { let old_surface_size = PhysicalSize::new(width, height); let surface_size = Arc::new(Mutex::new(PhysicalSize::new(new_width, new_height))); - app.window_event( - event_loop, - self.id(), - WindowEvent::ScaleFactorChanged { - scale_factor: new_monitor.scale_factor, - surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), - }, - ); + app.window_event(event_loop, self.id(), WindowEvent::ScaleFactorChanged { + scale_factor: new_monitor.scale_factor, + surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&surface_size)), + }); let new_surface_size = *surface_size.lock().unwrap(); drop(surface_size); From c329e37bc6c8bfabe4cd356f4277dc3c2ff88b9f Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Thu, 10 Jul 2025 12:47:36 -0400 Subject: [PATCH 14/18] fix the docs --- winit-appkit/src/lib.rs | 3 ++- winit-core/src/cursor.rs | 2 +- winit-core/src/event.rs | 8 ++++---- winit-core/src/monitor.rs | 14 +++++++------- winit-core/src/window.rs | 35 ++++++++++++++++++----------------- winit-uikit/src/window.rs | 6 +++--- winit-wayland/src/lib.rs | 2 +- winit-web/src/lib.rs | 2 +- winit-x11/src/lib.rs | 2 +- 9 files changed, 38 insertions(+), 36 deletions(-) diff --git a/winit-appkit/src/lib.rs b/winit-appkit/src/lib.rs index 546e768c99..48a68ce69b 100644 --- a/winit-appkit/src/lib.rs +++ b/winit-appkit/src/lib.rs @@ -98,6 +98,7 @@ pub use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes}; use self::monitor::MonitorHandle as AppKitMonitorHandle; use self::window::Window as AppKitWindow; + /// Additional methods on [`Window`] that are specific to MacOS. pub trait WindowExtMacOS { /// Returns whether or not the window is in simple fullscreen mode. @@ -324,7 +325,7 @@ pub enum ActivationPolicy { /// - `with_titlebar_buttons_hidden` /// - `with_fullsize_content_view` /// -/// [`WindowAttributes::with_decorations`]: crate::window::WindowAttributes::with_decorations +/// [`WindowAttributes::with_decorations`]: winit_core::window::WindowAttributes::with_decorations #[derive(Clone, Debug, PartialEq)] pub struct WindowAttributesMacOS { pub(crate) movable_by_window_background: bool, diff --git a/winit-core/src/cursor.rs b/winit-core/src/cursor.rs index 9acebd4095..45aebb1b6c 100644 --- a/winit-core/src/cursor.rs +++ b/winit-core/src/cursor.rs @@ -15,7 +15,7 @@ pub const MAX_CURSOR_SIZE: u16 = 2048; const PIXEL_SIZE: usize = 4; -/// See [`Window::set_cursor()`][crate::window::Window::set_cursor] for more details. +/// See [`Surface::set_cursor()`][crate::window::Surface::set_cursor] for more details. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Cursor { Icon(CursorIcon), diff --git a/winit-core/src/event.rs b/winit-core/src/event.rs index cd10a8eb56..c8f88cbe32 100644 --- a/winit-core/src/event.rs +++ b/winit-core/src/event.rs @@ -11,7 +11,7 @@ use crate::error::RequestError; use crate::event_loop::AsyncRequestSerial; use crate::keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState}; #[cfg(doc)] -use crate::window::Window; +use crate::window::{Surface, Window}; use crate::window::{ActivationToken, Theme}; use crate::Instant; @@ -48,10 +48,10 @@ pub enum WindowEvent { /// The size of the window's surface has changed. /// /// Contains the new dimensions of the surface (can also be retrieved with - /// [`Window::surface_size`]). + /// [`Surface::surface_size`]). /// /// This event will not necessarily be emitted upon window creation, query - /// [`Window::surface_size`] if you need to determine the surface's initial size. + /// [`Surface::surface_size`] if you need to determine the surface's initial size. /// /// [`Surface::surface_size`]: crate::window::Surface::surface_size SurfaceResized(PhysicalSize), @@ -411,7 +411,7 @@ pub enum WindowEvent { /// This gets triggered in a few scenarios: /// - The OS has performed an operation that's invalidated the window's contents (such as /// resizing the window, or changing [the safe area]). - /// - The application has explicitly requested a redraw via [`Window::request_redraw`]. + /// - The application has explicitly requested a redraw via [`Surface::request_redraw`]. /// /// Winit will aggregate duplicate redraw requests into a single event, to /// help avoid duplicating rendering work. diff --git a/winit-core/src/monitor.rs b/winit-core/src/monitor.rs index f24e388825..eff9b16c26 100644 --- a/winit-core/src/monitor.rs +++ b/winit-core/src/monitor.rs @@ -4,7 +4,7 @@ //! [`MonitorHandle`] type. This is retrieved from one of the following //! methods, which return an iterator of [`MonitorHandle`]: //! - [`ActiveEventLoop::available_monitors`][crate::event_loop::ActiveEventLoop::available_monitors]. -//! - [`Window::available_monitors`][crate::window::Window::available_monitors]. +//! - [`Surface::available_monitors`][crate::window::Surface::available_monitors]. use std::borrow::Cow; use std::fmt; use std::num::{NonZeroU16, NonZeroU32}; @@ -25,7 +25,7 @@ use crate::as_any::{impl_dyn_casting, AsAny}; /// This can be retrieved from one of the following methods, which return an /// iterator of [`MonitorHandle`]s: /// - [`ActiveEventLoop::available_monitors`](crate::event_loop::ActiveEventLoop::available_monitors). -/// - [`Window::available_monitors`](crate::window::Window::available_monitors). +/// - [`Surface::available_monitors`](crate::window::Surface::available_monitors). /// /// ## Platform-specific /// @@ -95,14 +95,14 @@ pub trait MonitorHandleProvider: AsAny + fmt::Debug + Send + Sync { fn position(&self) -> Option>; /// Returns the scale factor of the underlying monitor. To map logical pixels to physical - /// pixels and vice versa, use [`Window::scale_factor`]. + /// pixels and vice versa, use [`Surface::scale_factor`]. /// /// See the [`dpi`] module for more information. /// - /// - **Wayland:** May differ from [`Window::scale_factor`]. + /// - **Wayland:** May differ from [`Surface::scale_factor`]. /// - **Web:** Always returns `0.0` without `detailed_monitor_permissions`. /// - /// [`Window::scale_factor`]: crate::window::Window::scale_factor + /// [`Surface::scale_factor`]: crate::window::Surface::scale_factor fn scale_factor(&self) -> f64; fn current_video_mode(&self) -> Option; @@ -141,9 +141,9 @@ impl VideoMode { } /// Returns the resolution of this video mode. This **must not** be used to create your - /// rendering surface. Use [`Window::surface_size()`] instead. + /// rendering surface. Use [`Surface::surface_size()`] instead. /// - /// [`Window::surface_size()`]: crate::window::Window::surface_size + /// [`Surface::surface_size()`]: crate::window::Surface::surface_size pub fn size(&self) -> PhysicalSize { self.size } diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index 97a6c46533..a04d0528da 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -17,7 +17,7 @@ use crate::monitor::{Fullscreen, MonitorHandle}; /// Identifier of a surface. Unique for each surface. /// -/// Can be obtained with [`surface.id()`][`Window::id`]. +/// Can be obtained with [`surface.id()`][`Surface::id`]. /// /// Whenever you receive an event specific to a surface, this event contains a `SurfaceId` which you /// can then compare to the ids of your windows. @@ -87,7 +87,7 @@ impl WindowAttributes { /// /// If this is not set, some platform-specific dimensions will be used. /// - /// See [`Window::request_surface_size`] for details. + /// See [`Surface::request_surface_size`] for details. #[inline] pub fn with_surface_size>(mut self, size: S) -> Self { self.surface_size = Some(size.into()); @@ -226,7 +226,7 @@ impl WindowAttributes { /// If this is `true`, writing colors with alpha values different than /// `1.0` will produce a transparent window. On some platforms this /// is more of a hint for the system and you'd still have the alpha - /// buffer. To control it see [`Window::set_transparent`]. + /// buffer. To control it see [`Surface::set_transparent`]. /// /// The default is `false`. #[inline] @@ -342,7 +342,7 @@ impl WindowAttributes { /// /// The default is [`CursorIcon::Default`]. /// - /// See [`Window::set_cursor()`] for more details. + /// See [`Surface::set_cursor()`] for more details. #[inline] pub fn with_cursor(mut self, cursor: impl Into) -> Self { self.cursor = cursor.into(); @@ -542,7 +542,7 @@ pub trait Surface: AsAny + Send + Sync + fmt::Debug { /// /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with /// OS-requested redraws (e.g. when a window gets resized). To improve the event delivery - /// consider using [`Window::pre_present_notify`] as described in docs. + /// consider using [`Surface::pre_present_notify`] as described in docs. /// /// Applications should always aim to redraw whenever they receive a `RedrawRequested` event. /// @@ -558,7 +558,7 @@ pub trait Surface: AsAny + Send + Sync + fmt::Debug { /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and /// `RedrawRequested` is emitted in sync with any `WM_PAINT` messages. /// - **Wayland:** The events are aligned with the frame callbacks when - /// [`Window::pre_present_notify`] is used. + /// [`Surface::pre_present_notify`] is used. /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the /// `requestAnimationFrame`. /// @@ -630,7 +630,7 @@ pub trait Surface: AsAny + Send + Sync + fmt::Debug { /// When `None` is returned, it means that the request went to the display system, /// and the actual size will be delivered later with the [`WindowEvent::SurfaceResized`]. /// - /// See [`Window::surface_size`] for more information about the values. + /// See [`Surface::surface_size`] for more information about the values. /// /// The request could automatically un-maximize the window if it's maximized. /// @@ -648,7 +648,7 @@ pub trait Surface: AsAny + Send + Sync + fmt::Debug { /// /// ## Platform-specific /// - /// - **Web:** Sets the size of the canvas element. Doesn't account for CSS [`trkansform`]. + /// - **Web:** Sets the size of the canvas element. Doesn't account for CSS [`transform`]. /// /// [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform @@ -903,12 +903,12 @@ pub trait Window: AsSurface { /// Returns the size of the entire window. /// /// These dimensions include window decorations like the title bar and borders. If you don't - /// want that (and you usually don't), use [`Window::surface_size`] instead. + /// want that (and you usually don't), use [`Surface::surface_size`] instead. /// /// ## Platform-specific /// /// - **Web:** Returns the size of the canvas element. _Note: this returns the same value as - /// [`Window::surface_size`]._ + /// [`Surface::surface_size`]._ fn outer_size(&self) -> PhysicalSize; /// The inset area of the surface that is unobstructed. @@ -921,7 +921,7 @@ pub trait Window: AsSurface { /// /// The safe area is a rectangle that is defined relative to the origin at the top-left corner /// of the surface, and the size extending downwards to the right. The area will not extend - /// beyond [the bounds of the surface][Window::surface_size]. + /// beyond [the bounds of the surface][Surface::surface_size]. /// /// Note that the safe area does not take occlusion from other windows into account; in a way, /// it is only a "hardware"-level occlusion. @@ -1054,7 +1054,7 @@ pub trait Window: AsSurface { /// Note that making the window unresizable doesn't exempt you from handling /// [`WindowEvent::SurfaceResized`], as that event can still be triggered by DPI scaling, /// entering fullscreen mode, etc. Also, the window could still be resized by calling - /// [`Window::request_surface_size`]. + /// [`Surface::request_surface_size`]. /// /// ## Platform-specific /// @@ -1508,7 +1508,7 @@ impl rwh_06::HasWindowHandle for dyn Window + '_ { /// The behavior of cursor grabbing. /// -/// Use this enum with [`Window::set_cursor_grab`] to grab the cursor. +/// Use this enum with [`Surface::set_cursor_grab`] to grab the cursor. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum CursorGrabMode { @@ -1794,11 +1794,11 @@ bitflags! { pub struct ImeRequestData { /// Text input purpose. /// - /// To support updating it, enable [`ImeCapabilities::PURPOSE`]. + /// To support updating it, call [`ImeCapabilities::with_purpose`]. pub purpose: Option, /// The IME cursor area which should not be covered by the input method popup. /// - /// To support updating it, enable [`ImeCapabilities::CURSOR_AREA`]. + /// To support updating it, call [`ImeCapabilities::with_cursor_area`]. pub cursor_area: Option<(Position, Size)>, } @@ -2036,9 +2036,10 @@ impl SurfaceDowncastMut<'_> { /// Helper macro for implementing [`Surface::try_downcast`] and [`Surface::try_downcast_mut`]. /// ## Syntax /// Use the names of variants of [`SurfaceDowncastRef`] or [`SurfaceDowncastMut`] to return that -/// type: ```ignore +/// type: +/// ```ignore /// impl_surface_downcast!(Window); -/// ``` +/// `````` /// You may also use the special identifier `None` to cause the downcast to fail. /// ```ignore /// impl_surface_downcast!(None); diff --git a/winit-uikit/src/window.rs b/winit-uikit/src/window.rs index 0adcc56cef..9c48469089 100644 --- a/winit-uikit/src/window.rs +++ b/winit-uikit/src/window.rs @@ -124,7 +124,7 @@ impl Inner { } pub fn set_transparent(&self, _transparent: bool) { - debug!("`Window::set_transparent` is ignored on iOS") + debug!("`Surface::set_transparent` is ignored on iOS") } pub fn set_blur(&self, _blur: bool) { @@ -259,7 +259,7 @@ impl Inner { } pub fn set_cursor(&self, _cursor: Cursor) { - debug!("`Window::set_cursor` ignored on iOS") + debug!("`Surface::set_cursor` ignored on iOS") } pub fn set_cursor_position(&self, _position: Position) -> Result<(), NotSupportedError> { @@ -271,7 +271,7 @@ impl Inner { } pub fn set_cursor_visible(&self, _visible: bool) { - debug!("`Window::set_cursor_visible` is ignored on iOS") + debug!("`Surface::set_cursor_visible` is ignored on iOS") } pub fn drag_window(&self) -> Result<(), NotSupportedError> { diff --git a/winit-wayland/src/lib.rs b/winit-wayland/src/lib.rs index c805cee3b1..ff2ecde3ba 100644 --- a/winit-wayland/src/lib.rs +++ b/winit-wayland/src/lib.rs @@ -61,7 +61,7 @@ pub trait EventLoopExtWayland { fn is_wayland(&self) -> bool; } -/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland. +/// Additional methods on `winit::EventLoopBuilder` that are specific to Wayland. pub trait EventLoopBuilderExtWayland { /// Force using Wayland. fn with_wayland(&mut self) -> &mut Self; diff --git a/winit-web/src/lib.rs b/winit-web/src/lib.rs index 3ea383c7fc..d0fd616cf4 100644 --- a/winit-web/src/lib.rs +++ b/winit-web/src/lib.rs @@ -34,7 +34,7 @@ //! - [`Window::set_outer_position()`] //! //! [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized -//! [`Window::(set_)surface_size()`]: crate::window::Window::surface_size +//! [`Window::(set_)surface_size()`]: crate::window::Surface::surface_size //! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded //! [`WindowEvent::PointerMoved`]: crate::event::WindowEvent::PointerMoved //! [`WindowEvent::PointerEntered`]: crate::event::WindowEvent::PointerEntered diff --git a/winit-x11/src/lib.rs b/winit-x11/src/lib.rs index 545e7a225c..8f3da9279e 100644 --- a/winit-x11/src/lib.rs +++ b/winit-x11/src/lib.rs @@ -125,7 +125,7 @@ pub trait EventLoopExtX11 { fn is_x11(&self) -> bool; } -/// Additional methods on [`EventLoopBuilder`] that are specific to X11. +/// Additional methods on `winit::EventLoopBuilder` that are specific to X11. pub trait EventLoopBuilderExtX11 { /// Force using X11. fn with_x11(&mut self) -> &mut Self; From a3318d93626cc8aa2f69e9bd795325d85e236fcc Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Thu, 10 Jul 2025 12:53:29 -0400 Subject: [PATCH 15/18] cargo fmt --- winit-appkit/src/lib.rs | 1 - winit-core/src/event.rs | 2 +- winit-core/src/window.rs | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/winit-appkit/src/lib.rs b/winit-appkit/src/lib.rs index 48a68ce69b..cb606eff1a 100644 --- a/winit-appkit/src/lib.rs +++ b/winit-appkit/src/lib.rs @@ -98,7 +98,6 @@ pub use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes}; use self::monitor::MonitorHandle as AppKitMonitorHandle; use self::window::Window as AppKitWindow; - /// Additional methods on [`Window`] that are specific to MacOS. pub trait WindowExtMacOS { /// Returns whether or not the window is in simple fullscreen mode. diff --git a/winit-core/src/event.rs b/winit-core/src/event.rs index c8f88cbe32..9c0aea9fd7 100644 --- a/winit-core/src/event.rs +++ b/winit-core/src/event.rs @@ -10,9 +10,9 @@ use smol_str::SmolStr; use crate::error::RequestError; use crate::event_loop::AsyncRequestSerial; use crate::keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState}; +use crate::window::{ActivationToken, Theme}; #[cfg(doc)] use crate::window::{Surface, Window}; -use crate::window::{ActivationToken, Theme}; use crate::Instant; /// Describes the reason the event loop is resuming. diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index a04d0528da..16b2a74769 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -2036,7 +2036,7 @@ impl SurfaceDowncastMut<'_> { /// Helper macro for implementing [`Surface::try_downcast`] and [`Surface::try_downcast_mut`]. /// ## Syntax /// Use the names of variants of [`SurfaceDowncastRef`] or [`SurfaceDowncastMut`] to return that -/// type: +/// type: /// ```ignore /// impl_surface_downcast!(Window); /// `````` From 2779ba53479d3265c958c7168e552f2c2af7263d Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Thu, 10 Jul 2025 12:58:38 -0400 Subject: [PATCH 16/18] rename SurfaceId to WindowId --- winit-core/src/application/macos.rs | 4 ++-- winit-core/src/application/mod.rs | 8 ++++---- winit-core/src/window.rs | 19 ++++++++++--------- winit-orbital/src/event_loop.rs | 14 +++++++------- winit-orbital/src/window.rs | 10 +++++----- winit-wayland/src/event_loop/mod.rs | 6 +++--- winit-wayland/src/event_loop/sink.rs | 4 ++-- winit-wayland/src/lib.rs | 6 +++--- winit-wayland/src/seat/keyboard/mod.rs | 4 ++-- winit-wayland/src/seat/pointer/mod.rs | 6 +++--- winit-wayland/src/state.rs | 12 ++++++------ winit-wayland/src/types/xdg_activation.rs | 4 ++-- winit-wayland/src/window/mod.rs | 8 ++++---- winit-wayland/src/window/state.rs | 4 ++-- winit-web/src/event_loop/runner.rs | 18 +++++++++--------- winit-web/src/event_loop/window_target.rs | 8 ++++---- winit-web/src/web_sys/canvas.rs | 8 ++++---- winit-web/src/window.rs | 9 +++++---- winit-x11/src/event_loop.rs | 14 +++++++------- winit-x11/src/event_processor.rs | 16 ++++++++-------- winit-x11/src/window.rs | 14 +++++++------- 21 files changed, 99 insertions(+), 97 deletions(-) diff --git a/winit-core/src/application/macos.rs b/winit-core/src/application/macos.rs index 1dbf878887..d18b4090e5 100644 --- a/winit-core/src/application/macos.rs +++ b/winit-core/src/application/macos.rs @@ -1,6 +1,6 @@ use crate::application::ApplicationHandler; use crate::event_loop::ActiveEventLoop; -use crate::window::SurfaceId; +use crate::window::WindowId; /// Additional events on [`ApplicationHandler`] that are specific to macOS. /// @@ -42,7 +42,7 @@ pub trait ApplicationHandlerExtMacOS: ApplicationHandler { fn standard_key_binding( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, action: &str, ) { let _ = event_loop; diff --git a/winit-core/src/application/mod.rs b/winit-core/src/application/mod.rs index 7f5ec5ac35..b9fd34bff1 100644 --- a/winit-core/src/application/mod.rs +++ b/winit-core/src/application/mod.rs @@ -2,7 +2,7 @@ use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent}; use crate::event_loop::ActiveEventLoop; -use crate::window::SurfaceId; +use crate::window::WindowId; pub mod macos; @@ -195,7 +195,7 @@ pub trait ApplicationHandler { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, event: WindowEvent, ); @@ -371,7 +371,7 @@ impl ApplicationHandler for &mut A { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, event: WindowEvent, ) { (**self).window_event(event_loop, window_id, event); @@ -439,7 +439,7 @@ impl ApplicationHandler for Box { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, event: WindowEvent, ) { (**self).window_event(event_loop, window_id, event); diff --git a/winit-core/src/window.rs b/winit-core/src/window.rs index 16b2a74769..aa6481c5b2 100644 --- a/winit-core/src/window.rs +++ b/winit-core/src/window.rs @@ -16,26 +16,27 @@ use crate::icon::Icon; use crate::monitor::{Fullscreen, MonitorHandle}; /// Identifier of a surface. Unique for each surface. +/// The name has been kept as `WindowId` for backwards compatibility. /// /// Can be obtained with [`surface.id()`][`Surface::id`]. /// -/// Whenever you receive an event specific to a surface, this event contains a `SurfaceId` which you +/// Whenever you receive an event specific to a surface, this event contains a `WindowId` which you /// can then compare to the ids of your windows. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct SurfaceId(usize); +pub struct WindowId(usize); -/// Alias to `SurfaceId` for compatibility with older versions of `winit`. -pub type WindowId = SurfaceId; +// TODO: possible name change of WindowId for consistency +// pub type WindowId = WindowId; -impl SurfaceId { - /// Convert the `SurfaceId` into the underlying integer. +impl WindowId { + /// Convert the `WindowId` into the underlying integer. /// /// This is useful if you need to pass the ID across an FFI boundary, or store it in an atomic. pub const fn into_raw(self) -> usize { self.0 } - /// Construct a `SurfaceId` from the underlying integer. + /// Construct a `WindowId` from the underlying integer. /// /// This should only be called with integers returned from [`WindowId::into_raw`]. pub const fn from_raw(id: usize) -> Self { @@ -43,7 +44,7 @@ impl SurfaceId { } } -impl fmt::Debug for SurfaceId { +impl fmt::Debug for WindowId { fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(fmtr) } @@ -471,7 +472,7 @@ pub trait Surface: AsAny + Send + Sync + fmt::Debug { fn try_downcast_mut(&mut self) -> Option>; /// Returns an identifier unique to the window. - fn id(&self) -> SurfaceId; + fn id(&self) -> WindowId; /// Returns the scale factor that can be used to map logical pixels to physical pixels, and /// vice versa. diff --git a/winit-orbital/src/event_loop.rs b/winit-orbital/src/event_loop.rs index 277691b8eb..77f1aaeaa3 100644 --- a/winit-orbital/src/event_loop.rs +++ b/winit-orbital/src/event_loop.rs @@ -24,7 +24,7 @@ use winit_core::keyboard::{ Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, PhysicalKey, }; -use winit_core::window::{SurfaceId, Theme, Window as CoreWindow}; +use winit_core::window::{Theme, Window as CoreWindow, WindowId}; use crate::window::Window; use crate::{RedoxSocket, TimeSocket, WindowProperties}; @@ -320,7 +320,7 @@ impl EventLoop { } fn process_event( - window_id: SurfaceId, + window_id: WindowId, event_option: EventOption, event_state: &mut EventState, window_target: &ActiveEventLoop, @@ -499,7 +499,7 @@ impl EventLoop { let mut creates = self.window_target.creates.lock().unwrap(); creates.pop_front() } { - let window_id = SurfaceId::from_raw(window.fd); + let window_id = WindowId::from_raw(window.fd); let mut buf: [u8; 4096] = [0; 4096]; let path = window.fpath(&mut buf).expect("failed to read properties"); @@ -523,14 +523,14 @@ impl EventLoop { } { app.window_event(&self.window_target, destroy_id, event::WindowEvent::Destroyed); self.windows - .retain(|(window, _event_state)| SurfaceId::from_raw(window.fd) != destroy_id); + .retain(|(window, _event_state)| WindowId::from_raw(window.fd) != destroy_id); } // Handle window events. let mut i = 0; // While loop is used here because the same window may be processed more than once. while let Some((window, event_state)) = self.windows.get_mut(i) { - let window_id = SurfaceId::from_raw(window.fd); + let window_id = WindowId::from_raw(window.fd); let mut event_buf = [0u8; 16 * mem::size_of::()]; let count = @@ -687,8 +687,8 @@ pub struct ActiveEventLoop { control_flow: Cell, exit: Cell, pub(super) creates: Mutex>>, - pub(super) redraws: Arc>>, - pub(super) destroys: Arc>>, + pub(super) redraws: Arc>>, + pub(super) destroys: Arc>>, pub(super) event_socket: Arc, pub(super) event_loop_proxy: Arc, } diff --git a/winit-orbital/src/window.rs b/winit-orbital/src/window.rs index 995263e39e..fabdc38296 100644 --- a/winit-orbital/src/window.rs +++ b/winit-orbital/src/window.rs @@ -7,7 +7,7 @@ use winit_core::cursor::Cursor; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; -use winit_core::window::{self, Surface as CoreSurface, SurfaceId, Window as CoreWindow}; +use winit_core::window::{self, Surface as CoreSurface, Window as CoreWindow, WindowId}; use crate::event_loop::{ActiveEventLoop, EventLoopProxy}; use crate::{RedoxSocket, WindowProperties}; @@ -26,8 +26,8 @@ const ORBITAL_FLAG_TRANSPARENT: char = 't'; #[derive(Debug)] pub struct Window { window_socket: Arc, - redraws: Arc>>, - destroys: Arc>>, + redraws: Arc>>, + destroys: Arc>>, event_loop_proxy: Arc, } @@ -160,8 +160,8 @@ impl Window { impl CoreSurface for Window { impl_surface_downcast!(Window); - fn id(&self) -> SurfaceId { - SurfaceId::from_raw(self.window_socket.fd) + fn id(&self) -> WindowId { + WindowId::from_raw(self.window_socket.fd) } #[inline] diff --git a/winit-wayland/src/event_loop/mod.rs b/winit-wayland/src/event_loop/mod.rs index 6e30f51001..ee6b4e8e92 100644 --- a/winit-wayland/src/event_loop/mod.rs +++ b/winit-wayland/src/event_loop/mod.rs @@ -41,13 +41,13 @@ pub use winit_core::event_loop::EventLoopProxy as CoreEventLoopProxy; use super::output::MonitorHandle; use super::state::{WindowCompositorUpdate, WinitState}; use super::window::state::FrameCallbackState; -use super::{logical_to_physical_rounded, SurfaceId}; +use super::{logical_to_physical_rounded, WindowId}; type WaylandDispatcher = calloop::Dispatcher<'static, WaylandSource, WinitState>; #[derive(Debug)] pub(crate) enum Event { - WindowEvent { window_id: SurfaceId, event: WindowEvent }, + WindowEvent { window_id: WindowId, event: WindowEvent }, DeviceEvent { event: DeviceEvent }, } @@ -59,7 +59,7 @@ pub struct EventLoop { buffer_sink: EventSink, compositor_updates: Vec, - window_ids: Vec, + window_ids: Vec, /// The Wayland dispatcher to has raw access to the queue when needed, such as /// when creating a new window. diff --git a/winit-wayland/src/event_loop/sink.rs b/winit-wayland/src/event_loop/sink.rs index 92ab5e893c..c67463d2e4 100644 --- a/winit-wayland/src/event_loop/sink.rs +++ b/winit-wayland/src/event_loop/sink.rs @@ -3,7 +3,7 @@ use std::vec::Drain; use winit_core::event::{DeviceEvent, WindowEvent}; -use winit_core::window::SurfaceId; +use winit_core::window::WindowId; use super::Event; @@ -33,7 +33,7 @@ impl EventSink { /// Add new window event to a queue. #[inline] - pub fn push_window_event(&mut self, event: WindowEvent, window_id: SurfaceId) { + pub fn push_window_event(&mut self, event: WindowEvent, window_id: WindowId) { self.window_events.push(Event::WindowEvent { event, window_id }); } diff --git a/winit-wayland/src/lib.rs b/winit-wayland/src/lib.rs index ff2ecde3ba..0c238a9050 100644 --- a/winit-wayland/src/lib.rs +++ b/winit-wayland/src/lib.rs @@ -23,7 +23,7 @@ use sctk::shm::slot::{Buffer, CreateBufferError, SlotPool}; use wayland_client::protocol::wl_shm::Format; use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop; use winit_core::window::{ - ActivationToken, PlatformWindowAttributes, SurfaceId, Window as CoreWindow, + ActivationToken, PlatformWindowAttributes, Window as CoreWindow, WindowId, }; macro_rules! os_error { @@ -130,8 +130,8 @@ impl PlatformWindowAttributes for WindowAttributesWayland { /// Get the WindowId out of the surface. #[inline] -fn make_wid(surface: &WlSurface) -> SurfaceId { - SurfaceId::from_raw(surface.id().as_ptr() as usize) +fn make_wid(surface: &WlSurface) -> WindowId { + WindowId::from_raw(surface.id().as_ptr() as usize) } /// The default routine does floor, but we need round on Wayland. diff --git a/winit-wayland/src/seat/keyboard/mod.rs b/winit-wayland/src/seat/keyboard/mod.rs index a40e0a4daf..227006857b 100644 --- a/winit-wayland/src/seat/keyboard/mod.rs +++ b/winit-wayland/src/seat/keyboard/mod.rs @@ -17,7 +17,7 @@ use winit_core::keyboard::ModifiersState; use crate::event_loop::sink::EventSink; use crate::state::WinitState; -use crate::SurfaceId; +use crate::WindowId; impl Dispatch for WinitState { fn event( @@ -344,7 +344,7 @@ impl Default for RepeatInfo { #[derive(Debug)] pub struct KeyboardData { /// The currently focused window surface. Could be `None` on bugged compositors, like mutter. - window_id: Mutex>, + window_id: Mutex>, /// The seat used to create this keyboard. seat: WlSeat, diff --git a/winit-wayland/src/seat/pointer/mod.rs b/winit-wayland/src/seat/pointer/mod.rs index 9f4da547b6..9dea4b7ff6 100644 --- a/winit-wayland/src/seat/pointer/mod.rs +++ b/winit-wayland/src/seat/pointer/mod.rs @@ -34,7 +34,7 @@ use winit_core::event::{ }; use crate::state::WinitState; -use crate::SurfaceId; +use crate::WindowId; pub mod relative_pointer; @@ -318,7 +318,7 @@ impl WinitPointerData { } /// Active window. - pub fn focused_window(&self) -> Option { + pub fn focused_window(&self) -> Option { self.inner.lock().unwrap().surface } @@ -370,7 +370,7 @@ pub struct WinitPointerDataInner { latest_button_serial: u32, /// Currently focused window. - surface: Option, + surface: Option, /// Current axis phase. phase: TouchPhase, diff --git a/winit-wayland/src/state.rs b/winit-wayland/src/state.rs index 1bccf9f3e2..9f8a4f490a 100644 --- a/winit-wayland/src/state.rs +++ b/winit-wayland/src/state.rs @@ -34,7 +34,7 @@ use crate::types::wp_viewporter::ViewporterState; use crate::types::xdg_activation::XdgActivationState; use crate::types::xdg_toplevel_icon_manager::XdgToplevelIconManagerState; use crate::window::{WindowRequests, WindowState}; -use crate::SurfaceId; +use crate::WindowId; /// Winit's Wayland state. #[derive(Debug)] @@ -61,10 +61,10 @@ pub struct WinitState { pub xdg_shell: XdgShell, /// The currently present windows. - pub windows: RefCell>>>, + pub windows: RefCell>>>, /// The requests from the `Window` to EventLoop, such as close operations and redraw requests. - pub window_requests: RefCell>>, + pub window_requests: RefCell>>, /// The events that were generated directly from the window. pub window_events_sink: Arc>, @@ -248,7 +248,7 @@ impl WinitState { } } - pub fn queue_close(updates: &mut Vec, window_id: SurfaceId) { + pub fn queue_close(updates: &mut Vec, window_id: WindowId) { let pos = if let Some(pos) = updates.iter().position(|update| update.window_id == window_id) { pos @@ -418,7 +418,7 @@ impl ProvidesRegistryState for WinitState { #[derive(Debug, Clone, Copy)] pub struct WindowCompositorUpdate { /// The id of the window this updates belongs to. - pub window_id: SurfaceId, + pub window_id: WindowId, /// New window size. pub resized: bool, @@ -431,7 +431,7 @@ pub struct WindowCompositorUpdate { } impl WindowCompositorUpdate { - fn new(window_id: SurfaceId) -> Self { + fn new(window_id: WindowId) -> Self { Self { window_id, resized: false, scale_changed: false, close_window: false } } } diff --git a/winit-wayland/src/types/xdg_activation.rs b/winit-wayland/src/types/xdg_activation.rs index 070aa6e442..9e9998cb42 100644 --- a/winit-wayland/src/types/xdg_activation.rs +++ b/winit-wayland/src/types/xdg_activation.rs @@ -12,7 +12,7 @@ use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_toke }; use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1; use winit_core::event_loop::AsyncRequestSerial; -use winit_core::window::{ActivationToken, SurfaceId}; +use winit_core::window::{ActivationToken, WindowId}; use crate::state::WinitState; @@ -95,7 +95,7 @@ pub enum XdgActivationTokenData { /// Request user attention for the given surface. Attention((WlSurface, Weak)), /// Get a token to be passed outside of the winit. - Obtain((SurfaceId, AsyncRequestSerial)), + Obtain((WindowId, AsyncRequestSerial)), } delegate_dispatch!(WinitState: [ XdgActivationV1: GlobalData] => XdgActivationState); diff --git a/winit-wayland/src/window/mod.rs b/winit-wayland/src/window/mod.rs index 6cc9cd39d1..f85d782128 100644 --- a/winit-wayland/src/window/mod.rs +++ b/winit-wayland/src/window/mod.rs @@ -22,8 +22,8 @@ use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle}; use winit_core::window::{ CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, - Surface as CoreSurface, SurfaceId, Theme, UserAttentionType, Window as CoreWindow, - WindowAttributes, WindowButtons, WindowLevel, + Surface as CoreSurface, Theme, UserAttentionType, Window as CoreWindow, WindowAttributes, + WindowButtons, WindowId, WindowLevel, }; use super::event_loop::sink::EventSink; @@ -44,7 +44,7 @@ pub struct Window { window: SctkWindow, /// Window id. - window_id: SurfaceId, + window_id: WindowId, /// The state of the window. window_state: Arc>, @@ -286,7 +286,7 @@ impl rwh_06::HasDisplayHandle for Window { impl CoreSurface for Window { impl_surface_downcast!(Window); - fn id(&self) -> SurfaceId { + fn id(&self) -> WindowId { self.window_id } diff --git a/winit-wayland/src/window/state.rs b/winit-wayland/src/window/state.rs index 32b6fa9910..899b0e0174 100644 --- a/winit-wayland/src/window/state.rs +++ b/winit-wayland/src/window/state.rs @@ -33,7 +33,7 @@ use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur; use winit_core::cursor::{CursorIcon, CustomCursor as CoreCustomCursor}; use winit_core::error::{NotSupportedError, RequestError}; use winit_core::window::{ - CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, SurfaceId, Theme, + CursorGrabMode, ImeCapabilities, ImeRequest, ImeRequestError, ResizeDirection, Theme, WindowId, }; use crate::event_loop::OwnedDisplayHandle; @@ -442,7 +442,7 @@ impl WindowState { seat: &WlSeat, serial: u32, timestamp: Duration, - window_id: SurfaceId, + window_id: WindowId, updates: &mut Vec, ) -> Option { match self.frame.as_mut()?.on_click(timestamp, click, pressed)? { diff --git a/winit-web/src/event_loop/runner.rs b/winit-web/src/event_loop/runner.rs index 7359cca3fb..4aeaf383e1 100644 --- a/winit-web/src/event_loop/runner.rs +++ b/winit-web/src/event_loop/runner.rs @@ -15,7 +15,7 @@ use winit_core::event::{ DeviceEvent, DeviceId, ElementState, RawKeyEvent, StartCause, WindowEvent, }; use winit_core::event_loop::{ControlFlow, DeviceEvents}; -use winit_core::window::SurfaceId; +use winit_core::window::WindowId; use super::proxy::EventLoopProxy; use super::state::State; @@ -55,9 +55,9 @@ struct Execution { navigator: Navigator, document: Document, #[allow(clippy::type_complexity)] - all_canvases: RefCell, DispatchRunner)>>, - redraw_pending: RefCell>, - destroy_pending: RefCell>, + all_canvases: RefCell, DispatchRunner)>>, + redraw_pending: RefCell>, + destroy_pending: RefCell>, pub(crate) monitor: Rc, safe_area: Rc, page_transition_event_handle: RefCell>, @@ -237,14 +237,14 @@ impl Shared { pub fn add_canvas( &self, - id: SurfaceId, + id: WindowId, canvas: Weak, runner: DispatchRunner, ) { self.0.all_canvases.borrow_mut().push((id, canvas, runner)); } - pub fn notify_destroy_window(&self, id: SurfaceId) { + pub fn notify_destroy_window(&self, id: WindowId) { self.0.destroy_pending.borrow_mut().push_back(id); } @@ -478,7 +478,7 @@ impl Shared { id } - pub fn request_redraw(&self, id: SurfaceId) { + pub fn request_redraw(&self, id: WindowId) { self.0.redraw_pending.borrow_mut().insert(id); self.send_events([]); } @@ -620,7 +620,7 @@ impl Shared { self.process_destroy_pending_windows(); // Collect all of the redraw events to avoid double-locking the RefCell - let redraw_events: Vec = self.0.redraw_pending.borrow_mut().drain().collect(); + let redraw_events: Vec = self.0.redraw_pending.borrow_mut().drain().collect(); for window_id in redraw_events { self.handle_event(Event::WindowEvent { window_id, @@ -877,7 +877,7 @@ impl WeakShared { #[allow(clippy::enum_variant_names)] pub(crate) enum Event { NewEvents(StartCause), - WindowEvent { window_id: SurfaceId, event: WindowEvent }, + WindowEvent { window_id: WindowId, event: WindowEvent }, ScaleChange { canvas: Weak, size: PhysicalSize, scale: f64 }, DeviceEvent { device_id: Option, event: DeviceEvent }, Suspended, diff --git a/winit-web/src/event_loop/window_target.rs b/winit-web/src/event_loop/window_target.rs index 1fd14b765c..84c080e8d1 100644 --- a/winit-web/src/event_loop/window_target.rs +++ b/winit-web/src/event_loop/window_target.rs @@ -15,7 +15,7 @@ use winit_core::event_loop::{ }; use winit_core::keyboard::ModifiersState; use winit_core::monitor::MonitorHandle as CoremMonitorHandle; -use winit_core::window::{SurfaceId, Theme}; +use winit_core::window::{Theme, WindowId}; use super::super::lock; use super::super::monitor::MonitorPermissionFuture; @@ -61,15 +61,15 @@ impl ActiveEventLoop { self.runner.start(app, self.clone()); } - pub fn generate_id(&self) -> SurfaceId { - SurfaceId::from_raw(self.runner.generate_id()) + pub fn generate_id(&self) -> WindowId { + WindowId::from_raw(self.runner.generate_id()) } pub fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture { CustomCursorFuture(CustomCursor::new_async(self, source)) } - pub fn register(&self, canvas: &Rc, window_id: SurfaceId) { + pub fn register(&self, canvas: &Rc, window_id: WindowId) { let canvas_clone = canvas.clone(); canvas.on_touch_start(); diff --git a/winit-web/src/web_sys/canvas.rs b/winit-web/src/web_sys/canvas.rs index 1e32f81e85..3a9f8ae546 100644 --- a/winit-web/src/web_sys/canvas.rs +++ b/winit-web/src/web_sys/canvas.rs @@ -18,7 +18,7 @@ use winit_core::event::{ }; use winit_core::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey}; use winit_core::monitor::Fullscreen; -use winit_core::window::{SurfaceId, WindowAttributes}; +use winit_core::window::{WindowAttributes, WindowId}; use super::super::cursor::CursorHandler; use super::super::event_loop::runner; @@ -35,7 +35,7 @@ use crate::WindowAttributesWeb; pub struct Canvas { main_thread: MainThreadMarker, common: Common, - id: SurfaceId, + id: WindowId, pub has_focus: Rc>, pub prevent_default: Rc>, pub is_intersecting: Cell>, @@ -81,7 +81,7 @@ pub struct Style { impl Canvas { pub(crate) fn create( main_thread: MainThreadMarker, - id: SurfaceId, + id: WindowId, window: web_sys::Window, navigator: Navigator, document: Document, @@ -489,7 +489,7 @@ impl Canvas { pub(crate) fn handle_scale_change( &self, runner: &super::super::event_loop::runner::Shared, - event_handler: impl FnOnce(SurfaceId, WindowEvent), + event_handler: impl FnOnce(WindowId, WindowEvent), current_size: PhysicalSize, scale: f64, ) { diff --git a/winit-web/src/window.rs b/winit-web/src/window.rs index 5988a5e888..3fcbb92504 100644 --- a/winit-web/src/window.rs +++ b/winit-web/src/window.rs @@ -13,8 +13,9 @@ use winit_core::icon::Icon; use winit_core::impl_surface_downcast; use winit_core::monitor::{Fullscreen, MonitorHandle as CoremMonitorHandle}; use winit_core::window::{ - CursorGrabMode, ImeRequestError, ResizeDirection, Surface as RootSurface, SurfaceId, Theme, - UserAttentionType, Window as RootWindow, WindowAttributes, WindowButtons, WindowLevel, + CursorGrabMode, ImeRequestError, ResizeDirection, Surface as RootSurface, Theme, + UserAttentionType, Window as RootWindow, WindowAttributes, WindowButtons, WindowId, + WindowLevel, }; use crate::event_loop::ActiveEventLoop; @@ -34,7 +35,7 @@ impl fmt::Debug for Window { } pub struct Inner { - id: SurfaceId, + id: WindowId, pub window: web_sys::Window, monitor: Rc, safe_area: Rc, @@ -106,7 +107,7 @@ impl Window { impl RootSurface for Window { impl_surface_downcast!(Window); - fn id(&self) -> SurfaceId { + fn id(&self) -> WindowId { self.inner.queue(|inner| inner.id) } diff --git a/winit-x11/src/event_loop.rs b/winit-x11/src/event_loop.rs index 57da2b51c9..b1b309ecb5 100644 --- a/winit-x11/src/event_loop.rs +++ b/winit-x11/src/event_loop.rs @@ -28,7 +28,7 @@ use winit_core::event_loop::{ OwnedDisplayHandle as CoreOwnedDisplayHandle, }; use winit_core::monitor::MonitorHandle as CoreMonitorHandle; -use winit_core::window::{SurfaceId, Theme, Window as CoreWindow, WindowAttributes}; +use winit_core::window::{Theme, Window as CoreWindow, WindowAttributes, WindowId}; use x11rb::connection::RequestConnection; use x11rb::errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError}; use x11rb::protocol::xinput::{self, ConnectionExt as _}; @@ -176,8 +176,8 @@ pub struct ActiveEventLoop { exit: Cell>, pub(crate) root: xproto::Window, pub(crate) ime: Option>, - pub(crate) windows: RefCell>>, - pub(crate) redraw_sender: WakeSender, + pub(crate) windows: RefCell>>, + pub(crate) redraw_sender: WakeSender, pub(crate) activation_sender: WakeSender, event_loop_proxy: CoreEventLoopProxy, device_events: Cell, @@ -188,14 +188,14 @@ pub struct EventLoop { loop_running: bool, event_loop: Loop<'static, EventLoopState>, event_processor: EventProcessor, - redraw_receiver: PeekableReceiver, + redraw_receiver: PeekableReceiver, activation_receiver: PeekableReceiver, /// The current state of the event loop. state: EventLoopState, } -pub(crate) type ActivationItem = (SurfaceId, winit_core::event_loop::AsyncRequestSerial); +pub(crate) type ActivationItem = (WindowId, winit_core::event_loop::AsyncRequestSerial); #[derive(Debug)] struct EventLoopState { @@ -991,8 +991,8 @@ impl CookieResultExt for Result, E> { } } -pub(crate) fn mkwid(w: xproto::Window) -> winit_core::window::SurfaceId { - winit_core::window::SurfaceId::from_raw(w as _) +pub(crate) fn mkwid(w: xproto::Window) -> winit_core::window::WindowId { + winit_core::window::WindowId::from_raw(w as _) } pub(crate) fn mkdid(w: xinput::DeviceId) -> DeviceId { diff --git a/winit-x11/src/event_processor.rs b/winit-x11/src/event_processor.rs index e782495736..eaf50260e4 100644 --- a/winit-x11/src/event_processor.rs +++ b/winit-x11/src/event_processor.rs @@ -13,7 +13,7 @@ use winit_core::event::{ WindowEvent, }; use winit_core::keyboard::ModifiersState; -use winit_core::window::SurfaceId; +use winit_core::window::WindowId; use x11_dl::xinput2::{ self, XIDeviceEvent, XIEnterEvent, XIFocusInEvent, XIFocusOutEvent, XIHierarchyEvent, XILeaveEvent, XIModifierState, XIRawEvent, @@ -334,7 +334,7 @@ impl EventProcessor { F: Fn(&Arc) -> Ret, { let mut deleted = false; - let window_id = SurfaceId::from_raw(window_id as _); + let window_id = WindowId::from_raw(window_id as _); let result = self .target .windows @@ -784,7 +784,7 @@ impl EventProcessor { // In the event that the window's been destroyed without being dropped first, we // cleanup again here. - self.target.windows.borrow_mut().remove(&SurfaceId::from_raw(window as _)); + self.target.windows.borrow_mut().remove(&WindowId::from_raw(window as _)); // Since all XIM stuff needs to happen from the same thread, we destroy the input // context here instead of when dropping the window. @@ -936,7 +936,7 @@ impl EventProcessor { fn send_synthic_modifier_from_core( &mut self, - window_id: winit_core::window::SurfaceId, + window_id: winit_core::window::WindowId, state: u16, app: &mut dyn ApplicationHandler, ) { @@ -1553,7 +1553,7 @@ impl EventProcessor { fn update_mods_from_query( &mut self, - window_id: winit_core::window::SurfaceId, + window_id: winit_core::window::WindowId, app: &mut dyn ApplicationHandler, ) { let xkb_state = match self.xkb_context.state_mut() { @@ -1586,7 +1586,7 @@ impl EventProcessor { pub(crate) fn update_mods_from_core_event( &mut self, - window_id: winit_core::window::SurfaceId, + window_id: winit_core::window::WindowId, state: u16, app: &mut dyn ApplicationHandler, ) { @@ -1663,7 +1663,7 @@ impl EventProcessor { /// unless `force` is passed. The `force` should be passed when the active window changes. fn send_modifiers( &self, - window_id: winit_core::window::SurfaceId, + window_id: winit_core::window::WindowId, modifiers: ModifiersState, force: bool, app: &mut dyn ApplicationHandler, @@ -1678,7 +1678,7 @@ impl EventProcessor { fn handle_pressed_keys( target: &ActiveEventLoop, - window_id: winit_core::window::SurfaceId, + window_id: winit_core::window::WindowId, state: ElementState, xkb_context: &mut Context, app: &mut dyn ApplicationHandler, diff --git a/winit-x11/src/window.rs b/winit-x11/src/window.rs index 7fa42f34ef..68a8e4d7a3 100644 --- a/winit-x11/src/window.rs +++ b/winit-x11/src/window.rs @@ -22,8 +22,8 @@ use winit_core::monitor::{ }; use winit_core::window::{ CursorGrabMode, ImeCapabilities, ImeRequest as CoreImeRequest, ImeRequestError, - ResizeDirection, Surface as CoreSurface, SurfaceId, Theme, UserAttentionType, - Window as CoreWindow, WindowAttributes, WindowButtons, WindowLevel, + ResizeDirection, Surface as CoreSurface, Theme, UserAttentionType, Window as CoreWindow, + WindowAttributes, WindowButtons, WindowId, WindowLevel, }; use x11rb::connection::{Connection, RequestConnection}; use x11rb::properties::{WmHints, WmSizeHints, WmSizeHintsSpecification}; @@ -70,7 +70,7 @@ impl Window { impl CoreSurface for Window { impl_surface_downcast!(Window); - fn id(&self) -> SurfaceId { + fn id(&self) -> WindowId { self.0.id() } @@ -432,7 +432,7 @@ pub struct UnownedWindow { cursor_visible: Mutex, ime_sender: Mutex, pub shared_state: Mutex, - redraw_sender: WakeSender, + redraw_sender: WakeSender, activation_sender: WakeSender, } macro_rules! leap { @@ -2216,8 +2216,8 @@ impl UnownedWindow { } #[inline] - pub fn id(&self) -> SurfaceId { - SurfaceId::from_raw(self.xwindow as _) + pub fn id(&self) -> WindowId { + WindowId::from_raw(self.xwindow as _) } pub(super) fn sync_counter_id(&self) -> Option { @@ -2226,7 +2226,7 @@ impl UnownedWindow { #[inline] pub fn request_redraw(&self) { - self.redraw_sender.send(SurfaceId::from_raw(self.xwindow as _)); + self.redraw_sender.send(WindowId::from_raw(self.xwindow as _)); } #[inline] From dbb7ec43308121447b011e40e5e114538c73c98b Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Fri, 11 Jul 2025 17:19:57 -0400 Subject: [PATCH 17/18] fix examples not compiling --- examples/application.rs | 12 ++++++------ examples/child_window.rs | 8 ++++---- examples/control_flow.rs | 4 ++-- examples/dnd.rs | 4 ++-- examples/pump_events.rs | 4 ++-- examples/run_on_demand.rs | 6 +++--- examples/util/fill.rs | 4 ++-- examples/window.rs | 4 ++-- examples/x11_embed.rs | 4 ++-- 9 files changed, 25 insertions(+), 25 deletions(-) diff --git a/examples/application.rs b/examples/application.rs index 0e6c2dbe24..00a77db2f2 100644 --- a/examples/application.rs +++ b/examples/application.rs @@ -41,7 +41,7 @@ use winit::platform::web::{ActiveEventLoopExtWeb, WindowAttributesWeb}; use winit::platform::x11::{ActiveEventLoopExtX11, WindowAttributesX11}; use winit::window::{ CursorGrabMode, ImeCapabilities, ImeEnableRequest, ImePurpose, ImeRequestData, ResizeDirection, - SurfaceId, Theme, Window, WindowAttributes, + WindowId, Theme, Window, WindowAttributes, }; use winit_core::application::macos::ApplicationHandlerExtMacOS; use winit_core::window::ImeRequest; @@ -95,7 +95,7 @@ struct Application { custom_cursors: Result, RequestError>, /// Application icon. icon: Icon, - windows: HashMap, + windows: HashMap, /// Drawing context. /// /// With OpenGL it could be EGLDisplay. @@ -147,7 +147,7 @@ impl Application { &mut self, event_loop: &dyn ActiveEventLoop, _tab_id: Option, - ) -> Result> { + ) -> Result> { // TODO read-out activation token. #[allow(unused_mut)] @@ -213,7 +213,7 @@ impl Application { fn handle_action_with_window( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, action: Action, ) { // let cursor_position = self.cursor_position; @@ -415,7 +415,7 @@ impl ApplicationHandler for Application { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, event: WindowEvent, ) { let window = match self.windows.get_mut(&window_id) { @@ -601,7 +601,7 @@ impl ApplicationHandlerExtMacOS for Application { fn standard_key_binding( &mut self, _event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, action: &str, ) { info!(?window_id, ?action, "macOS standard key binding"); diff --git a/examples/child_window.rs b/examples/child_window.rs index 7f359b74ee..1e70f68675 100644 --- a/examples/child_window.rs +++ b/examples/child_window.rs @@ -8,7 +8,7 @@ fn main() -> Result<(), impl std::error::Error> { use winit::event::{ElementState, KeyEvent, WindowEvent}; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::raw_window_handle::HasRawWindowHandle; - use winit::window::{SurfaceId, Window, WindowAttributes}; + use winit::window::{WindowId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; @@ -27,8 +27,8 @@ fn main() -> Result<(), impl std::error::Error> { #[derive(Default, Debug)] struct Application { - parent_window_id: Option, - windows: HashMap, + parent_window_id: Option, + windows: HashMap, } impl ApplicationHandler for Application { @@ -47,7 +47,7 @@ fn main() -> Result<(), impl std::error::Error> { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: winit::window::SurfaceId, + window_id: winit::window::WindowId, event: WindowEvent, ) { match event { diff --git a/examples/control_flow.rs b/examples/control_flow.rs index 6a7a9f0f0f..bbd4475be6 100644 --- a/examples/control_flow.rs +++ b/examples/control_flow.rs @@ -11,7 +11,7 @@ use winit::application::ApplicationHandler; use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent}; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; use winit::keyboard::{Key, NamedKey}; -use winit::window::{SurfaceId, Window, WindowAttributes}; +use winit::window::{WindowId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; @@ -75,7 +75,7 @@ impl ApplicationHandler for ControlFlowDemo { fn window_event( &mut self, _event_loop: &dyn ActiveEventLoop, - _window_id: SurfaceId, + _window_id: WindowId, event: WindowEvent, ) { info!("{event:?}"); diff --git a/examples/dnd.rs b/examples/dnd.rs index 71e198e9b3..5d674bb02c 100644 --- a/examples/dnd.rs +++ b/examples/dnd.rs @@ -3,7 +3,7 @@ use std::error::Error; use winit::application::ApplicationHandler; use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; -use winit::window::{SurfaceId, Window, WindowAttributes}; +use winit::window::{WindowId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; @@ -41,7 +41,7 @@ impl ApplicationHandler for Application { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - _window_id: SurfaceId, + _window_id: WindowId, event: WindowEvent, ) { match event { diff --git a/examples/pump_events.rs b/examples/pump_events.rs index 8af60a0a6a..5cce9f0785 100644 --- a/examples/pump_events.rs +++ b/examples/pump_events.rs @@ -11,7 +11,7 @@ fn main() -> std::process::ExitCode { use winit::event::WindowEvent; use winit::event_loop::pump_events::{EventLoopExtPumpEvents, PumpStatus}; use winit::event_loop::{ActiveEventLoop, EventLoop}; - use winit::window::{SurfaceId, Window, WindowAttributes}; + use winit::window::{WindowId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; @@ -30,7 +30,7 @@ fn main() -> std::process::ExitCode { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - _window_id: SurfaceId, + _window_id: WindowId, event: WindowEvent, ) { println!("{event:?}"); diff --git a/examples/run_on_demand.rs b/examples/run_on_demand.rs index 6b48988130..8bd86cd58a 100644 --- a/examples/run_on_demand.rs +++ b/examples/run_on_demand.rs @@ -9,7 +9,7 @@ fn main() -> Result<(), Box> { use winit::event::WindowEvent; use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand; use winit::event_loop::{ActiveEventLoop, EventLoop}; - use winit::window::{SurfaceId, Window, WindowAttributes}; + use winit::window::{WindowId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; @@ -17,7 +17,7 @@ fn main() -> Result<(), Box> { #[derive(Default, Debug)] struct App { idx: usize, - window_id: Option, + window_id: Option, window: Option>, } @@ -40,7 +40,7 @@ fn main() -> Result<(), Box> { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - window_id: SurfaceId, + window_id: WindowId, event: WindowEvent, ) { if event == WindowEvent::Destroyed && self.window_id == Some(window_id) { diff --git a/examples/util/fill.rs b/examples/util/fill.rs index a77bbac7ef..22423ac74b 100644 --- a/examples/util/fill.rs +++ b/examples/util/fill.rs @@ -29,7 +29,7 @@ mod platform { use softbuffer::{Context, Surface}; #[cfg(all(web_platform, not(android_platform)))] use web_time::Instant; - use winit::window::{SurfaceId, Window}; + use winit::window::{WindowId, Window}; thread_local! { // NOTE: You should never do things like that, create context and drop it before @@ -46,7 +46,7 @@ mod platform { context: RefCell>, /// The hash map of window IDs to surfaces. - surfaces: HashMap>, + surfaces: HashMap>, } impl GraphicsContext { diff --git a/examples/window.rs b/examples/window.rs index f9a7383980..c92593648d 100644 --- a/examples/window.rs +++ b/examples/window.rs @@ -7,7 +7,7 @@ use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; #[cfg(web_platform)] use winit::platform::web::WindowAttributesWeb; -use winit::window::{SurfaceId, Window, WindowAttributes}; +use winit::window::{WindowId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; @@ -36,7 +36,7 @@ impl ApplicationHandler for App { } } - fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _: SurfaceId, event: WindowEvent) { + fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _: WindowId, event: WindowEvent) { println!("{event:?}"); match event { WindowEvent::CloseRequested => { diff --git a/examples/x11_embed.rs b/examples/x11_embed.rs index ded67b3332..54ca5933a4 100644 --- a/examples/x11_embed.rs +++ b/examples/x11_embed.rs @@ -7,7 +7,7 @@ fn main() -> Result<(), Box> { use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::platform::x11::WindowAttributesX11; - use winit::window::{SurfaceId, Window, WindowAttributes}; + use winit::window::{WindowId, Window, WindowAttributes}; #[path = "util/fill.rs"] mod fill; @@ -33,7 +33,7 @@ fn main() -> Result<(), Box> { fn window_event( &mut self, event_loop: &dyn ActiveEventLoop, - _window_id: SurfaceId, + _window_id: WindowId, event: WindowEvent, ) { let window = self.window.as_ref().unwrap(); From 56f14819b56563a2836024e6c82f88146715d5ff Mon Sep 17 00:00:00 2001 From: jgcodes2020 Date: Fri, 11 Jul 2025 17:22:17 -0400 Subject: [PATCH 18/18] fix tests not compiling --- winit/tests/send_objects.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/winit/tests/send_objects.rs b/winit/tests/send_objects.rs index dbb0023929..48bfa3b94f 100644 --- a/winit/tests/send_objects.rs +++ b/winit/tests/send_objects.rs @@ -18,7 +18,7 @@ fn window_builder_send() { #[test] fn ids_send() { - needs_send::(); + needs_send::(); needs_send::(); needs_send::(); }