file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
src/platform/unix.rs
Rust
use glib::IsA; use crate::{ event_loop::EventLoopWindowTarget, platform_impl::ApplicationName, window::{Window, WindowBuilder}, }; pub use crate::platform_impl::hit_test; /// Additional methods on `Window` that are specific to Unix. pub trait WindowExtUnix { /// Returns the `gtk::ApplicatonWindow` from gtk crate that is used by this window. fn gtk_window(&self) -> &gtk::ApplicationWindow; /// Returns the vertical `gtk::Box` that is added by default as the sole child of this window. /// Returns `None` if the default vertical `gtk::Box` creation was disabled by [`WindowBuilderExtUnix::with_default_vbox`]. fn default_vbox(&self) -> Option<&gtk::Box>; /// Whether to show the window icon in the taskbar or not. fn set_skip_taskbar(&self, skip: bool); } impl WindowExtUnix for Window { fn gtk_window(&self) -> &gtk::ApplicationWindow { &self.window.window } fn default_vbox(&self) -> Option<&gtk::Box> { self.window.default_vbox.as_ref() } fn set_skip_taskbar(&self, skip: bool) { self.window.set_skip_taskbar(skip); } } pub trait WindowBuilderExtUnix { /// Build window with the given `general` and `instance` names. /// /// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the /// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "general", "instance"`. /// /// For details about application ID conventions, see the /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self; /// Whether to create the window icon with the taskbar icon or not. fn with_skip_taskbar(self, skip: bool) -> WindowBuilder; /// Set this window as a transient dialog for `parent` /// <https://gtk-rs.org/gtk3-rs/stable/latest/docs/gdk/struct.Window.html#method.set_transient_for> fn with_transient_for(self, parent: &impl IsA<gtk::Window>) -> WindowBuilder; /// Whether to enable or disable the internal draw for transparent window. /// /// When tranparent attribute is enabled, we will call `connect_draw` and draw a transparent background. /// For anyone who wants to draw the background themselves, set this to `false`. /// Default is `true`. fn with_transparent_draw(self, draw: bool) -> WindowBuilder; /// Whether to enable or disable the double buffered rendering of the window. /// /// Default is `true`. fn with_double_buffered(self, double_buffered: bool) -> WindowBuilder; /// Whether to enable the rgba visual for the window. /// /// Default is `false` but is always `true` if [`WindowAttributes::transparent`](crate::window::WindowAttributes::transparent) is `true` fn with_rgba_visual(self, rgba_visual: bool) -> WindowBuilder; /// Wether to set this window as app paintable /// /// <https://docs.gtk.org/gtk3/method.Widget.set_app_paintable.html> /// /// Default is `false` but is always `true` if [`WindowAttributes::transparent`](crate::window::WindowAttributes::transparent) is `true` fn with_app_paintable(self, app_paintable: bool) -> WindowBuilder; /// Whether to create a vertical `gtk::Box` and add it as the sole child of this window. /// Created by default. fn with_default_vbox(self, add: bool) -> WindowBuilder; } impl WindowBuilderExtUnix for WindowBuilder { fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self { // TODO We haven't implemented it yet. self.platform_specific.name = Some(ApplicationName::new(general.into(), instance.into())); self } fn with_transient_for(mut self, parent: &impl IsA<gtk::Window>) -> WindowBuilder { self.platform_specific.parent = Some(parent.clone().into()); self } fn with_skip_taskbar(mut self, skip: bool) -> WindowBuilder { self.platform_specific.skip_taskbar = skip; self } fn with_transparent_draw(mut self, draw: bool) -> WindowBuilder { self.platform_specific.auto_transparent = draw; self } fn with_double_buffered(mut self, double_buffered: bool) -> WindowBuilder { self.platform_specific.double_buffered = double_buffered; self } fn with_rgba_visual(mut self, rgba_visual: bool) -> WindowBuilder { self.platform_specific.rgba_visual = rgba_visual; self } fn with_app_paintable(mut self, app_paintable: bool) -> WindowBuilder { self.platform_specific.app_paintable = app_paintable; self } fn with_default_vbox(mut self, add: bool) -> WindowBuilder { self.platform_specific.default_vbox = add; self } } /// Additional methods on `EventLoopWindowTarget` that are specific to Unix. pub trait EventLoopWindowTargetExtUnix { /// True if the `EventLoopWindowTarget` uses Wayland. fn is_wayland(&self) -> bool; } impl<T> EventLoopWindowTargetExtUnix for EventLoopWindowTarget<T> { #[inline] fn is_wayland(&self) -> bool { self.p.is_wayland() } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform/wayland.rs
Rust
use std::os::raw; use crate::{ event_loop::{EventLoopBuilder, EventLoopWindowTarget}, monitor::MonitorHandle, window::{Window, WindowBuilder}, }; use crate::platform_impl::{ ApplicationName, Backend, EventLoopWindowTarget as LinuxEventLoopWindowTarget, Window as LinuxWindow, }; pub use crate::window::Theme; /// Additional methods on [`EventLoopWindowTarget`] that are specific to Wayland. pub trait EventLoopWindowTargetExtWayland { /// True if the [`EventLoopWindowTarget`] uses Wayland. fn is_wayland(&self) -> bool; /// Returns a pointer to the `wl_display` object of wayland that is used by this /// [`EventLoopWindowTarget`]. /// /// Returns `None` if the [`EventLoop`] doesn't use wayland (if it uses xlib for example). /// /// The pointer will become invalid when the winit [`EventLoop`] is destroyed. /// /// [`EventLoop`]: crate::event_loop::EventLoop fn wayland_display(&self) -> Option<*mut raw::c_void>; } impl<T> EventLoopWindowTargetExtWayland for EventLoopWindowTarget<T> { #[inline] fn is_wayland(&self) -> bool { self.p.is_wayland() } #[inline] fn wayland_display(&self) -> Option<*mut raw::c_void> { match self.p { LinuxEventLoopWindowTarget::Wayland(ref p) => { Some(p.display().get_display_ptr() as *mut _) } #[cfg(x11_platform)] _ => None, } } } /// Additional methods on [`EventLoopBuilder`] that are specific to Wayland. pub trait EventLoopBuilderExtWayland { /// Force using Wayland. fn with_wayland(&mut self) -> &mut Self; /// Whether to allow the event loop to be created off of the main thread. /// /// By default, the window is only allowed to be created on the main /// thread, to make platform compatibility easier. fn with_any_thread(&mut self, any_thread: bool) -> &mut Self; } impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> { #[inline] fn with_wayland(&mut self) -> &mut Self { self.platform_specific.forced_backend = Some(Backend::Wayland); self } #[inline] fn with_any_thread(&mut self, any_thread: bool) -> &mut Self { self.platform_specific.any_thread = any_thread; self } } /// Additional methods on [`Window`] that are specific to Wayland. pub trait WindowExtWayland { /// Returns a pointer to the `wl_surface` object of wayland that is used by this window. /// /// Returns `None` if the window doesn't use wayland (if it uses xlib for example). /// /// The pointer will become invalid when the [`Window`] is destroyed. fn wayland_surface(&self) -> Option<*mut raw::c_void>; /// Returns a pointer to the `wl_display` object of wayland that is used by this window. /// /// Returns `None` if the window doesn't use wayland (if it uses xlib for example). /// /// The pointer will become invalid when the [`Window`] is destroyed. fn wayland_display(&self) -> Option<*mut raw::c_void>; } impl WindowExtWayland for Window { #[inline] fn wayland_surface(&self) -> Option<*mut raw::c_void> { match self.window { LinuxWindow::Wayland(ref w) => Some(w.surface().as_ref().c_ptr() as *mut _), #[cfg(x11_platform)] _ => None, } } #[inline] fn wayland_display(&self) -> Option<*mut raw::c_void> { match self.window { LinuxWindow::Wayland(ref w) => Some(w.display().get_display_ptr() as *mut _), #[cfg(x11_platform)] _ => None, } } } /// Additional methods on [`WindowBuilder`] that are specific to Wayland. pub trait WindowBuilderExtWayland { /// Build window with the given name. /// /// The `general` name sets an application ID, which should match the `.desktop` /// file destributed with your program. The `instance` is a `no-op`. /// /// For details about application ID conventions, see the /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self; } impl WindowBuilderExtWayland for WindowBuilder { #[inline] fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self { self.platform_specific.name = Some(ApplicationName::new(general.into(), instance.into())); self } } /// Additional methods on `MonitorHandle` that are specific to Wayland. pub trait MonitorHandleExtWayland { /// Returns the inner identifier of the monitor. fn native_id(&self) -> u32; } impl MonitorHandleExtWayland for MonitorHandle { #[inline] fn native_id(&self) -> u32 { self.inner.native_identifier() } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform/web.rs
Rust
//! The web target does not automatically insert the canvas element object into the web page, to //! allow end users to determine how the page should be laid out. Use the [`WindowExtWebSys`] trait //! to retrieve the canvas from the Window. Alternatively, use the [`WindowBuilderExtWebSys`] trait //! to provide your own canvas. use crate::event::Event; use crate::event_loop::ControlFlow; use crate::event_loop::EventLoop; use crate::event_loop::EventLoopWindowTarget; use crate::window::WindowBuilder; use web_sys::HtmlCanvasElement; pub trait WindowExtWebSys { fn canvas(&self) -> HtmlCanvasElement; /// Whether the browser reports the preferred color scheme to be "dark". fn is_dark_mode(&self) -> bool; } pub trait WindowBuilderExtWebSys { fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self; /// Whether `event.preventDefault` should be automatically called to prevent event propagation /// when appropriate. /// /// For example, mouse wheel events are only handled by the canvas by default. This avoids /// the default behavior of scrolling the page. fn with_prevent_default(self, prevent_default: bool) -> Self; /// Whether the canvas should be focusable using the tab key. This is necessary to capture /// canvas keyboard events. fn with_focusable(self, focusable: bool) -> Self; } impl WindowBuilderExtWebSys for WindowBuilder { fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self { self.platform_specific.canvas = canvas; self } fn with_prevent_default(mut self, prevent_default: bool) -> Self { self.platform_specific.prevent_default = prevent_default; self } fn with_focusable(mut self, focusable: bool) -> Self { self.platform_specific.focusable = focusable; self } } /// Additional methods on `EventLoop` that are specific to the web. pub trait EventLoopExtWebSys { /// A type provided by the user that can be passed through `Event::UserEvent`. type UserEvent; /// Initializes the winit event loop. /// /// Unlike `run`, this returns immediately, and doesn't throw an exception in order to /// satisfy its `!` return type. fn spawn<F>(self, event_handler: F) where F: 'static + FnMut( Event<'_, Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>, &mut ControlFlow, ); } impl<T> EventLoopExtWebSys for EventLoop<T> { type UserEvent = T; fn spawn<F>(self, event_handler: F) where F: 'static + FnMut( Event<'_, Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>, &mut ControlFlow, ), { self.event_loop.spawn(event_handler) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform/windows.rs
Rust
use std::{ffi::c_void, path::Path}; use crate::{ dpi::PhysicalSize, event::DeviceId, event_loop::EventLoopBuilder, monitor::MonitorHandle, platform_impl::WinIcon, window::{BadIcon, Icon, Window, WindowBuilder}, }; /// Window Handle type used by Win32 API pub type HWND = isize; /// Menu Handle type used by Win32 API pub type HMENU = isize; /// Monitor Handle type used by Win32 API pub type HMONITOR = isize; /// Instance Handle type used by Win32 API pub type HINSTANCE = isize; /// Additional methods on `EventLoop` that are specific to Windows. pub trait EventLoopBuilderExtWindows { /// Whether to allow the event loop to be created off of the main thread. /// /// By default, the window is only allowed to be created on the main /// thread, to make platform compatibility easier. /// /// # `Window` caveats /// /// Note that any `Window` created on the new thread will be destroyed when the thread /// terminates. Attempting to use a `Window` after its parent thread terminates has /// unspecified, although explicitly not undefined, behavior. fn with_any_thread(&mut self, any_thread: bool) -> &mut Self; /// Whether to enable process-wide DPI awareness. /// /// By default, `winit` will attempt to enable process-wide DPI awareness. If /// that's undesirable, you can disable it with this function. /// /// # Example /// /// Disable process-wide DPI awareness. /// /// ``` /// use winit::event_loop::EventLoopBuilder; /// #[cfg(target_os = "windows")] /// use winit::platform::windows::EventLoopBuilderExtWindows; /// /// let mut builder = EventLoopBuilder::new(); /// #[cfg(target_os = "windows")] /// builder.with_dpi_aware(false); /// # if false { // We can't test this part /// let event_loop = builder.build(); /// # } /// ``` fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self; /// A callback to be executed before dispatching a win32 message to the window procedure. /// Return true to disable winit's internal message dispatching. /// /// # Example /// /// ``` /// # use windows_sys::Win32::UI::WindowsAndMessaging::{ACCEL, CreateAcceleratorTableW, TranslateAcceleratorW, DispatchMessageW, TranslateMessage, MSG}; /// use winit::event_loop::EventLoopBuilder; /// #[cfg(target_os = "windows")] /// use winit::platform::windows::EventLoopBuilderExtWindows; /// /// let mut builder = EventLoopBuilder::new(); /// #[cfg(target_os = "windows")] /// builder.with_msg_hook(|msg|{ /// let msg = msg as *const MSG; /// # let accels: Vec<ACCEL> = Vec::new(); /// let translated = unsafe { /// TranslateAcceleratorW( /// (*msg).hwnd, /// CreateAcceleratorTableW(accels.as_ptr() as _, 1), /// msg, /// ) == 1 /// }; /// translated /// }); /// ``` fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self where F: FnMut(*const c_void) -> bool + 'static; } impl<T> EventLoopBuilderExtWindows for EventLoopBuilder<T> { #[inline] fn with_any_thread(&mut self, any_thread: bool) -> &mut Self { self.platform_specific.any_thread = any_thread; self } #[inline] fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self { self.platform_specific.dpi_aware = dpi_aware; self } #[inline] fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self where F: FnMut(*const c_void) -> bool + 'static, { self.platform_specific.msg_hook = Some(Box::new(callback)); self } } /// Additional methods on `Window` that are specific to Windows. pub trait WindowExtWindows { /// Returns the HINSTANCE of the window fn hinstance(&self) -> HINSTANCE; /// Returns the native handle that is used by this window. /// /// The pointer will become invalid when the native window was destroyed. fn hwnd(&self) -> HWND; /// Enables or disables mouse and keyboard input to the specified window. /// /// A window must be enabled before it can be activated. /// If an application has create a modal dialog box by disabling its owner window /// (as described in [`WindowBuilderExtWindows::with_owner_window`]), the application must enable /// the owner window before destroying the dialog box. /// Otherwise, another window will receive the keyboard focus and be activated. /// /// If a child window is disabled, it is ignored when the system tries to determine which /// window should receive mouse messages. /// /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enablewindow#remarks> /// and <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#disabled-windows> fn set_enable(&self, enabled: bool); /// This sets `ICON_BIG`. A good ceiling here is 256x256. fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>); /// Whether to show or hide the window icon in the taskbar. fn set_skip_taskbar(&self, skip: bool); /// Shows or hides the background drop shadow for undecorated windows. /// /// Enabling the shadow causes a thin 1px line to appear on the top of the window. fn set_undecorated_shadow(&self, shadow: bool); } impl WindowExtWindows for Window { #[inline] fn hinstance(&self) -> HINSTANCE { self.window.hinstance() } #[inline] fn hwnd(&self) -> HWND { self.window.hwnd() } #[inline] fn set_enable(&self, enabled: bool) { self.window.set_enable(enabled) } #[inline] fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) { self.window.set_taskbar_icon(taskbar_icon) } #[inline] fn set_skip_taskbar(&self, skip: bool) { self.window.set_skip_taskbar(skip) } #[inline] fn set_undecorated_shadow(&self, shadow: bool) { self.window.set_undecorated_shadow(shadow) } } /// Additional methods on `WindowBuilder` that are specific to Windows. pub trait WindowBuilderExtWindows { /// Set an owner to the window to be created. Can be used to create a dialog box, for example. /// This only works when [`WindowBuilder::with_parent_window`] isn't called or set to `None`. /// Can be used in combination with [`WindowExtWindows::set_enable(false)`](WindowExtWindows::set_enable) /// on the owner window to create a modal dialog box. /// /// From MSDN: /// - An owned window is always above its owner in the z-order. /// - The system automatically destroys an owned window when its owner is destroyed. /// - An owned window is hidden when its owner is minimized. /// /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows> fn with_owner_window(self, parent: HWND) -> WindowBuilder; /// Sets a menu on the window to be created. /// /// Parent and menu are mutually exclusive; a child window cannot have a menu! /// /// The menu must have been manually created beforehand with [`CreateMenu`] or similar. /// /// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how the menus look. /// If you use this, it is recommended that you combine it with `with_theme(Some(Theme::Light))` to avoid a jarring effect. /// /// [`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu fn with_menu(self, menu: HMENU) -> WindowBuilder; /// This sets `ICON_BIG`. A good ceiling here is 256x256. fn with_taskbar_icon(self, taskbar_icon: Option<Icon>) -> WindowBuilder; /// This sets `WS_EX_NOREDIRECTIONBITMAP`. fn with_no_redirection_bitmap(self, flag: bool) -> WindowBuilder; /// Enables or disables drag and drop support (enabled by default). Will interfere with other crates /// that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` instead of /// `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still attempt to initialize /// COM API regardless of this option. Currently only fullscreen mode does that, but there may be more in the future. /// If you need COM API with `COINIT_MULTITHREADED` you must initialize it before calling any winit functions. /// See <https://docs.microsoft.com/en-us/windows/win32/api/objbase/nf-objbase-coinitialize#remarks> for more information. fn with_drag_and_drop(self, flag: bool) -> WindowBuilder; /// Whether show or hide the window icon in the taskbar. fn with_skip_taskbar(self, skip: bool) -> WindowBuilder; /// Shows or hides the background drop shadow for undecorated windows. /// /// The shadow is hidden by default. /// Enabling the shadow causes a thin 1px line to appear on the top of the window. fn with_undecorated_shadow(self, shadow: bool) -> WindowBuilder; } impl WindowBuilderExtWindows for WindowBuilder { #[inline] fn with_owner_window(mut self, parent: HWND) -> WindowBuilder { self.platform_specific.owner = Some(parent); self } #[inline] fn with_menu(mut self, menu: HMENU) -> WindowBuilder { self.platform_specific.menu = Some(menu); self } #[inline] fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> WindowBuilder { self.platform_specific.taskbar_icon = taskbar_icon; self } #[inline] fn with_no_redirection_bitmap(mut self, flag: bool) -> WindowBuilder { self.platform_specific.no_redirection_bitmap = flag; self } #[inline] fn with_drag_and_drop(mut self, flag: bool) -> WindowBuilder { self.platform_specific.drag_and_drop = flag; self } #[inline] fn with_skip_taskbar(mut self, skip: bool) -> WindowBuilder { self.platform_specific.skip_taskbar = skip; self } #[inline] fn with_undecorated_shadow(mut self, shadow: bool) -> WindowBuilder { self.platform_specific.decoration_shadow = shadow; self } } /// Additional methods on `MonitorHandle` that are specific to Windows. pub trait MonitorHandleExtWindows { /// Returns the name of the monitor adapter specific to the Win32 API. fn native_id(&self) -> String; /// Returns the handle of the monitor - `HMONITOR`. fn hmonitor(&self) -> HMONITOR; } impl MonitorHandleExtWindows for MonitorHandle { #[inline] fn native_id(&self) -> String { self.inner.native_identifier() } #[inline] fn hmonitor(&self) -> HMONITOR { self.inner.hmonitor() } } /// Additional methods on `DeviceId` that are specific to Windows. pub trait DeviceIdExtWindows { /// Returns an identifier that persistently refers to this specific device. /// /// Will return `None` if the device is no longer available. fn persistent_identifier(&self) -> Option<String>; } impl DeviceIdExtWindows for DeviceId { #[inline] fn persistent_identifier(&self) -> Option<String> { self.0.persistent_identifier() } } /// Additional methods on `Icon` that are specific to Windows. pub trait IconExtWindows: Sized { /// Create an icon from a file path. /// /// Specify `size` to load a specific icon size from the file, or `None` to load the default /// icon size from the file. /// /// In cases where the specified size does not exist in the file, Windows may perform scaling /// to get an icon of the desired size. fn from_path<P: AsRef<Path>>(path: P, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>; /// Create an icon from a resource embedded in this executable or library. /// /// Specify `size` to load a specific icon size from the file, or `None` to load the default /// icon size from the file. /// /// In cases where the specified size does not exist in the file, Windows may perform scaling /// to get an icon of the desired size. fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>; } impl IconExtWindows for Icon { fn from_path<P: AsRef<Path>>( path: P, size: Option<PhysicalSize<u32>>, ) -> Result<Self, BadIcon> { let win_icon = WinIcon::from_path(path, size)?; Ok(Icon { inner: win_icon }) } fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> { let win_icon = WinIcon::from_resource(ordinal, size)?; Ok(Icon { inner: win_icon }) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform/x11.rs
Rust
use std::os::raw; use std::ptr; use crate::{ event_loop::{EventLoopBuilder, EventLoopWindowTarget}, monitor::MonitorHandle, window::{Window, WindowBuilder}, }; use crate::dpi::Size; use crate::platform_impl::{ x11::ffi::XVisualInfo, ApplicationName, Backend, Window as LinuxWindow, XLIB_ERROR_HOOKS, }; pub use crate::platform_impl::{x11::util::WindowType as XWindowType, XNotSupported}; /// The first argument in the provided hook will be the pointer to `XDisplay` /// and the second one the pointer to [`XErrorEvent`]. The returned `bool` is an /// indicator whether the error was handled by the callback. /// /// [`XErrorEvent`]: https://linux.die.net/man/3/xerrorevent pub type XlibErrorHook = Box<dyn Fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> bool + Send + Sync>; /// Hook to winit's xlib error handling callback. /// /// This method is provided as a safe way to handle the errors comming from X11 /// when using xlib in external crates, like glutin for GLX access. Trying to /// handle errors by speculating with `XSetErrorHandler` is [`unsafe`]. /// /// **Be aware that your hook is always invoked and returning `true` from it will /// prevent `winit` from getting the error itself. It's wise to always return /// `false` if you're not initiated the `Sync`.** /// /// [`unsafe`]: https://www.remlab.net/op/xlib.shtml #[inline] pub fn register_xlib_error_hook(hook: XlibErrorHook) { // Append new hook. unsafe { XLIB_ERROR_HOOKS.lock().unwrap().push(hook); } } /// Additional methods on [`EventLoopWindowTarget`] that are specific to X11. pub trait EventLoopWindowTargetExtX11 { /// True if the [`EventLoopWindowTarget`] uses X11. fn is_x11(&self) -> bool; } impl<T> EventLoopWindowTargetExtX11 for EventLoopWindowTarget<T> { #[inline] fn is_x11(&self) -> bool { !self.p.is_wayland() } } /// Additional methods on [`EventLoopBuilder`] that are specific to X11. pub trait EventLoopBuilderExtX11 { /// Force using X11. fn with_x11(&mut self) -> &mut Self; /// Whether to allow the event loop to be created off of the main thread. /// /// By default, the window is only allowed to be created on the main /// thread, to make platform compatibility easier. fn with_any_thread(&mut self, any_thread: bool) -> &mut Self; } impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> { #[inline] fn with_x11(&mut self) -> &mut Self { self.platform_specific.forced_backend = Some(Backend::X); self } #[inline] fn with_any_thread(&mut self, any_thread: bool) -> &mut Self { self.platform_specific.any_thread = any_thread; self } } /// Additional methods on [`Window`] that are specific to X11. pub trait WindowExtX11 { /// Returns the ID of the [`Window`] xlib object that is used by this window. /// /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). fn xlib_window(&self) -> Option<raw::c_ulong>; /// Returns a pointer to the `Display` object of xlib that is used by this window. /// /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). /// /// The pointer will become invalid when the [`Window`] is destroyed. fn xlib_display(&self) -> Option<*mut raw::c_void>; fn xlib_screen_id(&self) -> Option<raw::c_int>; /// This function returns the underlying `xcb_connection_t` of an xlib `Display`. /// /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). /// /// The pointer will become invalid when the [`Window`] is destroyed. fn xcb_connection(&self) -> Option<*mut raw::c_void>; } impl WindowExtX11 for Window { #[inline] fn xlib_window(&self) -> Option<raw::c_ulong> { match self.window { LinuxWindow::X(ref w) => Some(w.xlib_window()), #[cfg(wayland_platform)] _ => None, } } #[inline] fn xlib_display(&self) -> Option<*mut raw::c_void> { match self.window { LinuxWindow::X(ref w) => Some(w.xlib_display()), #[cfg(wayland_platform)] _ => None, } } #[inline] fn xlib_screen_id(&self) -> Option<raw::c_int> { match self.window { LinuxWindow::X(ref w) => Some(w.xlib_screen_id()), #[cfg(wayland_platform)] _ => None, } } #[inline] fn xcb_connection(&self) -> Option<*mut raw::c_void> { match self.window { LinuxWindow::X(ref w) => Some(w.xcb_connection()), #[cfg(wayland_platform)] _ => None, } } } /// Additional methods on [`WindowBuilder`] that are specific to X11. pub trait WindowBuilderExtX11 { fn with_x11_visual<T>(self, visual_infos: *const T) -> Self; fn with_x11_screen(self, screen_id: i32) -> Self; /// Build window with the given `general` and `instance` names. /// /// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the /// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "general", "instance"`. /// /// For details about application ID conventions, see the /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self; /// Build window with override-redirect flag; defaults to false. Only relevant on X11. fn with_override_redirect(self, override_redirect: bool) -> Self; /// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`. Only relevant on X11. fn with_x11_window_type(self, x11_window_type: Vec<XWindowType>) -> Self; /// Build window with base size hint. Only implemented on X11. /// /// ``` /// # use winit::dpi::{LogicalSize, PhysicalSize}; /// # use winit::window::WindowBuilder; /// # use winit::platform::x11::WindowBuilderExtX11; /// // Specify the size in logical dimensions like this: /// WindowBuilder::new().with_base_size(LogicalSize::new(400.0, 200.0)); /// /// // Or specify the size in physical dimensions like this: /// WindowBuilder::new().with_base_size(PhysicalSize::new(400, 200)); /// ``` fn with_base_size<S: Into<Size>>(self, base_size: S) -> Self; } impl WindowBuilderExtX11 for WindowBuilder { #[inline] fn with_x11_visual<T>(mut self, visual_infos: *const T) -> Self { { self.platform_specific.visual_infos = Some(unsafe { ptr::read(visual_infos as *const XVisualInfo) }); } self } #[inline] fn with_x11_screen(mut self, screen_id: i32) -> Self { self.platform_specific.screen_id = Some(screen_id); self } #[inline] fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self { self.platform_specific.name = Some(ApplicationName::new(general.into(), instance.into())); self } #[inline] fn with_override_redirect(mut self, override_redirect: bool) -> Self { self.platform_specific.override_redirect = override_redirect; self } #[inline] fn with_x11_window_type(mut self, x11_window_types: Vec<XWindowType>) -> Self { self.platform_specific.x11_window_types = x11_window_types; self } #[inline] fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self { self.platform_specific.base_size = Some(base_size.into()); self } } /// Additional methods on `MonitorHandle` that are specific to X11. pub trait MonitorHandleExtX11 { /// Returns the inner identifier of the monitor. fn native_id(&self) -> u32; } impl MonitorHandleExtX11 for MonitorHandle { #[inline] fn native_id(&self) -> u32 { self.inner.native_identifier() } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/android/mod.rs
Rust
#![cfg(android_platform)] use std::{ collections::VecDeque, hash::Hash, sync::{ atomic::{AtomicBool, Ordering}, mpsc, Arc, RwLock, }, time::{Duration, Instant}, }; use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction}; use android_activity::{ AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect, }; use once_cell::sync::Lazy; use raw_window_handle::{ AndroidDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, }; use crate::platform_impl::Fullscreen; use crate::{ dpi::{PhysicalPosition, PhysicalSize, Position, Size}, error, event::{self, StartCause, VirtualKeyCode}, event_loop::{self, ControlFlow, EventLoopWindowTarget as RootELW}, window::{ self, CursorGrabMode, ImePurpose, ResizeDirection, Theme, WindowButtons, WindowLevel, }, }; static HAS_FOCUS: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(true)); fn ndk_keycode_to_virtualkeycode(keycode: Keycode) -> Option<event::VirtualKeyCode> { match keycode { Keycode::A => Some(VirtualKeyCode::A), Keycode::B => Some(VirtualKeyCode::B), Keycode::C => Some(VirtualKeyCode::C), Keycode::D => Some(VirtualKeyCode::D), Keycode::E => Some(VirtualKeyCode::E), Keycode::F => Some(VirtualKeyCode::F), Keycode::G => Some(VirtualKeyCode::G), Keycode::H => Some(VirtualKeyCode::H), Keycode::I => Some(VirtualKeyCode::I), Keycode::J => Some(VirtualKeyCode::J), Keycode::K => Some(VirtualKeyCode::K), Keycode::L => Some(VirtualKeyCode::L), Keycode::M => Some(VirtualKeyCode::M), Keycode::N => Some(VirtualKeyCode::N), Keycode::O => Some(VirtualKeyCode::O), Keycode::P => Some(VirtualKeyCode::P), Keycode::Q => Some(VirtualKeyCode::Q), Keycode::R => Some(VirtualKeyCode::R), Keycode::S => Some(VirtualKeyCode::S), Keycode::T => Some(VirtualKeyCode::T), Keycode::U => Some(VirtualKeyCode::U), Keycode::V => Some(VirtualKeyCode::V), Keycode::W => Some(VirtualKeyCode::W), Keycode::X => Some(VirtualKeyCode::X), Keycode::Y => Some(VirtualKeyCode::Y), Keycode::Z => Some(VirtualKeyCode::Z), Keycode::Keycode0 => Some(VirtualKeyCode::Key0), Keycode::Keycode1 => Some(VirtualKeyCode::Key1), Keycode::Keycode2 => Some(VirtualKeyCode::Key2), Keycode::Keycode3 => Some(VirtualKeyCode::Key3), Keycode::Keycode4 => Some(VirtualKeyCode::Key4), Keycode::Keycode5 => Some(VirtualKeyCode::Key5), Keycode::Keycode6 => Some(VirtualKeyCode::Key6), Keycode::Keycode7 => Some(VirtualKeyCode::Key7), Keycode::Keycode8 => Some(VirtualKeyCode::Key8), Keycode::Keycode9 => Some(VirtualKeyCode::Key9), Keycode::Numpad0 => Some(VirtualKeyCode::Numpad0), Keycode::Numpad1 => Some(VirtualKeyCode::Numpad1), Keycode::Numpad2 => Some(VirtualKeyCode::Numpad2), Keycode::Numpad3 => Some(VirtualKeyCode::Numpad3), Keycode::Numpad4 => Some(VirtualKeyCode::Numpad4), Keycode::Numpad5 => Some(VirtualKeyCode::Numpad5), Keycode::Numpad6 => Some(VirtualKeyCode::Numpad6), Keycode::Numpad7 => Some(VirtualKeyCode::Numpad7), Keycode::Numpad8 => Some(VirtualKeyCode::Numpad8), Keycode::Numpad9 => Some(VirtualKeyCode::Numpad9), Keycode::NumpadAdd => Some(VirtualKeyCode::NumpadAdd), Keycode::NumpadSubtract => Some(VirtualKeyCode::NumpadSubtract), Keycode::NumpadMultiply => Some(VirtualKeyCode::NumpadMultiply), Keycode::NumpadDivide => Some(VirtualKeyCode::NumpadDivide), Keycode::NumpadEnter => Some(VirtualKeyCode::NumpadEnter), Keycode::NumpadEquals => Some(VirtualKeyCode::NumpadEquals), Keycode::NumpadComma => Some(VirtualKeyCode::NumpadComma), Keycode::NumpadDot => Some(VirtualKeyCode::NumpadDecimal), Keycode::NumLock => Some(VirtualKeyCode::Numlock), Keycode::DpadLeft => Some(VirtualKeyCode::Left), Keycode::DpadRight => Some(VirtualKeyCode::Right), Keycode::DpadUp => Some(VirtualKeyCode::Up), Keycode::DpadDown => Some(VirtualKeyCode::Down), Keycode::F1 => Some(VirtualKeyCode::F1), Keycode::F2 => Some(VirtualKeyCode::F2), Keycode::F3 => Some(VirtualKeyCode::F3), Keycode::F4 => Some(VirtualKeyCode::F4), Keycode::F5 => Some(VirtualKeyCode::F5), Keycode::F6 => Some(VirtualKeyCode::F6), Keycode::F7 => Some(VirtualKeyCode::F7), Keycode::F8 => Some(VirtualKeyCode::F8), Keycode::F9 => Some(VirtualKeyCode::F9), Keycode::F10 => Some(VirtualKeyCode::F10), Keycode::F11 => Some(VirtualKeyCode::F11), Keycode::F12 => Some(VirtualKeyCode::F12), Keycode::Space => Some(VirtualKeyCode::Space), Keycode::Escape => Some(VirtualKeyCode::Escape), Keycode::Enter => Some(VirtualKeyCode::Return), // not on the Numpad Keycode::Tab => Some(VirtualKeyCode::Tab), Keycode::PageUp => Some(VirtualKeyCode::PageUp), Keycode::PageDown => Some(VirtualKeyCode::PageDown), Keycode::MoveHome => Some(VirtualKeyCode::Home), Keycode::MoveEnd => Some(VirtualKeyCode::End), Keycode::Insert => Some(VirtualKeyCode::Insert), Keycode::Del => Some(VirtualKeyCode::Back), // Backspace (above Enter) Keycode::ForwardDel => Some(VirtualKeyCode::Delete), // Delete (below Insert) Keycode::Copy => Some(VirtualKeyCode::Copy), Keycode::Paste => Some(VirtualKeyCode::Paste), Keycode::Cut => Some(VirtualKeyCode::Cut), Keycode::VolumeUp => Some(VirtualKeyCode::VolumeUp), Keycode::VolumeDown => Some(VirtualKeyCode::VolumeDown), Keycode::VolumeMute => Some(VirtualKeyCode::Mute), // ??? Keycode::Mute => Some(VirtualKeyCode::Mute), // ??? Keycode::MediaPlayPause => Some(VirtualKeyCode::PlayPause), Keycode::MediaStop => Some(VirtualKeyCode::MediaStop), // ??? simple "Stop"? Keycode::MediaNext => Some(VirtualKeyCode::NextTrack), Keycode::MediaPrevious => Some(VirtualKeyCode::PrevTrack), Keycode::Plus => Some(VirtualKeyCode::Plus), Keycode::Minus => Some(VirtualKeyCode::Minus), Keycode::Equals => Some(VirtualKeyCode::Equals), Keycode::Semicolon => Some(VirtualKeyCode::Semicolon), Keycode::Slash => Some(VirtualKeyCode::Slash), Keycode::Backslash => Some(VirtualKeyCode::Backslash), Keycode::Comma => Some(VirtualKeyCode::Comma), Keycode::Period => Some(VirtualKeyCode::Period), Keycode::Apostrophe => Some(VirtualKeyCode::Apostrophe), Keycode::Grave => Some(VirtualKeyCode::Grave), Keycode::At => Some(VirtualKeyCode::At), // TODO: Maybe mapping this to Snapshot makes more sense? See: "PrtScr/SysRq" Keycode::Sysrq => Some(VirtualKeyCode::Sysrq), // These are usually the same (Pause/Break) Keycode::Break => Some(VirtualKeyCode::Pause), // These are exactly the same Keycode::ScrollLock => Some(VirtualKeyCode::Scroll), Keycode::Yen => Some(VirtualKeyCode::Yen), Keycode::Kana => Some(VirtualKeyCode::Kana), Keycode::CtrlLeft => Some(VirtualKeyCode::LControl), Keycode::CtrlRight => Some(VirtualKeyCode::RControl), Keycode::ShiftLeft => Some(VirtualKeyCode::LShift), Keycode::ShiftRight => Some(VirtualKeyCode::RShift), Keycode::AltLeft => Some(VirtualKeyCode::LAlt), Keycode::AltRight => Some(VirtualKeyCode::RAlt), // Different names for the same keys Keycode::MetaLeft => Some(VirtualKeyCode::LWin), Keycode::MetaRight => Some(VirtualKeyCode::RWin), Keycode::LeftBracket => Some(VirtualKeyCode::LBracket), Keycode::RightBracket => Some(VirtualKeyCode::RBracket), Keycode::Power => Some(VirtualKeyCode::Power), Keycode::Sleep => Some(VirtualKeyCode::Sleep), // what about SoftSleep? Keycode::Wakeup => Some(VirtualKeyCode::Wake), Keycode::NavigateNext => Some(VirtualKeyCode::NavigateForward), Keycode::NavigatePrevious => Some(VirtualKeyCode::NavigateBackward), Keycode::Calculator => Some(VirtualKeyCode::Calculator), Keycode::Explorer => Some(VirtualKeyCode::MyComputer), // "close enough" Keycode::Envelope => Some(VirtualKeyCode::Mail), // "close enough" Keycode::Star => Some(VirtualKeyCode::Asterisk), // ??? Keycode::AllApps => Some(VirtualKeyCode::Apps), // ??? Keycode::AppSwitch => Some(VirtualKeyCode::Apps), // ??? Keycode::Refresh => Some(VirtualKeyCode::WebRefresh), // ??? _ => None, } } struct PeekableReceiver<T> { recv: mpsc::Receiver<T>, first: Option<T>, } impl<T> PeekableReceiver<T> { pub fn from_recv(recv: mpsc::Receiver<T>) -> Self { Self { recv, first: None } } pub fn has_incoming(&mut self) -> bool { if self.first.is_some() { return true; } match self.recv.try_recv() { Ok(v) => { self.first = Some(v); true } Err(mpsc::TryRecvError::Empty) => false, Err(mpsc::TryRecvError::Disconnected) => { warn!("Channel was disconnected when checking incoming"); false } } } pub fn try_recv(&mut self) -> Result<T, mpsc::TryRecvError> { if let Some(first) = self.first.take() { return Ok(first); } self.recv.try_recv() } } #[derive(Clone)] struct SharedFlagSetter { flag: Arc<AtomicBool>, } impl SharedFlagSetter { pub fn set(&self) -> bool { self.flag .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) .is_ok() } } struct SharedFlag { flag: Arc<AtomicBool>, } // Used for queuing redraws from arbitrary threads. We don't care how many // times a redraw is requested (so don't actually need to queue any data, // we just need to know at the start of a main loop iteration if a redraw // was queued and be able to read and clear the state atomically) impl SharedFlag { pub fn new() -> Self { Self { flag: Arc::new(AtomicBool::new(false)), } } pub fn setter(&self) -> SharedFlagSetter { SharedFlagSetter { flag: self.flag.clone(), } } pub fn get_and_reset(&self) -> bool { self.flag.swap(false, std::sync::atomic::Ordering::AcqRel) } } #[derive(Clone)] pub struct RedrawRequester { flag: SharedFlagSetter, waker: AndroidAppWaker, } impl RedrawRequester { fn new(flag: &SharedFlag, waker: AndroidAppWaker) -> Self { RedrawRequester { flag: flag.setter(), waker, } } pub fn request_redraw(&self) { if self.flag.set() { // Only explicitly try to wake up the main loop when the flag // value changes self.waker.wake(); } } } pub struct EventLoop<T: 'static> { android_app: AndroidApp, window_target: event_loop::EventLoopWindowTarget<T>, redraw_flag: SharedFlag, user_events_sender: mpsc::Sender<T>, user_events_receiver: PeekableReceiver<T>, //must wake looper whenever something gets sent running: bool, } #[derive(Default, Debug, Clone, PartialEq)] pub(crate) struct PlatformSpecificEventLoopAttributes { pub(crate) android_app: Option<AndroidApp>, } fn sticky_exit_callback<T, F>( evt: event::Event<'_, T>, target: &RootELW<T>, control_flow: &mut ControlFlow, callback: &mut F, ) where F: FnMut(event::Event<'_, T>, &RootELW<T>, &mut ControlFlow), { // make ControlFlow::ExitWithCode sticky by providing a dummy // control flow reference if it is already ExitWithCode. if let ControlFlow::ExitWithCode(code) = *control_flow { callback(evt, target, &mut ControlFlow::ExitWithCode(code)) } else { callback(evt, target, control_flow) } } struct IterationResult { deadline: Option<Instant>, timeout: Option<Duration>, wait_start: Instant, } impl<T: 'static> EventLoop<T> { pub(crate) fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Self { let (user_events_sender, user_events_receiver) = mpsc::channel(); let android_app = attributes.android_app.as_ref().expect("An `AndroidApp` as passed to android_main() is required to create an `EventLoop` on Android"); let redraw_flag = SharedFlag::new(); Self { android_app: android_app.clone(), window_target: event_loop::EventLoopWindowTarget { p: EventLoopWindowTarget { app: android_app.clone(), redraw_requester: RedrawRequester::new( &redraw_flag, android_app.create_waker(), ), _marker: std::marker::PhantomData, }, _marker: std::marker::PhantomData, }, redraw_flag, user_events_sender, user_events_receiver: PeekableReceiver::from_recv(user_events_receiver), running: false, } } fn single_iteration<F>( &mut self, control_flow: &mut ControlFlow, main_event: Option<MainEvent<'_>>, pending_redraw: &mut bool, cause: &mut StartCause, callback: &mut F, ) -> IterationResult where F: FnMut(event::Event<'_, T>, &RootELW<T>, &mut ControlFlow), { trace!("Mainloop iteration"); sticky_exit_callback( event::Event::NewEvents(*cause), self.window_target(), control_flow, callback, ); let mut resized = false; if let Some(event) = main_event { trace!("Handling main event {:?}", event); match event { MainEvent::InitWindow { .. } => { sticky_exit_callback( event::Event::Resumed, self.window_target(), control_flow, callback, ); } MainEvent::TerminateWindow { .. } => { sticky_exit_callback( event::Event::Suspended, self.window_target(), control_flow, callback, ); } MainEvent::WindowResized { .. } => resized = true, MainEvent::RedrawNeeded { .. } => *pending_redraw = true, MainEvent::ContentRectChanged { .. } => { warn!("TODO: find a way to notify application of content rect change"); } MainEvent::GainedFocus => { *HAS_FOCUS.write().unwrap() = true; sticky_exit_callback( event::Event::WindowEvent { window_id: window::WindowId(WindowId), event: event::WindowEvent::Focused(true), }, self.window_target(), control_flow, callback, ); } MainEvent::LostFocus => { *HAS_FOCUS.write().unwrap() = false; sticky_exit_callback( event::Event::WindowEvent { window_id: window::WindowId(WindowId), event: event::WindowEvent::Focused(false), }, self.window_target(), control_flow, callback, ); } MainEvent::ConfigChanged { .. } => { let monitor = MonitorHandle::new(self.android_app.clone()); let old_scale_factor = monitor.scale_factor(); let scale_factor = monitor.scale_factor(); if (scale_factor - old_scale_factor).abs() < f64::EPSILON { let mut size = MonitorHandle::new(self.android_app.clone()).size(); let event = event::Event::WindowEvent { window_id: window::WindowId(WindowId), event: event::WindowEvent::ScaleFactorChanged { new_inner_size: &mut size, scale_factor, }, }; sticky_exit_callback(event, self.window_target(), control_flow, callback); } } MainEvent::LowMemory => { // XXX: how to forward this state to applications? // It seems like ideally winit should support lifecycle and // low-memory events, especially for mobile platforms. warn!("TODO: handle Android LowMemory notification"); } MainEvent::Start => { // XXX: how to forward this state to applications? warn!("TODO: forward onStart notification to application"); } MainEvent::Resume { .. } => { debug!("App Resumed - is running"); self.running = true; } MainEvent::SaveState { .. } => { // XXX: how to forward this state to applications? // XXX: also how do we expose state restoration to apps? warn!("TODO: forward saveState notification to application"); } MainEvent::Pause => { debug!("App Paused - stopped running"); self.running = false; } MainEvent::Stop => { // XXX: how to forward this state to applications? warn!("TODO: forward onStop notification to application"); } MainEvent::Destroy => { // XXX: maybe exit mainloop to drop things before being // killed by the OS? warn!("TODO: forward onDestroy notification to application"); } MainEvent::InsetsChanged { .. } => { // XXX: how to forward this state to applications? warn!("TODO: handle Android InsetsChanged notification"); } unknown => { trace!("Unknown MainEvent {unknown:?} (ignored)"); } } } else { trace!("No main event to handle"); } // Process input events self.android_app.input_events(|event| { match event { InputEvent::MotionEvent(motion_event) => { let window_id = window::WindowId(WindowId); let device_id = event::DeviceId(DeviceId); let phase = match motion_event.action() { MotionAction::Down | MotionAction::PointerDown => { Some(event::TouchPhase::Started) } MotionAction::Up | MotionAction::PointerUp => { Some(event::TouchPhase::Ended) } MotionAction::Move => Some(event::TouchPhase::Moved), MotionAction::Cancel => { Some(event::TouchPhase::Cancelled) } _ => { None // TODO mouse events } }; if let Some(phase) = phase { let pointers: Box< dyn Iterator<Item = android_activity::input::Pointer<'_>>, > = match phase { event::TouchPhase::Started | event::TouchPhase::Ended => { Box::new( std::iter::once(motion_event.pointer_at_index( motion_event.pointer_index(), )) ) }, event::TouchPhase::Moved | event::TouchPhase::Cancelled => { Box::new(motion_event.pointers()) } }; for pointer in pointers { let location = PhysicalPosition { x: pointer.x() as _, y: pointer.y() as _, }; trace!("Input event {device_id:?}, {phase:?}, loc={location:?}, pointer={pointer:?}"); let event = event::Event::WindowEvent { window_id, event: event::WindowEvent::Touch( event::Touch { device_id, phase, location, id: pointer.pointer_id() as u64, force: None, }, ), }; sticky_exit_callback( event, self.window_target(), control_flow, callback ); } } } InputEvent::KeyEvent(key) => { let device_id = event::DeviceId(DeviceId); let state = match key.action() { KeyAction::Down => event::ElementState::Pressed, KeyAction::Up => event::ElementState::Released, _ => event::ElementState::Released, }; #[allow(deprecated)] let event = event::Event::WindowEvent { window_id: window::WindowId(WindowId), event: event::WindowEvent::KeyboardInput { device_id, input: event::KeyboardInput { scancode: key.scan_code() as u32, state, virtual_keycode: ndk_keycode_to_virtualkeycode( key.key_code(), ), modifiers: event::ModifiersState::default(), }, is_synthetic: false, }, }; sticky_exit_callback( event, self.window_target(), control_flow, callback ); } _ => { warn!("Unknown android_activity input event {event:?}") } } // Assume all events are handled, while Winit doesn't currently give a way for // applications to report whether they handled an input event. InputStatus::Handled }); // Empty the user event buffer { while let Ok(event) = self.user_events_receiver.try_recv() { sticky_exit_callback( crate::event::Event::UserEvent(event), self.window_target(), control_flow, callback, ); } } sticky_exit_callback( event::Event::MainEventsCleared, self.window_target(), control_flow, callback, ); if self.running { if resized { let size = if let Some(native_window) = self.android_app.native_window().as_ref() { let width = native_window.width() as _; let height = native_window.height() as _; PhysicalSize::new(width, height) } else { PhysicalSize::new(0, 0) }; let event = event::Event::WindowEvent { window_id: window::WindowId(WindowId), event: event::WindowEvent::Resized(size), }; sticky_exit_callback(event, self.window_target(), control_flow, callback); } *pending_redraw |= self.redraw_flag.get_and_reset(); if *pending_redraw { *pending_redraw = false; let event = event::Event::RedrawRequested(window::WindowId(WindowId)); sticky_exit_callback(event, self.window_target(), control_flow, callback); } } sticky_exit_callback( event::Event::RedrawEventsCleared, self.window_target(), control_flow, callback, ); let start = Instant::now(); let (deadline, timeout); match control_flow { ControlFlow::ExitWithCode(_) => { deadline = None; timeout = None; } ControlFlow::Poll => { *cause = StartCause::Poll; deadline = None; timeout = Some(Duration::from_millis(0)); } ControlFlow::Wait => { *cause = StartCause::WaitCancelled { start, requested_resume: None, }; deadline = None; timeout = None; } ControlFlow::WaitUntil(wait_deadline) => { *cause = StartCause::ResumeTimeReached { start, requested_resume: *wait_deadline, }; timeout = if *wait_deadline > start { Some(*wait_deadline - start) } else { Some(Duration::from_millis(0)) }; deadline = Some(*wait_deadline); } } IterationResult { wait_start: start, deadline, timeout, } } pub fn run<F>(mut self, event_handler: F) -> ! where F: 'static + FnMut(event::Event<'_, T>, &event_loop::EventLoopWindowTarget<T>, &mut ControlFlow), { let exit_code = self.run_return(event_handler); ::std::process::exit(exit_code); } pub fn run_return<F>(&mut self, mut callback: F) -> i32 where F: FnMut(event::Event<'_, T>, &RootELW<T>, &mut ControlFlow), { let mut control_flow = ControlFlow::default(); let mut cause = StartCause::Init; let mut pending_redraw = false; // run the initial loop iteration let mut iter_result = self.single_iteration( &mut control_flow, None, &mut pending_redraw, &mut cause, &mut callback, ); let exit_code = loop { if let ControlFlow::ExitWithCode(code) = control_flow { break code; } let mut timeout = iter_result.timeout; // If we already have work to do then we don't want to block on the next poll... pending_redraw |= self.redraw_flag.get_and_reset(); if self.running && (pending_redraw || self.user_events_receiver.has_incoming()) { timeout = Some(Duration::from_millis(0)) } let app = self.android_app.clone(); // Don't borrow self as part of poll expression app.poll_events(timeout, |poll_event| { let mut main_event = None; match poll_event { android_activity::PollEvent::Wake => { // In the X11 backend it's noted that too many false-positive wake ups // would cause the event loop to run continuously. They handle this by re-checking // for pending events (assuming they cover all valid reasons for a wake up). // // For now, user_events and redraw_requests are the only reasons to expect // a wake up here so we can ignore the wake up if there are no events/requests. // We also ignore wake ups while suspended. pending_redraw |= self.redraw_flag.get_and_reset(); if !self.running || (!pending_redraw && !self.user_events_receiver.has_incoming()) { return; } } android_activity::PollEvent::Timeout => {} android_activity::PollEvent::Main(event) => { main_event = Some(event); } unknown_event => { warn!("Unknown poll event {unknown_event:?} (ignored)"); } } let wait_cancelled = iter_result .deadline .map_or(false, |deadline| Instant::now() < deadline); if wait_cancelled { cause = StartCause::WaitCancelled { start: iter_result.wait_start, requested_resume: iter_result.deadline, }; } iter_result = self.single_iteration( &mut control_flow, main_event, &mut pending_redraw, &mut cause, &mut callback, ); }); }; sticky_exit_callback( event::Event::LoopDestroyed, self.window_target(), &mut control_flow, &mut callback, ); exit_code } pub fn window_target(&self) -> &event_loop::EventLoopWindowTarget<T> { &self.window_target } pub fn create_proxy(&self) -> EventLoopProxy<T> { EventLoopProxy { user_events_sender: self.user_events_sender.clone(), waker: self.android_app.create_waker(), } } } pub struct EventLoopProxy<T: 'static> { user_events_sender: mpsc::Sender<T>, waker: AndroidAppWaker, } impl<T: 'static> Clone for EventLoopProxy<T> { fn clone(&self) -> Self { EventLoopProxy { user_events_sender: self.user_events_sender.clone(), waker: self.waker.clone(), } } } impl<T> EventLoopProxy<T> { pub fn send_event(&self, event: T) -> Result<(), event_loop::EventLoopClosed<T>> { self.user_events_sender .send(event) .map_err(|err| event_loop::EventLoopClosed(err.0))?; self.waker.wake(); Ok(()) } } pub struct EventLoopWindowTarget<T: 'static> { app: AndroidApp, redraw_requester: RedrawRequester, _marker: std::marker::PhantomData<T>, } impl<T: 'static> EventLoopWindowTarget<T> { pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle::new(self.app.clone())) } pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { let mut v = VecDeque::with_capacity(1); v.push_back(MonitorHandle::new(self.app.clone())); v } pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Android(AndroidDisplayHandle::empty()) } } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub(crate) struct WindowId; impl WindowId { pub const fn dummy() -> Self { WindowId } } impl From<WindowId> for u64 { fn from(_: WindowId) -> Self { 0 } } impl From<u64> for WindowId { fn from(_: u64) -> Self { Self } } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct DeviceId; impl DeviceId { pub const fn dummy() -> Self { DeviceId } } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct PlatformSpecificWindowBuilderAttributes; pub(crate) struct Window { app: AndroidApp, redraw_requester: RedrawRequester, } impl Window { pub(crate) fn new<T: 'static>( el: &EventLoopWindowTarget<T>, _window_attrs: window::WindowAttributes, _: PlatformSpecificWindowBuilderAttributes, ) -> Result<Self, error::OsError> { // FIXME this ignores requested window attributes Ok(Self { app: el.app.clone(), redraw_requester: el.redraw_requester.clone(), }) } pub fn id(&self) -> WindowId { WindowId } pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle::new(self.app.clone())) } pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { let mut v = VecDeque::with_capacity(1); v.push_back(MonitorHandle::new(self.app.clone())); v } pub fn current_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle::new(self.app.clone())) } pub fn scale_factor(&self) -> f64 { MonitorHandle::new(self.app.clone()).scale_factor() } pub fn request_redraw(&self) { self.redraw_requester.request_redraw() } pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { Err(error::NotSupportedError::new()) } pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { Err(error::NotSupportedError::new()) } pub fn set_outer_position(&self, _position: Position) { // no effect } pub fn inner_size(&self) -> PhysicalSize<u32> { self.outer_size() } pub fn set_inner_size(&self, _size: Size) { warn!("Cannot set window size on Android"); } pub fn outer_size(&self) -> PhysicalSize<u32> { MonitorHandle::new(self.app.clone()).size() } pub fn set_min_inner_size(&self, _: Option<Size>) {} pub fn set_max_inner_size(&self, _: Option<Size>) {} pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { None } pub fn set_resize_increments(&self, _increments: Option<Size>) {} pub fn set_title(&self, _title: &str) {} pub fn set_transparent(&self, _transparent: bool) {} pub fn set_visible(&self, _visibility: bool) {} pub fn is_visible(&self) -> Option<bool> { None } pub fn set_resizable(&self, _resizeable: bool) {} pub fn is_resizable(&self) -> bool { false } pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {} pub fn enabled_buttons(&self) -> WindowButtons { WindowButtons::all() } pub fn set_minimized(&self, _minimized: bool) {} pub fn is_minimized(&self) -> Option<bool> { None } pub fn set_maximized(&self, _maximized: bool) {} pub fn is_maximized(&self) -> bool { false } pub fn set_fullscreen(&self, _monitor: Option<Fullscreen>) { warn!("Cannot set fullscreen on Android"); } pub fn fullscreen(&self) -> Option<Fullscreen> { None } pub fn set_decorations(&self, _decorations: bool) {} pub fn is_decorated(&self) -> bool { true } pub fn set_window_level(&self, _level: WindowLevel) {} pub fn set_window_icon(&self, _window_icon: Option<crate::icon::Icon>) {} pub fn set_ime_position(&self, _position: Position) {} pub fn set_ime_allowed(&self, _allowed: bool) {} pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} pub fn focus_window(&self) {} pub fn request_user_attention(&self, _request_type: Option<window::UserAttentionType>) {} pub fn set_cursor_icon(&self, _: window::CursorIcon) {} pub fn set_cursor_position(&self, _: Position) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } pub fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } pub fn set_cursor_visible(&self, _: bool) {} pub fn drag_window(&self) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } pub fn drag_resize_window( &self, _direction: ResizeDirection, ) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } pub fn raw_window_handle(&self) -> RawWindowHandle { if let Some(native_window) = self.app.native_window().as_ref() { native_window.raw_window_handle() } else { panic!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events."); } } pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Android(AndroidDisplayHandle::empty()) } pub fn config(&self) -> ConfigurationRef { self.app.config() } pub fn content_rect(&self) -> Rect { self.app.content_rect() } pub fn set_theme(&self, _theme: Option<Theme>) {} pub fn theme(&self) -> Option<Theme> { None } pub fn has_focus(&self) -> bool { *HAS_FOCUS.read().unwrap() } pub fn title(&self) -> String { String::new() } } #[derive(Default, Clone, Debug)] pub struct OsError; use std::fmt::{self, Display, Formatter}; impl Display for OsError { fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(fmt, "Android OS Error") } } pub(crate) use crate::icon::NoIcon as PlatformIcon; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct MonitorHandle { app: AndroidApp, } impl PartialOrd for MonitorHandle { fn partial_cmp(&self, _other: &Self) -> Option<std::cmp::Ordering> { Some(std::cmp::Ordering::Equal) } } impl Ord for MonitorHandle { fn cmp(&self, _other: &Self) -> std::cmp::Ordering { std::cmp::Ordering::Equal } } impl MonitorHandle { pub(crate) fn new(app: AndroidApp) -> Self { Self { app } } pub fn name(&self) -> Option<String> { Some("Android Device".to_owned()) } pub fn size(&self) -> PhysicalSize<u32> { if let Some(native_window) = self.app.native_window() { PhysicalSize::new(native_window.width() as _, native_window.height() as _) } else { PhysicalSize::new(0, 0) } } pub fn position(&self) -> PhysicalPosition<i32> { (0, 0).into() } pub fn scale_factor(&self) -> f64 { self.app .config() .density() .map(|dpi| dpi as f64 / 160.0) .unwrap_or(1.0) } pub fn refresh_rate_millihertz(&self) -> Option<u32> { // FIXME no way to get real refresh rate for now. None } pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> { let size = self.size().into(); // FIXME this is not the real refresh rate // (it is guaranteed to support 32 bit color though) std::iter::once(VideoMode { size, bit_depth: 32, refresh_rate_millihertz: 60000, monitor: self.clone(), }) } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct VideoMode { size: (u32, u32), bit_depth: u16, refresh_rate_millihertz: u32, monitor: MonitorHandle, } impl VideoMode { pub fn size(&self) -> PhysicalSize<u32> { self.size.into() } pub fn bit_depth(&self) -> u16 { self.bit_depth } pub fn refresh_rate_millihertz(&self) -> u32 { self.refresh_rate_millihertz } pub fn monitor(&self) -> MonitorHandle { self.monitor.clone() } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/app_state.rs
Rust
#![deny(unused_results)] use std::{ cell::{RefCell, RefMut}, collections::HashSet, mem, os::raw::c_void, ptr, time::Instant, }; use core_foundation::base::CFRelease; use core_foundation::date::CFAbsoluteTimeGetCurrent; use core_foundation::runloop::{ kCFRunLoopCommonModes, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, }; use objc2::foundation::{CGRect, CGSize, NSInteger, NSProcessInfo}; use objc2::rc::{Id, Shared}; use objc2::runtime::Object; use objc2::{msg_send, sel}; use once_cell::sync::Lazy; use super::uikit::UIView; use super::view::WinitUIWindow; use crate::{ dpi::LogicalSize, event::{Event, StartCause, WindowEvent}, event_loop::ControlFlow, platform_impl::platform::{ event_loop::{EventHandler, EventProxy, EventWrapper, Never}, ffi::NSOperatingSystemVersion, }, window::WindowId as RootWindowId, }; macro_rules! bug { ($($msg:tt)*) => { panic!("winit iOS bug, file an issue: {}", format!($($msg)*)) }; } macro_rules! bug_assert { ($test:expr, $($msg:tt)*) => { assert!($test, "winit iOS bug, file an issue: {}", format!($($msg)*)) }; } enum UserCallbackTransitionResult<'a> { Success { event_handler: Box<dyn EventHandler>, active_control_flow: ControlFlow, processing_redraws: bool, }, ReentrancyPrevented { queued_events: &'a mut Vec<EventWrapper>, }, } impl Event<'static, Never> { fn is_redraw(&self) -> bool { matches!(self, Event::RedrawRequested(_)) } } // this is the state machine for the app lifecycle #[derive(Debug)] #[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"] enum AppStateImpl { NotLaunched { queued_windows: Vec<Id<WinitUIWindow, Shared>>, queued_events: Vec<EventWrapper>, queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>, }, Launching { queued_windows: Vec<Id<WinitUIWindow, Shared>>, queued_events: Vec<EventWrapper>, queued_event_handler: Box<dyn EventHandler>, queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>, }, ProcessingEvents { event_handler: Box<dyn EventHandler>, queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>, active_control_flow: ControlFlow, }, // special state to deal with reentrancy and prevent mutable aliasing. InUserCallback { queued_events: Vec<EventWrapper>, queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>, }, ProcessingRedraws { event_handler: Box<dyn EventHandler>, active_control_flow: ControlFlow, }, Waiting { waiting_event_handler: Box<dyn EventHandler>, start: Instant, }, PollFinished { waiting_event_handler: Box<dyn EventHandler>, }, Terminated, } struct AppState { // This should never be `None`, except for briefly during a state transition. app_state: Option<AppStateImpl>, control_flow: ControlFlow, waker: EventLoopWaker, } impl AppState { // requires main thread unsafe fn get_mut() -> RefMut<'static, AppState> { // basically everything in UIKit requires the main thread, so it's pointless to use the // std::sync APIs. // must be mut because plain `static` requires `Sync` static mut APP_STATE: RefCell<Option<AppState>> = RefCell::new(None); if cfg!(debug_assertions) { assert_main_thread!( "bug in winit: `AppState::get_mut()` can only be called on the main thread" ); } let mut guard = APP_STATE.borrow_mut(); if guard.is_none() { #[inline(never)] #[cold] unsafe fn init_guard(guard: &mut RefMut<'static, Option<AppState>>) { let waker = EventLoopWaker::new(CFRunLoopGetMain()); **guard = Some(AppState { app_state: Some(AppStateImpl::NotLaunched { queued_windows: Vec::new(), queued_events: Vec::new(), queued_gpu_redraws: HashSet::new(), }), control_flow: ControlFlow::default(), waker, }); } init_guard(&mut guard) } RefMut::map(guard, |state| state.as_mut().unwrap()) } fn state(&self) -> &AppStateImpl { match &self.app_state { Some(ref state) => state, None => bug!("`AppState` previously failed a state transition"), } } fn state_mut(&mut self) -> &mut AppStateImpl { match &mut self.app_state { Some(ref mut state) => state, None => bug!("`AppState` previously failed a state transition"), } } fn take_state(&mut self) -> AppStateImpl { match self.app_state.take() { Some(state) => state, None => bug!("`AppState` previously failed a state transition"), } } fn set_state(&mut self, new_state: AppStateImpl) { bug_assert!( self.app_state.is_none(), "attempted to set an `AppState` without calling `take_state` first {:?}", self.app_state ); self.app_state = Some(new_state) } fn replace_state(&mut self, new_state: AppStateImpl) -> AppStateImpl { match &mut self.app_state { Some(ref mut state) => mem::replace(state, new_state), None => bug!("`AppState` previously failed a state transition"), } } fn has_launched(&self) -> bool { !matches!( self.state(), AppStateImpl::NotLaunched { .. } | AppStateImpl::Launching { .. } ) } fn will_launch_transition(&mut self, queued_event_handler: Box<dyn EventHandler>) { let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() { AppStateImpl::NotLaunched { queued_windows, queued_events, queued_gpu_redraws, } => (queued_windows, queued_events, queued_gpu_redraws), s => bug!("unexpected state {:?}", s), }; self.set_state(AppStateImpl::Launching { queued_windows, queued_events, queued_event_handler, queued_gpu_redraws, }); } fn did_finish_launching_transition( &mut self, ) -> (Vec<Id<WinitUIWindow, Shared>>, Vec<EventWrapper>) { let (windows, events, event_handler, queued_gpu_redraws) = match self.take_state() { AppStateImpl::Launching { queued_windows, queued_events, queued_event_handler, queued_gpu_redraws, } => ( queued_windows, queued_events, queued_event_handler, queued_gpu_redraws, ), s => bug!("unexpected state {:?}", s), }; self.set_state(AppStateImpl::ProcessingEvents { event_handler, active_control_flow: ControlFlow::Poll, queued_gpu_redraws, }); (windows, events) } fn wakeup_transition(&mut self) -> Option<EventWrapper> { // before `AppState::did_finish_launching` is called, pretend there is no running // event loop. if !self.has_launched() { return None; } let (event_handler, event) = match (self.control_flow, self.take_state()) { ( ControlFlow::Poll, AppStateImpl::PollFinished { waiting_event_handler, }, ) => ( waiting_event_handler, EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll)), ), ( ControlFlow::Wait, AppStateImpl::Waiting { waiting_event_handler, start, }, ) => ( waiting_event_handler, EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled { start, requested_resume: None, })), ), ( ControlFlow::WaitUntil(requested_resume), AppStateImpl::Waiting { waiting_event_handler, start, }, ) => { let event = if Instant::now() >= requested_resume { EventWrapper::StaticEvent(Event::NewEvents(StartCause::ResumeTimeReached { start, requested_resume, })) } else { EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled { start, requested_resume: Some(requested_resume), })) }; (waiting_event_handler, event) } (ControlFlow::ExitWithCode(_), _) => bug!("unexpected `ControlFlow` `Exit`"), s => bug!("`EventHandler` unexpectedly woke up {:?}", s), }; self.set_state(AppStateImpl::ProcessingEvents { event_handler, queued_gpu_redraws: Default::default(), active_control_flow: self.control_flow, }); Some(event) } fn try_user_callback_transition(&mut self) -> UserCallbackTransitionResult<'_> { // If we're not able to process an event due to recursion or `Init` not having been sent out // yet, then queue the events up. match self.state_mut() { &mut AppStateImpl::Launching { ref mut queued_events, .. } | &mut AppStateImpl::NotLaunched { ref mut queued_events, .. } | &mut AppStateImpl::InUserCallback { ref mut queued_events, .. } => { // A lifetime cast: early returns are not currently handled well with NLL, but // polonius handles them well. This transmute is a safe workaround. return unsafe { mem::transmute::< UserCallbackTransitionResult<'_>, UserCallbackTransitionResult<'_>, >(UserCallbackTransitionResult::ReentrancyPrevented { queued_events, }) }; } &mut AppStateImpl::ProcessingEvents { .. } | &mut AppStateImpl::ProcessingRedraws { .. } => {} s @ &mut AppStateImpl::PollFinished { .. } | s @ &mut AppStateImpl::Waiting { .. } | s @ &mut AppStateImpl::Terminated => { bug!("unexpected attempted to process an event {:?}", s) } } let (event_handler, queued_gpu_redraws, active_control_flow, processing_redraws) = match self.take_state() { AppStateImpl::Launching { .. } | AppStateImpl::NotLaunched { .. } | AppStateImpl::InUserCallback { .. } => unreachable!(), AppStateImpl::ProcessingEvents { event_handler, queued_gpu_redraws, active_control_flow, } => ( event_handler, queued_gpu_redraws, active_control_flow, false, ), AppStateImpl::ProcessingRedraws { event_handler, active_control_flow, } => (event_handler, Default::default(), active_control_flow, true), AppStateImpl::PollFinished { .. } | AppStateImpl::Waiting { .. } | AppStateImpl::Terminated => unreachable!(), }; self.set_state(AppStateImpl::InUserCallback { queued_events: Vec::new(), queued_gpu_redraws, }); UserCallbackTransitionResult::Success { event_handler, active_control_flow, processing_redraws, } } fn main_events_cleared_transition(&mut self) -> HashSet<Id<WinitUIWindow, Shared>> { let (event_handler, queued_gpu_redraws, active_control_flow) = match self.take_state() { AppStateImpl::ProcessingEvents { event_handler, queued_gpu_redraws, active_control_flow, } => (event_handler, queued_gpu_redraws, active_control_flow), s => bug!("unexpected state {:?}", s), }; self.set_state(AppStateImpl::ProcessingRedraws { event_handler, active_control_flow, }); queued_gpu_redraws } fn events_cleared_transition(&mut self) { if !self.has_launched() { return; } let (waiting_event_handler, old) = match self.take_state() { AppStateImpl::ProcessingRedraws { event_handler, active_control_flow, } => (event_handler, active_control_flow), s => bug!("unexpected state {:?}", s), }; let new = self.control_flow; match (old, new) { (ControlFlow::Poll, ControlFlow::Poll) => self.set_state(AppStateImpl::PollFinished { waiting_event_handler, }), (ControlFlow::Wait, ControlFlow::Wait) => { let start = Instant::now(); self.set_state(AppStateImpl::Waiting { waiting_event_handler, start, }); } (ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant)) if old_instant == new_instant => { let start = Instant::now(); self.set_state(AppStateImpl::Waiting { waiting_event_handler, start, }); } (_, ControlFlow::Wait) => { let start = Instant::now(); self.set_state(AppStateImpl::Waiting { waiting_event_handler, start, }); self.waker.stop() } (_, ControlFlow::WaitUntil(new_instant)) => { let start = Instant::now(); self.set_state(AppStateImpl::Waiting { waiting_event_handler, start, }); self.waker.start_at(new_instant) } (_, ControlFlow::Poll) => { self.set_state(AppStateImpl::PollFinished { waiting_event_handler, }); self.waker.start() } (_, ControlFlow::ExitWithCode(_)) => { // https://developer.apple.com/library/archive/qa/qa1561/_index.html // it is not possible to quit an iOS app gracefully and programatically warn!("`ControlFlow::Exit` ignored on iOS"); self.control_flow = old } } } fn terminated_transition(&mut self) -> Box<dyn EventHandler> { match self.replace_state(AppStateImpl::Terminated) { AppStateImpl::ProcessingEvents { event_handler, .. } => event_handler, s => bug!( "`LoopDestroyed` happened while not processing events {:?}", s ), } } } // requires main thread and window is a UIWindow // retains window pub(crate) unsafe fn set_key_window(window: &Id<WinitUIWindow, Shared>) { let mut this = AppState::get_mut(); match this.state_mut() { &mut AppStateImpl::NotLaunched { ref mut queued_windows, .. } => return queued_windows.push(window.clone()), &mut AppStateImpl::ProcessingEvents { .. } | &mut AppStateImpl::InUserCallback { .. } | &mut AppStateImpl::ProcessingRedraws { .. } => {} s @ &mut AppStateImpl::Launching { .. } | s @ &mut AppStateImpl::Waiting { .. } | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), &mut AppStateImpl::Terminated => { panic!("Attempt to create a `Window` after the app has terminated") } } drop(this); window.makeKeyAndVisible(); } // requires main thread and window is a UIWindow // retains window pub(crate) unsafe fn queue_gl_or_metal_redraw(window: Id<WinitUIWindow, Shared>) { let mut this = AppState::get_mut(); match this.state_mut() { &mut AppStateImpl::NotLaunched { ref mut queued_gpu_redraws, .. } | &mut AppStateImpl::Launching { ref mut queued_gpu_redraws, .. } | &mut AppStateImpl::ProcessingEvents { ref mut queued_gpu_redraws, .. } | &mut AppStateImpl::InUserCallback { ref mut queued_gpu_redraws, .. } => { let _ = queued_gpu_redraws.insert(window); } s @ &mut AppStateImpl::ProcessingRedraws { .. } | s @ &mut AppStateImpl::Waiting { .. } | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), &mut AppStateImpl::Terminated => { panic!("Attempt to create a `Window` after the app has terminated") } } } // requires main thread pub unsafe fn will_launch(queued_event_handler: Box<dyn EventHandler>) { AppState::get_mut().will_launch_transition(queued_event_handler) } // requires main thread pub unsafe fn did_finish_launching() { let mut this = AppState::get_mut(); let windows = match this.state_mut() { AppStateImpl::Launching { queued_windows, .. } => mem::take(queued_windows), s => bug!("unexpected state {:?}", s), }; // start waking up the event loop now! bug_assert!( this.control_flow == ControlFlow::Poll, "unexpectedly not setup to `Poll` on launch!" ); this.waker.start(); // have to drop RefMut because the window setup code below can trigger new events drop(this); for window in windows { // Do a little screen dance here to account for windows being created before // `UIApplicationMain` is called. This fixes visual issues such as being // offcenter and sized incorrectly. Additionally, to fix orientation issues, we // gotta reset the `rootViewController`. // // relevant iOS log: // ``` // [ApplicationLifecycle] Windows were created before application initialzation // completed. This may result in incorrect visual appearance. // ``` let screen = window.screen(); let _: () = msg_send![&window, setScreen: ptr::null::<Object>()]; window.setScreen(&screen); let controller = window.rootViewController(); window.setRootViewController(None); window.setRootViewController(controller.as_deref()); window.makeKeyAndVisible(); } let (windows, events) = AppState::get_mut().did_finish_launching_transition(); let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents( StartCause::Init, ))) .chain(events); handle_nonuser_events(events); // the above window dance hack, could possibly trigger new windows to be created. // we can just set those windows up normally, as they were created after didFinishLaunching for window in windows { window.makeKeyAndVisible(); } } // requires main thread // AppState::did_finish_launching handles the special transition `Init` pub unsafe fn handle_wakeup_transition() { let mut this = AppState::get_mut(); let wakeup_event = match this.wakeup_transition() { None => return, Some(wakeup_event) => wakeup_event, }; drop(this); handle_nonuser_event(wakeup_event) } // requires main thread pub(crate) unsafe fn handle_nonuser_event(event: EventWrapper) { handle_nonuser_events(std::iter::once(event)) } // requires main thread pub(crate) unsafe fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(events: I) { let mut this = AppState::get_mut(); let (mut event_handler, active_control_flow, processing_redraws) = match this.try_user_callback_transition() { UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => { queued_events.extend(events); return; } UserCallbackTransitionResult::Success { event_handler, active_control_flow, processing_redraws, } => (event_handler, active_control_flow, processing_redraws), }; let mut control_flow = this.control_flow; drop(this); for wrapper in events { match wrapper { EventWrapper::StaticEvent(event) => { if !processing_redraws && event.is_redraw() { log::info!("processing `RedrawRequested` during the main event loop"); } else if processing_redraws && !event.is_redraw() { log::warn!( "processing non `RedrawRequested` event after the main event loop: {:#?}", event ); } event_handler.handle_nonuser_event(event, &mut control_flow) } EventWrapper::EventProxy(proxy) => { handle_event_proxy(&mut event_handler, control_flow, proxy) } } } loop { let mut this = AppState::get_mut(); let queued_events = match this.state_mut() { &mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _, } => mem::take(queued_events), s => bug!("unexpected state {:?}", s), }; if queued_events.is_empty() { let queued_gpu_redraws = match this.take_state() { AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws, } => queued_gpu_redraws, _ => unreachable!(), }; this.app_state = Some(if processing_redraws { bug_assert!( queued_gpu_redraws.is_empty(), "redraw queued while processing redraws" ); AppStateImpl::ProcessingRedraws { event_handler, active_control_flow, } } else { AppStateImpl::ProcessingEvents { event_handler, queued_gpu_redraws, active_control_flow, } }); this.control_flow = control_flow; break; } drop(this); for wrapper in queued_events { match wrapper { EventWrapper::StaticEvent(event) => { if !processing_redraws && event.is_redraw() { log::info!("processing `RedrawRequested` during the main event loop"); } else if processing_redraws && !event.is_redraw() { log::warn!( "processing non-`RedrawRequested` event after the main event loop: {:#?}", event ); } event_handler.handle_nonuser_event(event, &mut control_flow) } EventWrapper::EventProxy(proxy) => { handle_event_proxy(&mut event_handler, control_flow, proxy) } } } } } // requires main thread unsafe fn handle_user_events() { let mut this = AppState::get_mut(); let mut control_flow = this.control_flow; let (mut event_handler, active_control_flow, processing_redraws) = match this.try_user_callback_transition() { UserCallbackTransitionResult::ReentrancyPrevented { .. } => { bug!("unexpected attempted to process an event") } UserCallbackTransitionResult::Success { event_handler, active_control_flow, processing_redraws, } => (event_handler, active_control_flow, processing_redraws), }; if processing_redraws { bug!("user events attempted to be sent out while `ProcessingRedraws`"); } drop(this); event_handler.handle_user_events(&mut control_flow); loop { let mut this = AppState::get_mut(); let queued_events = match this.state_mut() { &mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _, } => mem::take(queued_events), s => bug!("unexpected state {:?}", s), }; if queued_events.is_empty() { let queued_gpu_redraws = match this.take_state() { AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws, } => queued_gpu_redraws, _ => unreachable!(), }; this.app_state = Some(AppStateImpl::ProcessingEvents { event_handler, queued_gpu_redraws, active_control_flow, }); this.control_flow = control_flow; break; } drop(this); for wrapper in queued_events { match wrapper { EventWrapper::StaticEvent(event) => { event_handler.handle_nonuser_event(event, &mut control_flow) } EventWrapper::EventProxy(proxy) => { handle_event_proxy(&mut event_handler, control_flow, proxy) } } } event_handler.handle_user_events(&mut control_flow); } } // requires main thread pub unsafe fn handle_main_events_cleared() { let mut this = AppState::get_mut(); if !this.has_launched() { return; } match this.state_mut() { AppStateImpl::ProcessingEvents { .. } => {} _ => bug!("`ProcessingRedraws` happened unexpectedly"), }; drop(this); // User events are always sent out at the end of the "MainEventLoop" handle_user_events(); handle_nonuser_event(EventWrapper::StaticEvent(Event::MainEventsCleared)); let mut this = AppState::get_mut(); let mut redraw_events: Vec<EventWrapper> = this .main_events_cleared_transition() .into_iter() .map(|window| EventWrapper::StaticEvent(Event::RedrawRequested(RootWindowId(window.id())))) .collect(); redraw_events.push(EventWrapper::StaticEvent(Event::RedrawEventsCleared)); drop(this); handle_nonuser_events(redraw_events); } // requires main thread pub unsafe fn handle_events_cleared() { AppState::get_mut().events_cleared_transition(); } // requires main thread pub unsafe fn terminated() { let mut this = AppState::get_mut(); let mut event_handler = this.terminated_transition(); let mut control_flow = this.control_flow; drop(this); event_handler.handle_nonuser_event(Event::LoopDestroyed, &mut control_flow) } fn handle_event_proxy( event_handler: &mut Box<dyn EventHandler>, control_flow: ControlFlow, proxy: EventProxy, ) { match proxy { EventProxy::DpiChangedProxy { suggested_size, scale_factor, window, } => handle_hidpi_proxy( event_handler, control_flow, suggested_size, scale_factor, window, ), } } fn handle_hidpi_proxy( event_handler: &mut Box<dyn EventHandler>, mut control_flow: ControlFlow, suggested_size: LogicalSize<f64>, scale_factor: f64, window: Id<WinitUIWindow, Shared>, ) { let mut size = suggested_size.to_physical(scale_factor); let new_inner_size = &mut size; let event = Event::WindowEvent { window_id: RootWindowId(window.id()), event: WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size, }, }; event_handler.handle_nonuser_event(event, &mut control_flow); let (view, screen_frame) = get_view_and_screen_frame(&window); let physical_size = *new_inner_size; let logical_size = physical_size.to_logical(scale_factor); let size = CGSize::new(logical_size.width, logical_size.height); let new_frame: CGRect = CGRect::new(screen_frame.origin, size); view.setFrame(new_frame); } fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Id<UIView, Shared>, CGRect) { let view_controller = window.rootViewController().unwrap(); let view = view_controller.view().unwrap(); let bounds = window.bounds(); let screen = window.screen(); let screen_space = screen.coordinateSpace(); let screen_frame = window.convertRect_toCoordinateSpace(bounds, &screen_space); (view, screen_frame) } struct EventLoopWaker { timer: CFRunLoopTimerRef, } impl Drop for EventLoopWaker { fn drop(&mut self) { unsafe { CFRunLoopTimerInvalidate(self.timer); CFRelease(self.timer as _); } } } impl EventLoopWaker { fn new(rl: CFRunLoopRef) -> EventLoopWaker { extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {} unsafe { // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. // It is initially setup with a first fire time really far into the // future, but that gets changed to fire immediately in did_finish_launching let timer = CFRunLoopTimerCreate( ptr::null_mut(), std::f64::MAX, 0.000_000_1, 0, 0, wakeup_main_loop, ptr::null_mut(), ); CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes); EventLoopWaker { timer } } } fn stop(&mut self) { unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MAX) } } fn start(&mut self) { unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MIN) } } fn start_at(&mut self, instant: Instant) { let now = Instant::now(); if now >= instant { self.start(); } else { unsafe { let current = CFAbsoluteTimeGetCurrent(); let duration = instant - now; let fsecs = duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64; CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs) } } } } macro_rules! os_capabilities { ( $( $(#[$attr:meta])* $error_name:ident: $objc_call:literal, $name:ident: $major:literal-$minor:literal ),* $(,)* ) => { #[derive(Clone, Debug)] pub struct OSCapabilities { $( pub $name: bool, )* os_version: NSOperatingSystemVersion, } impl From<NSOperatingSystemVersion> for OSCapabilities { fn from(os_version: NSOperatingSystemVersion) -> OSCapabilities { $(let $name = os_version.meets_requirements($major, $minor);)* OSCapabilities { $($name,)* os_version, } } } impl OSCapabilities {$( $(#[$attr])* pub fn $error_name(&self, extra_msg: &str) { log::warn!( concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"), $major, $minor, self.os_version.major, self.os_version.minor, self.os_version.patch, extra_msg ) } )*} }; } os_capabilities! { /// <https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc> #[allow(unused)] // error message unused safe_area_err_msg: "-[UIView safeAreaInsets]", safe_area: 11-0, /// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc> home_indicator_hidden_err_msg: "-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]", home_indicator_hidden: 11-0, /// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc> defer_system_gestures_err_msg: "-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystem]", defer_system_gestures: 11-0, /// <https://developer.apple.com/documentation/uikit/uiscreen/2806814-maximumframespersecond?language=objc> maximum_frames_per_second_err_msg: "-[UIScreen maximumFramesPerSecond]", maximum_frames_per_second: 10-3, /// <https://developer.apple.com/documentation/uikit/uitouch/1618110-force?language=objc> #[allow(unused)] // error message unused force_touch_err_msg: "-[UITouch force]", force_touch: 9-0, } impl NSOperatingSystemVersion { fn meets_requirements(&self, required_major: NSInteger, required_minor: NSInteger) -> bool { (self.major, self.minor) >= (required_major, required_minor) } } pub fn os_capabilities() -> OSCapabilities { static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| { let version: NSOperatingSystemVersion = unsafe { let process_info = NSProcessInfo::process_info(); let atleast_ios_8: bool = msg_send![ &process_info, respondsToSelector: sel!(operatingSystemVersion) ]; // winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions. // Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support // debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS // simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7 // has been tested to not even run on macOS 10.15 - Xcode 8 might? // // The minimum required iOS version is likely to grow in the future. assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater"); msg_send![&process_info, operatingSystemVersion] }; version.into() }); OS_CAPABILITIES.clone() }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/event_loop.rs
Rust
use std::{ collections::VecDeque, ffi::c_void, fmt::{self, Debug}, marker::PhantomData, ptr, sync::mpsc::{self, Receiver, Sender}, }; use core_foundation::base::{CFIndex, CFRelease}; use core_foundation::runloop::{ kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopDefaultMode, kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddSource, CFRunLoopGetMain, CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext, CFRunLoopSourceCreate, CFRunLoopSourceInvalidate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp, }; use objc2::foundation::{MainThreadMarker, NSString}; use objc2::rc::{Id, Shared}; use objc2::ClassType; use raw_window_handle::{RawDisplayHandle, UiKitDisplayHandle}; use super::uikit::{UIApplication, UIApplicationMain, UIDevice, UIScreen}; use super::view::WinitUIWindow; use super::{app_state, monitor, view, MonitorHandle}; use crate::{ dpi::LogicalSize, event::Event, event_loop::{ ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootEventLoopWindowTarget, }, platform::ios::Idiom, }; #[derive(Debug)] pub(crate) enum EventWrapper { StaticEvent(Event<'static, Never>), EventProxy(EventProxy), } #[derive(Debug, PartialEq)] pub(crate) enum EventProxy { DpiChangedProxy { window: Id<WinitUIWindow, Shared>, suggested_size: LogicalSize<f64>, scale_factor: f64, }, } pub struct EventLoopWindowTarget<T: 'static> { receiver: Receiver<T>, sender_to_clone: Sender<T>, } impl<T: 'static> EventLoopWindowTarget<T> { pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { monitor::uiscreens(MainThreadMarker::new().unwrap()) } pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle::new(UIScreen::main( MainThreadMarker::new().unwrap(), ))) } pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::UiKit(UiKitDisplayHandle::empty()) } } pub struct EventLoop<T: 'static> { window_target: RootEventLoopWindowTarget<T>, } #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) struct PlatformSpecificEventLoopAttributes {} impl<T: 'static> EventLoop<T> { pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> EventLoop<T> { assert_main_thread!("`EventLoop` can only be created on the main thread on iOS"); static mut SINGLETON_INIT: bool = false; unsafe { assert!( !SINGLETON_INIT, "Only one `EventLoop` is supported on iOS. \ `EventLoopProxy` might be helpful" ); SINGLETON_INIT = true; } let (sender_to_clone, receiver) = mpsc::channel(); // this line sets up the main run loop before `UIApplicationMain` setup_control_flow_observers(); EventLoop { window_target: RootEventLoopWindowTarget { p: EventLoopWindowTarget { receiver, sender_to_clone, }, _marker: PhantomData, }, } } pub fn run<F>(self, event_handler: F) -> ! where F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow), { unsafe { let application = UIApplication::shared(MainThreadMarker::new().unwrap()); assert!( application.is_none(), "\ `EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\n\ Note: `EventLoop::run` calls `UIApplicationMain` on iOS", ); app_state::will_launch(Box::new(EventLoopHandler { f: event_handler, event_loop: self.window_target, })); // Ensure application delegate is initialized view::WinitApplicationDelegate::class(); UIApplicationMain( 0, ptr::null(), None, Some(&NSString::from_str("WinitApplicationDelegate")), ); unreachable!() } } pub fn create_proxy(&self) -> EventLoopProxy<T> { EventLoopProxy::new(self.window_target.p.sender_to_clone.clone()) } pub fn window_target(&self) -> &RootEventLoopWindowTarget<T> { &self.window_target } } // EventLoopExtIOS impl<T: 'static> EventLoop<T> { pub fn idiom(&self) -> Idiom { UIDevice::current(MainThreadMarker::new().unwrap()) .userInterfaceIdiom() .into() } } pub struct EventLoopProxy<T> { sender: Sender<T>, source: CFRunLoopSourceRef, } unsafe impl<T: Send> Send for EventLoopProxy<T> {} impl<T> Clone for EventLoopProxy<T> { fn clone(&self) -> EventLoopProxy<T> { EventLoopProxy::new(self.sender.clone()) } } impl<T> Drop for EventLoopProxy<T> { fn drop(&mut self) { unsafe { CFRunLoopSourceInvalidate(self.source); CFRelease(self.source as _); } } } impl<T> EventLoopProxy<T> { fn new(sender: Sender<T>) -> EventLoopProxy<T> { unsafe { // just wake up the eventloop extern "C" fn event_loop_proxy_handler(_: *const c_void) {} // adding a Source to the main CFRunLoop lets us wake it up and // process user events through the normal OS EventLoop mechanisms. let rl = CFRunLoopGetMain(); let mut context = CFRunLoopSourceContext { version: 0, info: ptr::null_mut(), retain: None, release: None, copyDescription: None, equal: None, hash: None, schedule: None, cancel: None, perform: event_loop_proxy_handler, }; let source = CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::max_value() - 1, &mut context); CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); CFRunLoopWakeUp(rl); EventLoopProxy { sender, source } } } pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { self.sender .send(event) .map_err(|::std::sync::mpsc::SendError(x)| EventLoopClosed(x))?; unsafe { // let the main thread know there's a new event CFRunLoopSourceSignal(self.source); let rl = CFRunLoopGetMain(); CFRunLoopWakeUp(rl); } Ok(()) } } fn setup_control_flow_observers() { unsafe { // begin is queued with the highest priority to ensure it is processed before other observers extern "C" fn control_flow_begin_handler( _: CFRunLoopObserverRef, activity: CFRunLoopActivity, _: *mut c_void, ) { unsafe { #[allow(non_upper_case_globals)] match activity { kCFRunLoopAfterWaiting => app_state::handle_wakeup_transition(), _ => unreachable!(), } } } // Core Animation registers its `CFRunLoopObserver` that performs drawing operations in // `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end // priority to be 0, in order to send MainEventsCleared before RedrawRequested. This value was // chosen conservatively to guard against apple using different priorities for their redraw // observers in different OS's or on different devices. If it so happens that it's too // conservative, the main symptom would be non-redraw events coming in after `MainEventsCleared`. // // The value of `0x1e8480` was determined by inspecting stack traces and the associated // registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4. // // Also tested to be `0x1e8480` on iPhone 8, iOS 13 beta 4. extern "C" fn control_flow_main_end_handler( _: CFRunLoopObserverRef, activity: CFRunLoopActivity, _: *mut c_void, ) { unsafe { #[allow(non_upper_case_globals)] match activity { kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(), kCFRunLoopExit => unimplemented!(), // not expected to ever happen _ => unreachable!(), } } } // end is queued with the lowest priority to ensure it is processed after other observers extern "C" fn control_flow_end_handler( _: CFRunLoopObserverRef, activity: CFRunLoopActivity, _: *mut c_void, ) { unsafe { #[allow(non_upper_case_globals)] match activity { kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(), kCFRunLoopExit => unimplemented!(), // not expected to ever happen _ => unreachable!(), } } } let main_loop = CFRunLoopGetMain(); let begin_observer = CFRunLoopObserverCreate( ptr::null_mut(), kCFRunLoopAfterWaiting, 1, // repeat = true CFIndex::min_value(), control_flow_begin_handler, ptr::null_mut(), ); CFRunLoopAddObserver(main_loop, begin_observer, kCFRunLoopDefaultMode); let main_end_observer = CFRunLoopObserverCreate( ptr::null_mut(), kCFRunLoopExit | kCFRunLoopBeforeWaiting, 1, // repeat = true 0, // see comment on `control_flow_main_end_handler` control_flow_main_end_handler, ptr::null_mut(), ); CFRunLoopAddObserver(main_loop, main_end_observer, kCFRunLoopDefaultMode); let end_observer = CFRunLoopObserverCreate( ptr::null_mut(), kCFRunLoopExit | kCFRunLoopBeforeWaiting, 1, // repeat = true CFIndex::max_value(), control_flow_end_handler, ptr::null_mut(), ); CFRunLoopAddObserver(main_loop, end_observer, kCFRunLoopDefaultMode); } } #[derive(Debug)] pub enum Never {} pub trait EventHandler: Debug { fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow); fn handle_user_events(&mut self, control_flow: &mut ControlFlow); } struct EventLoopHandler<F, T: 'static> { f: F, event_loop: RootEventLoopWindowTarget<T>, } impl<F, T: 'static> Debug for EventLoopHandler<F, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("EventLoopHandler") .field("event_loop", &self.event_loop) .finish() } } impl<F, T> EventHandler for EventLoopHandler<F, T> where F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow), T: 'static, { fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow) { (self.f)( event.map_nonuser_event().unwrap(), &self.event_loop, control_flow, ); } fn handle_user_events(&mut self, control_flow: &mut ControlFlow) { for event in self.event_loop.p.receiver.try_iter() { (self.f)(Event::UserEvent(event), &self.event_loop, control_flow); } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/ffi.rs
Rust
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)] use std::convert::TryInto; use objc2::encode::{Encode, Encoding}; use objc2::foundation::{NSInteger, NSUInteger}; use crate::platform::ios::{Idiom, ScreenEdge}; #[repr(C)] #[derive(Clone, Debug)] pub struct NSOperatingSystemVersion { pub major: NSInteger, pub minor: NSInteger, pub patch: NSInteger, } unsafe impl Encode for NSOperatingSystemVersion { const ENCODING: Encoding = Encoding::Struct( "NSOperatingSystemVersion", &[ NSInteger::ENCODING, NSInteger::ENCODING, NSInteger::ENCODING, ], ); } #[repr(transparent)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UIUserInterfaceIdiom(NSInteger); unsafe impl Encode for UIUserInterfaceIdiom { const ENCODING: Encoding = NSInteger::ENCODING; } impl UIUserInterfaceIdiom { pub const Unspecified: UIUserInterfaceIdiom = UIUserInterfaceIdiom(-1); pub const Phone: UIUserInterfaceIdiom = UIUserInterfaceIdiom(0); pub const Pad: UIUserInterfaceIdiom = UIUserInterfaceIdiom(1); pub const TV: UIUserInterfaceIdiom = UIUserInterfaceIdiom(2); pub const CarPlay: UIUserInterfaceIdiom = UIUserInterfaceIdiom(3); } impl From<Idiom> for UIUserInterfaceIdiom { fn from(idiom: Idiom) -> UIUserInterfaceIdiom { match idiom { Idiom::Unspecified => UIUserInterfaceIdiom::Unspecified, Idiom::Phone => UIUserInterfaceIdiom::Phone, Idiom::Pad => UIUserInterfaceIdiom::Pad, Idiom::TV => UIUserInterfaceIdiom::TV, Idiom::CarPlay => UIUserInterfaceIdiom::CarPlay, } } } impl From<UIUserInterfaceIdiom> for Idiom { fn from(ui_idiom: UIUserInterfaceIdiom) -> Idiom { match ui_idiom { UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified, UIUserInterfaceIdiom::Phone => Idiom::Phone, UIUserInterfaceIdiom::Pad => Idiom::Pad, UIUserInterfaceIdiom::TV => Idiom::TV, UIUserInterfaceIdiom::CarPlay => Idiom::CarPlay, _ => unreachable!(), } } } #[repr(transparent)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UIRectEdge(NSUInteger); unsafe impl Encode for UIRectEdge { const ENCODING: Encoding = NSUInteger::ENCODING; } impl From<ScreenEdge> for UIRectEdge { fn from(screen_edge: ScreenEdge) -> UIRectEdge { assert_eq!( screen_edge.bits() & !ScreenEdge::ALL.bits(), 0, "invalid `ScreenEdge`" ); UIRectEdge(screen_edge.bits().into()) } } impl From<UIRectEdge> for ScreenEdge { fn from(ui_rect_edge: UIRectEdge) -> ScreenEdge { let bits: u8 = ui_rect_edge.0.try_into().expect("invalid `UIRectEdge`"); ScreenEdge::from_bits(bits).expect("invalid `ScreenEdge`") } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/mod.rs
Rust
//! iOS support //! //! # Building app //! To build ios app you will need rustc built for this targets: //! //! - armv7-apple-ios //! - armv7s-apple-ios //! - i386-apple-ios //! - aarch64-apple-ios //! - x86_64-apple-ios //! //! Then //! //! ``` //! cargo build --target=... //! ``` //! The simplest way to integrate your app into xcode environment is to build it //! as a static library. Wrap your main function and export it. //! //! ```rust, ignore //! #[no_mangle] //! pub extern fn start_winit_app() { //! start_inner() //! } //! //! fn start_inner() { //! ... //! } //! ``` //! //! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode. //! //! ```ignore //! void start_winit_app(); //! ``` //! //! Use start_winit_app inside your xcode's main function. //! //! //! # App lifecycle and events //! //! iOS environment is very different from other platforms and you must be very //! careful with it's events. Familiarize yourself with //! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/). //! //! //! This is how those event are represented in winit: //! //! - applicationDidBecomeActive is Resumed //! - applicationWillResignActive is Suspended //! - applicationWillTerminate is LoopDestroyed //! //! Keep in mind that after LoopDestroyed event is received every attempt to draw with //! opengl will result in segfault. //! //! Also note that app may not receive the LoopDestroyed event if suspended; it might be SIGKILL'ed. #![cfg(ios_platform)] #![allow(clippy::let_unit_value)] // TODO: (mtak-) UIKit requires main thread for virtually all function/method calls. This could be // worked around in the future by using GCD (grand central dispatch) and/or caching of values like // window size/position. macro_rules! assert_main_thread { ($($t:tt)*) => { if !::objc2::foundation::is_main_thread() { panic!($($t)*); } }; } mod app_state; mod event_loop; mod ffi; mod monitor; mod uikit; mod view; mod window; use std::fmt; pub(crate) use self::{ event_loop::{ EventLoop, EventLoopProxy, EventLoopWindowTarget, PlatformSpecificEventLoopAttributes, }, monitor::{MonitorHandle, VideoMode}, window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId}, }; use self::uikit::UIScreen; pub(crate) use crate::icon::NoIcon as PlatformIcon; pub(self) use crate::platform_impl::Fullscreen; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DeviceId { uiscreen: *const UIScreen, } impl DeviceId { pub const unsafe fn dummy() -> Self { DeviceId { uiscreen: std::ptr::null(), } } } unsafe impl Send for DeviceId {} unsafe impl Sync for DeviceId {} #[derive(Debug)] pub enum OsError {} impl fmt::Display for OsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "os error") } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/monitor.rs
Rust
#![allow(clippy::unnecessary_cast)] use std::{ collections::{BTreeSet, VecDeque}, fmt, ops::{Deref, DerefMut}, }; use objc2::foundation::{MainThreadMarker, NSInteger}; use objc2::rc::{Id, Shared}; use super::uikit::{UIScreen, UIScreenMode}; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, monitor::VideoMode as RootVideoMode, platform_impl::platform::app_state, }; // TODO(madsmtm): Remove or refactor this #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub(crate) struct ScreenModeSendSync(pub(crate) Id<UIScreenMode, Shared>); unsafe impl Send for ScreenModeSendSync {} unsafe impl Sync for ScreenModeSendSync {} #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub struct VideoMode { pub(crate) size: (u32, u32), pub(crate) bit_depth: u16, pub(crate) refresh_rate_millihertz: u32, pub(crate) screen_mode: ScreenModeSendSync, pub(crate) monitor: MonitorHandle, } impl VideoMode { fn new(uiscreen: Id<UIScreen, Shared>, screen_mode: Id<UIScreenMode, Shared>) -> VideoMode { assert_main_thread!("`VideoMode` can only be created on the main thread on iOS"); let refresh_rate_millihertz = refresh_rate_millihertz(&uiscreen); let size = screen_mode.size(); VideoMode { size: (size.width as u32, size.height as u32), bit_depth: 32, refresh_rate_millihertz, screen_mode: ScreenModeSendSync(screen_mode), monitor: MonitorHandle::new(uiscreen), } } pub fn size(&self) -> PhysicalSize<u32> { self.size.into() } pub fn bit_depth(&self) -> u16 { self.bit_depth } pub fn refresh_rate_millihertz(&self) -> u32 { self.refresh_rate_millihertz } pub fn monitor(&self) -> MonitorHandle { self.monitor.clone() } } #[derive(Clone, PartialEq, Eq, Hash)] pub struct Inner { uiscreen: Id<UIScreen, Shared>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct MonitorHandle { inner: Inner, } impl PartialOrd for MonitorHandle { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for MonitorHandle { fn cmp(&self, other: &Self) -> std::cmp::Ordering { // TODO: Make a better ordering (self as *const Self).cmp(&(other as *const Self)) } } impl Deref for MonitorHandle { type Target = Inner; fn deref(&self) -> &Inner { assert_main_thread!("`MonitorHandle` methods can only be run on the main thread on iOS"); &self.inner } } impl DerefMut for MonitorHandle { fn deref_mut(&mut self) -> &mut Inner { assert_main_thread!("`MonitorHandle` methods can only be run on the main thread on iOS"); &mut self.inner } } unsafe impl Send for MonitorHandle {} unsafe impl Sync for MonitorHandle {} impl Drop for MonitorHandle { fn drop(&mut self) { assert_main_thread!("`MonitorHandle` can only be dropped on the main thread on iOS"); } } impl fmt::Debug for MonitorHandle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: Do this using the proper fmt API #[derive(Debug)] #[allow(dead_code)] struct MonitorHandle { name: Option<String>, size: PhysicalSize<u32>, position: PhysicalPosition<i32>, scale_factor: f64, } let monitor_id_proxy = MonitorHandle { name: self.name(), size: self.size(), position: self.position(), scale_factor: self.scale_factor(), }; monitor_id_proxy.fmt(f) } } impl MonitorHandle { pub(crate) fn new(uiscreen: Id<UIScreen, Shared>) -> Self { assert_main_thread!("`MonitorHandle` can only be created on the main thread on iOS"); Self { inner: Inner { uiscreen }, } } } impl Inner { pub fn name(&self) -> Option<String> { let main = UIScreen::main(MainThreadMarker::new().unwrap()); if self.uiscreen == main { Some("Primary".to_string()) } else if self.uiscreen == main.mirroredScreen() { Some("Mirrored".to_string()) } else { UIScreen::screens(MainThreadMarker::new().unwrap()) .iter() .position(|rhs| rhs == &*self.uiscreen) .map(|idx| idx.to_string()) } } pub fn size(&self) -> PhysicalSize<u32> { let bounds = self.uiscreen.nativeBounds(); PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32) } pub fn position(&self) -> PhysicalPosition<i32> { let bounds = self.uiscreen.nativeBounds(); (bounds.origin.x as f64, bounds.origin.y as f64).into() } pub fn scale_factor(&self) -> f64 { self.uiscreen.nativeScale() as f64 } pub fn refresh_rate_millihertz(&self) -> Option<u32> { Some(refresh_rate_millihertz(&self.uiscreen)) } pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> { // Use Ord impl of RootVideoMode let modes: BTreeSet<_> = self .uiscreen .availableModes() .into_iter() .map(|mode| { let mode: *const UIScreenMode = mode; let mode = unsafe { Id::retain(mode as *mut UIScreenMode).unwrap() }; RootVideoMode { video_mode: VideoMode::new(self.uiscreen.clone(), mode), } }) .collect(); modes.into_iter().map(|mode| mode.video_mode) } } fn refresh_rate_millihertz(uiscreen: &UIScreen) -> u32 { let refresh_rate_millihertz: NSInteger = { let os_capabilities = app_state::os_capabilities(); if os_capabilities.maximum_frames_per_second { uiscreen.maximumFramesPerSecond() } else { // https://developer.apple.com/library/archive/technotes/tn2460/_index.html // https://en.wikipedia.org/wiki/IPad_Pro#Model_comparison // // All iOS devices support 60 fps, and on devices where `maximumFramesPerSecond` is not // supported, they are all guaranteed to have 60hz refresh rates. This does not // correctly handle external displays. ProMotion displays support 120fps, but they were // introduced at the same time as the `maximumFramesPerSecond` API. // // FIXME: earlier OSs could calculate the refresh rate using // `-[CADisplayLink duration]`. os_capabilities.maximum_frames_per_second_err_msg("defaulting to 60 fps"); 60 } }; refresh_rate_millihertz as u32 * 1000 } // MonitorHandleExtIOS impl Inner { pub(crate) fn ui_screen(&self) -> &Id<UIScreen, Shared> { &self.uiscreen } pub fn preferred_video_mode(&self) -> VideoMode { VideoMode::new( self.uiscreen.clone(), self.uiscreen.preferredMode().unwrap(), ) } } pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque<MonitorHandle> { UIScreen::screens(mtm) .into_iter() .map(|screen| { let screen: *const UIScreen = screen; let screen = unsafe { Id::retain(screen as *mut UIScreen).unwrap() }; MonitorHandle::new(screen) }) .collect() }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/application.rs
Rust
use objc2::foundation::{CGRect, MainThreadMarker, NSArray, NSObject}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{UIResponder, UIWindow}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIApplication; unsafe impl ClassType for UIApplication { #[inherits(NSObject)] type Super = UIResponder; } ); extern_methods!( unsafe impl UIApplication { pub fn shared(_mtm: MainThreadMarker) -> Option<Id<Self, Shared>> { unsafe { msg_send_id![Self::class(), sharedApplication] } } pub fn windows(&self) -> Id<NSArray<UIWindow, Shared>, Shared> { unsafe { msg_send_id![self, windows] } } #[sel(statusBarFrame)] pub fn statusBarFrame(&self) -> CGRect; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/coordinate_space.rs
Rust
use objc2::foundation::NSObject; use objc2::{extern_class, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UICoordinateSpace; unsafe impl ClassType for UICoordinateSpace { type Super = NSObject; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/device.rs
Rust
use objc2::foundation::{MainThreadMarker, NSObject}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::super::ffi::UIUserInterfaceIdiom; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIDevice; unsafe impl ClassType for UIDevice { type Super = NSObject; } ); extern_methods!( unsafe impl UIDevice { pub fn current(_mtm: MainThreadMarker) -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), currentDevice] } } #[sel(userInterfaceIdiom)] pub fn userInterfaceIdiom(&self) -> UIUserInterfaceIdiom; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/event.rs
Rust
use objc2::foundation::NSObject; use objc2::{extern_class, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIEvent; unsafe impl ClassType for UIEvent { type Super = NSObject; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/mod.rs
Rust
#![deny(unsafe_op_in_unsafe_fn)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] use std::os::raw::{c_char, c_int}; use objc2::foundation::NSString; mod application; mod coordinate_space; mod device; mod event; mod responder; mod screen; mod screen_mode; mod touch; mod trait_collection; mod view; mod view_controller; mod window; pub(crate) use self::application::UIApplication; pub(crate) use self::coordinate_space::UICoordinateSpace; pub(crate) use self::device::UIDevice; pub(crate) use self::event::UIEvent; pub(crate) use self::responder::UIResponder; pub(crate) use self::screen::{UIScreen, UIScreenOverscanCompensation}; pub(crate) use self::screen_mode::UIScreenMode; pub(crate) use self::touch::{UITouch, UITouchPhase, UITouchType}; pub(crate) use self::trait_collection::{UIForceTouchCapability, UITraitCollection}; #[allow(unused_imports)] pub(crate) use self::view::{UIEdgeInsets, UIView}; pub(crate) use self::view_controller::{UIInterfaceOrientationMask, UIViewController}; pub(crate) use self::window::UIWindow; #[link(name = "UIKit", kind = "framework")] extern "C" { pub fn UIApplicationMain( argc: c_int, argv: *const c_char, principalClassName: Option<&NSString>, delegateClassName: Option<&NSString>, ) -> c_int; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/responder.rs
Rust
use objc2::foundation::NSObject; use objc2::{extern_class, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIResponder; unsafe impl ClassType for UIResponder { type Super = NSObject; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/screen.rs
Rust
use objc2::encode::{Encode, Encoding}; use objc2::foundation::{CGFloat, CGRect, MainThreadMarker, NSArray, NSInteger, NSObject}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{UICoordinateSpace, UIScreenMode}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIScreen; unsafe impl ClassType for UIScreen { type Super = NSObject; } ); extern_methods!( unsafe impl UIScreen { pub fn main(_mtm: MainThreadMarker) -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), mainScreen] } } pub fn screens(_mtm: MainThreadMarker) -> Id<NSArray<Self, Shared>, Shared> { unsafe { msg_send_id![Self::class(), screens] } } #[sel(bounds)] pub fn bounds(&self) -> CGRect; #[sel(scale)] pub fn scale(&self) -> CGFloat; #[sel(nativeBounds)] pub fn nativeBounds(&self) -> CGRect; #[sel(nativeScale)] pub fn nativeScale(&self) -> CGFloat; #[sel(maximumFramesPerSecond)] pub fn maximumFramesPerSecond(&self) -> NSInteger; pub fn mirroredScreen(&self) -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), mirroredScreen] } } pub fn preferredMode(&self) -> Option<Id<UIScreenMode, Shared>> { unsafe { msg_send_id![self, preferredMode] } } #[sel(setCurrentMode:)] pub fn setCurrentMode(&self, mode: Option<&UIScreenMode>); pub fn availableModes(&self) -> Id<NSArray<UIScreenMode, Shared>, Shared> { unsafe { msg_send_id![self, availableModes] } } #[sel(setOverscanCompensation:)] pub fn setOverscanCompensation(&self, overscanCompensation: UIScreenOverscanCompensation); pub fn coordinateSpace(&self) -> Id<UICoordinateSpace, Shared> { unsafe { msg_send_id![self, coordinateSpace] } } } ); #[repr(transparent)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UIScreenOverscanCompensation(NSInteger); unsafe impl Encode for UIScreenOverscanCompensation { const ENCODING: Encoding = NSInteger::ENCODING; } #[allow(dead_code)] impl UIScreenOverscanCompensation { pub const Scale: Self = Self(0); pub const InsetBounds: Self = Self(1); pub const None: Self = Self(2); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/screen_mode.rs
Rust
use objc2::foundation::{CGSize, NSObject}; use objc2::{extern_class, extern_methods, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIScreenMode; unsafe impl ClassType for UIScreenMode { type Super = NSObject; } ); extern_methods!( unsafe impl UIScreenMode { #[sel(size)] pub fn size(&self) -> CGSize; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/touch.rs
Rust
use objc2::encode::{Encode, Encoding}; use objc2::foundation::{CGFloat, CGPoint, NSInteger, NSObject}; use objc2::{extern_class, extern_methods, ClassType}; use super::UIView; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UITouch; unsafe impl ClassType for UITouch { type Super = NSObject; } ); extern_methods!( unsafe impl UITouch { #[sel(locationInView:)] pub fn locationInView(&self, view: Option<&UIView>) -> CGPoint; #[sel(type)] pub fn type_(&self) -> UITouchType; #[sel(force)] pub fn force(&self) -> CGFloat; #[sel(maximumPossibleForce)] pub fn maximumPossibleForce(&self) -> CGFloat; #[sel(altitudeAngle)] pub fn altitudeAngle(&self) -> CGFloat; #[sel(phase)] pub fn phase(&self) -> UITouchPhase; } ); #[derive(Debug, PartialEq, Eq)] #[allow(dead_code)] #[repr(isize)] pub enum UITouchType { Direct = 0, Indirect, Pencil, } unsafe impl Encode for UITouchType { const ENCODING: Encoding = NSInteger::ENCODING; } #[derive(Debug)] #[allow(dead_code)] #[repr(isize)] pub enum UITouchPhase { Began = 0, Moved, Stationary, Ended, Cancelled, } unsafe impl Encode for UITouchPhase { const ENCODING: Encoding = NSInteger::ENCODING; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/trait_collection.rs
Rust
use objc2::encode::{Encode, Encoding}; use objc2::foundation::{NSInteger, NSObject}; use objc2::{extern_class, extern_methods, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UITraitCollection; unsafe impl ClassType for UITraitCollection { type Super = NSObject; } ); extern_methods!( unsafe impl UITraitCollection { #[sel(forceTouchCapability)] pub fn forceTouchCapability(&self) -> UIForceTouchCapability; } ); #[derive(Debug, PartialEq, Eq)] #[allow(dead_code)] #[repr(isize)] pub enum UIForceTouchCapability { Unknown = 0, Unavailable, Available, } unsafe impl Encode for UIForceTouchCapability { const ENCODING: Encoding = NSInteger::ENCODING; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/view.rs
Rust
use objc2::encode::{Encode, Encoding}; use objc2::foundation::{CGFloat, CGRect, NSObject}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{UICoordinateSpace, UIResponder, UIViewController}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIView; unsafe impl ClassType for UIView { #[inherits(NSObject)] type Super = UIResponder; } ); extern_methods!( unsafe impl UIView { #[sel(bounds)] pub fn bounds(&self) -> CGRect; #[sel(setBounds:)] pub fn setBounds(&self, value: CGRect); #[sel(frame)] pub fn frame(&self) -> CGRect; #[sel(setFrame:)] pub fn setFrame(&self, value: CGRect); #[sel(contentScaleFactor)] pub fn contentScaleFactor(&self) -> CGFloat; #[sel(setContentScaleFactor:)] pub fn setContentScaleFactor(&self, val: CGFloat); #[sel(setMultipleTouchEnabled:)] pub fn setMultipleTouchEnabled(&self, val: bool); pub fn rootViewController(&self) -> Option<Id<UIViewController, Shared>> { unsafe { msg_send_id![self, rootViewController] } } #[sel(setRootViewController:)] pub fn setRootViewController(&self, rootViewController: Option<&UIViewController>); #[sel(convertRect:toCoordinateSpace:)] pub fn convertRect_toCoordinateSpace( &self, rect: CGRect, coordinateSpace: &UICoordinateSpace, ) -> CGRect; #[sel(convertRect:fromCoordinateSpace:)] pub fn convertRect_fromCoordinateSpace( &self, rect: CGRect, coordinateSpace: &UICoordinateSpace, ) -> CGRect; #[sel(safeAreaInsets)] pub fn safeAreaInsets(&self) -> UIEdgeInsets; #[sel(setNeedsDisplay)] pub fn setNeedsDisplay(&self); } ); #[repr(C)] #[derive(Debug, Clone)] pub struct UIEdgeInsets { pub top: CGFloat, pub left: CGFloat, pub bottom: CGFloat, pub right: CGFloat, } unsafe impl Encode for UIEdgeInsets { const ENCODING: Encoding = Encoding::Struct( "UIEdgeInsets", &[ CGFloat::ENCODING, CGFloat::ENCODING, CGFloat::ENCODING, CGFloat::ENCODING, ], ); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/view_controller.rs
Rust
use objc2::encode::{Encode, Encoding}; use objc2::foundation::{NSObject, NSUInteger}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{UIResponder, UIView}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIViewController; unsafe impl ClassType for UIViewController { #[inherits(NSObject)] type Super = UIResponder; } ); extern_methods!( unsafe impl UIViewController { #[sel(attemptRotationToDeviceOrientation)] pub fn attemptRotationToDeviceOrientation(); #[sel(setNeedsStatusBarAppearanceUpdate)] pub fn setNeedsStatusBarAppearanceUpdate(&self); #[sel(setNeedsUpdateOfHomeIndicatorAutoHidden)] pub fn setNeedsUpdateOfHomeIndicatorAutoHidden(&self); #[sel(setNeedsUpdateOfScreenEdgesDeferringSystemGestures)] pub fn setNeedsUpdateOfScreenEdgesDeferringSystemGestures(&self); pub fn view(&self) -> Option<Id<UIView, Shared>> { unsafe { msg_send_id![self, view] } } #[sel(setView:)] pub fn setView(&self, view: Option<&UIView>); } ); bitflags! { pub struct UIInterfaceOrientationMask: NSUInteger { const Portrait = 1 << 1; const PortraitUpsideDown = 1 << 2; const LandscapeRight = 1 << 3; const LandscapeLeft = 1 << 4; const Landscape = Self::LandscapeLeft.bits() | Self::LandscapeRight.bits(); const AllButUpsideDown = Self::Landscape.bits() | Self::Portrait.bits(); const All = Self::AllButUpsideDown.bits() | Self::PortraitUpsideDown.bits(); } } unsafe impl Encode for UIInterfaceOrientationMask { const ENCODING: Encoding = NSUInteger::ENCODING; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/uikit/window.rs
Rust
use objc2::foundation::NSObject; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{UIResponder, UIScreen, UIView}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct UIWindow; unsafe impl ClassType for UIWindow { #[inherits(UIResponder, NSObject)] type Super = UIView; } ); extern_methods!( unsafe impl UIWindow { pub fn screen(&self) -> Id<UIScreen, Shared> { unsafe { msg_send_id![self, screen] } } #[sel(setScreen:)] pub fn setScreen(&self, screen: &UIScreen); #[sel(setHidden:)] pub fn setHidden(&self, flag: bool); #[sel(makeKeyAndVisible)] pub fn makeKeyAndVisible(&self); #[sel(isKeyWindow)] pub fn isKeyWindow(&self) -> bool; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/view.rs
Rust
#![allow(clippy::unnecessary_cast)] use objc2::foundation::{CGFloat, CGRect, MainThreadMarker, NSObject, NSSet}; use objc2::rc::{Id, Shared}; use objc2::runtime::Class; use objc2::{declare_class, extern_methods, msg_send, msg_send_id, ClassType}; use super::uikit::{ UIApplication, UIDevice, UIEvent, UIForceTouchCapability, UIInterfaceOrientationMask, UIResponder, UITouch, UITouchPhase, UITouchType, UITraitCollection, UIView, UIViewController, UIWindow, }; use super::window::WindowId; use crate::{ dpi::PhysicalPosition, event::{DeviceId as RootDeviceId, Event, Force, Touch, TouchPhase, WindowEvent}, platform::ios::ValidOrientations, platform_impl::platform::{ app_state, event_loop::{EventProxy, EventWrapper}, ffi::{UIRectEdge, UIUserInterfaceIdiom}, window::PlatformSpecificWindowBuilderAttributes, DeviceId, Fullscreen, }, window::{WindowAttributes, WindowId as RootWindowId}, }; declare_class!( pub(crate) struct WinitView {} unsafe impl ClassType for WinitView { #[inherits(UIResponder, NSObject)] type Super = UIView; const NAME: &'static str = "WinitUIView"; } unsafe impl WinitView { #[sel(drawRect:)] fn draw_rect(&self, rect: CGRect) { let window = self.window().unwrap(); unsafe { app_state::handle_nonuser_events( std::iter::once(EventWrapper::StaticEvent(Event::RedrawRequested( RootWindowId(window.id()), ))) .chain(std::iter::once(EventWrapper::StaticEvent( Event::RedrawEventsCleared, ))), ); } let _: () = unsafe { msg_send![super(self), drawRect: rect] }; } #[sel(layoutSubviews)] fn layout_subviews(&self) { let _: () = unsafe { msg_send![super(self), layoutSubviews] }; let window = self.window().unwrap(); let window_bounds = window.bounds(); let screen = window.screen(); let screen_space = screen.coordinateSpace(); let screen_frame = self.convertRect_toCoordinateSpace(window_bounds, &screen_space); let scale_factor = screen.scale(); let size = crate::dpi::LogicalSize { width: screen_frame.size.width as f64, height: screen_frame.size.height as f64, } .to_physical(scale_factor as f64); // If the app is started in landscape, the view frame and window bounds can be mismatched. // The view frame will be in portrait and the window bounds in landscape. So apply the // window bounds to the view frame to make it consistent. let view_frame = self.frame(); if view_frame != window_bounds { self.setFrame(window_bounds); } unsafe { app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent { window_id: RootWindowId(window.id()), event: WindowEvent::Resized(size), })); } } #[sel(setContentScaleFactor:)] fn set_content_scale_factor(&self, untrusted_scale_factor: CGFloat) { let _: () = unsafe { msg_send![super(self), setContentScaleFactor: untrusted_scale_factor] }; // `window` is null when `setContentScaleFactor` is invoked prior to `[UIWindow // makeKeyAndVisible]` at window creation time (either manually or internally by // UIKit when the `UIView` is first created), in which case we send no events here let window = match self.window() { Some(window) => window, None => return, }; // `setContentScaleFactor` may be called with a value of 0, which means "reset the // content scale factor to a device-specific default value", so we can't use the // parameter here. We can query the actual factor using the getter let scale_factor = self.contentScaleFactor(); assert!( !scale_factor.is_nan() && scale_factor.is_finite() && scale_factor.is_sign_positive() && scale_factor > 0.0, "invalid scale_factor set on UIView", ); let scale_factor = scale_factor as f64; let bounds = self.bounds(); let screen = window.screen(); let screen_space = screen.coordinateSpace(); let screen_frame = self.convertRect_toCoordinateSpace(bounds, &screen_space); let size = crate::dpi::LogicalSize { width: screen_frame.size.width as _, height: screen_frame.size.height as _, }; let window_id = RootWindowId(window.id()); unsafe { app_state::handle_nonuser_events( std::iter::once(EventWrapper::EventProxy(EventProxy::DpiChangedProxy { window, scale_factor, suggested_size: size, })) .chain(std::iter::once(EventWrapper::StaticEvent( Event::WindowEvent { window_id, event: WindowEvent::Resized(size.to_physical(scale_factor)), }, ))), ); } } #[sel(touchesBegan:withEvent:)] fn touches_began(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { self.handle_touches(touches) } #[sel(touchesMoved:withEvent:)] fn touches_moved(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { self.handle_touches(touches) } #[sel(touchesEnded:withEvent:)] fn touches_ended(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { self.handle_touches(touches) } #[sel(touchesCancelled:withEvent:)] fn touches_cancelled(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { self.handle_touches(touches) } } ); extern_methods!( #[allow(non_snake_case)] unsafe impl WinitView { fn window(&self) -> Option<Id<WinitUIWindow, Shared>> { unsafe { msg_send_id![self, window] } } unsafe fn traitCollection(&self) -> Id<UITraitCollection, Shared> { msg_send_id![self, traitCollection] } // TODO: Allow the user to customize this #[sel(layerClass)] pub(crate) fn layerClass() -> &'static Class; } ); impl WinitView { pub(crate) fn new( _mtm: MainThreadMarker, _window_attributes: &WindowAttributes, platform_attributes: &PlatformSpecificWindowBuilderAttributes, frame: CGRect, ) -> Id<Self, Shared> { let this: Id<Self, Shared> = unsafe { msg_send_id![msg_send_id![Self::class(), alloc], initWithFrame: frame] }; this.setMultipleTouchEnabled(true); if let Some(scale_factor) = platform_attributes.scale_factor { this.setContentScaleFactor(scale_factor as _); } this } fn handle_touches(&self, touches: &NSSet<UITouch>) { let window = self.window().unwrap(); let uiscreen = window.screen(); let mut touch_events = Vec::new(); let os_supports_force = app_state::os_capabilities().force_touch; for touch in touches { let logical_location = touch.locationInView(None); let touch_type = touch.type_(); let force = if os_supports_force { let trait_collection = unsafe { self.traitCollection() }; let touch_capability = trait_collection.forceTouchCapability(); // Both the OS _and_ the device need to be checked for force touch support. if touch_capability == UIForceTouchCapability::Available { let force = touch.force(); let max_possible_force = touch.maximumPossibleForce(); let altitude_angle: Option<f64> = if touch_type == UITouchType::Pencil { let angle = touch.altitudeAngle(); Some(angle as _) } else { None }; Some(Force::Calibrated { force: force as _, max_possible_force: max_possible_force as _, altitude_angle, }) } else { None } } else { None }; let touch_id = touch as *const UITouch as u64; let phase = touch.phase(); let phase = match phase { UITouchPhase::Began => TouchPhase::Started, UITouchPhase::Moved => TouchPhase::Moved, // 2 is UITouchPhase::Stationary and is not expected here UITouchPhase::Ended => TouchPhase::Ended, UITouchPhase::Cancelled => TouchPhase::Cancelled, _ => panic!("unexpected touch phase: {:?}", phase as i32), }; let physical_location = { let scale_factor = self.contentScaleFactor(); PhysicalPosition::from_logical::<(f64, f64), f64>( (logical_location.x as _, logical_location.y as _), scale_factor as f64, ) }; touch_events.push(EventWrapper::StaticEvent(Event::WindowEvent { window_id: RootWindowId(window.id()), event: WindowEvent::Touch(Touch { device_id: RootDeviceId(DeviceId { uiscreen: Id::as_ptr(&uiscreen), }), id: touch_id, location: physical_location, force, phase, }), })); } unsafe { app_state::handle_nonuser_events(touch_events); } } } declare_class!( pub(crate) struct WinitViewController { _prefers_status_bar_hidden: bool, _prefers_home_indicator_auto_hidden: bool, _supported_orientations: UIInterfaceOrientationMask, _preferred_screen_edges_deferring_system_gestures: UIRectEdge, } unsafe impl ClassType for WinitViewController { #[inherits(UIResponder, NSObject)] type Super = UIViewController; const NAME: &'static str = "WinitUIViewController"; } unsafe impl WinitViewController { #[sel(shouldAutorotate)] fn should_autorotate(&self) -> bool { true } } unsafe impl WinitViewController { #[sel(prefersStatusBarHidden)] fn prefers_status_bar_hidden(&self) -> bool { *self._prefers_status_bar_hidden } #[sel(setPrefersStatusBarHidden:)] fn set_prefers_status_bar_hidden(&mut self, val: bool) { *self._prefers_status_bar_hidden = val; self.setNeedsStatusBarAppearanceUpdate(); } #[sel(prefersHomeIndicatorAutoHidden)] fn prefers_home_indicator_auto_hidden(&self) -> bool { *self._prefers_home_indicator_auto_hidden } #[sel(setPrefersHomeIndicatorAutoHidden:)] fn set_prefers_home_indicator_auto_hidden(&mut self, val: bool) { *self._prefers_home_indicator_auto_hidden = val; let os_capabilities = app_state::os_capabilities(); if os_capabilities.home_indicator_hidden { self.setNeedsUpdateOfHomeIndicatorAutoHidden(); } else { os_capabilities.home_indicator_hidden_err_msg("ignoring") } } #[sel(supportedInterfaceOrientations)] fn supported_orientations(&self) -> UIInterfaceOrientationMask { *self._supported_orientations } #[sel(setSupportedInterfaceOrientations:)] fn set_supported_orientations(&mut self, val: UIInterfaceOrientationMask) { *self._supported_orientations = val; UIViewController::attemptRotationToDeviceOrientation(); } #[sel(preferredScreenEdgesDeferringSystemGestures)] fn preferred_screen_edges_deferring_system_gestures(&self) -> UIRectEdge { *self._preferred_screen_edges_deferring_system_gestures } #[sel(setPreferredScreenEdgesDeferringSystemGestures:)] fn set_preferred_screen_edges_deferring_system_gestures(&mut self, val: UIRectEdge) { *self._preferred_screen_edges_deferring_system_gestures = val; let os_capabilities = app_state::os_capabilities(); if os_capabilities.defer_system_gestures { self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures(); } else { os_capabilities.defer_system_gestures_err_msg("ignoring") } } } ); extern_methods!( #[allow(non_snake_case)] unsafe impl WinitViewController { #[sel(setPrefersStatusBarHidden:)] pub(crate) fn setPrefersStatusBarHidden(&self, flag: bool); #[sel(setSupportedInterfaceOrientations:)] pub(crate) fn setSupportedInterfaceOrientations(&self, val: UIInterfaceOrientationMask); #[sel(setPrefersHomeIndicatorAutoHidden:)] pub(crate) fn setPrefersHomeIndicatorAutoHidden(&self, val: bool); #[sel(setPreferredScreenEdgesDeferringSystemGestures:)] pub(crate) fn setPreferredScreenEdgesDeferringSystemGestures(&self, val: UIRectEdge); } ); impl WinitViewController { pub(crate) fn set_supported_interface_orientations( &self, mtm: MainThreadMarker, valid_orientations: ValidOrientations, ) { let mask = match ( valid_orientations, UIDevice::current(mtm).userInterfaceIdiom(), ) { (ValidOrientations::LandscapeAndPortrait, UIUserInterfaceIdiom::Phone) => { UIInterfaceOrientationMask::AllButUpsideDown } (ValidOrientations::LandscapeAndPortrait, _) => UIInterfaceOrientationMask::All, (ValidOrientations::Landscape, _) => UIInterfaceOrientationMask::Landscape, (ValidOrientations::Portrait, UIUserInterfaceIdiom::Phone) => { UIInterfaceOrientationMask::Portrait } (ValidOrientations::Portrait, _) => { UIInterfaceOrientationMask::Portrait | UIInterfaceOrientationMask::PortraitUpsideDown } }; self.setSupportedInterfaceOrientations(mask); } pub(crate) fn new( mtm: MainThreadMarker, _window_attributes: &WindowAttributes, platform_attributes: &PlatformSpecificWindowBuilderAttributes, view: &UIView, ) -> Id<Self, Shared> { let this: Id<Self, Shared> = unsafe { msg_send_id![msg_send_id![Self::class(), alloc], init] }; this.setPrefersStatusBarHidden(platform_attributes.prefers_status_bar_hidden); this.set_supported_interface_orientations(mtm, platform_attributes.valid_orientations); this.setPrefersHomeIndicatorAutoHidden(platform_attributes.prefers_home_indicator_hidden); this.setPreferredScreenEdgesDeferringSystemGestures( platform_attributes .preferred_screen_edges_deferring_system_gestures .into(), ); this.setView(Some(view)); this } } declare_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct WinitUIWindow {} unsafe impl ClassType for WinitUIWindow { #[inherits(UIResponder, NSObject)] type Super = UIWindow; } unsafe impl WinitUIWindow { #[sel(becomeKeyWindow)] fn become_key_window(&self) { unsafe { app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent { window_id: RootWindowId(self.id()), event: WindowEvent::Focused(true), })); } let _: () = unsafe { msg_send![super(self), becomeKeyWindow] }; } #[sel(resignKeyWindow)] fn resign_key_window(&self) { unsafe { app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent { window_id: RootWindowId(self.id()), event: WindowEvent::Focused(false), })); } let _: () = unsafe { msg_send![super(self), resignKeyWindow] }; } } ); impl WinitUIWindow { pub(crate) fn new( _mtm: MainThreadMarker, window_attributes: &WindowAttributes, _platform_attributes: &PlatformSpecificWindowBuilderAttributes, frame: CGRect, view_controller: &UIViewController, ) -> Id<Self, Shared> { let this: Id<Self, Shared> = unsafe { msg_send_id![msg_send_id![Self::class(), alloc], initWithFrame: frame] }; this.setRootViewController(Some(view_controller)); match window_attributes.fullscreen.clone().map(Into::into) { Some(Fullscreen::Exclusive(ref video_mode)) => { let monitor = video_mode.monitor(); let screen = monitor.ui_screen(); screen.setCurrentMode(Some(&video_mode.screen_mode.0)); this.setScreen(screen); } Some(Fullscreen::Borderless(Some(ref monitor))) => { let screen = monitor.ui_screen(); this.setScreen(screen); } _ => (), } this } pub(crate) fn id(&self) -> WindowId { (self as *const Self as usize as u64).into() } } declare_class!( pub struct WinitApplicationDelegate {} unsafe impl ClassType for WinitApplicationDelegate { type Super = NSObject; } // UIApplicationDelegate protocol unsafe impl WinitApplicationDelegate { #[sel(application:didFinishLaunchingWithOptions:)] fn did_finish_launching(&self, _application: &UIApplication, _: *mut NSObject) -> bool { unsafe { app_state::did_finish_launching(); } true } #[sel(applicationDidBecomeActive:)] fn did_become_active(&self, _application: &UIApplication) { unsafe { app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::Resumed)) } } #[sel(applicationWillResignActive:)] fn will_resign_active(&self, _application: &UIApplication) { unsafe { app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::Suspended)) } } #[sel(applicationWillEnterForeground:)] fn will_enter_foreground(&self, _application: &UIApplication) {} #[sel(applicationDidEnterBackground:)] fn did_enter_background(&self, _application: &UIApplication) {} #[sel(applicationWillTerminate:)] fn will_terminate(&self, application: &UIApplication) { let mut events = Vec::new(); for window in application.windows().iter() { if window.is_kind_of::<WinitUIWindow>() { // SAFETY: We just checked that the window is a `winit` window let window = unsafe { let ptr: *const UIWindow = window; let ptr: *const WinitUIWindow = ptr.cast(); &*ptr }; events.push(EventWrapper::StaticEvent(Event::WindowEvent { window_id: RootWindowId(window.id()), event: WindowEvent::Destroyed, })); } } unsafe { app_state::handle_nonuser_events(events); app_state::terminated(); } } } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/ios/window.rs
Rust
#![allow(clippy::unnecessary_cast)] use std::{ collections::VecDeque, ffi::c_void, ops::{Deref, DerefMut}, }; use objc2::foundation::{CGFloat, CGPoint, CGRect, CGSize, MainThreadMarker}; use objc2::rc::{Id, Shared}; use objc2::runtime::Object; use objc2::{class, msg_send}; use raw_window_handle::{RawDisplayHandle, RawWindowHandle, UiKitDisplayHandle, UiKitWindowHandle}; use super::uikit::{UIApplication, UIScreen, UIScreenOverscanCompensation}; use super::view::{WinitUIWindow, WinitView, WinitViewController}; use crate::{ dpi::{self, LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}, error::{ExternalError, NotSupportedError, OsError as RootOsError}, event::{Event, WindowEvent}, icon::Icon, platform::ios::{ScreenEdge, ValidOrientations}, platform_impl::platform::{ app_state, event_loop::{EventProxy, EventWrapper}, ffi::UIRectEdge, monitor, EventLoopWindowTarget, Fullscreen, MonitorHandle, }, window::{ CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, WindowButtons, WindowId as RootWindowId, WindowLevel, }, }; pub struct Inner { pub(crate) window: Id<WinitUIWindow, Shared>, pub(crate) view_controller: Id<WinitViewController, Shared>, pub(crate) view: Id<WinitView, Shared>, gl_or_metal_backed: bool, } impl Inner { pub fn set_title(&self, _title: &str) { debug!("`Window::set_title` is ignored on iOS") } pub fn set_transparent(&self, _transparent: bool) { debug!("`Window::set_transparent` is ignored on iOS") } pub fn set_visible(&self, visible: bool) { self.window.setHidden(!visible) } pub fn is_visible(&self) -> Option<bool> { warn!("`Window::is_visible` is ignored on iOS"); None } pub fn request_redraw(&self) { unsafe { if self.gl_or_metal_backed { // `setNeedsDisplay` does nothing on UIViews which are directly backed by CAEAGLLayer or CAMetalLayer. // Ordinarily the OS sets up a bunch of UIKit state before calling drawRect: on a UIView, but when using // raw or gl/metal for drawing this work is completely avoided. // // The docs for `setNeedsDisplay` don't mention `CAMetalLayer`; however, this has been confirmed via // testing. // // https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay?language=objc app_state::queue_gl_or_metal_redraw(self.window.clone()); } else { self.view.setNeedsDisplay(); } } } pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { unsafe { let safe_area = self.safe_area_screen_space(); let position = LogicalPosition { x: safe_area.origin.x as f64, y: safe_area.origin.y as f64, }; let scale_factor = self.scale_factor(); Ok(position.to_physical(scale_factor)) } } pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { unsafe { let screen_frame = self.screen_frame(); let position = LogicalPosition { x: screen_frame.origin.x as f64, y: screen_frame.origin.y as f64, }; let scale_factor = self.scale_factor(); Ok(position.to_physical(scale_factor)) } } pub fn set_outer_position(&self, physical_position: Position) { unsafe { let scale_factor = self.scale_factor(); let position = physical_position.to_logical::<f64>(scale_factor); let screen_frame = self.screen_frame(); let new_screen_frame = CGRect { origin: CGPoint { x: position.x as _, y: position.y as _, }, size: screen_frame.size, }; let bounds = self.rect_from_screen_space(new_screen_frame); self.window.setBounds(bounds); } } pub fn inner_size(&self) -> PhysicalSize<u32> { unsafe { let scale_factor = self.scale_factor(); let safe_area = self.safe_area_screen_space(); let size = LogicalSize { width: safe_area.size.width as f64, height: safe_area.size.height as f64, }; size.to_physical(scale_factor) } } pub fn outer_size(&self) -> PhysicalSize<u32> { unsafe { let scale_factor = self.scale_factor(); let screen_frame = self.screen_frame(); let size = LogicalSize { width: screen_frame.size.width as f64, height: screen_frame.size.height as f64, }; size.to_physical(scale_factor) } } pub fn set_inner_size(&self, _size: Size) { warn!("not clear what `Window::set_inner_size` means on iOS"); } pub fn set_min_inner_size(&self, _dimensions: Option<Size>) { warn!("`Window::set_min_inner_size` is ignored on iOS") } pub fn set_max_inner_size(&self, _dimensions: Option<Size>) { warn!("`Window::set_max_inner_size` is ignored on iOS") } pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { None } #[inline] pub fn set_resize_increments(&self, _increments: Option<Size>) { warn!("`Window::set_resize_increments` is ignored on iOS") } pub fn set_resizable(&self, _resizable: bool) { warn!("`Window::set_resizable` is ignored on iOS") } pub fn is_resizable(&self) -> bool { warn!("`Window::is_resizable` is ignored on iOS"); false } #[inline] pub fn set_enabled_buttons(&self, _buttons: WindowButtons) { warn!("`Window::set_enabled_buttons` is ignored on iOS"); } #[inline] pub fn enabled_buttons(&self) -> WindowButtons { warn!("`Window::enabled_buttons` is ignored on iOS"); WindowButtons::all() } pub fn scale_factor(&self) -> f64 { self.view.contentScaleFactor() as _ } pub fn set_cursor_icon(&self, _cursor: CursorIcon) { debug!("`Window::set_cursor_icon` ignored on iOS") } pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } pub fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } pub fn set_cursor_visible(&self, _visible: bool) { debug!("`Window::set_cursor_visible` is ignored on iOS") } pub fn drag_window(&self) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } pub fn set_minimized(&self, _minimized: bool) { warn!("`Window::set_minimized` is ignored on iOS") } pub fn is_minimized(&self) -> Option<bool> { warn!("`Window::is_minimized` is ignored on iOS"); None } pub fn set_maximized(&self, _maximized: bool) { warn!("`Window::set_maximized` is ignored on iOS") } pub fn is_maximized(&self) -> bool { warn!("`Window::is_maximized` is ignored on iOS"); false } pub(crate) fn set_fullscreen(&self, monitor: Option<Fullscreen>) { let uiscreen = match &monitor { Some(Fullscreen::Exclusive(video_mode)) => { let uiscreen = video_mode.monitor.ui_screen(); uiscreen.setCurrentMode(Some(&video_mode.screen_mode.0)); uiscreen.clone() } Some(Fullscreen::Borderless(Some(monitor))) => monitor.ui_screen().clone(), Some(Fullscreen::Borderless(None)) => self.current_monitor_inner().ui_screen().clone(), None => { warn!("`Window::set_fullscreen(None)` ignored on iOS"); return; } }; // this is pretty slow on iOS, so avoid doing it if we can let current = self.window.screen(); if uiscreen != current { self.window.setScreen(&uiscreen); } let bounds = uiscreen.bounds(); self.window.setFrame(bounds); // For external displays, we must disable overscan compensation or // the displayed image will have giant black bars surrounding it on // each side uiscreen.setOverscanCompensation(UIScreenOverscanCompensation::None); } pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { unsafe { let monitor = self.current_monitor_inner(); let uiscreen = monitor.ui_screen(); let screen_space_bounds = self.screen_frame(); let screen_bounds = uiscreen.bounds(); // TODO: track fullscreen instead of relying on brittle float comparisons if screen_space_bounds.origin.x == screen_bounds.origin.x && screen_space_bounds.origin.y == screen_bounds.origin.y && screen_space_bounds.size.width == screen_bounds.size.width && screen_space_bounds.size.height == screen_bounds.size.height { Some(Fullscreen::Borderless(Some(monitor))) } else { None } } } pub fn set_decorations(&self, _decorations: bool) {} pub fn is_decorated(&self) -> bool { true } pub fn set_window_level(&self, _level: WindowLevel) { warn!("`Window::set_window_level` is ignored on iOS") } pub fn set_window_icon(&self, _icon: Option<Icon>) { warn!("`Window::set_window_icon` is ignored on iOS") } pub fn set_ime_position(&self, _position: Position) { warn!("`Window::set_ime_position` is ignored on iOS") } pub fn set_ime_allowed(&self, _allowed: bool) { warn!("`Window::set_ime_allowed` is ignored on iOS") } pub fn set_ime_purpose(&self, _purpose: ImePurpose) { warn!("`Window::set_ime_allowed` is ignored on iOS") } pub fn focus_window(&self) { warn!("`Window::set_focus` is ignored on iOS") } pub fn request_user_attention(&self, _request_type: Option<UserAttentionType>) { warn!("`Window::request_user_attention` is ignored on iOS") } // Allow directly accessing the current monitor internally without unwrapping. fn current_monitor_inner(&self) -> MonitorHandle { MonitorHandle::new(self.window.screen()) } pub fn current_monitor(&self) -> Option<MonitorHandle> { Some(self.current_monitor_inner()) } pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { monitor::uiscreens(MainThreadMarker::new().unwrap()) } pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle::new(UIScreen::main( MainThreadMarker::new().unwrap(), ))) } pub fn id(&self) -> WindowId { self.window.id() } pub fn raw_window_handle(&self) -> RawWindowHandle { let mut window_handle = UiKitWindowHandle::empty(); window_handle.ui_window = Id::as_ptr(&self.window) as _; window_handle.ui_view = Id::as_ptr(&self.view) as _; window_handle.ui_view_controller = Id::as_ptr(&self.view_controller) as _; RawWindowHandle::UiKit(window_handle) } pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::UiKit(UiKitDisplayHandle::empty()) } pub fn theme(&self) -> Option<Theme> { warn!("`Window::theme` is ignored on iOS"); None } pub fn has_focus(&self) -> bool { self.window.isKeyWindow() } #[inline] pub fn set_theme(&self, _theme: Option<Theme>) { warn!("`Window::set_theme` is ignored on iOS"); } pub fn title(&self) -> String { warn!("`Window::title` is ignored on iOS"); String::new() } } pub struct Window { pub inner: Inner, } impl Drop for Window { fn drop(&mut self) { assert_main_thread!("`Window::drop` can only be run on the main thread on iOS"); } } unsafe impl Send for Window {} unsafe impl Sync for Window {} impl Deref for Window { type Target = Inner; fn deref(&self) -> &Inner { assert_main_thread!("`Window` methods can only be run on the main thread on iOS"); &self.inner } } impl DerefMut for Window { fn deref_mut(&mut self) -> &mut Inner { assert_main_thread!("`Window` methods can only be run on the main thread on iOS"); &mut self.inner } } impl Window { pub(crate) fn new<T>( _event_loop: &EventLoopWindowTarget<T>, window_attributes: WindowAttributes, platform_attributes: PlatformSpecificWindowBuilderAttributes, ) -> Result<Window, RootOsError> { let mtm = MainThreadMarker::new().unwrap(); if window_attributes.min_inner_size.is_some() { warn!("`WindowAttributes::min_inner_size` is ignored on iOS"); } if window_attributes.max_inner_size.is_some() { warn!("`WindowAttributes::max_inner_size` is ignored on iOS"); } // TODO: transparency, visible let main_screen = UIScreen::main(mtm); let fullscreen = window_attributes.fullscreen.clone().map(Into::into); let screen = match fullscreen { Some(Fullscreen::Exclusive(ref video_mode)) => video_mode.monitor.ui_screen(), Some(Fullscreen::Borderless(Some(ref monitor))) => monitor.ui_screen(), Some(Fullscreen::Borderless(None)) | None => &main_screen, }; let screen_bounds = screen.bounds(); let frame = match window_attributes.inner_size { Some(dim) => { let scale_factor = screen.scale(); let size = dim.to_logical::<f64>(scale_factor as f64); CGRect { origin: screen_bounds.origin, size: CGSize { width: size.width as _, height: size.height as _, }, } } None => screen_bounds, }; let view = WinitView::new(mtm, &window_attributes, &platform_attributes, frame); let gl_or_metal_backed = unsafe { let layer_class = WinitView::layerClass(); let is_metal = msg_send![layer_class, isSubclassOfClass: class!(CAMetalLayer)]; let is_gl = msg_send![layer_class, isSubclassOfClass: class!(CAEAGLLayer)]; is_metal || is_gl }; let view_controller = WinitViewController::new(mtm, &window_attributes, &platform_attributes, &view); let window = WinitUIWindow::new( mtm, &window_attributes, &platform_attributes, frame, &view_controller, ); unsafe { app_state::set_key_window(&window) }; // Like the Windows and macOS backends, we send a `ScaleFactorChanged` and `Resized` // event on window creation if the DPI factor != 1.0 let scale_factor = view.contentScaleFactor(); let scale_factor = scale_factor as f64; if scale_factor != 1.0 { let bounds = view.bounds(); let screen = window.screen(); let screen_space = screen.coordinateSpace(); let screen_frame = view.convertRect_toCoordinateSpace(bounds, &screen_space); let size = crate::dpi::LogicalSize { width: screen_frame.size.width as _, height: screen_frame.size.height as _, }; let window_id = RootWindowId(window.id()); unsafe { app_state::handle_nonuser_events( std::iter::once(EventWrapper::EventProxy(EventProxy::DpiChangedProxy { window: window.clone(), scale_factor, suggested_size: size, })) .chain(std::iter::once(EventWrapper::StaticEvent( Event::WindowEvent { window_id, event: WindowEvent::Resized(size.to_physical(scale_factor)), }, ))), ); } } Ok(Window { inner: Inner { window, view_controller, view, gl_or_metal_backed, }, }) } } // WindowExtIOS impl Inner { pub fn ui_window(&self) -> *mut c_void { Id::as_ptr(&self.window) as *mut c_void } pub fn ui_view_controller(&self) -> *mut c_void { Id::as_ptr(&self.view_controller) as *mut c_void } pub fn ui_view(&self) -> *mut c_void { Id::as_ptr(&self.view) as *mut c_void } pub fn set_scale_factor(&self, scale_factor: f64) { assert!( dpi::validate_scale_factor(scale_factor), "`WindowExtIOS::set_scale_factor` received an invalid hidpi factor" ); let scale_factor = scale_factor as CGFloat; self.view.setContentScaleFactor(scale_factor); } pub fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { self.view_controller.set_supported_interface_orientations( MainThreadMarker::new().unwrap(), valid_orientations, ); } pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) { self.view_controller .setPrefersHomeIndicatorAutoHidden(hidden); } pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { let edges: UIRectEdge = edges.into(); self.view_controller .setPreferredScreenEdgesDeferringSystemGestures(edges); } pub fn set_prefers_status_bar_hidden(&self, hidden: bool) { self.view_controller.setPrefersStatusBarHidden(hidden); } } impl Inner { // requires main thread unsafe fn screen_frame(&self) -> CGRect { self.rect_to_screen_space(self.window.bounds()) } // requires main thread unsafe fn rect_to_screen_space(&self, rect: CGRect) -> CGRect { let screen_space = self.window.screen().coordinateSpace(); self.window .convertRect_toCoordinateSpace(rect, &screen_space) } // requires main thread unsafe fn rect_from_screen_space(&self, rect: CGRect) -> CGRect { let screen_space = self.window.screen().coordinateSpace(); self.window .convertRect_fromCoordinateSpace(rect, &screen_space) } // requires main thread unsafe fn safe_area_screen_space(&self) -> CGRect { let bounds = self.window.bounds(); if app_state::os_capabilities().safe_area { let safe_area = self.window.safeAreaInsets(); let safe_bounds = CGRect { origin: CGPoint { x: bounds.origin.x + safe_area.left, y: bounds.origin.y + safe_area.top, }, size: CGSize { width: bounds.size.width - safe_area.left - safe_area.right, height: bounds.size.height - safe_area.top - safe_area.bottom, }, }; self.rect_to_screen_space(safe_bounds) } else { let screen_frame = self.rect_to_screen_space(bounds); let status_bar_frame = { let app = UIApplication::shared(MainThreadMarker::new().unwrap_unchecked()).expect( "`Window::get_inner_position` cannot be called before `EventLoop::run` on iOS", ); app.statusBarFrame() }; let (y, height) = if screen_frame.origin.y > status_bar_frame.size.height { (screen_frame.origin.y, screen_frame.size.height) } else { let y = status_bar_frame.size.height; let height = screen_frame.size.height - (status_bar_frame.size.height - screen_frame.origin.y); (y, height) }; CGRect { origin: CGPoint { x: screen_frame.origin.x, y, }, size: CGSize { width: screen_frame.size.width, height, }, } } } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WindowId { window: *mut WinitUIWindow, } impl WindowId { pub const unsafe fn dummy() -> Self { WindowId { window: std::ptr::null_mut(), } } } impl From<WindowId> for u64 { fn from(window_id: WindowId) -> Self { window_id.window as u64 } } impl From<u64> for WindowId { fn from(raw_id: u64) -> Self { Self { window: raw_id as _, } } } unsafe impl Send for WindowId {} unsafe impl Sync for WindowId {} impl From<&Object> for WindowId { fn from(window: &Object) -> WindowId { WindowId { window: window as *const _ as _, } } } #[derive(Clone, Default)] pub struct PlatformSpecificWindowBuilderAttributes { pub scale_factor: Option<f64>, pub valid_orientations: ValidOrientations, pub prefers_home_indicator_hidden: bool, pub prefers_status_bar_hidden: bool, pub preferred_screen_edges_deferring_system_gestures: ScreenEdge, }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/linux/eventloop.rs
Rust
use std::{ cell::RefCell, collections::{HashSet, VecDeque}, process, rc::Rc, sync::atomic::{AtomicU32, Ordering}, time::Instant, }; use cairo::{RectangleInt, Region}; use crossbeam_channel::SendError; use gdk::{ prelude::{ApplicationExt, DisplayExtManual}, Cursor, CursorType, EventKey, EventMask, ScrollDirection, WindowEdge, WindowState, }; use gio::Cancellable; use glib::{MainContext, ObjectType, Priority}; use gtk::{ prelude::{DeviceExt, SeatExt, WidgetExtManual}, traits::{GtkApplicationExt, GtkWindowExt, WidgetExt}, }; use raw_window_handle::{RawDisplayHandle, WaylandDisplayHandle, XlibDisplayHandle}; use crate::{ dpi::{LogicalPosition, LogicalSize}, event::{ ElementState, Event, KeyboardInput, ModifiersState, MouseButton, MouseScrollDelta, StartCause, TouchPhase, WindowEvent, }, event_loop::{ ControlFlow, DeviceEventFilter, EventLoopClosed, EventLoopWindowTarget as RootELW, }, window::{CursorIcon, WindowId as RootWindowId}, }; use super::{ keyboard, monitor::MonitorHandle, util, window::{hit_test, WindowRequest}, Fullscreen, PlatformSpecificEventLoopAttributes, WindowId, DEVICE_ID, }; pub struct EventLoop<T: 'static> { /// Window target. window_target: RootELW<T>, /// User event sender for EventLoopProxy pub(crate) user_event_tx: crossbeam_channel::Sender<Event<'static, T>>, /// Event queue of EventLoop events: crossbeam_channel::Receiver<Event<'static, T>>, /// Draw queue of EventLoop draws: crossbeam_channel::Receiver<WindowId>, } /// Used to send custom events to `EventLoop`. #[derive(Debug)] pub struct EventLoopProxy<T: 'static> { user_event_tx: crossbeam_channel::Sender<Event<'static, T>>, } impl<T: 'static> Clone for EventLoopProxy<T> { fn clone(&self) -> Self { Self { user_event_tx: self.user_event_tx.clone(), } } } impl<T: 'static> EventLoop<T> { pub(crate) fn new(_attributes: &PlatformSpecificEventLoopAttributes) -> Self { let context = MainContext::default(); let app = gtk::Application::new(None, gio::ApplicationFlags::empty()); let app_ = app.clone(); let cancellable: Option<&Cancellable> = None; app.register(cancellable) .expect("Failed to register GtkApplication"); // Create channels for handling events and send StartCause::Init event let (event_tx, event_rx) = crossbeam_channel::unbounded(); let (draw_tx, draw_rx) = crossbeam_channel::unbounded(); let event_tx_ = event_tx.clone(); let draw_tx_ = draw_tx.clone(); let user_event_tx = event_tx.clone(); app.connect_activate(move |_| { if let Err(e) = event_tx_.send(Event::NewEvents(StartCause::Init)) { log::warn!("Failed to send init event to event channel: {}", e); } }); // Create event loop window target. let (window_requests_tx, window_requests_rx) = glib::MainContext::channel(Priority::default()); let display = gdk::Display::default() .expect("GdkDisplay not found. This usually means `gkt_init` hasn't called yet."); let window_target = EventLoopWindowTarget { display, app, windows: Rc::new(RefCell::new(HashSet::new())), window_requests_tx, draw_tx: draw_tx_, _marker: std::marker::PhantomData, }; // TODO: Spawn x11/wayland thread to receive Device events. // Window Request window_requests_rx.attach(Some(&context), move |(id, request)| { if let Some(window) = app_.window_by_id(id.0 as u32) { match request { WindowRequest::Title(title) => window.set_title(&title), WindowRequest::Position((x, y)) => window.move_(x, y), WindowRequest::Size((w, h)) => window.resize(w, h), WindowRequest::SizeConstraints(min, max) => { util::set_size_constraints(&window, min, max); } WindowRequest::Visible(visible) => { if visible { window.show_all(); } else { window.hide(); } } WindowRequest::Focus => { window.present_with_time(gdk_sys::GDK_CURRENT_TIME as _); } WindowRequest::Resizable(resizable) => window.set_resizable(resizable), // WindowRequest::Closable(closable) => window.set_deletable(closable), WindowRequest::Minimized(minimized) => { if minimized { window.iconify(); } else { window.deiconify(); } } WindowRequest::Maximized(maximized) => { if maximized { window.maximize(); } else { window.unmaximize(); } } WindowRequest::DragWindow => { if let Some(cursor) = window .display() .default_seat() .and_then(|seat| seat.pointer()) { let (_, x, y) = cursor.position(); window.begin_move_drag(1, x, y, 0); } } WindowRequest::Fullscreen(fullscreen) => match fullscreen { Some(f) => { let m = match f { Fullscreen::Exclusive(m) => Some(m.monitor), Fullscreen::Borderless(Some(m)) => Some(m.monitor), _ => None, }; if let Some(monitor) = m { let display = window.display(); let monitors = display.n_monitors(); for i in 0..monitors { let m = display.monitor(i).unwrap(); if m == monitor { let screen = display.default_screen(); window.fullscreen_on_monitor(&screen, i); } } } else { window.fullscreen(); } } None => window.unfullscreen(), }, WindowRequest::Decorations(decorations) => window.set_decorated(decorations), WindowRequest::AlwaysOnBottom(always_on_bottom) => { window.set_keep_below(always_on_bottom) } WindowRequest::AlwaysOnTop(always_on_top) => { window.set_keep_above(always_on_top) } WindowRequest::WindowIcon(window_icon) => { if let Some(icon) = window_icon { window.set_icon(Some(&icon.inner.into())); } } WindowRequest::UserAttention(request_type) => { window.set_urgency_hint(request_type.is_some()) } WindowRequest::SetSkipTaskbar(skip) => { window.set_skip_taskbar_hint(skip); window.set_skip_pager_hint(skip) } // WindowRequest::SetVisibleOnAllWorkspaces(visible) => { // if visible { // window.stick(); // } else { // window.unstick(); // } // } WindowRequest::CursorIcon(cursor) => { if let Some(gdk_window) = window.window() { let display = window.display(); match cursor { Some(cr) => gdk_window.set_cursor( Cursor::from_name( &display, match cr { CursorIcon::Crosshair => "crosshair", CursorIcon::Hand => "pointer", CursorIcon::Arrow => "arrow", CursorIcon::Move => "move", CursorIcon::Text => "text", CursorIcon::Wait => "wait", CursorIcon::Help => "help", CursorIcon::Progress => "progress", CursorIcon::NotAllowed => "not-allowed", CursorIcon::ContextMenu => "context-menu", CursorIcon::Cell => "cell", CursorIcon::VerticalText => "vertical-text", CursorIcon::Alias => "alias", CursorIcon::Copy => "copy", CursorIcon::NoDrop => "no-drop", CursorIcon::Grab => "grab", CursorIcon::Grabbing => "grabbing", CursorIcon::AllScroll => "all-scroll", CursorIcon::ZoomIn => "zoom-in", CursorIcon::ZoomOut => "zoom-out", CursorIcon::EResize => "e-resize", CursorIcon::NResize => "n-resize", CursorIcon::NeResize => "ne-resize", CursorIcon::NwResize => "nw-resize", CursorIcon::SResize => "s-resize", CursorIcon::SeResize => "se-resize", CursorIcon::SwResize => "sw-resize", CursorIcon::WResize => "w-resize", CursorIcon::EwResize => "ew-resize", CursorIcon::NsResize => "ns-resize", CursorIcon::NeswResize => "nesw-resize", CursorIcon::NwseResize => "nwse-resize", CursorIcon::ColResize => "col-resize", CursorIcon::RowResize => "row-resize", CursorIcon::Default => "default", }, ) .as_ref(), ), None => gdk_window.set_cursor( Cursor::for_display(&display, CursorType::BlankCursor).as_ref(), ), } }; } WindowRequest::CursorPosition((x, y)) => { if let Some(cursor) = window .display() .default_seat() .and_then(|seat| seat.pointer()) { if let Some(screen) = GtkWindowExt::screen(&window) { cursor.warp(&screen, x, y); } } } WindowRequest::CursorIgnoreEvents(ignore) => { if ignore { let empty_region = Region::create_rectangle(&RectangleInt::new(0, 0, 1, 1)); window.window().unwrap().input_shape_combine_region( &empty_region, 0, 0, ); } else { window.input_shape_combine_region(None) }; } // WindowRequest::ProgressBarState(_) => unreachable!(), WindowRequest::WireUpEvents { transparent, } => { window.add_events( EventMask::POINTER_MOTION_MASK | EventMask::BUTTON1_MOTION_MASK | EventMask::BUTTON_PRESS_MASK | EventMask::TOUCH_MASK | EventMask::STRUCTURE_MASK | EventMask::FOCUS_CHANGE_MASK | EventMask::SCROLL_MASK, ); // Allow resizing unmaximized borderless window window.connect_motion_notify_event(|window, event| { if !window.is_decorated() && window.is_resizable() && !window.is_maximized() { if let Some(window) = window.window() { let (cx, cy) = event.root(); let edge = hit_test(&window, cx, cy); window.set_cursor( Cursor::from_name( &window.display(), match edge { WindowEdge::North => "n-resize", WindowEdge::South => "s-resize", WindowEdge::East => "e-resize", WindowEdge::West => "w-resize", WindowEdge::NorthWest => "nw-resize", WindowEdge::NorthEast => "ne-resize", WindowEdge::SouthEast => "se-resize", WindowEdge::SouthWest => "sw-resize", _ => "default", }, ) .as_ref(), ); } } glib::Propagation::Proceed }); window.connect_button_press_event(|window, event| { if !window.is_decorated() && window.is_resizable() && event.button() == 1 { if let Some(window) = window.window() { let (cx, cy) = event.root(); let result = hit_test(&window, cx, cy); // Ignore the `__Unknown` variant so the window receives the click correctly if it is not on the edges. match result { WindowEdge::__Unknown(_) => (), _ => { // FIXME: calling `window.begin_resize_drag` uses the default cursor, it should show a resizing cursor instead window.begin_resize_drag( result, 1, cx as i32, cy as i32, event.time(), ) } } } } glib::Propagation::Proceed }); window.connect_touch_event(|window, event| { if !window.is_decorated() && window.is_resizable() { if let Some(window) = window.window() { if let Some((cx, cy)) = event.root_coords() { if let Some(device) = event.device() { let result = hit_test(&window, cx, cy); // Ignore the `__Unknown` variant so the window receives the click correctly if it is not on the edges. match result { WindowEdge::__Unknown(_) => (), _ => window.begin_resize_drag_for_device( result, &device, 0, cx as i32, cy as i32, event.time(), ), } } } } } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_delete_event(move |_, _| { if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CloseRequested, }) { log::warn!( "Failed to send window close event to event channel: {}", e ); } glib::Propagation::Stop }); let tx_clone = event_tx.clone(); window.connect_configure_event(move |window, event| { let scale_factor = window.scale_factor(); let (x, y) = event.position(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Moved( LogicalPosition::new(x, y).to_physical(scale_factor as f64), ), }) { log::warn!( "Failed to send window moved event to event channel: {}", e ); } let (w, h) = event.size(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Resized( LogicalSize::new(w, h).to_physical(scale_factor as f64), ), }) { log::warn!( "Failed to send window resized event to event channel: {}", e ); } false }); let tx_clone = event_tx.clone(); window.connect_focus_in_event(move |_, _| { if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Focused(true), }) { log::warn!( "Failed to send window focus-in event to event channel: {}", e ); } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_focus_out_event(move |_, _| { if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Focused(false), }) { log::warn!( "Failed to send window focus-out event to event channel: {}", e ); } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_destroy(move |_| { if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Destroyed, }) { log::warn!( "Failed to send window destroyed event to event channel: {}", e ); } }); let tx_clone = event_tx.clone(); window.connect_enter_notify_event(move |_, _| { if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CursorEntered { device_id: DEVICE_ID, }, }) { log::warn!( "Failed to send cursor entered event to event channel: {}", e ); } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_motion_notify_event(move |window, motion| { if let Some(cursor) = motion.device() { let scale_factor = window.scale_factor(); let (_, x, y) = cursor.window_at_position(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CursorMoved { position: LogicalPosition::new(x, y).to_physical(scale_factor as f64), device_id: DEVICE_ID, // this field is depracted so it is fine to pass empty state modifiers: ModifiersState::empty(), }, }) { log::warn!("Failed to send cursor moved event to event channel: {}", e); } } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_leave_notify_event(move |_, _| { if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CursorLeft { device_id: DEVICE_ID, }, }) { log::warn!( "Failed to send cursor left event to event channel: {}", e ); } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_button_press_event(move |_, event| { let button = event.button(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::MouseInput { button: match button { 1 => MouseButton::Left, 2 => MouseButton::Middle, 3 => MouseButton::Right, _ => MouseButton::Other(button as u16), }, state: ElementState::Pressed, device_id: DEVICE_ID, // this field is depracted so it is fine to pass empty state modifiers: ModifiersState::empty(), }, }) { log::warn!( "Failed to send mouse input preseed event to event channel: {}", e ); } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_button_release_event(move |_, event| { let button = event.button(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::MouseInput { button: match button { 1 => MouseButton::Left, 2 => MouseButton::Middle, 3 => MouseButton::Right, _ => MouseButton::Other(button as u16), }, state: ElementState::Released, device_id: DEVICE_ID, // this field is depracted so it is fine to pass empty state modifiers: ModifiersState::empty(), }, }) { log::warn!( "Failed to send mouse input released event to event channel: {}", e ); } glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_scroll_event(move |_, event| { let (x, y) = event.delta(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::MouseWheel { device_id: DEVICE_ID, delta: MouseScrollDelta::LineDelta(-x as f32, -y as f32), phase: match event.direction() { ScrollDirection::Smooth => TouchPhase::Moved, _ => TouchPhase::Ended, }, modifiers: ModifiersState::empty(), }, }) { log::warn!("Failed to send scroll event to event channel: {}", e); } glib::Propagation::Proceed }); // TODO Follwong WindowEvents are missing see #2 for mor info. // - Touch // - TouchpadMagnify // - TouchpadRotate // - TouchpadPressure // - SmartMagnify // - ReceivedCharacter // - Ime // - ScaleFactorChanged // - DroppedFile // - HoveredFile // - HoveredFileCancelled // - ThemeChanged // - AxisMotion // - Occluded let tx_clone = event_tx.clone(); let modifiers = AtomicU32::new(ModifiersState::empty().bits()); let keyboard_handler = Rc::new(move |event_key: EventKey, element_state| { // if we have a modifier lets send it let new_mods = keyboard::get_modifiers(&event_key); if new_mods.bits() != modifiers.load(Ordering::Relaxed) { modifiers.store(new_mods.bits(), Ordering::Relaxed); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::ModifiersChanged(new_mods), }) { log::warn!("Failed to send modifiers changed event to event channel: {}",e); } } let virtual_key = keyboard::gdk_key_to_virtual_key(event_key.keyval()); #[allow(deprecated)] if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { scancode: event_key.scancode() as u32, state: element_state, virtual_keycode: virtual_key, modifiers: new_mods, }, is_synthetic: false, }, }) { log::warn!( "Failed to send keyboard event to event channel: {}", e ); } glib::ControlFlow::Continue }); // let tx_clone = event_tx.clone(); // // TODO Add actual IME from system // let ime = gtk::IMContextSimple::default(); // ime.set_client_window(window.window().as_ref()); // ime.focus_in(); // ime.connect_commit(move |_, s| { // let c = s.chars().collect::<Vec<char>>(); // if let Err(e) = tx_clone.send(Event::WindowEvent { // window_id: RootWindowId(id), // event: WindowEvent::ReceivedCharacter(c[0]), // }) { // log::warn!( // "Failed to send received IME text event to event channel: {}", // e // ); // } // }); let handler = keyboard_handler.clone(); window.connect_key_press_event(move |_, event_key| { handler(event_key.to_owned(), ElementState::Pressed); // ime.filter_keypress(event_key); glib::Propagation::Proceed }); let handler = keyboard_handler.clone(); window.connect_key_release_event(move |_, event_key| { handler(event_key.to_owned(), ElementState::Released); glib::Propagation::Proceed }); let tx_clone = event_tx.clone(); window.connect_window_state_event(move |window, event| { let state = event.changed_mask(); if state.contains(WindowState::ICONIFIED) || state.contains(WindowState::MAXIMIZED) { let scale_factor = window.scale_factor(); let (x, y) = window.position(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Moved( LogicalPosition::new(x, y).to_physical(scale_factor as f64), ), }) { log::warn!( "Failed to send window moved event to event channel: {}", e ); } let (w, h) = window.size(); if let Err(e) = tx_clone.send(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Resized( LogicalSize::new(w, h).to_physical(scale_factor as f64), ), }) { log::warn!( "Failed to send window resized event to event channel: {}", e ); } } glib::Propagation::Proceed }); // Receive draw events of the window. let draw_clone = draw_tx.clone(); window.connect_draw(move |_, cr| { if let Err(e) = draw_clone.send(id) { log::warn!("Failed to send redraw event to event channel: {}", e); } if transparent.load(Ordering::Relaxed) { cr.set_source_rgba(0., 0., 0., 0.); cr.set_operator(cairo::Operator::Source); let _ = cr.paint(); cr.set_operator(cairo::Operator::Over); } glib::Propagation::Proceed }); } } } glib::ControlFlow::Continue }); // Create event loop itself. Self { window_target: RootELW { p: window_target, _marker: std::marker::PhantomData, }, user_event_tx, events: event_rx, draws: draw_rx, } } /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop. pub fn create_proxy(&self) -> EventLoopProxy<T> { EventLoopProxy { user_event_tx: self.user_event_tx.clone(), } } #[inline] pub fn run<F>(mut self, callback: F) -> ! where F: 'static + FnMut(crate::event::Event<'_, T>, &RootELW<T>, &mut ControlFlow), { let exit_code = self.run_return(callback); process::exit(exit_code) } /// This is the core event loop logic. It basically loops on `gtk_main_iteration` and processes one /// event along with that iteration. Depends on current control flow and what it should do, an /// event state is defined. The whole state flow chart runs like following: /// /// ```ignore /// Poll/Wait/WaitUntil /// +-------------------------------------------------------------------------+ /// | | /// | Receiving event from event channel | Receiving event from draw channel /// | +-------+ | +---+ /// v v | | v | /// +----------+ Poll/Wait/WaitUntil +------------+ Poll/Wait/WaitUntil +-----------+ | /// | NewStart | ---------------------> | EventQueue | ---------------------> | DrawQueue | | /// +----------+ +------------+ +-----------+ | /// |ExitWithCode |ExitWithCode ExitWithCode| | | /// +------------------------------------+------------------------------------+ +---+ /// | /// v /// +---------------+ /// | LoopDestroyed | /// +---------------+ /// ``` /// /// There are a dew notibale event will sent to callback when state is transisted: /// - On any state moves to `LoopDestroyed`, a `LoopDestroyed` event is sent. /// - On `NewStart` to `EventQueue`, a `NewEvents` with corresponding `StartCause` depends on /// current control flow is sent. /// - On `EventQueue` to `DrawQueue`, a `MainEventsCleared` event is sent. /// - On `DrawQueue` back to `NewStart`, a `RedrawEventsCleared` event is sent. pub(crate) fn run_return<F>(&mut self, mut callback: F) -> i32 where F: FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow), { enum EventState { NewStart, EventQueue, DrawQueue, } let context = MainContext::default(); context .with_thread_default(|| { let mut control_flow = ControlFlow::default(); let window_target = &self.window_target; let events = &self.events; let draws = &self.draws; window_target.p.app.activate(); let mut state = EventState::NewStart; let exit_code = loop { let mut blocking = false; match state { EventState::NewStart => match control_flow { ControlFlow::ExitWithCode(code) => { callback(Event::LoopDestroyed, window_target, &mut control_flow); break code; } ControlFlow::Wait => { if !events.is_empty() { callback( Event::NewEvents(StartCause::WaitCancelled { start: Instant::now(), requested_resume: None, }), window_target, &mut control_flow, ); state = EventState::EventQueue; } else { blocking = true; } } ControlFlow::WaitUntil(requested_resume) => { let start = Instant::now(); if start >= requested_resume { callback( Event::NewEvents(StartCause::ResumeTimeReached { start, requested_resume, }), window_target, &mut control_flow, ); state = EventState::EventQueue; } else if !events.is_empty() { callback( Event::NewEvents(StartCause::WaitCancelled { start, requested_resume: Some(requested_resume), }), window_target, &mut control_flow, ); state = EventState::EventQueue; } else { blocking = true; } } _ => { callback( Event::NewEvents(StartCause::Poll), window_target, &mut control_flow, ); state = EventState::EventQueue; } }, EventState::EventQueue => match control_flow { ControlFlow::ExitWithCode(code) => { callback(Event::LoopDestroyed, window_target, &mut control_flow); break (code); } _ => match events.try_recv() { Ok(event) => match event { Event::LoopDestroyed => { control_flow = ControlFlow::ExitWithCode(1) } _ => callback(event, window_target, &mut control_flow), }, Err(_) => { callback( Event::MainEventsCleared, window_target, &mut control_flow, ); state = EventState::DrawQueue; } }, }, EventState::DrawQueue => match control_flow { ControlFlow::ExitWithCode(code) => { callback(Event::LoopDestroyed, window_target, &mut control_flow); break code; } _ => { if let Ok(id) = draws.try_recv() { callback( Event::RedrawRequested(RootWindowId(id)), window_target, &mut control_flow, ); } callback( Event::RedrawEventsCleared, window_target, &mut control_flow, ); state = EventState::NewStart; } }, } gtk::main_iteration_do(blocking); }; exit_code }) .unwrap_or(1) } pub fn window_target(&self) -> &crate::event_loop::EventLoopWindowTarget<T> { &self.window_target } } impl<T: 'static> EventLoopProxy<T> { pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { self.user_event_tx .send(Event::UserEvent(event)) .map_err(|SendError(event)| { if let Event::UserEvent(error) = event { EventLoopClosed(error) } else { unreachable!(); } })?; let context = MainContext::default(); context.wakeup(); Ok(()) } } #[derive(Clone)] pub struct EventLoopWindowTarget<T> { /// Gdk display pub(crate) display: gdk::Display, /// Gtk application pub(crate) app: gtk::Application, /// Window Ids of the application pub(crate) windows: Rc<RefCell<HashSet<WindowId>>>, /// Window requests sender pub(crate) window_requests_tx: glib::Sender<(WindowId, WindowRequest)>, /// Draw event sender pub(crate) draw_tx: crossbeam_channel::Sender<WindowId>, _marker: std::marker::PhantomData<T>, } impl<T> EventLoopWindowTarget<T> { #[inline] pub fn is_wayland(&self) -> bool { self.display.backend().is_wayland() } #[inline] pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { let mut handles = VecDeque::new(); let display = &self.display; let numbers = display.n_monitors(); for i in 0..numbers { let monitor = MonitorHandle::new(display, i); handles.push_back(monitor); } handles } #[inline] pub fn primary_monitor(&self) -> Option<MonitorHandle> { let monitor = self.display.primary_monitor(); monitor.map(|monitor| MonitorHandle { monitor }) } #[inline] pub fn set_device_event_filter(&self, _filter: DeviceEventFilter) { // TODO implement this } pub fn raw_display_handle(&self) -> raw_window_handle::RawDisplayHandle { if self.is_wayland() { let mut display_handle = WaylandDisplayHandle::empty(); display_handle.display = unsafe { gdk_wayland_sys::gdk_wayland_display_get_wl_display(self.display.as_ptr() as *mut _) }; RawDisplayHandle::Wayland(display_handle) } else { let mut display_handle = XlibDisplayHandle::empty(); unsafe { if let Ok(xlib) = x11_dl::xlib::Xlib::open() { let display = (xlib.XOpenDisplay)(std::ptr::null()); display_handle.display = display as _; display_handle.screen = (xlib.XDefaultScreen)(display) as _; } } RawDisplayHandle::Xlib(display_handle) } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/linux/keyboard.rs
Rust
use gdk::{ keys::{constants::*, Key}, EventKey, ModifierType, }; use crate::event::{ModifiersState, VirtualKeyCode}; const MODIFIER_MAP: &[(ModifierType, ModifiersState)] = &[ (ModifierType::SHIFT_MASK, ModifiersState::SHIFT), (ModifierType::MOD1_MASK, ModifiersState::ALT), (ModifierType::CONTROL_MASK, ModifiersState::CTRL), (ModifierType::SUPER_MASK, ModifiersState::LOGO), ]; // we use the EventKey to extract the modifier mainly because // we need to have the modifier before the second key is entered to follow // other os' logic -- this way we can emit the new `ModifiersState` before // we receive the next key, if needed the developer can update his local state. pub(crate) fn get_modifiers(key: &EventKey) -> ModifiersState { let state = key.state(); // start with empty state let mut result = ModifiersState::empty(); // loop trough our modifier map for (gdk_mod, modifier) in MODIFIER_MAP { if state == *gdk_mod { result |= *modifier; } } result } #[allow(clippy::just_underscores_and_digits, non_upper_case_globals)] pub(crate) fn gdk_key_to_virtual_key(gdk_key: Key) -> Option<VirtualKeyCode> { match gdk_key { Escape => Some(VirtualKeyCode::Escape), BackSpace => Some(VirtualKeyCode::Backslash), Tab | ISO_Left_Tab => Some(VirtualKeyCode::Tab), Return => Some(VirtualKeyCode::Return), Control_L => Some(VirtualKeyCode::LControl), Control_R => Some(VirtualKeyCode::RControl), Alt_L => Some(VirtualKeyCode::LAlt), Alt_R => Some(VirtualKeyCode::RAlt), Shift_L => Some(VirtualKeyCode::LShift), Shift_R => Some(VirtualKeyCode::RShift), // TODO: investigate mapping. Map Meta_[LR]? Super_L => Some(VirtualKeyCode::LWin), Super_R => Some(VirtualKeyCode::RWin), Caps_Lock => Some(VirtualKeyCode::Capital), F1 => Some(VirtualKeyCode::F1), F2 => Some(VirtualKeyCode::F2), F3 => Some(VirtualKeyCode::F3), F4 => Some(VirtualKeyCode::F4), F5 => Some(VirtualKeyCode::F5), F6 => Some(VirtualKeyCode::F6), F7 => Some(VirtualKeyCode::F7), F8 => Some(VirtualKeyCode::F8), F9 => Some(VirtualKeyCode::F9), F10 => Some(VirtualKeyCode::F10), F11 => Some(VirtualKeyCode::F11), F12 => Some(VirtualKeyCode::F12), Print => Some(VirtualKeyCode::Snapshot), Scroll_Lock => Some(VirtualKeyCode::Scroll), // Pause/Break not audio. Pause => Some(VirtualKeyCode::Pause), Insert => Some(VirtualKeyCode::Insert), Delete => Some(VirtualKeyCode::Delete), Home => Some(VirtualKeyCode::Home), End => Some(VirtualKeyCode::End), Page_Up => Some(VirtualKeyCode::PageUp), Page_Down => Some(VirtualKeyCode::PageDown), Num_Lock => Some(VirtualKeyCode::Numlock), Up => Some(VirtualKeyCode::Up), Down => Some(VirtualKeyCode::Down), Left => Some(VirtualKeyCode::Left), Right => Some(VirtualKeyCode::Right), // Clear => Some(VirtualKeyCode::Clear), // Menu => Some(VirtualKeyCode::ContextMenu), // WakeUp => Some(VirtualKeyCode::WakeUp), // Launch0 => Some(VirtualKeyCode::LaunchApplication1), // Launch1 => Some(VirtualKeyCode::LaunchApplication2), // ISO_Level3_Shift => Some(VirtualKeyCode::AltGraph), // KP_Begin => Some(VirtualKeyCode::Clear), // KP_Delete => Some(VirtualKeyCode::Delete), // KP_Down => Some(VirtualKeyCode::ArrowDown), // KP_End => Some(VirtualKeyCode::End), // KP_Enter => Some(VirtualKeyCode::NumpadEnter), // KP_F1 => Some(VirtualKeyCode::F1), // KP_F2 => Some(VirtualKeyCode::F2), // KP_F3 => Some(VirtualKeyCode::F3), // KP_F4 => Some(VirtualKeyCode::F4), // KP_Home => Some(VirtualKeyCode::Home), // KP_Insert => Some(VirtualKeyCode::Insert), // KP_Left => Some(VirtualKeyCode::ArrowLeft), // KP_Page_Down => Some(VirtualKeyCode::PageDown), // KP_Page_Up => Some(VirtualKeyCode::PageUp), // KP_Right => Some(VirtualKeyCode::ArrowRight), // // KP_Separator? What does it map to? // KP_Tab => Some(VirtualKeyCode::Tab), // KP_Up => Some(VirtualKeyCode::ArrowUp), // TODO: more mappings (media etc) _ => None, } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/linux/mod.rs
Rust
#![cfg(free_unix)] use std::fmt; use crate::event::DeviceId as RootDeviceId; pub(crate) use crate::icon::RgbaIcon as PlatformIcon; use crate::platform_impl::Fullscreen; mod eventloop; mod keyboard; mod monitor; mod util; mod window; pub use eventloop::{EventLoop, EventLoopProxy, EventLoopWindowTarget}; use gdk_pixbuf::{Colorspace, Pixbuf}; pub use monitor::{MonitorHandle, VideoMode}; pub use window::{hit_test, Window}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) enum Backend { // #[cfg(x11_platform)] // X, // #[cfg(wayland_platform)] // Wayland, } #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) struct PlatformSpecificEventLoopAttributes { pub(crate) forced_backend: Option<Backend>, pub(crate) any_thread: bool, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ApplicationName { pub general: String, pub instance: String, } impl ApplicationName { pub fn new(general: String, instance: String) -> Self { Self { general, instance } } } #[derive(Clone)] pub struct PlatformSpecificWindowBuilderAttributes { pub name: Option<ApplicationName>, pub parent: Option<gtk::Window>, pub skip_taskbar: bool, pub auto_transparent: bool, pub double_buffered: bool, pub app_paintable: bool, pub rgba_visual: bool, pub default_vbox: bool, } impl Default for PlatformSpecificWindowBuilderAttributes { fn default() -> Self { Self { name: None, parent: None, skip_taskbar: Default::default(), auto_transparent: true, double_buffered: true, app_paintable: false, rgba_visual: false, default_vbox: true, } } } #[derive(Debug, Clone)] pub enum OsError { // Misc(&'static str), } impl fmt::Display for OsError { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { // match *self { // OsError::Misc(e) => _f.pad(e), // } Ok(()) } } impl From<PlatformIcon> for Pixbuf { fn from(icon: PlatformIcon) -> Self { let height = icon.height as i32; let width = icon.width as i32; let row_stride = Pixbuf::calculate_rowstride(Colorspace::Rgb, true, 8, width, height); Pixbuf::from_mut_slice( icon.rgba, gdk_pixbuf::Colorspace::Rgb, true, 8, width, height, row_stride, ) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WindowId(pub u64); impl From<WindowId> for u64 { fn from(window_id: WindowId) -> Self { window_id.0 } } impl From<u64> for WindowId { fn from(raw_id: u64) -> Self { Self(raw_id) } } impl WindowId { pub const unsafe fn dummy() -> Self { Self(0) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DeviceId(usize); impl DeviceId { pub const unsafe fn dummy() -> Self { Self(0) } } // TODO: currently we use a dummy device id, find if we can get device id from gtk pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId(0));
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/linux/monitor.rs
Rust
use crate::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; use gdk::prelude::MonitorExt; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct MonitorHandle { pub(crate) monitor: gdk::Monitor, } impl MonitorHandle { pub fn new(display: &gdk::Display, number: i32) -> Self { let monitor = display.monitor(number).unwrap(); Self { monitor } } #[inline] pub fn name(&self) -> Option<String> { self.monitor.model().map(|s| s.as_str().to_string()) } #[inline] pub fn size(&self) -> PhysicalSize<u32> { let rect = self.monitor.geometry(); LogicalSize { width: rect.width() as u32, height: rect.height() as u32, } .to_physical(self.scale_factor()) } #[inline] pub fn position(&self) -> PhysicalPosition<i32> { let rect = self.monitor.geometry(); LogicalPosition { x: rect.x(), y: rect.y(), } .to_physical(self.scale_factor()) } #[inline] pub fn refresh_rate_millihertz(&self) -> Option<u32> { Some(self.monitor.refresh_rate() as u32) } #[inline] pub fn scale_factor(&self) -> f64 { self.monitor.scale_factor() as f64 } #[inline] pub fn video_modes(&self) -> Box<dyn Iterator<Item = VideoMode>> { Box::new( vec![VideoMode { monitor: self.monitor.clone(), }] .into_iter(), ) } } unsafe impl Send for MonitorHandle {} unsafe impl Sync for MonitorHandle {} #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct VideoMode { /// gdk::Screen is deprecated. We make VideoMode and MonitorHandle /// being the same type. If we want to enrich this feature. We will /// need to look for x11/wayland implementations. pub(crate) monitor: gdk::Monitor, } impl VideoMode { #[inline] pub fn size(&self) -> PhysicalSize<u32> { let rect = self.monitor.geometry(); LogicalSize { width: rect.width() as u32, height: rect.height() as u32, } .to_physical(self.monitor.scale_factor() as f64) } #[inline] pub fn bit_depth(&self) -> u16 { 32 } #[inline] pub fn refresh_rate_millihertz(&self) -> u32 { self.monitor.refresh_rate() as u32 } #[inline] pub fn monitor(&self) -> MonitorHandle { MonitorHandle { monitor: self.monitor.clone(), } } } unsafe impl Send for VideoMode {} unsafe impl Sync for VideoMode {}
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/linux/util.rs
Rust
use gtk::traits::{GtkWindowExt, WidgetExt}; use crate::dpi::{LogicalSize, Size}; pub fn set_size_constraints<W: GtkWindowExt + WidgetExt>( window: &W, min_size: Option<Size>, max_size: Option<Size>, ) { let mut geom_mask = gdk::WindowHints::empty(); if min_size.is_some() { geom_mask |= gdk::WindowHints::MIN_SIZE; } if max_size.is_some() { geom_mask |= gdk::WindowHints::MAX_SIZE; } let scale_factor = window.scale_factor() as f64; let min_size: LogicalSize<i32> = min_size .map(|s| s.to_logical(scale_factor)) .unwrap_or(LogicalSize::new(0, 0)); let max_size: LogicalSize<i32> = max_size .map(|s| s.to_logical(scale_factor)) .unwrap_or(LogicalSize::new(i32::MAX, i32::MAX)); let picky_none: Option<&gtk::Window> = None; window.set_geometry_hints( picky_none, Some(&gdk::Geometry::new( min_size.width, min_size.height, max_size.width, max_size.height, 0, 0, 0, 0, 0f64, 0f64, gdk::Gravity::Center, )), geom_mask, ) }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/linux/window.rs
Rust
use std::{ cell::RefCell, collections::VecDeque, rc::Rc, sync::atomic::{AtomicBool, AtomicI32, Ordering}, }; use gdk::{prelude::DisplayExtManual, WindowEdge, WindowState}; use glib::{translate::ToGlibPtr, Cast, ObjectType}; use gtk::{ prelude::GtkSettingsExt, traits::{ApplicationWindowExt, ContainerExt, GtkWindowExt, WidgetExt}, Settings, }; use raw_window_handle::{ RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle, WaylandWindowHandle, XlibDisplayHandle, XlibWindowHandle, }; use crate::{ dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}, error::{ExternalError, NotSupportedError, OsError as RootOsError}, platform_impl::WindowId, window::{ CursorGrabMode, CursorIcon, Icon, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, WindowButtons, WindowLevel, }, }; use super::{ util, EventLoopWindowTarget, Fullscreen, MonitorHandle, PlatformSpecificWindowBuilderAttributes, }; // Currently GTK doesn't provide feature for detect theme, so we need to check theme manually. // ref: https://github.com/WebKit/WebKit/blob/e44ffaa0d999a9807f76f1805943eea204cfdfbc/Source/WebKit/UIProcess/API/gtk/PageClientImpl.cpp#L587 const GTK_THEME_SUFFIX_LIST: [&str; 3] = ["-dark", "-Dark", "-Darker"]; pub(crate) enum WindowRequest { Title(String), Position((i32, i32)), Size((i32, i32)), SizeConstraints(Option<Size>, Option<Size>), Visible(bool), Focus, Resizable(bool), // Closable(bool), Minimized(bool), Maximized(bool), DragWindow, Fullscreen(Option<Fullscreen>), Decorations(bool), AlwaysOnBottom(bool), AlwaysOnTop(bool), WindowIcon(Option<Icon>), UserAttention(Option<UserAttentionType>), SetSkipTaskbar(bool), CursorIcon(Option<CursorIcon>), CursorPosition((i32, i32)), CursorIgnoreEvents(bool), WireUpEvents { transparent: Rc<AtomicBool> }, // SetVisibleOnAllWorkspaces(bool), // ProgressBarState(ProgressBarState), } pub struct Window { /// Window id. pub(crate) window_id: WindowId, /// Gtk application window. pub(crate) window: gtk::ApplicationWindow, pub(crate) default_vbox: Option<gtk::Box>, /// Window requests sender pub(crate) window_requests_tx: glib::Sender<(WindowId, WindowRequest)>, scale_factor: Rc<AtomicI32>, position: Rc<(AtomicI32, AtomicI32)>, size: Rc<(AtomicI32, AtomicI32)>, maximized: Rc<AtomicBool>, minimized: Rc<AtomicBool>, fullscreen: RefCell<Option<Fullscreen>>, min_size: RefCell<Option<Size>>, max_size: RefCell<Option<Size>>, transparent: Rc<AtomicBool>, /// Draw event Sender draw_tx: crossbeam_channel::Sender<WindowId>, } impl Window { #[inline] pub(crate) fn new<T>( window_target: &EventLoopWindowTarget<T>, attribs: WindowAttributes, pl_attribs: PlatformSpecificWindowBuilderAttributes, ) -> Result<Self, RootOsError> { let app = &window_target.app; let window_requests_tx = window_target.window_requests_tx.clone(); let draw_tx = window_target.draw_tx.clone(); let window = gtk::ApplicationWindow::builder() .application(app) .accept_focus(attribs.active) .build(); let window_id = WindowId(window.id() as u64); window_target.windows.borrow_mut().insert(window_id); // Set Width/Height & Resizable let win_scale_factor = window.scale_factor(); let (width, height) = attribs .inner_size .map(|size| size.to_logical::<f64>(win_scale_factor as f64).into()) .unwrap_or((800, 600)); window.set_default_size(1, 1); window.resize(width, height); if attribs.maximized { window.maximize(); } window.set_resizable(attribs.resizable); // window.set_deletable(attribs.closable); // Set Min/Max Size util::set_size_constraints(&window, attribs.min_inner_size, attribs.max_inner_size); // Set Position if let Some(position) = attribs.position { let (x, y): (i32, i32) = position.to_logical::<i32>(win_scale_factor as f64).into(); window.move_(x, y); } // Set GDK Visual if pl_attribs.rgba_visual || attribs.transparent { if let Some(screen) = GtkWindowExt::screen(&window) { if let Some(visual) = screen.rgba_visual() { window.set_visual(Some(&visual)); } } } if pl_attribs.app_paintable || attribs.transparent { // Set a few attributes to make the window can be painted. // See Gtk drawing model for more info: // https://docs.gtk.org/gtk3/drawing-model.html window.set_app_paintable(true); } if !pl_attribs.double_buffered { let widget = window.upcast_ref::<gtk::Widget>(); if !window_target.is_wayland() { unsafe { gtk::ffi::gtk_widget_set_double_buffered(widget.to_glib_none().0, 0); } } } // Add vbox for utilities like menu let default_vbox = if pl_attribs.default_vbox { let box_ = gtk::Box::new(gtk::Orientation::Vertical, 0); window.add(&box_); Some(box_) } else { None }; // Rest attributes window.set_title(&attribs.title); let fullscreen = attribs.fullscreen.map(|f| f.into()); if fullscreen != None { let m = match fullscreen { Some(Fullscreen::Exclusive(ref m)) => Some(&m.monitor), Some(Fullscreen::Borderless(Some(ref m))) => Some(&m.monitor), _ => None, }; if let Some(monitor) = m { let display = window.display(); let monitors = display.n_monitors(); for i in 0..monitors { let m = display.monitor(i).unwrap(); if &m == monitor { let screen = display.default_screen(); window.fullscreen_on_monitor(&screen, i); } } } else { window.fullscreen(); } } window.set_visible(attribs.visible); window.set_decorated(attribs.decorations); match attribs.window_level { WindowLevel::AlwaysOnBottom => window.set_keep_below(true), WindowLevel::Normal => (), WindowLevel::AlwaysOnTop => window.set_keep_above(true), } // TODO imeplement this? // if attribs.visible_on_all_workspaces { // window.stick(); // } if let Some(icon) = attribs.window_icon { window.set_icon(Some(&icon.inner.into())); } // Set theme let settings = Settings::default(); if let Some(settings) = settings { if let Some(preferred_theme) = attribs.preferred_theme { match preferred_theme { Theme::Dark => settings.set_gtk_application_prefer_dark_theme(true), Theme::Light => { let theme_name = settings.gtk_theme_name().map(|t| t.as_str().to_owned()); if let Some(theme) = theme_name { // Remove dark variant. if let Some(theme) = GTK_THEME_SUFFIX_LIST .iter() .find(|t| theme.ends_with(*t)) .map(|v| theme.strip_suffix(v)) { settings.set_gtk_theme_name(theme); } } } } } } if attribs.visible { window.show_all(); } else { window.hide(); } // TODO it's impossible to set parent window from raw handle. // We need a gtk variant of it. if let Some(parent) = pl_attribs.parent { window.set_transient_for(Some(&parent)); } // TODO I don't understand why unfocussed window need focus // restore accept-focus after the window has been drawn // if the window was initially created without focus // if !attributes.focused { // let signal_id = Arc::new(RefCell::new(None)); // let signal_id_ = signal_id.clone(); // let id = window.connect_draw(move |window, _| { // if let Some(id) = signal_id_.take() { // window.set_accept_focus(true); // window.disconnect(id); // } // glib::Propagation::Proceed // }); // signal_id.borrow_mut().replace(id); // } // Set window position and size callback let w_pos = window.position(); let position: Rc<(AtomicI32, AtomicI32)> = Rc::new((w_pos.0.into(), w_pos.1.into())); let position_clone = position.clone(); let w_size = window.size(); let size: Rc<(AtomicI32, AtomicI32)> = Rc::new((w_size.0.into(), w_size.1.into())); let size_clone = size.clone(); window.connect_configure_event(move |_, event| { let (x, y) = event.position(); position_clone.0.store(x, Ordering::Release); position_clone.1.store(y, Ordering::Release); let (w, h) = event.size(); size_clone.0.store(w as i32, Ordering::Release); size_clone.1.store(h as i32, Ordering::Release); false }); // Set minimized/maximized callback let w_max = window.is_maximized(); let maximized: Rc<AtomicBool> = Rc::new(w_max.into()); let max_clone = maximized.clone(); let minimized = Rc::new(AtomicBool::new(false)); let minimized_clone = minimized.clone(); window.connect_window_state_event(move |_, event| { let state = event.new_window_state(); max_clone.store(state.contains(WindowState::MAXIMIZED), Ordering::Release); minimized_clone.store(state.contains(WindowState::ICONIFIED), Ordering::Release); glib::Propagation::Proceed }); // Set scale factor callback let scale_factor: Rc<AtomicI32> = Rc::new(win_scale_factor.into()); let scale_factor_clone = scale_factor.clone(); window.connect_scale_factor_notify(move |window| { scale_factor_clone.store(window.scale_factor(), Ordering::Release); }); // Check if we should paint the transparent background ourselves. let mut transparent = false; if attribs.transparent && pl_attribs.auto_transparent { transparent = true; } let transparent = Rc::new(AtomicBool::new(transparent)); // Send WireUp event to let eventloop handle the rest of window setup to prevent gtk panic // in other thread. if let Err(e) = window_requests_tx.send(( window_id, WindowRequest::WireUpEvents { transparent: transparent.clone(), }, )) { log::warn!("Fail to send wire up events request: {}", e); } if let Err(e) = draw_tx.send(window_id) { log::warn!("Failed to send redraw event to event channel: {}", e); } let win = Self { window_id, window, default_vbox, window_requests_tx, draw_tx, scale_factor, position, size, maximized, minimized, fullscreen: RefCell::new(fullscreen), min_size: RefCell::new(attribs.min_inner_size), max_size: RefCell::new(attribs.min_inner_size), transparent, }; win.set_skip_taskbar(pl_attribs.skip_taskbar); Ok(win) } #[inline] pub fn id(&self) -> WindowId { self.window_id } #[inline] pub fn set_title(&self, title: &str) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Title(title.to_string()))) { log::warn!("Fail to send title request: {}", e); } } #[inline] pub fn set_transparent(&self, transparent: bool) { self.transparent.store(transparent, Ordering::Relaxed); } #[inline] pub fn set_visible(&self, visible: bool) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Visible(visible))) { log::warn!("Fail to send visible request: {}", e); } } #[inline] pub fn is_visible(&self) -> Option<bool> { Some(self.window.is_visible()) } #[inline] pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { let (x, y) = &*self.position; Ok( LogicalPosition::new(x.load(Ordering::Acquire), y.load(Ordering::Acquire)) .to_physical(self.scale_factor.load(Ordering::Acquire) as f64), ) } #[inline] pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { let (x, y) = &*self.position; Ok( LogicalPosition::new(x.load(Ordering::Acquire), y.load(Ordering::Acquire)) .to_physical(self.scale_factor.load(Ordering::Acquire) as f64), ) } #[inline] pub fn set_outer_position(&self, position: Position) { let (x, y): (i32, i32) = position.to_logical::<i32>(self.scale_factor()).into(); if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Position((x, y)))) { log::warn!("Fail to send position request: {}", e); } } #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { let (width, height) = &*self.size; LogicalSize::new( width.load(Ordering::Acquire) as u32, height.load(Ordering::Acquire) as u32, ) .to_physical(self.scale_factor.load(Ordering::Acquire) as f64) } #[inline] pub fn outer_size(&self) -> PhysicalSize<u32> { let (width, height) = &*self.size; LogicalSize::new( width.load(Ordering::Acquire) as u32, height.load(Ordering::Acquire) as u32, ) .to_physical(self.scale_factor.load(Ordering::Acquire) as f64) } #[inline] pub fn set_inner_size(&self, size: Size) { let (width, height) = size.to_logical::<i32>(self.scale_factor()).into(); if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Size((width, height)))) { log::warn!("Fail to send size request: {}", e); } } fn set_size_constraints(&self) { if let Err(e) = self.window_requests_tx.send(( self.window_id, WindowRequest::SizeConstraints(*self.min_size.borrow(), *self.max_size.borrow()), )) { log::warn!("Fail to send size constraint request: {}", e); } } #[inline] pub fn set_min_inner_size(&self, dimensions: Option<Size>) { let mut min_size = self.min_size.borrow_mut(); *min_size = dimensions; self.set_size_constraints() } #[inline] pub fn set_max_inner_size(&self, dimensions: Option<Size>) { let mut max_size = self.min_size.borrow_mut(); *max_size = dimensions; self.set_size_constraints() } #[inline] pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { // TODO implement this None } #[inline] pub fn set_resize_increments(&self, _increments: Option<Size>) { // TODO implement this } #[inline] pub fn set_resizable(&self, resizable: bool) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Resizable(resizable))) { log::warn!("Fail to send resizable request: {}", e); } } #[inline] pub fn is_resizable(&self) -> bool { self.window.is_resizable() } #[inline] pub fn set_enabled_buttons(&self, _buttons: WindowButtons) { // TODO implement this } #[inline] pub fn enabled_buttons(&self) -> WindowButtons { // TODO implement this WindowButtons::empty() } #[inline] pub fn set_cursor_icon(&self, cursor: CursorIcon) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::CursorIcon(Some(cursor)))) { log::warn!("Fail to send cursor icon request: {}", e); } } #[inline] pub fn set_cursor_grab(&self, _mode: CursorGrabMode) -> Result<(), ExternalError> { // TODO implement this Ok(()) } #[inline] pub fn set_cursor_visible(&self, visible: bool) { let cursor = if visible { Some(CursorIcon::Default) } else { None }; if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::CursorIcon(cursor))) { log::warn!("Fail to send cursor visibility request: {}", e); } } #[inline] pub fn drag_window(&self) -> Result<(), ExternalError> { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::DragWindow)) { log::warn!("Fail to send drag window request: {}", e); } Ok(()) } #[inline] pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { // TODO implement this Ok(()) } #[inline] pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::CursorIgnoreEvents(!hittest))) { log::warn!("Fail to send cursor position request: {}", e); } Ok(()) } #[inline] pub fn scale_factor(&self) -> f64 { self.scale_factor.load(Ordering::Acquire) as f64 } #[inline] pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { let inner_pos = self.inner_position().unwrap_or_default(); let (x, y): (i32, i32) = position.to_logical::<i32>(self.scale_factor()).into(); if let Err(e) = self.window_requests_tx.send(( self.window_id, WindowRequest::CursorPosition((x + inner_pos.x, y + inner_pos.y)), )) { log::warn!("Fail to send cursor position request: {}", e); } Ok(()) } #[inline] pub fn set_maximized(&self, maximized: bool) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Maximized(maximized))) { log::warn!("Fail to send maximized request: {}", e); } } #[inline] pub fn is_maximized(&self) -> bool { self.maximized.load(Ordering::Acquire) } #[inline] pub fn set_minimized(&self, minimized: bool) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Minimized(minimized))) { log::warn!("Fail to send minimized request: {}", e); } } #[inline] pub fn is_minimized(&self) -> Option<bool> { Some(self.minimized.load(Ordering::Acquire)) } #[inline] pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { self.fullscreen.borrow().clone() } #[inline] pub(crate) fn set_fullscreen(&self, monitor: Option<Fullscreen>) { self.fullscreen.replace(monitor.clone()); if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Fullscreen(monitor))) { log::warn!("Fail to send fullscreen request: {}", e); } } #[inline] pub fn set_decorations(&self, decorations: bool) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Decorations(decorations))) { log::warn!("Fail to send decorations request: {}", e); } } #[inline] pub fn is_decorated(&self) -> bool { self.window.is_decorated() } #[inline] pub fn set_window_level(&self, level: WindowLevel) { match level { WindowLevel::AlwaysOnBottom => { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::AlwaysOnTop(true))) { log::warn!("Fail to send always on top request: {}", e); } } WindowLevel::Normal => (), WindowLevel::AlwaysOnTop => { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::AlwaysOnBottom(true))) { log::warn!("Fail to send always on bottom request: {}", e); } } } } #[inline] pub fn set_window_icon(&self, window_icon: Option<Icon>) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::WindowIcon(window_icon))) { log::warn!("Fail to send window icon request: {}", e); } } #[inline] pub fn set_ime_position(&self, _position: Position) { // TODO implement this } #[inline] pub fn set_ime_allowed(&self, _allowed: bool) { // TODO implement this } #[inline] pub fn set_ime_purpose(&self, _purpose: ImePurpose) { // TODO implement this } #[inline] pub fn focus_window(&self) { if !self.minimized.load(Ordering::Acquire) && self.window.get_visible() { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::Focus)) { log::warn!("Fail to send visible request: {}", e); } } } pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::UserAttention(request_type))) { log::warn!("Fail to send user attention request: {}", e); } } #[inline] pub fn request_redraw(&self) { if let Err(e) = self.draw_tx.send(self.window_id) { log::warn!("Failed to send redraw event to event channel: {}", e); } } #[inline] pub fn current_monitor(&self) -> Option<MonitorHandle> { let display = self.window.display(); // `.window()` returns `None` if the window is invisible; // we fallback to the primary monitor self.window .window() .map(|window| display.monitor_at_window(&window)) .unwrap_or_else(|| display.primary_monitor()) .map(|monitor| MonitorHandle { monitor }) } #[inline] pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { let mut handles = VecDeque::new(); let display = self.window.display(); let numbers = display.n_monitors(); for i in 0..numbers { let monitor = MonitorHandle::new(&display, i); handles.push_back(monitor); } handles } #[inline] pub fn primary_monitor(&self) -> Option<MonitorHandle> { let display = self.window.display(); display .primary_monitor() .map(|monitor| MonitorHandle { monitor }) } fn is_wayland(&self) -> bool { self.window.display().backend().is_wayland() } #[inline] pub fn raw_window_handle(&self) -> RawWindowHandle { if self.is_wayland() { let mut window_handle = WaylandWindowHandle::empty(); if let Some(window) = self.window.window() { window_handle.surface = unsafe { gdk_wayland_sys::gdk_wayland_window_get_wl_surface(window.as_ptr() as *mut _) }; } RawWindowHandle::Wayland(window_handle) } else { let mut window_handle = XlibWindowHandle::empty(); unsafe { if let Some(window) = self.window.window() { window_handle.window = gdk_x11_sys::gdk_x11_window_get_xid(window.as_ptr() as *mut _); } } RawWindowHandle::Xlib(window_handle) } } #[inline] pub fn raw_display_handle(&self) -> RawDisplayHandle { if self.is_wayland() { let mut display_handle = WaylandDisplayHandle::empty(); display_handle.display = unsafe { gdk_wayland_sys::gdk_wayland_display_get_wl_display( self.window.display().as_ptr() as *mut _ ) }; RawDisplayHandle::Wayland(display_handle) } else { let mut display_handle = XlibDisplayHandle::empty(); unsafe { if let Ok(xlib) = x11_dl::xlib::Xlib::open() { let display = (xlib.XOpenDisplay)(std::ptr::null()); display_handle.display = display as _; display_handle.screen = (xlib.XDefaultScreen)(display) as _; } } RawDisplayHandle::Xlib(display_handle) } } #[inline] pub fn set_theme(&self, theme: Option<Theme>) { if let Some(settings) = Settings::default() { if let Some(preferred_theme) = theme { match preferred_theme { Theme::Dark => settings.set_gtk_application_prefer_dark_theme(true), Theme::Light => { let theme_name = settings.gtk_theme_name().map(|t| t.as_str().to_owned()); if let Some(theme) = theme_name { // Remove dark variant. if let Some(theme) = GTK_THEME_SUFFIX_LIST .iter() .find(|t| theme.ends_with(*t)) .map(|v| theme.strip_suffix(v)) { settings.set_gtk_theme_name(theme); } } } } } } } #[inline] pub fn theme(&self) -> Option<Theme> { if let Some(settings) = Settings::default() { let theme_name = settings.gtk_theme_name().map(|s| s.as_str().to_owned()); if let Some(theme) = theme_name { if GTK_THEME_SUFFIX_LIST.iter().any(|t| theme.ends_with(t)) { return Some(Theme::Dark); } } } Some(Theme::Light) } #[inline] pub fn has_focus(&self) -> bool { self.window.is_active() } pub fn title(&self) -> String { self.window .title() .map(|t| t.as_str().to_string()) .unwrap_or_default() } pub fn set_skip_taskbar(&self, skip: bool) { if let Err(e) = self .window_requests_tx .send((self.window_id, WindowRequest::SetSkipTaskbar(skip))) { log::warn!("Fail to send skip taskbar request: {}", e); } } } // We need to keep GTK window which isn't thread safe. // We make sure all non thread safe window calls are sent to event loop to handle. unsafe impl Send for Window {} unsafe impl Sync for Window {} /// A constant used to determine how much inside the window, the resize handler should appear (only used in Linux(gtk) and Windows). /// You probably need to scale it by the scale_factor of the window. pub const BORDERLESS_RESIZE_INSET: i32 = 5; pub fn hit_test(window: &gdk::Window, cx: f64, cy: f64) -> WindowEdge { let (left, top) = window.position(); let (w, h) = (window.width(), window.height()); let (right, bottom) = (left + w, top + h); let (cx, cy) = (cx as i32, cy as i32); const LEFT: i32 = 0b0001; const RIGHT: i32 = 0b0010; const TOP: i32 = 0b0100; const BOTTOM: i32 = 0b1000; const TOPLEFT: i32 = TOP | LEFT; const TOPRIGHT: i32 = TOP | RIGHT; const BOTTOMLEFT: i32 = BOTTOM | LEFT; const BOTTOMRIGHT: i32 = BOTTOM | RIGHT; let inset = BORDERLESS_RESIZE_INSET * window.scale_factor(); #[rustfmt::skip] let result = (LEFT * (if cx < (left + inset) { 1 } else { 0 })) | (RIGHT * (if cx >= (right - inset) { 1 } else { 0 })) | (TOP * (if cy < (top + inset) { 1 } else { 0 })) | (BOTTOM * (if cy >= (bottom - inset) { 1 } else { 0 })); match result { LEFT => WindowEdge::West, TOP => WindowEdge::North, RIGHT => WindowEdge::East, BOTTOM => WindowEdge::South, TOPLEFT => WindowEdge::NorthWest, TOPRIGHT => WindowEdge::NorthEast, BOTTOMLEFT => WindowEdge::SouthWest, BOTTOMRIGHT => WindowEdge::SouthEast, // we return `WindowEdge::__Unknown` to be ignored later. // we must return 8 or bigger, otherwise it will be the same as one of the other 7 variants of `WindowEdge` enum. _ => WindowEdge::__Unknown(8), } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/app.rs
Rust
#![allow(clippy::unnecessary_cast)] use objc2::foundation::NSObject; use objc2::{declare_class, msg_send, ClassType}; use super::appkit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSResponder}; use super::{app_state::AppState, event::EventWrapper, DEVICE_ID}; use crate::event::{DeviceEvent, ElementState, Event}; declare_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(super) struct WinitApplication {} unsafe impl ClassType for WinitApplication { #[inherits(NSResponder, NSObject)] type Super = NSApplication; } unsafe impl WinitApplication { // Normally, holding Cmd + any key never sends us a `keyUp` event for that key. // Overriding `sendEvent:` like this fixes that. (https://stackoverflow.com/a/15294196) // Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553) #[sel(sendEvent:)] fn send_event(&self, event: &NSEvent) { // For posterity, there are some undocumented event types // (https://github.com/servo/cocoa-rs/issues/155) // but that doesn't really matter here. let event_type = event.type_(); let modifier_flags = event.modifierFlags(); if event_type == NSEventType::NSKeyUp && modifier_flags.contains(NSEventModifierFlags::NSCommandKeyMask) { if let Some(key_window) = self.keyWindow() { unsafe { key_window.sendEvent(event) }; } } else { maybe_dispatch_device_event(event); unsafe { msg_send![super(self), sendEvent: event] } } } } ); fn maybe_dispatch_device_event(event: &NSEvent) { let event_type = event.type_(); match event_type { NSEventType::NSMouseMoved | NSEventType::NSLeftMouseDragged | NSEventType::NSOtherMouseDragged | NSEventType::NSRightMouseDragged => { let delta_x = event.deltaX() as f64; let delta_y = event.deltaY() as f64; if delta_x != 0.0 { queue_device_event(DeviceEvent::Motion { axis: 0, value: delta_x, }); } if delta_y != 0.0 { queue_device_event(DeviceEvent::Motion { axis: 1, value: delta_y, }) } if delta_x != 0.0 || delta_y != 0.0 { queue_device_event(DeviceEvent::MouseMotion { delta: (delta_x, delta_y), }); } } NSEventType::NSLeftMouseDown | NSEventType::NSRightMouseDown | NSEventType::NSOtherMouseDown => { queue_device_event(DeviceEvent::Button { button: event.buttonNumber() as u32, state: ElementState::Pressed, }); } NSEventType::NSLeftMouseUp | NSEventType::NSRightMouseUp | NSEventType::NSOtherMouseUp => { queue_device_event(DeviceEvent::Button { button: event.buttonNumber() as u32, state: ElementState::Released, }); } _ => (), } } fn queue_device_event(event: DeviceEvent) { let event = Event::DeviceEvent { device_id: DEVICE_ID, event, }; AppState::queue_event(EventWrapper::StaticEvent(event)); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/app_delegate.rs
Rust
use objc2::foundation::NSObject; use objc2::rc::{Id, Shared}; use objc2::runtime::Object; use objc2::{declare_class, msg_send, msg_send_id, ClassType}; use super::app_state::AppState; use super::appkit::NSApplicationActivationPolicy; declare_class!( #[derive(Debug)] pub(super) struct ApplicationDelegate { activation_policy: NSApplicationActivationPolicy, default_menu: bool, activate_ignoring_other_apps: bool, } unsafe impl ClassType for ApplicationDelegate { type Super = NSObject; const NAME: &'static str = "WinitApplicationDelegate"; } unsafe impl ApplicationDelegate { #[sel(initWithActivationPolicy:defaultMenu:activateIgnoringOtherApps:)] fn init( &mut self, activation_policy: NSApplicationActivationPolicy, default_menu: bool, activate_ignoring_other_apps: bool, ) -> Option<&mut Self> { let this: Option<&mut Self> = unsafe { msg_send![super(self), init] }; this.map(|this| { *this.activation_policy = activation_policy; *this.default_menu = default_menu; *this.activate_ignoring_other_apps = activate_ignoring_other_apps; this }) } #[sel(applicationDidFinishLaunching:)] fn did_finish_launching(&self, _sender: *const Object) { trace_scope!("applicationDidFinishLaunching:"); AppState::launched( *self.activation_policy, *self.default_menu, *self.activate_ignoring_other_apps, ); } #[sel(applicationWillTerminate:)] fn will_terminate(&self, _sender: *const Object) { trace_scope!("applicationWillTerminate:"); // TODO: Notify every window that it will be destroyed, like done in iOS? AppState::exit(); } } ); impl ApplicationDelegate { pub(super) fn new( activation_policy: NSApplicationActivationPolicy, default_menu: bool, activate_ignoring_other_apps: bool, ) -> Id<Self, Shared> { unsafe { msg_send_id![ msg_send_id![Self::class(), alloc], initWithActivationPolicy: activation_policy, defaultMenu: default_menu, activateIgnoringOtherApps: activate_ignoring_other_apps, ] } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/app_state.rs
Rust
use std::{ cell::{RefCell, RefMut}, collections::VecDeque, fmt::{self, Debug}, mem, rc::{Rc, Weak}, sync::{ atomic::{AtomicBool, Ordering}, Mutex, MutexGuard, }, time::Instant, }; use core_foundation::runloop::{CFRunLoopGetMain, CFRunLoopWakeUp}; use objc2::foundation::{is_main_thread, NSSize}; use objc2::rc::autoreleasepool; use once_cell::sync::Lazy; use super::appkit::{NSApp, NSApplication, NSApplicationActivationPolicy, NSEvent}; use crate::{ dpi::LogicalSize, event::{Event, StartCause, WindowEvent}, event_loop::{ControlFlow, EventLoopWindowTarget as RootWindowTarget}, platform_impl::platform::{ event::{EventProxy, EventWrapper}, event_loop::PanicInfo, menu, observer::EventLoopWaker, util::Never, window::WinitWindow, }, window::WindowId, }; static HANDLER: Lazy<Handler> = Lazy::new(Default::default); impl<'a, Never> Event<'a, Never> { fn userify<T: 'static>(self) -> Event<'a, T> { self.map_nonuser_event() // `Never` can't be constructed, so the `UserEvent` variant can't // be present here. .unwrap_or_else(|_| unreachable!()) } } pub trait EventHandler: Debug { // Not sure probably it should accept Event<'static, Never> fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow); fn handle_user_events(&mut self, control_flow: &mut ControlFlow); } pub(crate) type Callback<T> = RefCell<dyn FnMut(Event<'_, T>, &RootWindowTarget<T>, &mut ControlFlow)>; struct EventLoopHandler<T: 'static> { callback: Weak<Callback<T>>, window_target: Rc<RootWindowTarget<T>>, } impl<T> EventLoopHandler<T> { fn with_callback<F>(&mut self, f: F) where F: FnOnce( &mut EventLoopHandler<T>, RefMut<'_, dyn FnMut(Event<'_, T>, &RootWindowTarget<T>, &mut ControlFlow)>, ), { if let Some(callback) = self.callback.upgrade() { let callback = callback.borrow_mut(); (f)(self, callback); } else { panic!( "Tried to dispatch an event, but the event loop that \ owned the event handler callback seems to be destroyed" ); } } } impl<T> Debug for EventLoopHandler<T> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("EventLoopHandler") .field("window_target", &self.window_target) .finish() } } impl<T> EventHandler for EventLoopHandler<T> { fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow) { self.with_callback(|this, mut callback| { if let ControlFlow::ExitWithCode(code) = *control_flow { let dummy = &mut ControlFlow::ExitWithCode(code); (callback)(event.userify(), &this.window_target, dummy); } else { (callback)(event.userify(), &this.window_target, control_flow); } }); } fn handle_user_events(&mut self, control_flow: &mut ControlFlow) { self.with_callback(|this, mut callback| { for event in this.window_target.p.receiver.try_iter() { if let ControlFlow::ExitWithCode(code) = *control_flow { let dummy = &mut ControlFlow::ExitWithCode(code); (callback)(Event::UserEvent(event), &this.window_target, dummy); } else { (callback)(Event::UserEvent(event), &this.window_target, control_flow); } } }); } } #[derive(Default)] struct Handler { ready: AtomicBool, in_callback: AtomicBool, control_flow: Mutex<ControlFlow>, control_flow_prev: Mutex<ControlFlow>, start_time: Mutex<Option<Instant>>, callback: Mutex<Option<Box<dyn EventHandler>>>, pending_events: Mutex<VecDeque<EventWrapper>>, pending_redraw: Mutex<Vec<WindowId>>, waker: Mutex<EventLoopWaker>, } unsafe impl Send for Handler {} unsafe impl Sync for Handler {} impl Handler { fn events(&self) -> MutexGuard<'_, VecDeque<EventWrapper>> { self.pending_events.lock().unwrap() } fn redraw(&self) -> MutexGuard<'_, Vec<WindowId>> { self.pending_redraw.lock().unwrap() } fn waker(&self) -> MutexGuard<'_, EventLoopWaker> { self.waker.lock().unwrap() } fn is_ready(&self) -> bool { self.ready.load(Ordering::Acquire) } fn set_ready(&self) { self.ready.store(true, Ordering::Release); } fn should_exit(&self) -> bool { matches!( *self.control_flow.lock().unwrap(), ControlFlow::ExitWithCode(_) ) } fn get_control_flow_and_update_prev(&self) -> ControlFlow { let control_flow = self.control_flow.lock().unwrap(); *self.control_flow_prev.lock().unwrap() = *control_flow; *control_flow } fn get_old_and_new_control_flow(&self) -> (ControlFlow, ControlFlow) { let old = *self.control_flow_prev.lock().unwrap(); let new = *self.control_flow.lock().unwrap(); (old, new) } fn get_start_time(&self) -> Option<Instant> { *self.start_time.lock().unwrap() } fn update_start_time(&self) { *self.start_time.lock().unwrap() = Some(Instant::now()); } fn take_events(&self) -> VecDeque<EventWrapper> { mem::take(&mut *self.events()) } fn should_redraw(&self) -> Vec<WindowId> { mem::take(&mut *self.redraw()) } fn get_in_callback(&self) -> bool { self.in_callback.load(Ordering::Acquire) } fn set_in_callback(&self, in_callback: bool) { self.in_callback.store(in_callback, Ordering::Release); } fn handle_nonuser_event(&self, wrapper: EventWrapper) { if let Some(ref mut callback) = *self.callback.lock().unwrap() { match wrapper { EventWrapper::StaticEvent(event) => { callback.handle_nonuser_event(event, &mut self.control_flow.lock().unwrap()) } EventWrapper::EventProxy(proxy) => self.handle_proxy(proxy, callback), } } } fn handle_user_events(&self) { if let Some(ref mut callback) = *self.callback.lock().unwrap() { callback.handle_user_events(&mut self.control_flow.lock().unwrap()); } } fn handle_scale_factor_changed_event( &self, callback: &mut Box<dyn EventHandler + 'static>, window: &WinitWindow, suggested_size: LogicalSize<f64>, scale_factor: f64, ) { let mut size = suggested_size.to_physical(scale_factor); let new_inner_size = &mut size; let event = Event::WindowEvent { window_id: WindowId(window.id()), event: WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size, }, }; callback.handle_nonuser_event(event, &mut self.control_flow.lock().unwrap()); let physical_size = *new_inner_size; let logical_size = physical_size.to_logical(scale_factor); let size = NSSize::new(logical_size.width, logical_size.height); window.setContentSize(size); } fn handle_proxy(&self, proxy: EventProxy, callback: &mut Box<dyn EventHandler + 'static>) { match proxy { EventProxy::DpiChangedProxy { window, suggested_size, scale_factor, } => self.handle_scale_factor_changed_event( callback, &window, suggested_size, scale_factor, ), } } } pub(crate) enum AppState {} impl AppState { pub fn set_callback<T>(callback: Weak<Callback<T>>, window_target: Rc<RootWindowTarget<T>>) { *HANDLER.callback.lock().unwrap() = Some(Box::new(EventLoopHandler { callback, window_target, })); } pub fn exit() -> i32 { HANDLER.set_in_callback(true); HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::LoopDestroyed)); HANDLER.set_in_callback(false); HANDLER.callback.lock().unwrap().take(); if let ControlFlow::ExitWithCode(code) = HANDLER.get_old_and_new_control_flow().1 { code } else { 0 } } pub fn launched( activation_policy: NSApplicationActivationPolicy, create_default_menu: bool, activate_ignoring_other_apps: bool, ) { let app = NSApp(); // We need to delay setting the activation policy and activating the app // until `applicationDidFinishLaunching` has been called. Otherwise the // menu bar is initially unresponsive on macOS 10.15. app.setActivationPolicy(activation_policy); window_activation_hack(&app); app.activateIgnoringOtherApps(activate_ignoring_other_apps); HANDLER.set_ready(); HANDLER.waker().start(); if create_default_menu { // The menubar initialization should be before the `NewEvents` event, to allow // overriding of the default menu even if it's created menu::initialize(); } HANDLER.set_in_callback(true); HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::NewEvents( StartCause::Init, ))); // NB: For consistency all platforms must emit a 'resumed' event even though macOS // applications don't themselves have a formal suspend/resume lifecycle. HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::Resumed)); HANDLER.set_in_callback(false); } pub fn wakeup(panic_info: Weak<PanicInfo>) { let panic_info = panic_info .upgrade() .expect("The panic info must exist here. This failure indicates a developer error."); // Return when in callback due to https://github.com/rust-windowing/winit/issues/1779 if panic_info.is_panicking() || !HANDLER.is_ready() || HANDLER.get_in_callback() { return; } let start = HANDLER.get_start_time().unwrap(); let cause = match HANDLER.get_control_flow_and_update_prev() { ControlFlow::Poll => StartCause::Poll, ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None, }, ControlFlow::WaitUntil(requested_resume) => { if Instant::now() >= requested_resume { StartCause::ResumeTimeReached { start, requested_resume, } } else { StartCause::WaitCancelled { start, requested_resume: Some(requested_resume), } } } ControlFlow::ExitWithCode(_) => StartCause::Poll, //panic!("unexpected `ControlFlow::Exit`"), }; HANDLER.set_in_callback(true); HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::NewEvents(cause))); HANDLER.set_in_callback(false); } // This is called from multiple threads at present pub fn queue_redraw(window_id: WindowId) { let mut pending_redraw = HANDLER.redraw(); if !pending_redraw.contains(&window_id) { pending_redraw.push(window_id); } unsafe { let rl = CFRunLoopGetMain(); CFRunLoopWakeUp(rl); } } pub fn handle_redraw(window_id: WindowId) { // Redraw request might come out of order from the OS. // -> Don't go back into the callback when our callstack originates from there if !HANDLER.in_callback.swap(true, Ordering::AcqRel) { HANDLER .handle_nonuser_event(EventWrapper::StaticEvent(Event::RedrawRequested(window_id))); HANDLER.set_in_callback(false); } } pub fn queue_event(wrapper: EventWrapper) { if !is_main_thread() { panic!("Event queued from different thread: {wrapper:#?}"); } HANDLER.events().push_back(wrapper); } pub fn cleared(panic_info: Weak<PanicInfo>) { let panic_info = panic_info .upgrade() .expect("The panic info must exist here. This failure indicates a developer error."); // Return when in callback due to https://github.com/rust-windowing/winit/issues/1779 if panic_info.is_panicking() || !HANDLER.is_ready() || HANDLER.get_in_callback() { return; } HANDLER.set_in_callback(true); HANDLER.handle_user_events(); for event in HANDLER.take_events() { HANDLER.handle_nonuser_event(event); } HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::MainEventsCleared)); for window_id in HANDLER.should_redraw() { HANDLER .handle_nonuser_event(EventWrapper::StaticEvent(Event::RedrawRequested(window_id))); } HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::RedrawEventsCleared)); HANDLER.set_in_callback(false); if HANDLER.should_exit() { let app = NSApp(); autoreleasepool(|_| { app.stop(None); // To stop event loop immediately, we need to post some event here. app.postEvent_atStart(&NSEvent::dummy(), true); }); } HANDLER.update_start_time(); match HANDLER.get_old_and_new_control_flow() { (ControlFlow::ExitWithCode(_), _) | (_, ControlFlow::ExitWithCode(_)) => (), (old, new) if old == new => (), (_, ControlFlow::Wait) => HANDLER.waker().stop(), (_, ControlFlow::WaitUntil(instant)) => HANDLER.waker().start_at(instant), (_, ControlFlow::Poll) => HANDLER.waker().start(), } } } /// A hack to make activation of multiple windows work when creating them before /// `applicationDidFinishLaunching:` / `Event::Event::NewEvents(StartCause::Init)`. /// /// Alternative to this would be the user calling `window.set_visible(true)` in /// `StartCause::Init`. /// /// If this becomes too bothersome to maintain, it can probably be removed /// without too much damage. fn window_activation_hack(app: &NSApplication) { // TODO: Proper ordering of the windows app.windows().into_iter().for_each(|window| { // Call `makeKeyAndOrderFront` if it was called on the window in `WinitWindow::new` // This way we preserve the user's desired initial visiblity status // TODO: Also filter on the type/"level" of the window, and maybe other things? if window.isVisible() { trace!("Activating visible window"); window.makeKeyAndOrderFront(None); } else { trace!("Skipping activating invisible window"); } }) }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/appearance.rs
Rust
use objc2::foundation::{NSArray, NSObject, NSString}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSAppearance; unsafe impl ClassType for NSAppearance { type Super = NSObject; } ); type NSAppearanceName = NSString; extern_methods!( unsafe impl NSAppearance { pub fn appearanceNamed(name: &NSAppearanceName) -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), appearanceNamed: name] } } pub fn bestMatchFromAppearancesWithNames( &self, appearances: &NSArray<NSAppearanceName>, ) -> Id<NSAppearanceName, Shared> { unsafe { msg_send_id![self, bestMatchFromAppearancesWithNames: appearances,] } } } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/application.rs
Rust
use objc2::foundation::{MainThreadMarker, NSArray, NSInteger, NSObject, NSUInteger}; use objc2::rc::{Id, Shared}; use objc2::runtime::Object; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use objc2::{Encode, Encoding}; use super::{NSAppearance, NSEvent, NSMenu, NSResponder, NSWindow}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSApplication; unsafe impl ClassType for NSApplication { #[inherits(NSObject)] type Super = NSResponder; } ); pub(crate) fn NSApp() -> Id<NSApplication, Shared> { // TODO: Only allow access from main thread NSApplication::shared(unsafe { MainThreadMarker::new_unchecked() }) } extern_methods!( unsafe impl NSApplication { /// This can only be called on the main thread since it may initialize /// the application and since it's parameters may be changed by the main /// thread at any time (hence it is only safe to access on the main thread). pub fn shared(_mtm: MainThreadMarker) -> Id<Self, Shared> { let app: Option<_> = unsafe { msg_send_id![Self::class(), sharedApplication] }; // SAFETY: `sharedApplication` always initializes the app if it isn't already unsafe { app.unwrap_unchecked() } } pub fn currentEvent(&self) -> Option<Id<NSEvent, Shared>> { unsafe { msg_send_id![self, currentEvent] } } #[sel(postEvent:atStart:)] pub fn postEvent_atStart(&self, event: &NSEvent, front_of_queue: bool); #[sel(presentationOptions)] pub fn presentationOptions(&self) -> NSApplicationPresentationOptions; pub fn windows(&self) -> Id<NSArray<NSWindow, Shared>, Shared> { unsafe { msg_send_id![self, windows] } } pub fn keyWindow(&self) -> Option<Id<NSWindow, Shared>> { unsafe { msg_send_id![self, keyWindow] } } // TODO: NSApplicationDelegate #[sel(setDelegate:)] pub fn setDelegate(&self, delegate: &Object); #[sel(setPresentationOptions:)] pub fn setPresentationOptions(&self, options: NSApplicationPresentationOptions); #[sel(hide:)] pub fn hide(&self, sender: Option<&Object>); #[sel(orderFrontCharacterPalette:)] #[allow(dead_code)] pub fn orderFrontCharacterPalette(&self, sender: Option<&Object>); #[sel(hideOtherApplications:)] pub fn hideOtherApplications(&self, sender: Option<&Object>); #[sel(stop:)] pub fn stop(&self, sender: Option<&Object>); #[sel(activateIgnoringOtherApps:)] pub fn activateIgnoringOtherApps(&self, ignore: bool); #[sel(requestUserAttention:)] pub fn requestUserAttention(&self, type_: NSRequestUserAttentionType) -> NSInteger; #[sel(setActivationPolicy:)] pub fn setActivationPolicy(&self, policy: NSApplicationActivationPolicy) -> bool; #[sel(setMainMenu:)] pub fn setMainMenu(&self, menu: &NSMenu); pub fn effectiveAppearance(&self) -> Id<NSAppearance, Shared> { unsafe { msg_send_id![self, effectiveAppearance] } } #[sel(setAppearance:)] pub fn setAppearance(&self, appearance: Option<&NSAppearance>); #[sel(run)] pub unsafe fn run(&self); } ); #[allow(dead_code)] #[repr(isize)] // NSInteger #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSApplicationActivationPolicy { NSApplicationActivationPolicyRegular = 0, NSApplicationActivationPolicyAccessory = 1, NSApplicationActivationPolicyProhibited = 2, NSApplicationActivationPolicyERROR = -1, } unsafe impl Encode for NSApplicationActivationPolicy { const ENCODING: Encoding = NSInteger::ENCODING; } bitflags! { pub struct NSApplicationPresentationOptions: NSUInteger { const NSApplicationPresentationDefault = 0; const NSApplicationPresentationAutoHideDock = 1 << 0; const NSApplicationPresentationHideDock = 1 << 1; const NSApplicationPresentationAutoHideMenuBar = 1 << 2; const NSApplicationPresentationHideMenuBar = 1 << 3; const NSApplicationPresentationDisableAppleMenu = 1 << 4; const NSApplicationPresentationDisableProcessSwitching = 1 << 5; const NSApplicationPresentationDisableForceQuit = 1 << 6; const NSApplicationPresentationDisableSessionTermination = 1 << 7; const NSApplicationPresentationDisableHideApplication = 1 << 8; const NSApplicationPresentationDisableMenuBarTransparency = 1 << 9; const NSApplicationPresentationFullScreen = 1 << 10; const NSApplicationPresentationAutoHideToolbar = 1 << 11; } } unsafe impl Encode for NSApplicationPresentationOptions { const ENCODING: Encoding = NSUInteger::ENCODING; } #[repr(usize)] // NSUInteger #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSRequestUserAttentionType { NSCriticalRequest = 0, NSInformationalRequest = 10, } unsafe impl Encode for NSRequestUserAttentionType { const ENCODING: Encoding = NSUInteger::ENCODING; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/button.rs
Rust
use objc2::foundation::NSObject; use objc2::{extern_class, ClassType}; use super::{NSControl, NSResponder, NSView}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSButton; unsafe impl ClassType for NSButton { #[inherits(NSView, NSResponder, NSObject)] type Super = NSControl; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/color.rs
Rust
use objc2::foundation::NSObject; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; extern_class!( /// An object that stores color data and sometimes opacity (alpha value). /// /// <https://developer.apple.com/documentation/appkit/nscolor?language=objc> #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSColor; unsafe impl ClassType for NSColor { type Super = NSObject; } ); // SAFETY: Documentation clearly states: // > Color objects are immutable and thread-safe unsafe impl Send for NSColor {} unsafe impl Sync for NSColor {} extern_methods!( unsafe impl NSColor { pub fn clear() -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), clearColor] } } } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/control.rs
Rust
use objc2::foundation::NSObject; use objc2::{extern_class, extern_methods, ClassType}; use super::{NSResponder, NSView}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSControl; unsafe impl ClassType for NSControl { #[inherits(NSResponder, NSObject)] type Super = NSView; } ); extern_methods!( unsafe impl NSControl { #[sel(setEnabled:)] pub fn setEnabled(&self, enabled: bool); #[sel(isEnabled)] pub fn isEnabled(&self) -> bool; } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/cursor.rs
Rust
use once_cell::sync::Lazy; use objc2::foundation::{NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSString}; use objc2::rc::{DefaultId, Id, Shared}; use objc2::runtime::Sel; use objc2::{extern_class, extern_methods, msg_send_id, ns_string, sel, ClassType}; use super::NSImage; use crate::window::CursorIcon; extern_class!( /// <https://developer.apple.com/documentation/appkit/nscursor?language=objc> #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSCursor; unsafe impl ClassType for NSCursor { type Super = NSObject; } ); // SAFETY: NSCursor is immutable, stated here: // https://developer.apple.com/documentation/appkit/nscursor/1527062-image?language=objc unsafe impl Send for NSCursor {} unsafe impl Sync for NSCursor {} macro_rules! def_cursor { {$( $(#[$($m:meta)*])* pub fn $name:ident(); )*} => {$( $(#[$($m)*])* pub fn $name() -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), $name] } } )*}; } macro_rules! def_undocumented_cursor { {$( $(#[$($m:meta)*])* pub fn $name:ident(); )*} => {$( $(#[$($m)*])* pub fn $name() -> Id<Self, Shared> { unsafe { Self::from_selector(sel!($name)).unwrap_or_else(|| Default::default()) } } )*}; } extern_methods!( /// Documented cursors unsafe impl NSCursor { def_cursor!( pub fn arrowCursor(); pub fn pointingHandCursor(); pub fn openHandCursor(); pub fn closedHandCursor(); pub fn IBeamCursor(); pub fn IBeamCursorForVerticalLayout(); pub fn dragCopyCursor(); pub fn dragLinkCursor(); pub fn operationNotAllowedCursor(); pub fn contextualMenuCursor(); pub fn crosshairCursor(); pub fn resizeRightCursor(); pub fn resizeUpCursor(); pub fn resizeLeftCursor(); pub fn resizeDownCursor(); pub fn resizeLeftRightCursor(); pub fn resizeUpDownCursor(); ); // Creating cursors should be thread-safe, though using them for anything probably isn't. pub fn new(image: &NSImage, hotSpot: NSPoint) -> Id<Self, Shared> { let this = unsafe { msg_send_id![Self::class(), alloc] }; unsafe { msg_send_id![this, initWithImage: image, hotSpot: hotSpot] } } pub fn invisible() -> Id<Self, Shared> { // 16x16 GIF data for invisible cursor // You can reproduce this via ImageMagick. // $ convert -size 16x16 xc:none cursor.gif static CURSOR_BYTES: &[u8] = &[ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0E, 0x84, 0x8F, 0xA9, 0xCB, 0xED, 0x0F, 0xA3, 0x9C, 0xB4, 0xDA, 0x8B, 0xB3, 0x3E, 0x05, 0x00, 0x3B, ]; static CURSOR: Lazy<Id<NSCursor, Shared>> = Lazy::new(|| { // TODO: Consider using `dataWithBytesNoCopy:` let data = NSData::with_bytes(CURSOR_BYTES); let image = NSImage::new_with_data(&data); NSCursor::new(&image, NSPoint::new(0.0, 0.0)) }); CURSOR.clone() } } /// Undocumented cursors unsafe impl NSCursor { #[sel(respondsToSelector:)] fn class_responds_to(sel: Sel) -> bool; unsafe fn from_selector_unchecked(sel: Sel) -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), performSelector: sel] } } unsafe fn from_selector(sel: Sel) -> Option<Id<Self, Shared>> { if Self::class_responds_to(sel) { Some(unsafe { Self::from_selector_unchecked(sel) }) } else { warn!("Cursor `{:?}` appears to be invalid", sel); None } } def_undocumented_cursor!( // Undocumented cursors: https://stackoverflow.com/a/46635398/5435443 pub fn _helpCursor(); pub fn _zoomInCursor(); pub fn _zoomOutCursor(); pub fn _windowResizeNorthEastCursor(); pub fn _windowResizeNorthWestCursor(); pub fn _windowResizeSouthEastCursor(); pub fn _windowResizeSouthWestCursor(); pub fn _windowResizeNorthEastSouthWestCursor(); pub fn _windowResizeNorthWestSouthEastCursor(); // While these two are available, the former just loads a white arrow, // and the latter loads an ugly deflated beachball! // pub fn _moveCursor(); // pub fn _waitCursor(); // An even more undocumented cursor... // https://bugs.eclipse.org/bugs/show_bug.cgi?id=522349 pub fn busyButClickableCursor(); ); } /// Webkit cursors unsafe impl NSCursor { // Note that loading `busybutclickable` with this code won't animate // the frames; instead you'll just get them all in a column. unsafe fn load_webkit_cursor(name: &NSString) -> Id<Self, Shared> { // Snatch a cursor from WebKit; They fit the style of the native // cursors, and will seem completely standard to macOS users. // // https://stackoverflow.com/a/21786835/5435443 let root = ns_string!("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors"); let cursor_path = root.join_path(name); let pdf_path = cursor_path.join_path(ns_string!("cursor.pdf")); let image = NSImage::new_by_referencing_file(&pdf_path); // TODO: Handle PLists better let info_path = cursor_path.join_path(ns_string!("info.plist")); let info: Id<NSDictionary<NSObject, NSObject>, Shared> = unsafe { msg_send_id![ <NSDictionary<NSObject, NSObject>>::class(), dictionaryWithContentsOfFile: &*info_path, ] }; let mut x = 0.0; if let Some(n) = info.get(&*ns_string!("hotx")) { if n.is_kind_of::<NSNumber>() { let ptr: *const NSObject = n; let ptr: *const NSNumber = ptr.cast(); x = unsafe { &*ptr }.as_cgfloat() } } let mut y = 0.0; if let Some(n) = info.get(&*ns_string!("hotx")) { if n.is_kind_of::<NSNumber>() { let ptr: *const NSObject = n; let ptr: *const NSNumber = ptr.cast(); y = unsafe { &*ptr }.as_cgfloat() } } let hotspot = NSPoint::new(x, y); Self::new(&image, hotspot) } pub fn moveCursor() -> Id<Self, Shared> { unsafe { Self::load_webkit_cursor(ns_string!("move")) } } pub fn cellCursor() -> Id<Self, Shared> { unsafe { Self::load_webkit_cursor(ns_string!("cell")) } } } ); impl NSCursor { pub fn from_icon(icon: CursorIcon) -> Id<Self, Shared> { match icon { CursorIcon::Default => Default::default(), CursorIcon::Arrow => Self::arrowCursor(), CursorIcon::Hand => Self::pointingHandCursor(), CursorIcon::Grab => Self::openHandCursor(), CursorIcon::Grabbing => Self::closedHandCursor(), CursorIcon::Text => Self::IBeamCursor(), CursorIcon::VerticalText => Self::IBeamCursorForVerticalLayout(), CursorIcon::Copy => Self::dragCopyCursor(), CursorIcon::Alias => Self::dragLinkCursor(), CursorIcon::NotAllowed | CursorIcon::NoDrop => Self::operationNotAllowedCursor(), CursorIcon::ContextMenu => Self::contextualMenuCursor(), CursorIcon::Crosshair => Self::crosshairCursor(), CursorIcon::EResize => Self::resizeRightCursor(), CursorIcon::NResize => Self::resizeUpCursor(), CursorIcon::WResize => Self::resizeLeftCursor(), CursorIcon::SResize => Self::resizeDownCursor(), CursorIcon::EwResize | CursorIcon::ColResize => Self::resizeLeftRightCursor(), CursorIcon::NsResize | CursorIcon::RowResize => Self::resizeUpDownCursor(), CursorIcon::Help => Self::_helpCursor(), CursorIcon::ZoomIn => Self::_zoomInCursor(), CursorIcon::ZoomOut => Self::_zoomOutCursor(), CursorIcon::NeResize => Self::_windowResizeNorthEastCursor(), CursorIcon::NwResize => Self::_windowResizeNorthWestCursor(), CursorIcon::SeResize => Self::_windowResizeSouthEastCursor(), CursorIcon::SwResize => Self::_windowResizeSouthWestCursor(), CursorIcon::NeswResize => Self::_windowResizeNorthEastSouthWestCursor(), CursorIcon::NwseResize => Self::_windowResizeNorthWestSouthEastCursor(), // This is the wrong semantics for `Wait`, but it's the same as // what's used in Safari and Chrome. CursorIcon::Wait | CursorIcon::Progress => Self::busyButClickableCursor(), CursorIcon::Move | CursorIcon::AllScroll => Self::moveCursor(), CursorIcon::Cell => Self::cellCursor(), } } } impl DefaultId for NSCursor { type Ownership = Shared; fn default_id() -> Id<Self, Shared> { Self::arrowCursor() } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/event.rs
Rust
use std::os::raw::c_ushort; use objc2::encode::{Encode, Encoding}; use objc2::foundation::{ CGFloat, NSCopying, NSInteger, NSObject, NSPoint, NSString, NSTimeInterval, NSUInteger, }; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSEvent; unsafe impl ClassType for NSEvent { type Super = NSObject; } ); // > Safely handled only on the same thread, whether that be the main thread // > or a secondary thread; otherwise you run the risk of having events get // > out of sequence. // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW47> // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-123383> extern_methods!( unsafe impl NSEvent { unsafe fn otherEventWithType( type_: NSEventType, location: NSPoint, flags: NSEventModifierFlags, time: NSTimeInterval, window_num: NSInteger, context: Option<&NSObject>, // NSGraphicsContext subtype: NSEventSubtype, data1: NSInteger, data2: NSInteger, ) -> Id<Self, Shared> { unsafe { msg_send_id![ Self::class(), otherEventWithType: type_, location: location, modifierFlags: flags, timestamp: time, windowNumber: window_num, context: context, subtype: subtype, data1: data1, data2: data2, ] } } pub fn dummy() -> Id<Self, Shared> { unsafe { Self::otherEventWithType( NSEventType::NSApplicationDefined, NSPoint::new(0.0, 0.0), NSEventModifierFlags::empty(), 0.0, 0, None, NSEventSubtype::NSWindowExposedEventType, 0, 0, ) } } pub fn keyEventWithType( type_: NSEventType, location: NSPoint, modifier_flags: NSEventModifierFlags, timestamp: NSTimeInterval, window_num: NSInteger, context: Option<&NSObject>, characters: &NSString, characters_ignoring_modifiers: &NSString, is_a_repeat: bool, scancode: c_ushort, ) -> Id<Self, Shared> { unsafe { msg_send_id![ Self::class(), keyEventWithType: type_, location: location, modifierFlags: modifier_flags, timestamp: timestamp, windowNumber: window_num, context: context, characters: characters, charactersIgnoringModifiers: characters_ignoring_modifiers, isARepeat: is_a_repeat, keyCode: scancode, ] } } #[sel(locationInWindow)] pub fn locationInWindow(&self) -> NSPoint; // TODO: MainThreadMarker #[sel(pressedMouseButtons)] pub fn pressedMouseButtons() -> NSUInteger; #[sel(modifierFlags)] pub fn modifierFlags(&self) -> NSEventModifierFlags; #[sel(type)] pub fn type_(&self) -> NSEventType; // In AppKit, `keyCode` refers to the position (scancode) of a key rather than its character, // and there is no easy way to navtively retrieve the layout-dependent character. // In winit, we use keycode to refer to the key's character, and so this function aligns // AppKit's terminology with ours. #[sel(keyCode)] pub fn scancode(&self) -> c_ushort; #[sel(magnification)] pub fn magnification(&self) -> CGFloat; #[sel(phase)] pub fn phase(&self) -> NSEventPhase; #[sel(momentumPhase)] pub fn momentumPhase(&self) -> NSEventPhase; #[sel(deltaX)] pub fn deltaX(&self) -> CGFloat; #[sel(deltaY)] pub fn deltaY(&self) -> CGFloat; #[sel(buttonNumber)] pub fn buttonNumber(&self) -> NSInteger; #[sel(scrollingDeltaX)] pub fn scrollingDeltaX(&self) -> CGFloat; #[sel(scrollingDeltaY)] pub fn scrollingDeltaY(&self) -> CGFloat; #[sel(hasPreciseScrollingDeltas)] pub fn hasPreciseScrollingDeltas(&self) -> bool; #[sel(rotation)] pub fn rotation(&self) -> f32; #[sel(pressure)] pub fn pressure(&self) -> f32; #[sel(stage)] pub fn stage(&self) -> NSInteger; #[sel(isARepeat)] pub fn is_a_repeat(&self) -> bool; #[sel(windowNumber)] pub fn window_number(&self) -> NSInteger; #[sel(timestamp)] pub fn timestamp(&self) -> NSTimeInterval; pub fn characters(&self) -> Option<Id<NSString, Shared>> { unsafe { msg_send_id![self, characters] } } pub fn charactersIgnoringModifiers(&self) -> Option<Id<NSString, Shared>> { unsafe { msg_send_id![self, charactersIgnoringModifiers] } } pub fn lalt_pressed(&self) -> bool { let raw_modifiers = self.modifierFlags().bits() as u32; raw_modifiers & NX_DEVICELALTKEYMASK != 0 } pub fn ralt_pressed(&self) -> bool { let raw_modifiers = self.modifierFlags().bits() as u32; raw_modifiers & NX_DEVICERALTKEYMASK != 0 } } ); unsafe impl NSCopying for NSEvent { type Ownership = Shared; type Output = NSEvent; } // The values are from the https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h#L258-L259 const NX_DEVICELALTKEYMASK: u32 = 0x00000020; const NX_DEVICERALTKEYMASK: u32 = 0x00000040; bitflags! { pub struct NSEventModifierFlags: NSUInteger { const NSAlphaShiftKeyMask = 1 << 16; const NSShiftKeyMask = 1 << 17; const NSControlKeyMask = 1 << 18; const NSAlternateKeyMask = 1 << 19; const NSCommandKeyMask = 1 << 20; const NSNumericPadKeyMask = 1 << 21; const NSHelpKeyMask = 1 << 22; const NSFunctionKeyMask = 1 << 23; const NSDeviceIndependentModifierFlagsMask = 0xffff0000; } } unsafe impl Encode for NSEventModifierFlags { const ENCODING: Encoding = NSUInteger::ENCODING; } bitflags! { pub struct NSEventPhase: NSUInteger { const NSEventPhaseNone = 0; const NSEventPhaseBegan = 0x1 << 0; const NSEventPhaseStationary = 0x1 << 1; const NSEventPhaseChanged = 0x1 << 2; const NSEventPhaseEnded = 0x1 << 3; const NSEventPhaseCancelled = 0x1 << 4; const NSEventPhaseMayBegin = 0x1 << 5; } } unsafe impl Encode for NSEventPhase { const ENCODING: Encoding = NSUInteger::ENCODING; } #[allow(dead_code)] #[repr(i16)] // short #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSEventSubtype { // TODO: Not sure what these values are // NSMouseEventSubtype = NX_SUBTYPE_DEFAULT, // NSTabletPointEventSubtype = NX_SUBTYPE_TABLET_POINT, // NSTabletProximityEventSubtype = NX_SUBTYPE_TABLET_PROXIMITY // NSTouchEventSubtype = NX_SUBTYPE_MOUSE_TOUCH, NSWindowExposedEventType = 0, NSApplicationActivatedEventType = 1, NSApplicationDeactivatedEventType = 2, NSWindowMovedEventType = 4, NSScreenChangedEventType = 8, NSAWTEventType = 16, } unsafe impl Encode for NSEventSubtype { const ENCODING: Encoding = i16::ENCODING; } #[allow(dead_code)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(usize)] // NSUInteger pub enum NSEventType { NSLeftMouseDown = 1, NSLeftMouseUp = 2, NSRightMouseDown = 3, NSRightMouseUp = 4, NSMouseMoved = 5, NSLeftMouseDragged = 6, NSRightMouseDragged = 7, NSMouseEntered = 8, NSMouseExited = 9, NSKeyDown = 10, NSKeyUp = 11, NSFlagsChanged = 12, NSAppKitDefined = 13, NSSystemDefined = 14, NSApplicationDefined = 15, NSPeriodic = 16, NSCursorUpdate = 17, NSScrollWheel = 22, NSTabletPoint = 23, NSTabletProximity = 24, NSOtherMouseDown = 25, NSOtherMouseUp = 26, NSOtherMouseDragged = 27, NSEventTypeGesture = 29, NSEventTypeMagnify = 30, NSEventTypeSwipe = 31, NSEventTypeRotate = 18, NSEventTypeBeginGesture = 19, NSEventTypeEndGesture = 20, NSEventTypePressure = 34, } unsafe impl Encode for NSEventType { const ENCODING: Encoding = NSUInteger::ENCODING; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/image.rs
Rust
use objc2::foundation::{NSData, NSObject, NSString}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; extern_class!( // TODO: Can this be mutable? #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSImage; unsafe impl ClassType for NSImage { type Super = NSObject; } ); // Documented Thread-Unsafe, but: // > One thread can create an NSImage object, draw to the image buffer, // > and pass it off to the main thread for drawing. The underlying image // > cache is shared among all threads. // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-126728> // // So really only unsafe to mutate on several threads. unsafe impl Send for NSImage {} unsafe impl Sync for NSImage {} extern_methods!( unsafe impl NSImage { pub fn new_by_referencing_file(path: &NSString) -> Id<Self, Shared> { let this = unsafe { msg_send_id![Self::class(), alloc] }; unsafe { msg_send_id![this, initByReferencingFile: path] } } pub fn new_with_data(data: &NSData) -> Id<Self, Shared> { let this = unsafe { msg_send_id![Self::class(), alloc] }; unsafe { msg_send_id![this, initWithData: data] } } } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/menu.rs
Rust
use objc2::foundation::NSObject; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::NSMenuItem; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSMenu; unsafe impl ClassType for NSMenu { type Super = NSObject; } ); extern_methods!( unsafe impl NSMenu { pub fn new() -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), new] } } #[sel(addItem:)] pub fn addItem(&self, item: &NSMenuItem); } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/menu_item.rs
Rust
use objc2::foundation::{NSObject, NSString}; use objc2::rc::{Id, Shared}; use objc2::runtime::Sel; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{NSEventModifierFlags, NSMenu}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSMenuItem; unsafe impl ClassType for NSMenuItem { type Super = NSObject; } ); extern_methods!( unsafe impl NSMenuItem { pub fn new() -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), new] } } pub fn newWithTitle( title: &NSString, action: Sel, key_equivalent: &NSString, ) -> Id<Self, Shared> { unsafe { msg_send_id![ msg_send_id![Self::class(), alloc], initWithTitle: title, action: action, keyEquivalent: key_equivalent, ] } } pub fn separatorItem() -> Id<Self, Shared> { unsafe { msg_send_id![Self::class(), separatorItem] } } #[sel(setKeyEquivalentModifierMask:)] pub fn setKeyEquivalentModifierMask(&self, mask: NSEventModifierFlags); #[sel(setSubmenu:)] pub fn setSubmenu(&self, submenu: &NSMenu); } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/mod.rs
Rust
//! Safe bindings for the AppKit framework. //! //! These are split out from the rest of `winit` to make safety easier to review. //! In the future, these should probably live in another crate like `cacao`. //! //! TODO: Main thread safety. // Objective-C methods have different conventions, and it's much easier to // understand if we just use the same names #![allow(non_snake_case)] #![allow(clippy::too_many_arguments)] #![allow(clippy::enum_variant_names)] #![allow(non_upper_case_globals)] mod appearance; mod application; mod button; mod color; mod control; mod cursor; mod event; mod image; mod menu; mod menu_item; mod pasteboard; mod responder; mod screen; mod text_input_context; mod version; mod view; mod window; pub(crate) use self::appearance::NSAppearance; pub(crate) use self::application::{ NSApp, NSApplication, NSApplicationActivationPolicy, NSApplicationPresentationOptions, NSRequestUserAttentionType, }; pub(crate) use self::button::NSButton; pub(crate) use self::color::NSColor; pub(crate) use self::control::NSControl; pub(crate) use self::cursor::NSCursor; #[allow(unused_imports)] pub(crate) use self::event::{ NSEvent, NSEventModifierFlags, NSEventPhase, NSEventSubtype, NSEventType, }; pub(crate) use self::image::NSImage; pub(crate) use self::menu::NSMenu; pub(crate) use self::menu_item::NSMenuItem; pub(crate) use self::pasteboard::{NSFilenamesPboardType, NSPasteboard, NSPasteboardType}; pub(crate) use self::responder::NSResponder; #[allow(unused_imports)] pub(crate) use self::screen::{NSDeviceDescriptionKey, NSScreen}; pub(crate) use self::text_input_context::NSTextInputContext; pub(crate) use self::version::NSAppKitVersion; pub(crate) use self::view::{NSTrackingRectTag, NSView}; pub(crate) use self::window::{ NSBackingStoreType, NSWindow, NSWindowButton, NSWindowLevel, NSWindowOcclusionState, NSWindowOrderingMode, NSWindowSharingType, NSWindowStyleMask, NSWindowTitleVisibility, }; #[link(name = "AppKit", kind = "framework")] extern "C" {}
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/pasteboard.rs
Rust
use objc2::foundation::{NSObject, NSString}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSPasteboard; unsafe impl ClassType for NSPasteboard { type Super = NSObject; } ); extern_methods!( unsafe impl NSPasteboard { pub fn propertyListForType(&self, type_: &NSPasteboardType) -> Id<NSObject, Shared> { unsafe { msg_send_id![self, propertyListForType: type_] } } } ); pub type NSPasteboardType = NSString; extern "C" { pub static NSFilenamesPboardType: &'static NSPasteboardType; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/responder.rs
Rust
use objc2::foundation::{NSArray, NSObject}; use objc2::rc::Shared; use objc2::{extern_class, extern_methods, ClassType}; use super::NSEvent; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSResponder; unsafe impl ClassType for NSResponder { type Super = NSObject; } ); // Documented as "Thread-Unsafe". extern_methods!( unsafe impl NSResponder { // TODO: Allow "immutably" on main thread #[sel(interpretKeyEvents:)] pub unsafe fn interpretKeyEvents(&mut self, events: &NSArray<NSEvent, Shared>); } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/screen.rs
Rust
use objc2::foundation::{CGFloat, NSArray, NSDictionary, NSNumber, NSObject, NSRect, NSString}; use objc2::rc::{Id, Shared}; use objc2::runtime::Object; use objc2::{extern_class, extern_methods, msg_send_id, ns_string, ClassType}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSScreen; unsafe impl ClassType for NSScreen { type Super = NSObject; } ); // TODO: Main thread marker! extern_methods!( unsafe impl NSScreen { /// The application object must have been created. pub fn main() -> Option<Id<Self, Shared>> { unsafe { msg_send_id![Self::class(), mainScreen] } } /// The application object must have been created. pub fn screens() -> Id<NSArray<Self, Shared>, Shared> { unsafe { msg_send_id![Self::class(), screens] } } #[sel(frame)] pub fn frame(&self) -> NSRect; #[sel(visibleFrame)] pub fn visibleFrame(&self) -> NSRect; pub fn deviceDescription( &self, ) -> Id<NSDictionary<NSDeviceDescriptionKey, Object>, Shared> { unsafe { msg_send_id![self, deviceDescription] } } pub fn display_id(&self) -> u32 { let key = ns_string!("NSScreenNumber"); objc2::rc::autoreleasepool(|_| { let device_description = self.deviceDescription(); // Retrieve the CGDirectDisplayID associated with this screen // // SAFETY: The value from @"NSScreenNumber" in deviceDescription is guaranteed // to be an NSNumber. See documentation for `deviceDescription` for details: // <https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc> let obj = device_description .get(key) .expect("failed getting screen display id from device description"); let obj: *const Object = obj; let obj: *const NSNumber = obj.cast(); let obj: &NSNumber = unsafe { &*obj }; obj.as_u32() }) } #[sel(backingScaleFactor)] pub fn backingScaleFactor(&self) -> CGFloat; } ); pub type NSDeviceDescriptionKey = NSString;
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/text_input_context.rs
Rust
use objc2::foundation::{NSObject, NSString}; use objc2::rc::{Id, Shared}; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; type NSTextInputSourceIdentifier = NSString; extern_class!( /// Main-Thread-Only! #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSTextInputContext; unsafe impl ClassType for NSTextInputContext { type Super = NSObject; } ); extern_methods!( unsafe impl NSTextInputContext { #[sel(invalidateCharacterCoordinates)] pub fn invalidateCharacterCoordinates(&self); #[sel(discardMarkedText)] pub fn discardMarkedText(&self); pub fn selectedKeyboardInputSource( &self, ) -> Option<Id<NSTextInputSourceIdentifier, Shared>> { unsafe { msg_send_id![self, selectedKeyboardInputSource] } } } );
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/version.rs
Rust
#[repr(transparent)] #[derive(PartialEq, PartialOrd, Debug, Clone, Copy)] pub struct NSAppKitVersion(f64); #[allow(dead_code)] #[allow(non_upper_case_globals)] impl NSAppKitVersion { pub fn current() -> Self { extern "C" { static NSAppKitVersionNumber: NSAppKitVersion; } unsafe { NSAppKitVersionNumber } } pub fn floor(self) -> Self { Self(self.0.floor()) } pub const NSAppKitVersionNumber10_0: Self = Self(577.0); pub const NSAppKitVersionNumber10_1: Self = Self(620.0); pub const NSAppKitVersionNumber10_2: Self = Self(663.0); pub const NSAppKitVersionNumber10_2_3: Self = Self(663.6); pub const NSAppKitVersionNumber10_3: Self = Self(743.0); pub const NSAppKitVersionNumber10_3_2: Self = Self(743.14); pub const NSAppKitVersionNumber10_3_3: Self = Self(743.2); pub const NSAppKitVersionNumber10_3_5: Self = Self(743.24); pub const NSAppKitVersionNumber10_3_7: Self = Self(743.33); pub const NSAppKitVersionNumber10_3_9: Self = Self(743.36); pub const NSAppKitVersionNumber10_4: Self = Self(824.0); pub const NSAppKitVersionNumber10_4_1: Self = Self(824.1); pub const NSAppKitVersionNumber10_4_3: Self = Self(824.23); pub const NSAppKitVersionNumber10_4_4: Self = Self(824.33); pub const NSAppKitVersionNumber10_4_7: Self = Self(824.41); pub const NSAppKitVersionNumber10_5: Self = Self(949.0); pub const NSAppKitVersionNumber10_5_2: Self = Self(949.27); pub const NSAppKitVersionNumber10_5_3: Self = Self(949.33); pub const NSAppKitVersionNumber10_6: Self = Self(1038.0); pub const NSAppKitVersionNumber10_7: Self = Self(1138.0); pub const NSAppKitVersionNumber10_7_2: Self = Self(1138.23); pub const NSAppKitVersionNumber10_7_3: Self = Self(1138.32); pub const NSAppKitVersionNumber10_7_4: Self = Self(1138.47); pub const NSAppKitVersionNumber10_8: Self = Self(1187.0); pub const NSAppKitVersionNumber10_9: Self = Self(1265.0); pub const NSAppKitVersionNumber10_10: Self = Self(1343.0); pub const NSAppKitVersionNumber10_10_2: Self = Self(1344.0); pub const NSAppKitVersionNumber10_10_3: Self = Self(1347.0); pub const NSAppKitVersionNumber10_10_4: Self = Self(1348.0); pub const NSAppKitVersionNumber10_10_5: Self = Self(1348.0); pub const NSAppKitVersionNumber10_10_Max: Self = Self(1349.0); pub const NSAppKitVersionNumber10_11: Self = Self(1404.0); pub const NSAppKitVersionNumber10_11_1: Self = Self(1404.13); pub const NSAppKitVersionNumber10_11_2: Self = Self(1404.34); pub const NSAppKitVersionNumber10_11_3: Self = Self(1404.34); pub const NSAppKitVersionNumber10_12: Self = Self(1504.0); pub const NSAppKitVersionNumber10_12_1: Self = Self(1504.60); pub const NSAppKitVersionNumber10_12_2: Self = Self(1504.76); pub const NSAppKitVersionNumber10_13: Self = Self(1561.0); pub const NSAppKitVersionNumber10_13_1: Self = Self(1561.1); pub const NSAppKitVersionNumber10_13_2: Self = Self(1561.2); pub const NSAppKitVersionNumber10_13_4: Self = Self(1561.4); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/view.rs
Rust
use std::ffi::c_void; use std::num::NonZeroIsize; use std::ptr; use objc2::foundation::{NSObject, NSPoint, NSRect}; use objc2::rc::{Id, Shared}; use objc2::runtime::Object; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{NSCursor, NSResponder, NSTextInputContext, NSWindow}; extern_class!( #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSView; unsafe impl ClassType for NSView { #[inherits(NSObject)] type Super = NSResponder; } ); // Documented as "Main Thread Only". // > generally thread safe, although operations on views such as creating, // > resizing, and moving should happen on the main thread. // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW47> // // > If you want to use a thread to draw to a view, bracket all drawing code // > between the lockFocusIfCanDraw and unlockFocus methods of NSView. // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-123351-BBCFIIEB> extern_methods!( /// Getter methods unsafe impl NSView { #[sel(frame)] pub fn frame(&self) -> NSRect; #[sel(bounds)] pub fn bounds(&self) -> NSRect; pub fn inputContext( &self, // _mtm: MainThreadMarker, ) -> Option<Id<NSTextInputContext, Shared>> { unsafe { msg_send_id![self, inputContext] } } #[sel(visibleRect)] pub fn visibleRect(&self) -> NSRect; #[sel(hasMarkedText)] pub fn hasMarkedText(&self) -> bool; #[sel(convertPoint:fromView:)] pub fn convertPoint_fromView(&self, point: NSPoint, view: Option<&NSView>) -> NSPoint; pub fn window(&self) -> Option<Id<NSWindow, Shared>> { unsafe { msg_send_id![self, window] } } } unsafe impl NSView { #[sel(setWantsBestResolutionOpenGLSurface:)] pub fn setWantsBestResolutionOpenGLSurface(&self, value: bool); #[sel(setWantsLayer:)] pub fn setWantsLayer(&self, wants_layer: bool); #[sel(setPostsFrameChangedNotifications:)] pub fn setPostsFrameChangedNotifications(&mut self, value: bool); #[sel(removeTrackingRect:)] pub fn removeTrackingRect(&self, tag: NSTrackingRectTag); #[sel(addTrackingRect:owner:userData:assumeInside:)] unsafe fn inner_addTrackingRect( &self, rect: NSRect, owner: &Object, user_data: *mut c_void, assume_inside: bool, ) -> Option<NSTrackingRectTag>; pub fn add_tracking_rect(&self, rect: NSRect, assume_inside: bool) -> NSTrackingRectTag { // SAFETY: The user data is NULL, so it is valid unsafe { self.inner_addTrackingRect(rect, self, ptr::null_mut(), assume_inside) } .expect("failed creating tracking rect") } #[sel(addCursorRect:cursor:)] // NSCursor safe to take by shared reference since it is already immutable pub fn addCursorRect(&self, rect: NSRect, cursor: &NSCursor); #[sel(setHidden:)] pub fn setHidden(&self, hidden: bool); } ); /// <https://developer.apple.com/documentation/appkit/nstrackingrecttag?language=objc> pub type NSTrackingRectTag = NonZeroIsize; // NSInteger, but non-zero!
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/appkit/window.rs
Rust
use objc2::encode::{Encode, Encoding}; use objc2::foundation::{ CGFloat, NSArray, NSInteger, NSObject, NSPoint, NSRect, NSSize, NSString, NSUInteger, }; use objc2::rc::{Id, Shared}; use objc2::runtime::Object; use objc2::{extern_class, extern_methods, msg_send_id, ClassType}; use super::{NSButton, NSColor, NSEvent, NSPasteboardType, NSResponder, NSScreen, NSView}; extern_class!( /// Main-Thread-Only! #[derive(Debug, PartialEq, Eq, Hash)] pub(crate) struct NSWindow; unsafe impl ClassType for NSWindow { #[inherits(NSObject)] type Super = NSResponder; } ); // Documented as "Main Thread Only", but: // > Thread safe in that you can create and manage them on a secondary thread. // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW47> // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-123364> // // So could in theory be `Send`, and perhaps also `Sync` - but we would like // interior mutability on windows, since that's just much easier, and in that // case, they can't be! extern_methods!( unsafe impl NSWindow { #[sel(frame)] pub fn frame(&self) -> NSRect; #[sel(backingScaleFactor)] pub fn backingScaleFactor(&self) -> CGFloat; pub fn contentView(&self) -> Id<NSView, Shared> { unsafe { msg_send_id![self, contentView] } } #[sel(setContentView:)] pub fn setContentView(&self, view: &NSView); #[sel(setInitialFirstResponder:)] pub fn setInitialFirstResponder(&self, view: &NSView); #[sel(makeFirstResponder:)] #[must_use] pub fn makeFirstResponder(&self, responder: Option<&NSResponder>) -> bool; #[sel(contentRectForFrameRect:)] pub fn contentRectForFrameRect(&self, windowFrame: NSRect) -> NSRect; pub fn screen(&self) -> Option<Id<NSScreen, Shared>> { unsafe { msg_send_id![self, screen] } } #[sel(setContentSize:)] pub fn setContentSize(&self, contentSize: NSSize); #[sel(setFrameTopLeftPoint:)] pub fn setFrameTopLeftPoint(&self, point: NSPoint); #[sel(setMinSize:)] pub fn setMinSize(&self, minSize: NSSize); #[sel(setMaxSize:)] pub fn setMaxSize(&self, maxSize: NSSize); #[sel(setResizeIncrements:)] pub fn setResizeIncrements(&self, increments: NSSize); #[sel(contentResizeIncrements)] pub fn contentResizeIncrements(&self) -> NSSize; #[sel(setContentResizeIncrements:)] pub fn setContentResizeIncrements(&self, increments: NSSize); #[sel(setFrame:display:)] pub fn setFrame_display(&self, frameRect: NSRect, flag: bool); #[sel(setMovable:)] pub fn setMovable(&self, movable: bool); #[sel(setSharingType:)] pub fn setSharingType(&self, sharingType: NSWindowSharingType); #[sel(setOpaque:)] pub fn setOpaque(&self, opaque: bool); #[sel(hasShadow)] pub fn hasShadow(&self) -> bool; #[sel(setHasShadow:)] pub fn setHasShadow(&self, has_shadow: bool); #[sel(setIgnoresMouseEvents:)] pub fn setIgnoresMouseEvents(&self, ignores: bool); #[sel(setBackgroundColor:)] pub fn setBackgroundColor(&self, color: &NSColor); #[sel(styleMask)] pub fn styleMask(&self) -> NSWindowStyleMask; #[sel(setStyleMask:)] pub fn setStyleMask(&self, mask: NSWindowStyleMask); #[sel(registerForDraggedTypes:)] pub fn registerForDraggedTypes(&self, types: &NSArray<NSPasteboardType>); #[sel(makeKeyAndOrderFront:)] pub fn makeKeyAndOrderFront(&self, sender: Option<&Object>); #[sel(orderFront:)] pub fn orderFront(&self, sender: Option<&Object>); #[sel(miniaturize:)] pub fn miniaturize(&self, sender: Option<&Object>); #[sel(sender:)] pub fn deminiaturize(&self, sender: Option<&Object>); #[sel(toggleFullScreen:)] pub fn toggleFullScreen(&self, sender: Option<&Object>); #[sel(orderOut:)] pub fn orderOut(&self, sender: Option<&Object>); #[sel(zoom:)] pub fn zoom(&self, sender: Option<&Object>); #[sel(selectNextKeyView:)] pub fn selectNextKeyView(&self, sender: Option<&Object>); #[sel(selectPreviousKeyView:)] pub fn selectPreviousKeyView(&self, sender: Option<&Object>); pub fn firstResponder(&self) -> Option<Id<NSResponder, Shared>> { unsafe { msg_send_id![self, firstResponder] } } pub fn standardWindowButton(&self, kind: NSWindowButton) -> Option<Id<NSButton, Shared>> { unsafe { msg_send_id![self, standardWindowButton: kind] } } #[sel(setTitle:)] pub fn setTitle(&self, title: &NSString); pub fn title_(&self) -> Id<NSString, Shared> { unsafe { msg_send_id![self, title] } } #[sel(setReleasedWhenClosed:)] pub fn setReleasedWhenClosed(&self, val: bool); #[sel(setAcceptsMouseMovedEvents:)] pub fn setAcceptsMouseMovedEvents(&self, val: bool); #[sel(setTitlebarAppearsTransparent:)] pub fn setTitlebarAppearsTransparent(&self, val: bool); #[sel(setTitleVisibility:)] pub fn setTitleVisibility(&self, visibility: NSWindowTitleVisibility); #[sel(setMovableByWindowBackground:)] pub fn setMovableByWindowBackground(&self, val: bool); #[sel(setLevel:)] pub fn setLevel(&self, level: NSWindowLevel); #[sel(setDocumentEdited:)] pub fn setDocumentEdited(&self, val: bool); #[sel(occlusionState)] pub fn occlusionState(&self) -> NSWindowOcclusionState; #[sel(center)] pub fn center(&self); #[sel(isResizable)] pub fn isResizable(&self) -> bool; #[sel(isMiniaturizable)] pub fn isMiniaturizable(&self) -> bool; #[sel(hasCloseBox)] pub fn hasCloseBox(&self) -> bool; #[sel(isMiniaturized)] pub fn isMiniaturized(&self) -> bool; #[sel(isVisible)] pub fn isVisible(&self) -> bool; #[sel(isKeyWindow)] pub fn isKeyWindow(&self) -> bool; #[sel(isZoomed)] pub fn isZoomed(&self) -> bool; #[sel(isDocumentEdited)] pub fn isDocumentEdited(&self) -> bool; #[sel(close)] pub fn close(&self); #[sel(performWindowDragWithEvent:)] // TODO: Can this actually accept NULL? pub fn performWindowDragWithEvent(&self, event: Option<&NSEvent>); #[sel(invalidateCursorRectsForView:)] pub fn invalidateCursorRectsForView(&self, view: &NSView); #[sel(setDelegate:)] pub fn setDelegate(&self, delegate: Option<&NSObject>); #[sel(sendEvent:)] pub unsafe fn sendEvent(&self, event: &NSEvent); #[sel(addChildWindow:ordered:)] pub unsafe fn addChildWindow(&self, child: &NSWindow, ordered: NSWindowOrderingMode); } ); #[allow(dead_code)] #[repr(isize)] // NSInteger #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSWindowTitleVisibility { #[doc(alias = "NSWindowTitleVisible")] Visible = 0, #[doc(alias = "NSWindowTitleHidden")] Hidden = 1, } unsafe impl Encode for NSWindowTitleVisibility { const ENCODING: Encoding = NSInteger::ENCODING; } #[allow(dead_code)] #[repr(usize)] // NSUInteger #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSWindowButton { #[doc(alias = "NSWindowCloseButton")] Close = 0, #[doc(alias = "NSWindowMiniaturizeButton")] Miniaturize = 1, #[doc(alias = "NSWindowZoomButton")] Zoom = 2, #[doc(alias = "NSWindowToolbarButton")] Toolbar = 3, #[doc(alias = "NSWindowDocumentIconButton")] DocumentIcon = 4, #[doc(alias = "NSWindowDocumentVersionsButton")] DocumentVersions = 6, #[doc(alias = "NSWindowFullScreenButton")] #[deprecated = "Deprecated since macOS 10.12"] FullScreen = 7, } unsafe impl Encode for NSWindowButton { const ENCODING: Encoding = NSUInteger::ENCODING; } // CGWindowLevel.h // // Note: There are two different things at play in this header: // `CGWindowLevel` and `CGWindowLevelKey`. // // It seems like there was a push towards using "key" values instead of the // raw window level values, and then you were supposed to use // `CGWindowLevelForKey` to get the actual level. // // But the values that `NSWindowLevel` has are compiled in, and as such has // to remain ABI compatible, so they're safe for us to hardcode as well. #[allow(dead_code)] mod window_level { const kCGNumReservedWindowLevels: i32 = 16; const kCGNumReservedBaseWindowLevels: i32 = 5; pub const kCGBaseWindowLevel: i32 = i32::MIN; pub const kCGMinimumWindowLevel: i32 = kCGBaseWindowLevel + kCGNumReservedBaseWindowLevels; pub const kCGMaximumWindowLevel: i32 = i32::MAX - kCGNumReservedWindowLevels; pub const kCGDesktopWindowLevel: i32 = kCGMinimumWindowLevel + 20; pub const kCGDesktopIconWindowLevel: i32 = kCGDesktopWindowLevel + 20; pub const kCGBackstopMenuLevel: i32 = -20; pub const kCGNormalWindowLevel: i32 = 0; pub const kCGFloatingWindowLevel: i32 = 3; pub const kCGTornOffMenuWindowLevel: i32 = 3; pub const kCGModalPanelWindowLevel: i32 = 8; pub const kCGUtilityWindowLevel: i32 = 19; pub const kCGDockWindowLevel: i32 = 20; pub const kCGMainMenuWindowLevel: i32 = 24; pub const kCGStatusWindowLevel: i32 = 25; pub const kCGPopUpMenuWindowLevel: i32 = 101; pub const kCGOverlayWindowLevel: i32 = 102; pub const kCGHelpWindowLevel: i32 = 200; pub const kCGDraggingWindowLevel: i32 = 500; pub const kCGScreenSaverWindowLevel: i32 = 1000; pub const kCGAssistiveTechHighWindowLevel: i32 = 1500; pub const kCGCursorWindowLevel: i32 = kCGMaximumWindowLevel - 1; } use window_level::*; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(transparent)] pub struct NSWindowLevel(pub NSInteger); #[allow(dead_code)] impl NSWindowLevel { #[doc(alias = "BelowNormalWindowLevel")] pub const BELOW_NORMAL: Self = Self((kCGNormalWindowLevel - 1) as _); #[doc(alias = "NSNormalWindowLevel")] pub const Normal: Self = Self(kCGNormalWindowLevel as _); #[doc(alias = "NSFloatingWindowLevel")] pub const Floating: Self = Self(kCGFloatingWindowLevel as _); #[doc(alias = "NSTornOffMenuWindowLevel")] pub const TornOffMenu: Self = Self(kCGTornOffMenuWindowLevel as _); #[doc(alias = "NSModalPanelWindowLevel")] pub const ModalPanel: Self = Self(kCGModalPanelWindowLevel as _); #[doc(alias = "NSMainMenuWindowLevel")] pub const MainMenu: Self = Self(kCGMainMenuWindowLevel as _); #[doc(alias = "NSStatusWindowLevel")] pub const Status: Self = Self(kCGStatusWindowLevel as _); #[doc(alias = "NSPopUpMenuWindowLevel")] pub const PopUpMenu: Self = Self(kCGPopUpMenuWindowLevel as _); #[doc(alias = "NSScreenSaverWindowLevel")] pub const ScreenSaver: Self = Self(kCGScreenSaverWindowLevel as _); } unsafe impl Encode for NSWindowLevel { const ENCODING: Encoding = NSInteger::ENCODING; } bitflags! { pub struct NSWindowOcclusionState: NSUInteger { const NSWindowOcclusionStateVisible = 1 << 1; } } unsafe impl Encode for NSWindowOcclusionState { const ENCODING: Encoding = NSUInteger::ENCODING; } bitflags! { pub struct NSWindowStyleMask: NSUInteger { const NSBorderlessWindowMask = 0; const NSTitledWindowMask = 1 << 0; const NSClosableWindowMask = 1 << 1; const NSMiniaturizableWindowMask = 1 << 2; const NSResizableWindowMask = 1 << 3; const NSTexturedBackgroundWindowMask = 1 << 8; const NSUnifiedTitleAndToolbarWindowMask = 1 << 12; const NSFullScreenWindowMask = 1 << 14; const NSFullSizeContentViewWindowMask = 1 << 15; } } unsafe impl Encode for NSWindowStyleMask { const ENCODING: Encoding = NSUInteger::ENCODING; } #[allow(dead_code)] #[repr(usize)] // NSUInteger #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSBackingStoreType { NSBackingStoreRetained = 0, NSBackingStoreNonretained = 1, NSBackingStoreBuffered = 2, } unsafe impl Encode for NSBackingStoreType { const ENCODING: Encoding = NSUInteger::ENCODING; } #[allow(dead_code)] #[repr(usize)] // NSUInteger #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSWindowSharingType { NSWindowSharingNone = 0, NSWindowSharingReadOnly = 1, NSWindowSharingReadWrite = 2, } unsafe impl Encode for NSWindowSharingType { const ENCODING: Encoding = NSUInteger::ENCODING; } #[allow(dead_code)] #[repr(isize)] // NSInteger #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NSWindowOrderingMode { NSWindowAbove = 1, NSWindowBelow = -1, NSWindowOut = 0, } unsafe impl Encode for NSWindowOrderingMode { const ENCODING: Encoding = NSInteger::ENCODING; }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/event.rs
Rust
use std::os::raw::c_ushort; use objc2::rc::{Id, Shared}; use super::appkit::{NSEvent, NSEventModifierFlags}; use super::window::WinitWindow; use crate::{ dpi::LogicalSize, event::{ElementState, Event, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent}, platform_impl::platform::{util::Never, DEVICE_ID}, }; #[derive(Debug)] pub(crate) enum EventWrapper { StaticEvent(Event<'static, Never>), EventProxy(EventProxy), } #[derive(Debug)] pub(crate) enum EventProxy { DpiChangedProxy { window: Id<WinitWindow, Shared>, suggested_size: LogicalSize<f64>, scale_factor: f64, }, } pub fn char_to_keycode(c: char) -> Option<VirtualKeyCode> { // We only translate keys that are affected by keyboard layout. // // Note that since keys are translated in a somewhat "dumb" way (reading character) // there is a concern that some combination, i.e. Cmd+char, causes the wrong // letter to be received, and so we receive the wrong key. // // Implementation reference: https://github.com/WebKit/webkit/blob/82bae82cf0f329dbe21059ef0986c4e92fea4ba6/Source/WebCore/platform/cocoa/KeyEventCocoa.mm#L626 Some(match c { 'a' | 'A' => VirtualKeyCode::A, 'b' | 'B' => VirtualKeyCode::B, 'c' | 'C' => VirtualKeyCode::C, 'd' | 'D' => VirtualKeyCode::D, 'e' | 'E' => VirtualKeyCode::E, 'f' | 'F' => VirtualKeyCode::F, 'g' | 'G' => VirtualKeyCode::G, 'h' | 'H' => VirtualKeyCode::H, 'i' | 'I' => VirtualKeyCode::I, 'j' | 'J' => VirtualKeyCode::J, 'k' | 'K' => VirtualKeyCode::K, 'l' | 'L' => VirtualKeyCode::L, 'm' | 'M' => VirtualKeyCode::M, 'n' | 'N' => VirtualKeyCode::N, 'o' | 'O' => VirtualKeyCode::O, 'p' | 'P' => VirtualKeyCode::P, 'q' | 'Q' => VirtualKeyCode::Q, 'r' | 'R' => VirtualKeyCode::R, 's' | 'S' => VirtualKeyCode::S, 't' | 'T' => VirtualKeyCode::T, 'u' | 'U' => VirtualKeyCode::U, 'v' | 'V' => VirtualKeyCode::V, 'w' | 'W' => VirtualKeyCode::W, 'x' | 'X' => VirtualKeyCode::X, 'y' | 'Y' => VirtualKeyCode::Y, 'z' | 'Z' => VirtualKeyCode::Z, '1' | '!' => VirtualKeyCode::Key1, '2' | '@' => VirtualKeyCode::Key2, '3' | '#' => VirtualKeyCode::Key3, '4' | '$' => VirtualKeyCode::Key4, '5' | '%' => VirtualKeyCode::Key5, '6' | '^' => VirtualKeyCode::Key6, '7' | '&' => VirtualKeyCode::Key7, '8' | '*' => VirtualKeyCode::Key8, '9' | '(' => VirtualKeyCode::Key9, '0' | ')' => VirtualKeyCode::Key0, '=' | '+' => VirtualKeyCode::Equals, '-' | '_' => VirtualKeyCode::Minus, ']' | '}' => VirtualKeyCode::RBracket, '[' | '{' => VirtualKeyCode::LBracket, '\'' | '"' => VirtualKeyCode::Apostrophe, ';' | ':' => VirtualKeyCode::Semicolon, '\\' | '|' => VirtualKeyCode::Backslash, ',' | '<' => VirtualKeyCode::Comma, '/' | '?' => VirtualKeyCode::Slash, '.' | '>' => VirtualKeyCode::Period, '`' | '~' => VirtualKeyCode::Grave, _ => return None, }) } pub fn scancode_to_keycode(scancode: c_ushort) -> Option<VirtualKeyCode> { Some(match scancode { 0x00 => VirtualKeyCode::A, 0x01 => VirtualKeyCode::S, 0x02 => VirtualKeyCode::D, 0x03 => VirtualKeyCode::F, 0x04 => VirtualKeyCode::H, 0x05 => VirtualKeyCode::G, 0x06 => VirtualKeyCode::Z, 0x07 => VirtualKeyCode::X, 0x08 => VirtualKeyCode::C, 0x09 => VirtualKeyCode::V, //0x0a => World 1, 0x0b => VirtualKeyCode::B, 0x0c => VirtualKeyCode::Q, 0x0d => VirtualKeyCode::W, 0x0e => VirtualKeyCode::E, 0x0f => VirtualKeyCode::R, 0x10 => VirtualKeyCode::Y, 0x11 => VirtualKeyCode::T, 0x12 => VirtualKeyCode::Key1, 0x13 => VirtualKeyCode::Key2, 0x14 => VirtualKeyCode::Key3, 0x15 => VirtualKeyCode::Key4, 0x16 => VirtualKeyCode::Key6, 0x17 => VirtualKeyCode::Key5, 0x18 => VirtualKeyCode::Equals, 0x19 => VirtualKeyCode::Key9, 0x1a => VirtualKeyCode::Key7, 0x1b => VirtualKeyCode::Minus, 0x1c => VirtualKeyCode::Key8, 0x1d => VirtualKeyCode::Key0, 0x1e => VirtualKeyCode::RBracket, 0x1f => VirtualKeyCode::O, 0x20 => VirtualKeyCode::U, 0x21 => VirtualKeyCode::LBracket, 0x22 => VirtualKeyCode::I, 0x23 => VirtualKeyCode::P, 0x24 => VirtualKeyCode::Return, 0x25 => VirtualKeyCode::L, 0x26 => VirtualKeyCode::J, 0x27 => VirtualKeyCode::Apostrophe, 0x28 => VirtualKeyCode::K, 0x29 => VirtualKeyCode::Semicolon, 0x2a => VirtualKeyCode::Backslash, 0x2b => VirtualKeyCode::Comma, 0x2c => VirtualKeyCode::Slash, 0x2d => VirtualKeyCode::N, 0x2e => VirtualKeyCode::M, 0x2f => VirtualKeyCode::Period, 0x30 => VirtualKeyCode::Tab, 0x31 => VirtualKeyCode::Space, 0x32 => VirtualKeyCode::Grave, 0x33 => VirtualKeyCode::Back, //0x34 => unkown, 0x35 => VirtualKeyCode::Escape, 0x36 => VirtualKeyCode::RWin, 0x37 => VirtualKeyCode::LWin, 0x38 => VirtualKeyCode::LShift, //0x39 => Caps lock, 0x3a => VirtualKeyCode::LAlt, 0x3b => VirtualKeyCode::LControl, 0x3c => VirtualKeyCode::RShift, 0x3d => VirtualKeyCode::RAlt, 0x3e => VirtualKeyCode::RControl, //0x3f => Fn key, 0x40 => VirtualKeyCode::F17, 0x41 => VirtualKeyCode::NumpadDecimal, //0x42 -> unkown, 0x43 => VirtualKeyCode::NumpadMultiply, //0x44 => unkown, 0x45 => VirtualKeyCode::NumpadAdd, //0x46 => unkown, 0x47 => VirtualKeyCode::Numlock, //0x48 => KeypadClear, 0x49 => VirtualKeyCode::VolumeUp, 0x4a => VirtualKeyCode::VolumeDown, 0x4b => VirtualKeyCode::NumpadDivide, 0x4c => VirtualKeyCode::NumpadEnter, //0x4d => unkown, 0x4e => VirtualKeyCode::NumpadSubtract, 0x4f => VirtualKeyCode::F18, 0x50 => VirtualKeyCode::F19, 0x51 => VirtualKeyCode::NumpadEquals, 0x52 => VirtualKeyCode::Numpad0, 0x53 => VirtualKeyCode::Numpad1, 0x54 => VirtualKeyCode::Numpad2, 0x55 => VirtualKeyCode::Numpad3, 0x56 => VirtualKeyCode::Numpad4, 0x57 => VirtualKeyCode::Numpad5, 0x58 => VirtualKeyCode::Numpad6, 0x59 => VirtualKeyCode::Numpad7, 0x5a => VirtualKeyCode::F20, 0x5b => VirtualKeyCode::Numpad8, 0x5c => VirtualKeyCode::Numpad9, 0x5d => VirtualKeyCode::Yen, //0x5e => JIS Ro, //0x5f => unkown, 0x60 => VirtualKeyCode::F5, 0x61 => VirtualKeyCode::F6, 0x62 => VirtualKeyCode::F7, 0x63 => VirtualKeyCode::F3, 0x64 => VirtualKeyCode::F8, 0x65 => VirtualKeyCode::F9, //0x66 => JIS Eisuu (macOS), 0x67 => VirtualKeyCode::F11, //0x68 => JIS Kanna (macOS), 0x69 => VirtualKeyCode::F13, 0x6a => VirtualKeyCode::F16, 0x6b => VirtualKeyCode::F14, //0x6c => unkown, 0x6d => VirtualKeyCode::F10, //0x6e => unkown, 0x6f => VirtualKeyCode::F12, //0x70 => unkown, 0x71 => VirtualKeyCode::F15, 0x72 => VirtualKeyCode::Insert, 0x73 => VirtualKeyCode::Home, 0x74 => VirtualKeyCode::PageUp, 0x75 => VirtualKeyCode::Delete, 0x76 => VirtualKeyCode::F4, 0x77 => VirtualKeyCode::End, 0x78 => VirtualKeyCode::F2, 0x79 => VirtualKeyCode::PageDown, 0x7a => VirtualKeyCode::F1, 0x7b => VirtualKeyCode::Left, 0x7c => VirtualKeyCode::Right, 0x7d => VirtualKeyCode::Down, 0x7e => VirtualKeyCode::Up, //0x7f => unkown, 0xa => VirtualKeyCode::Caret, _ => return None, }) } // While F1-F20 have scancodes we can match on, we have to check against UTF-16 // constants for the rest. // https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?preferredLanguage=occ pub fn check_function_keys(string: &str) -> Option<VirtualKeyCode> { if let Some(ch) = string.encode_utf16().next() { return Some(match ch { 0xf718 => VirtualKeyCode::F21, 0xf719 => VirtualKeyCode::F22, 0xf71a => VirtualKeyCode::F23, 0xf71b => VirtualKeyCode::F24, _ => return None, }); } None } pub(super) fn event_mods(event: &NSEvent) -> ModifiersState { let flags = event.modifierFlags(); let mut m = ModifiersState::empty(); m.set( ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::NSShiftKeyMask), ); m.set( ModifiersState::CTRL, flags.contains(NSEventModifierFlags::NSControlKeyMask), ); m.set( ModifiersState::ALT, flags.contains(NSEventModifierFlags::NSAlternateKeyMask), ); m.set( ModifiersState::LOGO, flags.contains(NSEventModifierFlags::NSCommandKeyMask), ); m } pub(super) fn modifier_event( event: &NSEvent, keymask: NSEventModifierFlags, was_key_pressed: bool, ) -> Option<WindowEvent<'static>> { if !was_key_pressed && event.modifierFlags().contains(keymask) || was_key_pressed && !event.modifierFlags().contains(keymask) { let state = if was_key_pressed { ElementState::Released } else { ElementState::Pressed }; let scancode = event.scancode(); let virtual_keycode = scancode_to_keycode(scancode); #[allow(deprecated)] Some(WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { state, scancode: scancode as _, virtual_keycode, modifiers: event_mods(event), }, is_synthetic: false, }) } else { None } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/event_loop.rs
Rust
use std::{ any::Any, cell::{Cell, RefCell}, collections::VecDeque, marker::PhantomData, mem, os::raw::c_void, panic::{catch_unwind, resume_unwind, RefUnwindSafe, UnwindSafe}, process, ptr, rc::{Rc, Weak}, sync::mpsc, }; use core_foundation::base::{CFIndex, CFRelease}; use core_foundation::runloop::{ kCFRunLoopCommonModes, CFRunLoopAddSource, CFRunLoopGetMain, CFRunLoopSourceContext, CFRunLoopSourceCreate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp, }; use objc2::foundation::is_main_thread; use objc2::rc::{autoreleasepool, Id, Shared}; use objc2::{msg_send_id, ClassType}; use raw_window_handle::{AppKitDisplayHandle, RawDisplayHandle}; use super::appkit::{NSApp, NSApplicationActivationPolicy, NSEvent}; use crate::{ event::Event, event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootWindowTarget}, platform::macos::ActivationPolicy, platform_impl::platform::{ app::WinitApplication, app_delegate::ApplicationDelegate, app_state::{AppState, Callback}, monitor::{self, MonitorHandle}, observer::setup_control_flow_observers, }, }; #[derive(Default)] pub struct PanicInfo { inner: Cell<Option<Box<dyn Any + Send + 'static>>>, } // WARNING: // As long as this struct is used through its `impl`, it is UnwindSafe. // (If `get_mut` is called on `inner`, unwind safety may get broken.) impl UnwindSafe for PanicInfo {} impl RefUnwindSafe for PanicInfo {} impl PanicInfo { pub fn is_panicking(&self) -> bool { let inner = self.inner.take(); let result = inner.is_some(); self.inner.set(inner); result } /// Overwrites the curret state if the current state is not panicking pub fn set_panic(&self, p: Box<dyn Any + Send + 'static>) { if !self.is_panicking() { self.inner.set(Some(p)); } } pub fn take(&self) -> Option<Box<dyn Any + Send + 'static>> { self.inner.take() } } pub struct EventLoopWindowTarget<T: 'static> { pub sender: mpsc::Sender<T>, // this is only here to be cloned elsewhere pub receiver: mpsc::Receiver<T>, } impl<T> Default for EventLoopWindowTarget<T> { fn default() -> Self { let (sender, receiver) = mpsc::channel(); EventLoopWindowTarget { sender, receiver } } } impl<T: 'static> EventLoopWindowTarget<T> { #[inline] pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { monitor::available_monitors() } #[inline] pub fn primary_monitor(&self) -> Option<MonitorHandle> { let monitor = monitor::primary_monitor(); Some(monitor) } #[inline] pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::AppKit(AppKitDisplayHandle::empty()) } } impl<T> EventLoopWindowTarget<T> { pub(crate) fn hide_application(&self) { NSApp().hide(None) } pub(crate) fn hide_other_applications(&self) { NSApp().hideOtherApplications(None) } } pub struct EventLoop<T: 'static> { /// The delegate is only weakly referenced by NSApplication, so we keep /// it around here as well. _delegate: Id<ApplicationDelegate, Shared>, window_target: Rc<RootWindowTarget<T>>, panic_info: Rc<PanicInfo>, /// We make sure that the callback closure is dropped during a panic /// by making the event loop own it. /// /// Every other reference should be a Weak reference which is only upgraded /// into a strong reference in order to call the callback but then the /// strong reference should be dropped as soon as possible. _callback: Option<Rc<Callback<T>>>, } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) struct PlatformSpecificEventLoopAttributes { pub(crate) activation_policy: ActivationPolicy, pub(crate) default_menu: bool, pub(crate) activate_ignoring_other_apps: bool, } impl Default for PlatformSpecificEventLoopAttributes { fn default() -> Self { Self { activation_policy: Default::default(), // Regular default_menu: true, activate_ignoring_other_apps: true, } } } impl<T> EventLoop<T> { pub(crate) fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Self { if !is_main_thread() { panic!("On macOS, `EventLoop` must be created on the main thread!"); } // This must be done before `NSApp()` (equivalent to sending // `sharedApplication`) is called anywhere else, or we'll end up // with the wrong `NSApplication` class and the wrong thread could // be marked as main. let app: Id<WinitApplication, Shared> = unsafe { msg_send_id![WinitApplication::class(), sharedApplication] }; use NSApplicationActivationPolicy::*; let activation_policy = match attributes.activation_policy { ActivationPolicy::Regular => NSApplicationActivationPolicyRegular, ActivationPolicy::Accessory => NSApplicationActivationPolicyAccessory, ActivationPolicy::Prohibited => NSApplicationActivationPolicyProhibited, }; let delegate = ApplicationDelegate::new( activation_policy, attributes.default_menu, attributes.activate_ignoring_other_apps, ); autoreleasepool(|_| { app.setDelegate(&delegate); }); let panic_info: Rc<PanicInfo> = Default::default(); setup_control_flow_observers(Rc::downgrade(&panic_info)); EventLoop { _delegate: delegate, window_target: Rc::new(RootWindowTarget { p: Default::default(), _marker: PhantomData, }), panic_info, _callback: None, } } pub fn window_target(&self) -> &RootWindowTarget<T> { &self.window_target } pub fn run<F>(mut self, callback: F) -> ! where F: 'static + FnMut(Event<'_, T>, &RootWindowTarget<T>, &mut ControlFlow), { let exit_code = self.run_return(callback); process::exit(exit_code); } pub fn run_return<F>(&mut self, callback: F) -> i32 where F: FnMut(Event<'_, T>, &RootWindowTarget<T>, &mut ControlFlow), { // This transmute is always safe, in case it was reached through `run`, since our // lifetime will be already 'static. In other cases caller should ensure that all data // they passed to callback will actually outlive it, some apps just can't move // everything to event loop, so this is something that they should care about. let callback = unsafe { mem::transmute::< Rc<RefCell<dyn FnMut(Event<'_, T>, &RootWindowTarget<T>, &mut ControlFlow)>>, Rc<RefCell<dyn FnMut(Event<'_, T>, &RootWindowTarget<T>, &mut ControlFlow)>>, >(Rc::new(RefCell::new(callback))) }; self._callback = Some(Rc::clone(&callback)); let exit_code = autoreleasepool(|_| { let app = NSApp(); // A bit of juggling with the callback references to make sure // that `self.callback` is the only owner of the callback. let weak_cb: Weak<_> = Rc::downgrade(&callback); drop(callback); AppState::set_callback(weak_cb, Rc::clone(&self.window_target)); unsafe { app.run() }; if let Some(panic) = self.panic_info.take() { drop(self._callback.take()); resume_unwind(panic); } AppState::exit() }); drop(self._callback.take()); exit_code } pub fn create_proxy(&self) -> EventLoopProxy<T> { EventLoopProxy::new(self.window_target.p.sender.clone()) } } /// Catches panics that happen inside `f` and when a panic /// happens, stops the `sharedApplication` #[inline] pub fn stop_app_on_panic<F: FnOnce() -> R + UnwindSafe, R>( panic_info: Weak<PanicInfo>, f: F, ) -> Option<R> { match catch_unwind(f) { Ok(r) => Some(r), Err(e) => { // It's important that we set the panic before requesting a `stop` // because some callback are still called during the `stop` message // and we need to know in those callbacks if the application is currently // panicking { let panic_info = panic_info.upgrade().unwrap(); panic_info.set_panic(e); } let app = NSApp(); app.stop(None); // Posting a dummy event to get `stop` to take effect immediately. // See: https://stackoverflow.com/questions/48041279/stopping-the-nsapplication-main-event-loop/48064752#48064752 app.postEvent_atStart(&NSEvent::dummy(), true); None } } } pub struct EventLoopProxy<T> { sender: mpsc::Sender<T>, source: CFRunLoopSourceRef, } unsafe impl<T: Send> Send for EventLoopProxy<T> {} impl<T> Drop for EventLoopProxy<T> { fn drop(&mut self) { unsafe { CFRelease(self.source as _); } } } impl<T> Clone for EventLoopProxy<T> { fn clone(&self) -> Self { EventLoopProxy::new(self.sender.clone()) } } impl<T> EventLoopProxy<T> { fn new(sender: mpsc::Sender<T>) -> Self { unsafe { // just wake up the eventloop extern "C" fn event_loop_proxy_handler(_: *const c_void) {} // adding a Source to the main CFRunLoop lets us wake it up and // process user events through the normal OS EventLoop mechanisms. let rl = CFRunLoopGetMain(); let mut context = CFRunLoopSourceContext { version: 0, info: ptr::null_mut(), retain: None, release: None, copyDescription: None, equal: None, hash: None, schedule: None, cancel: None, perform: event_loop_proxy_handler, }; let source = CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::max_value() - 1, &mut context); CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); CFRunLoopWakeUp(rl); EventLoopProxy { sender, source } } } pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { self.sender .send(event) .map_err(|mpsc::SendError(x)| EventLoopClosed(x))?; unsafe { // let the main thread know there's a new event CFRunLoopSourceSignal(self.source); let rl = CFRunLoopGetMain(); CFRunLoopWakeUp(rl); } Ok(()) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/ffi.rs
Rust
// TODO: Upstream these #![allow(dead_code, non_snake_case, non_upper_case_globals)] use std::ffi::c_void; use core_foundation::{ array::CFArrayRef, dictionary::CFDictionaryRef, string::CFStringRef, uuid::CFUUIDRef, }; use core_graphics::{ base::CGError, display::{CGDirectDisplayID, CGDisplayConfigRef}, }; pub type CGDisplayFadeInterval = f32; pub type CGDisplayReservationInterval = f32; pub type CGDisplayBlendFraction = f32; pub const kCGDisplayBlendNormal: f32 = 0.0; pub const kCGDisplayBlendSolidColor: f32 = 1.0; pub type CGDisplayFadeReservationToken = u32; pub const kCGDisplayFadeReservationInvalidToken: CGDisplayFadeReservationToken = 0; pub type Boolean = u8; pub const FALSE: Boolean = 0; pub const TRUE: Boolean = 1; pub const kCGErrorSuccess: i32 = 0; pub const kCGErrorFailure: i32 = 1000; pub const kCGErrorIllegalArgument: i32 = 1001; pub const kCGErrorInvalidConnection: i32 = 1002; pub const kCGErrorInvalidContext: i32 = 1003; pub const kCGErrorCannotComplete: i32 = 1004; pub const kCGErrorNotImplemented: i32 = 1006; pub const kCGErrorRangeCheck: i32 = 1007; pub const kCGErrorTypeCheck: i32 = 1008; pub const kCGErrorInvalidOperation: i32 = 1010; pub const kCGErrorNoneAvailable: i32 = 1011; pub const IO1BitIndexedPixels: &str = "P"; pub const IO2BitIndexedPixels: &str = "PP"; pub const IO4BitIndexedPixels: &str = "PPPP"; pub const IO8BitIndexedPixels: &str = "PPPPPPPP"; pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB"; pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB"; pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB"; pub const kIO64BitDirectPixels: &str = "-16R16G16B16"; pub const kIO16BitFloatPixels: &str = "-16FR16FG16FB16"; pub const kIO32BitFloatPixels: &str = "-32FR32FG32FB32"; pub const IOYUV422Pixels: &str = "Y4U2V2"; pub const IO8BitOverlayPixels: &str = "O8"; pub type CGWindowLevel = i32; pub type CGDisplayModeRef = *mut c_void; // `CGDisplayCreateUUIDFromDisplayID` comes from the `ColorSync` framework. // However, that framework was only introduced "publicly" in macOS 10.13. // // Since we want to support older versions, we can't link to `ColorSync` // directly. Fortunately, it has always been available as a subframework of // `ApplicationServices`, see: // https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/OSX_Technology_Overview/SystemFrameworks/SystemFrameworks.html#//apple_ref/doc/uid/TP40001067-CH210-BBCFFIEG #[link(name = "ApplicationServices", kind = "framework")] extern "C" { pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef; } #[link(name = "CoreGraphics", kind = "framework")] extern "C" { pub fn CGRestorePermanentDisplayConfiguration(); pub fn CGDisplayCapture(display: CGDirectDisplayID) -> CGError; pub fn CGDisplayRelease(display: CGDirectDisplayID) -> CGError; pub fn CGConfigureDisplayFadeEffect( config: CGDisplayConfigRef, fadeOutSeconds: CGDisplayFadeInterval, fadeInSeconds: CGDisplayFadeInterval, fadeRed: f32, fadeGreen: f32, fadeBlue: f32, ) -> CGError; pub fn CGAcquireDisplayFadeReservation( seconds: CGDisplayReservationInterval, token: *mut CGDisplayFadeReservationToken, ) -> CGError; pub fn CGDisplayFade( token: CGDisplayFadeReservationToken, duration: CGDisplayFadeInterval, startBlend: CGDisplayBlendFraction, endBlend: CGDisplayBlendFraction, redBlend: f32, greenBlend: f32, blueBlend: f32, synchronous: Boolean, ) -> CGError; pub fn CGReleaseDisplayFadeReservation(token: CGDisplayFadeReservationToken) -> CGError; pub fn CGShieldingWindowLevel() -> CGWindowLevel; pub fn CGDisplaySetDisplayMode( display: CGDirectDisplayID, mode: CGDisplayModeRef, options: CFDictionaryRef, ) -> CGError; pub fn CGDisplayCopyAllDisplayModes( display: CGDirectDisplayID, options: CFDictionaryRef, ) -> CFArrayRef; pub fn CGDisplayModeGetPixelWidth(mode: CGDisplayModeRef) -> usize; pub fn CGDisplayModeGetPixelHeight(mode: CGDisplayModeRef) -> usize; pub fn CGDisplayModeGetRefreshRate(mode: CGDisplayModeRef) -> f64; pub fn CGDisplayModeCopyPixelEncoding(mode: CGDisplayModeRef) -> CFStringRef; pub fn CGDisplayModeRetain(mode: CGDisplayModeRef); pub fn CGDisplayModeRelease(mode: CGDisplayModeRef); } mod core_video { use super::*; #[link(name = "CoreVideo", kind = "framework")] extern "C" {} // CVBase.h pub type CVTimeFlags = i32; // int32_t pub const kCVTimeIsIndefinite: CVTimeFlags = 1 << 0; #[repr(C)] #[derive(Debug, Clone)] pub struct CVTime { pub time_value: i64, // int64_t pub time_scale: i32, // int32_t pub flags: i32, // int32_t } // CVReturn.h pub type CVReturn = i32; // int32_t pub const kCVReturnSuccess: CVReturn = 0; // CVDisplayLink.h pub type CVDisplayLinkRef = *mut c_void; extern "C" { pub fn CVDisplayLinkCreateWithCGDisplay( displayID: CGDirectDisplayID, displayLinkOut: *mut CVDisplayLinkRef, ) -> CVReturn; pub fn CVDisplayLinkGetNominalOutputVideoRefreshPeriod( displayLink: CVDisplayLinkRef, ) -> CVTime; pub fn CVDisplayLinkRelease(displayLink: CVDisplayLinkRef); } } pub use core_video::*;
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/menu.rs
Rust
use objc2::foundation::{NSProcessInfo, NSString}; use objc2::rc::{Id, Shared}; use objc2::runtime::Sel; use objc2::{ns_string, sel}; use super::appkit::{NSApp, NSEventModifierFlags, NSMenu, NSMenuItem}; struct KeyEquivalent<'a> { key: &'a NSString, masks: Option<NSEventModifierFlags>, } pub fn initialize() { let menubar = NSMenu::new(); let app_menu_item = NSMenuItem::new(); menubar.addItem(&app_menu_item); let app_menu = NSMenu::new(); let process_name = NSProcessInfo::process_info().process_name(); // About menu item let about_item_title = ns_string!("About ").concat(&process_name); let about_item = menu_item(&about_item_title, sel!(orderFrontStandardAboutPanel:), None); // Seperator menu item let sep_first = NSMenuItem::separatorItem(); // Hide application menu item let hide_item_title = ns_string!("Hide ").concat(&process_name); let hide_item = menu_item( &hide_item_title, sel!(hide:), Some(KeyEquivalent { key: ns_string!("h"), masks: None, }), ); // Hide other applications menu item let hide_others_item_title = ns_string!("Hide Others"); let hide_others_item = menu_item( hide_others_item_title, sel!(hideOtherApplications:), Some(KeyEquivalent { key: ns_string!("h"), masks: Some( NSEventModifierFlags::NSAlternateKeyMask | NSEventModifierFlags::NSCommandKeyMask, ), }), ); // Show applications menu item let show_all_item_title = ns_string!("Show All"); let show_all_item = menu_item(show_all_item_title, sel!(unhideAllApplications:), None); // Seperator menu item let sep = NSMenuItem::separatorItem(); // Quit application menu item let quit_item_title = ns_string!("Quit ").concat(&process_name); let quit_item = menu_item( &quit_item_title, sel!(terminate:), Some(KeyEquivalent { key: ns_string!("q"), masks: None, }), ); app_menu.addItem(&about_item); app_menu.addItem(&sep_first); app_menu.addItem(&hide_item); app_menu.addItem(&hide_others_item); app_menu.addItem(&show_all_item); app_menu.addItem(&sep); app_menu.addItem(&quit_item); app_menu_item.setSubmenu(&app_menu); let app = NSApp(); app.setMainMenu(&menubar); } fn menu_item( title: &NSString, selector: Sel, key_equivalent: Option<KeyEquivalent<'_>>, ) -> Id<NSMenuItem, Shared> { let (key, masks) = match key_equivalent { Some(ke) => (ke.key, ke.masks), None => (ns_string!(""), None), }; let item = NSMenuItem::newWithTitle(title, selector, key); if let Some(masks) = masks { item.setKeyEquivalentModifierMask(masks) } item }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/mod.rs
Rust
#![deny(unsafe_op_in_unsafe_fn)] #[macro_use] mod util; mod app; mod app_delegate; mod app_state; mod appkit; mod event; mod event_loop; mod ffi; mod menu; mod monitor; mod observer; mod view; mod window; mod window_delegate; use std::{fmt, ops::Deref}; use self::window::WinitWindow; use self::window_delegate::WinitWindowDelegate; pub(crate) use self::{ event_loop::{ EventLoop, EventLoopProxy, EventLoopWindowTarget, PlatformSpecificEventLoopAttributes, }, monitor::{MonitorHandle, VideoMode}, window::{PlatformSpecificWindowBuilderAttributes, WindowId}, }; use crate::{ error::OsError as RootOsError, event::DeviceId as RootDeviceId, window::WindowAttributes, }; use objc2::rc::{autoreleasepool, Id, Shared}; pub(crate) use crate::icon::NoIcon as PlatformIcon; pub(self) use crate::platform_impl::Fullscreen; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DeviceId; impl DeviceId { pub const unsafe fn dummy() -> Self { DeviceId } } // Constant device ID; to be removed when if backend is updated to report real device IDs. pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId); pub(crate) struct Window { pub(crate) window: Id<WinitWindow, Shared>, // We keep this around so that it doesn't get dropped until the window does. _delegate: Id<WinitWindowDelegate, Shared>, } impl Drop for Window { fn drop(&mut self) { // Ensure the window is closed util::close_sync(&self.window); } } #[derive(Debug)] pub enum OsError { CGError(core_graphics::base::CGError), CreationError(&'static str), } unsafe impl Send for Window {} unsafe impl Sync for Window {} impl Deref for Window { type Target = WinitWindow; #[inline] fn deref(&self) -> &Self::Target { &self.window } } impl Window { pub(crate) fn new<T: 'static>( _window_target: &EventLoopWindowTarget<T>, attributes: WindowAttributes, pl_attribs: PlatformSpecificWindowBuilderAttributes, ) -> Result<Self, RootOsError> { let (window, _delegate) = autoreleasepool(|_| WinitWindow::new(attributes, pl_attribs))?; Ok(Window { window, _delegate }) } } impl fmt::Display for OsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { OsError::CGError(e) => f.pad(&format!("CGError {e}")), OsError::CreationError(e) => f.pad(e), } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/monitor.rs
Rust
#![allow(clippy::unnecessary_cast)] use std::{collections::VecDeque, fmt}; use core_foundation::{ array::{CFArrayGetCount, CFArrayGetValueAtIndex}, base::{CFRelease, TCFType}, string::CFString, }; use core_graphics::display::{CGDirectDisplayID, CGDisplay, CGDisplayBounds}; use objc2::rc::{Id, Shared}; use super::appkit::NSScreen; use super::ffi; use crate::dpi::{PhysicalPosition, PhysicalSize}; #[derive(Clone)] pub struct VideoMode { pub(crate) size: (u32, u32), pub(crate) bit_depth: u16, pub(crate) refresh_rate_millihertz: u32, pub(crate) monitor: MonitorHandle, pub(crate) native_mode: NativeDisplayMode, } impl PartialEq for VideoMode { fn eq(&self, other: &Self) -> bool { self.size == other.size && self.bit_depth == other.bit_depth && self.refresh_rate_millihertz == other.refresh_rate_millihertz && self.monitor == other.monitor } } impl Eq for VideoMode {} impl std::hash::Hash for VideoMode { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.size.hash(state); self.bit_depth.hash(state); self.refresh_rate_millihertz.hash(state); self.monitor.hash(state); } } impl std::fmt::Debug for VideoMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("VideoMode") .field("size", &self.size) .field("bit_depth", &self.bit_depth) .field("refresh_rate_millihertz", &self.refresh_rate_millihertz) .field("monitor", &self.monitor) .finish() } } pub struct NativeDisplayMode(pub ffi::CGDisplayModeRef); unsafe impl Send for NativeDisplayMode {} impl Drop for NativeDisplayMode { fn drop(&mut self) { unsafe { ffi::CGDisplayModeRelease(self.0); } } } impl Clone for NativeDisplayMode { fn clone(&self) -> Self { unsafe { ffi::CGDisplayModeRetain(self.0); } NativeDisplayMode(self.0) } } impl VideoMode { pub fn size(&self) -> PhysicalSize<u32> { self.size.into() } pub fn bit_depth(&self) -> u16 { self.bit_depth } pub fn refresh_rate_millihertz(&self) -> u32 { self.refresh_rate_millihertz } pub fn monitor(&self) -> MonitorHandle { self.monitor.clone() } } #[derive(Clone)] pub struct MonitorHandle(CGDirectDisplayID); // `CGDirectDisplayID` changes on video mode change, so we cannot rely on that // for comparisons, but we can use `CGDisplayCreateUUIDFromDisplayID` to get an // unique identifier that persists even across system reboots impl PartialEq for MonitorHandle { fn eq(&self, other: &Self) -> bool { unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(self.0) == ffi::CGDisplayCreateUUIDFromDisplayID(other.0) } } } impl Eq for MonitorHandle {} impl PartialOrd for MonitorHandle { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for MonitorHandle { fn cmp(&self, other: &Self) -> std::cmp::Ordering { unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(self.0) .cmp(&ffi::CGDisplayCreateUUIDFromDisplayID(other.0)) } } } impl std::hash::Hash for MonitorHandle { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(self.0).hash(state); } } } pub fn available_monitors() -> VecDeque<MonitorHandle> { if let Ok(displays) = CGDisplay::active_displays() { let mut monitors = VecDeque::with_capacity(displays.len()); for display in displays { monitors.push_back(MonitorHandle(display)); } monitors } else { VecDeque::with_capacity(0) } } pub fn primary_monitor() -> MonitorHandle { MonitorHandle(CGDisplay::main().id) } impl fmt::Debug for MonitorHandle { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: Do this using the proper fmt API #[derive(Debug)] #[allow(dead_code)] struct MonitorHandle { name: Option<String>, native_identifier: u32, size: PhysicalSize<u32>, position: PhysicalPosition<i32>, scale_factor: f64, } let monitor_id_proxy = MonitorHandle { name: self.name(), native_identifier: self.native_identifier(), size: self.size(), position: self.position(), scale_factor: self.scale_factor(), }; monitor_id_proxy.fmt(f) } } impl MonitorHandle { pub fn new(id: CGDirectDisplayID) -> Self { MonitorHandle(id) } pub fn name(&self) -> Option<String> { let MonitorHandle(display_id) = *self; let screen_num = CGDisplay::new(display_id).model_number(); Some(format!("Monitor #{screen_num}")) } #[inline] pub fn native_identifier(&self) -> u32 { self.0 } pub fn size(&self) -> PhysicalSize<u32> { let MonitorHandle(display_id) = *self; let display = CGDisplay::new(display_id); let height = display.pixels_high(); let width = display.pixels_wide(); PhysicalSize::from_logical::<_, f64>((width as f64, height as f64), self.scale_factor()) } #[inline] pub fn position(&self) -> PhysicalPosition<i32> { let bounds = unsafe { CGDisplayBounds(self.native_identifier()) }; PhysicalPosition::from_logical::<_, f64>( (bounds.origin.x as f64, bounds.origin.y as f64), self.scale_factor(), ) } pub fn scale_factor(&self) -> f64 { match self.ns_screen() { Some(screen) => screen.backingScaleFactor() as f64, None => 1.0, // default to 1.0 when we can't find the screen } } pub fn refresh_rate_millihertz(&self) -> Option<u32> { unsafe { let mut display_link = std::ptr::null_mut(); if ffi::CVDisplayLinkCreateWithCGDisplay(self.0, &mut display_link) != ffi::kCVReturnSuccess { return None; } let time = ffi::CVDisplayLinkGetNominalOutputVideoRefreshPeriod(display_link); ffi::CVDisplayLinkRelease(display_link); // This value is indefinite if an invalid display link was specified if time.flags & ffi::kCVTimeIsIndefinite != 0 { return None; } (time.time_scale as i64) .checked_div(time.time_value) .map(|v| (v * 1000) as u32) } } pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> { let refresh_rate_millihertz = self.refresh_rate_millihertz().unwrap_or(0); let monitor = self.clone(); unsafe { let modes = { let array = ffi::CGDisplayCopyAllDisplayModes(self.0, std::ptr::null()); assert!(!array.is_null(), "failed to get list of display modes"); let array_count = CFArrayGetCount(array); let modes: Vec<_> = (0..array_count) .map(move |i| { let mode = CFArrayGetValueAtIndex(array, i) as *mut _; ffi::CGDisplayModeRetain(mode); mode }) .collect(); CFRelease(array as *const _); modes }; modes.into_iter().map(move |mode| { let cg_refresh_rate_millihertz = ffi::CGDisplayModeGetRefreshRate(mode).round() as i64; // CGDisplayModeGetRefreshRate returns 0.0 for any display that // isn't a CRT let refresh_rate_millihertz = if cg_refresh_rate_millihertz > 0 { (cg_refresh_rate_millihertz * 1000) as u32 } else { refresh_rate_millihertz }; let pixel_encoding = CFString::wrap_under_create_rule(ffi::CGDisplayModeCopyPixelEncoding(mode)) .to_string(); let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) { 32 } else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) { 16 } else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) { 30 } else { unimplemented!() }; VideoMode { size: ( ffi::CGDisplayModeGetPixelWidth(mode) as u32, ffi::CGDisplayModeGetPixelHeight(mode) as u32, ), refresh_rate_millihertz, bit_depth, monitor: monitor.clone(), native_mode: NativeDisplayMode(mode), } }) } } pub(crate) fn ns_screen(&self) -> Option<Id<NSScreen, Shared>> { let uuid = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(self.0) }; NSScreen::screens() .into_iter() .find(|screen| { let other_native_id = screen.display_id(); let other_uuid = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(other_native_id as CGDirectDisplayID) }; uuid == other_uuid }) .map(|screen| unsafe { Id::retain(screen as *const NSScreen as *mut NSScreen).unwrap() }) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/observer.rs
Rust
use std::{ self, ffi::c_void, panic::{AssertUnwindSafe, UnwindSafe}, ptr, rc::Weak, time::Instant, }; use crate::platform_impl::platform::{ app_state::AppState, event_loop::{stop_app_on_panic, PanicInfo}, ffi, }; use core_foundation::base::{CFIndex, CFOptionFlags, CFRelease}; use core_foundation::date::CFAbsoluteTimeGetCurrent; use core_foundation::runloop::{ kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopObserverCallBack, CFRunLoopObserverContext, CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, }; unsafe fn control_flow_handler<F>(panic_info: *mut c_void, f: F) where F: FnOnce(Weak<PanicInfo>) + UnwindSafe, { let info_from_raw = unsafe { Weak::from_raw(panic_info as *mut PanicInfo) }; // Asserting unwind safety on this type should be fine because `PanicInfo` is // `RefUnwindSafe` and `Rc<T>` is `UnwindSafe` if `T` is `RefUnwindSafe`. let panic_info = AssertUnwindSafe(Weak::clone(&info_from_raw)); // `from_raw` takes ownership of the data behind the pointer. // But if this scope takes ownership of the weak pointer, then // the weak pointer will get free'd at the end of the scope. // However we want to keep that weak reference around after the function. std::mem::forget(info_from_raw); stop_app_on_panic(Weak::clone(&panic_info), move || { let _ = &panic_info; f(panic_info.0) }); } // begin is queued with the highest priority to ensure it is processed before other observers extern "C" fn control_flow_begin_handler( _: CFRunLoopObserverRef, activity: CFRunLoopActivity, panic_info: *mut c_void, ) { unsafe { control_flow_handler(panic_info, |panic_info| { #[allow(non_upper_case_globals)] match activity { kCFRunLoopAfterWaiting => { //trace!("Triggered `CFRunLoopAfterWaiting`"); AppState::wakeup(panic_info); //trace!("Completed `CFRunLoopAfterWaiting`"); } _ => unreachable!(), } }); } } // end is queued with the lowest priority to ensure it is processed after other observers // without that, LoopDestroyed would get sent after MainEventsCleared extern "C" fn control_flow_end_handler( _: CFRunLoopObserverRef, activity: CFRunLoopActivity, panic_info: *mut c_void, ) { unsafe { control_flow_handler(panic_info, |panic_info| { #[allow(non_upper_case_globals)] match activity { kCFRunLoopBeforeWaiting => { //trace!("Triggered `CFRunLoopBeforeWaiting`"); AppState::cleared(panic_info); //trace!("Completed `CFRunLoopBeforeWaiting`"); } kCFRunLoopExit => (), //unimplemented!(), // not expected to ever happen _ => unreachable!(), } }); } } struct RunLoop(CFRunLoopRef); impl RunLoop { unsafe fn get() -> Self { RunLoop(unsafe { CFRunLoopGetMain() }) } unsafe fn add_observer( &self, flags: CFOptionFlags, priority: CFIndex, handler: CFRunLoopObserverCallBack, context: *mut CFRunLoopObserverContext, ) { let observer = unsafe { CFRunLoopObserverCreate( ptr::null_mut(), flags, ffi::TRUE, // Indicates we want this to run repeatedly priority, // The lower the value, the sooner this will run handler, context, ) }; unsafe { CFRunLoopAddObserver(self.0, observer, kCFRunLoopCommonModes) }; } } pub fn setup_control_flow_observers(panic_info: Weak<PanicInfo>) { unsafe { let mut context = CFRunLoopObserverContext { info: Weak::into_raw(panic_info) as *mut _, version: 0, retain: None, release: None, copyDescription: None, }; let run_loop = RunLoop::get(); run_loop.add_observer( kCFRunLoopAfterWaiting, CFIndex::min_value(), control_flow_begin_handler, &mut context as *mut _, ); run_loop.add_observer( kCFRunLoopExit | kCFRunLoopBeforeWaiting, CFIndex::max_value(), control_flow_end_handler, &mut context as *mut _, ); } } pub struct EventLoopWaker { timer: CFRunLoopTimerRef, } impl Drop for EventLoopWaker { fn drop(&mut self) { unsafe { CFRunLoopTimerInvalidate(self.timer); CFRelease(self.timer as _); } } } impl Default for EventLoopWaker { fn default() -> EventLoopWaker { extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {} unsafe { // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. // It is initially setup with a first fire time really far into the // future, but that gets changed to fire immediately in did_finish_launching let timer = CFRunLoopTimerCreate( ptr::null_mut(), std::f64::MAX, 0.000_000_1, 0, 0, wakeup_main_loop, ptr::null_mut(), ); CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopCommonModes); EventLoopWaker { timer } } } } impl EventLoopWaker { pub fn stop(&mut self) { unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MAX) } } pub fn start(&mut self) { unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MIN) } } pub fn start_at(&mut self, instant: Instant) { let now = Instant::now(); if now >= instant { self.start(); } else { unsafe { let current = CFAbsoluteTimeGetCurrent(); let duration = instant - now; let fsecs = duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64; CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs) } } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/util/async.rs
Rust
use std::ops::Deref; use dispatch::Queue; use objc2::foundation::{is_main_thread, CGFloat, NSPoint, NSSize, NSString}; use objc2::rc::{autoreleasepool, Id}; use crate::{ dpi::{LogicalPosition, LogicalSize}, platform_impl::platform::{ appkit::{NSScreen, NSWindow, NSWindowLevel, NSWindowStyleMask}, ffi, window::WinitWindow, }, }; // Unsafe wrapper type that allows us to dispatch things that aren't Send. // This should *only* be used to dispatch to the main queue. // While it is indeed not guaranteed that these types can safely be sent to // other threads, we know that they're safe to use on the main thread. struct MainThreadSafe<T>(T); unsafe impl<T> Send for MainThreadSafe<T> {} impl<T> Deref for MainThreadSafe<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } fn run_on_main<R: Send>(f: impl FnOnce() -> R + Send) -> R { if is_main_thread() { f() } else { Queue::main().exec_sync(f) } } fn set_style_mask(window: &NSWindow, mask: NSWindowStyleMask) { window.setStyleMask(mask); // If we don't do this, key handling will break // (at least until the window is clicked again/etc.) let _ = window.makeFirstResponder(Some(&window.contentView())); } // Always use this function instead of trying to modify `styleMask` directly! // `setStyleMask:` isn't thread-safe, so we have to use Grand Central Dispatch. // Otherwise, this would vomit out errors about not being on the main thread // and fail to do anything. pub(crate) fn set_style_mask_sync(window: &NSWindow, mask: NSWindowStyleMask) { let window = MainThreadSafe(window); run_on_main(move || { set_style_mask(&window, mask); }) } // `setContentSize:` isn't thread-safe either, though it doesn't log any errors // and just fails silently. Anyway, GCD to the rescue! pub(crate) fn set_content_size_sync(window: &NSWindow, size: LogicalSize<f64>) { let window = MainThreadSafe(window); run_on_main(move || { window.setContentSize(NSSize::new(size.width as CGFloat, size.height as CGFloat)); }); } // `setFrameTopLeftPoint:` isn't thread-safe, but fortunately has the courtesy // to log errors. pub(crate) fn set_frame_top_left_point_sync(window: &NSWindow, point: NSPoint) { let window = MainThreadSafe(window); run_on_main(move || { window.setFrameTopLeftPoint(point); }); } // `setFrameTopLeftPoint:` isn't thread-safe, and fails silently. pub(crate) fn set_level_sync(window: &NSWindow, level: NSWindowLevel) { let window = MainThreadSafe(window); run_on_main(move || { window.setLevel(level); }); } // `setIgnoresMouseEvents_:` isn't thread-safe, and fails silently. pub(crate) fn set_ignore_mouse_events_sync(window: &NSWindow, ignore: bool) { let window = MainThreadSafe(window); run_on_main(move || { window.setIgnoresMouseEvents(ignore); }); } // `toggleFullScreen` is thread-safe, but our additional logic to account for // window styles isn't. pub(crate) fn toggle_full_screen_sync(window: &WinitWindow, not_fullscreen: bool) { let window = MainThreadSafe(window); run_on_main(move || { // `toggleFullScreen` doesn't work if the `StyleMask` is none, so we // set a normal style temporarily. The previous state will be // restored in `WindowDelegate::window_did_exit_fullscreen`. if not_fullscreen { let curr_mask = window.styleMask(); let required = NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSResizableWindowMask; if !curr_mask.contains(required) { set_style_mask(&window, required); window .lock_shared_state("toggle_full_screen_sync") .saved_style = Some(curr_mask); } } // Window level must be restored from `CGShieldingWindowLevel() // + 1` back to normal in order for `toggleFullScreen` to do // anything window.setLevel(NSWindowLevel::Normal); window.toggleFullScreen(None); }); } pub(crate) unsafe fn restore_display_mode_sync(ns_screen: u32) { run_on_main(move || { unsafe { ffi::CGRestorePermanentDisplayConfiguration() }; assert_eq!( unsafe { ffi::CGDisplayRelease(ns_screen) }, ffi::kCGErrorSuccess ); }); } // `setMaximized` is not thread-safe pub(crate) fn set_maximized_sync(window: &WinitWindow, is_zoomed: bool, maximized: bool) { let window = MainThreadSafe(window); run_on_main(move || { let mut shared_state = window.lock_shared_state("set_maximized_sync"); // Save the standard frame sized if it is not zoomed if !is_zoomed { shared_state.standard_frame = Some(window.frame()); } shared_state.maximized = maximized; if shared_state.fullscreen.is_some() { // Handle it in window_did_exit_fullscreen return; } if window .styleMask() .contains(NSWindowStyleMask::NSResizableWindowMask) { drop(shared_state); // Just use the native zoom if resizable window.zoom(None); } else { // if it's not resizable, we set the frame directly let new_rect = if maximized { let screen = NSScreen::main().expect("no screen found"); screen.visibleFrame() } else { shared_state.saved_standard_frame() }; drop(shared_state); window.setFrame_display(new_rect, false); } }); } // `orderOut:` isn't thread-safe. Calling it from another thread actually works, // but with an odd delay. pub(crate) fn order_out_sync(window: &NSWindow) { let window = MainThreadSafe(window); run_on_main(move || { window.orderOut(None); }); } // `makeKeyAndOrderFront:` isn't thread-safe. Calling it from another thread // actually works, but with an odd delay. pub(crate) fn make_key_and_order_front_sync(window: &NSWindow) { let window = MainThreadSafe(window); run_on_main(move || { window.makeKeyAndOrderFront(None); }); } // `setTitle:` isn't thread-safe. Calling it from another thread invalidates the // window drag regions, which throws an exception when not done in the main // thread pub(crate) fn set_title_sync(window: &NSWindow, title: &str) { let window = MainThreadSafe(window); run_on_main(move || { window.setTitle(&NSString::from_str(title)); }); } // `close:` is thread-safe, but we want the event to be triggered from the main // thread. Though, it's a good idea to look into that more... pub(crate) fn close_sync(window: &NSWindow) { let window = MainThreadSafe(window); run_on_main(move || { autoreleasepool(move |_| { window.close(); }); }); } pub(crate) fn set_ime_position_sync(window: &WinitWindow, logical_spot: LogicalPosition<f64>) { let window = MainThreadSafe(window); run_on_main(move || { // TODO(madsmtm): Remove the need for this unsafe { Id::from_shared(window.view()) }.set_ime_position(logical_spot); }); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/util/mod.rs
Rust
#![allow(clippy::unnecessary_cast)] mod r#async; pub(crate) use self::r#async::*; use core_graphics::display::CGDisplay; use objc2::foundation::{CGFloat, NSNotFound, NSPoint, NSRange, NSRect, NSUInteger}; use crate::dpi::LogicalPosition; // Replace with `!` once stable #[derive(Debug)] pub enum Never {} pub const EMPTY_RANGE: NSRange = NSRange { location: NSNotFound as NSUInteger, length: 0, }; macro_rules! trace_scope { ($s:literal) => { let _crate = $crate::platform_impl::platform::util::TraceGuard::new(module_path!(), $s); }; } pub(crate) struct TraceGuard { module_path: &'static str, called_from_fn: &'static str, } impl TraceGuard { #[inline] pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self { trace!(target: module_path, "Triggered `{}`", called_from_fn); Self { module_path, called_from_fn, } } } impl Drop for TraceGuard { #[inline] fn drop(&mut self) { trace!(target: self.module_path, "Completed `{}`", self.called_from_fn); } } // For consistency with other platforms, this will... // 1. translate the bottom-left window corner into the top-left window corner // 2. translate the coordinate from a bottom-left origin coordinate system to a top-left one pub fn bottom_left_to_top_left(rect: NSRect) -> f64 { CGDisplay::main().pixels_high() as f64 - (rect.origin.y + rect.size.height) as f64 } /// Converts from winit screen-coordinates to macOS screen-coordinates. /// Winit: top-left is (0, 0) and y increasing downwards /// macOS: bottom-left is (0, 0) and y increasing upwards pub fn window_position(position: LogicalPosition<f64>) -> NSPoint { NSPoint::new( position.x as CGFloat, CGDisplay::main().pixels_high() as CGFloat - position.y as CGFloat, ) }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/view.rs
Rust
#![allow(clippy::unnecessary_cast)] use std::{boxed::Box, os::raw::*, ptr, str, sync::Mutex}; use objc2::declare::{Ivar, IvarDrop}; use objc2::foundation::{ NSArray, NSAttributedString, NSAttributedStringKey, NSCopying, NSMutableAttributedString, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString, NSUInteger, }; use objc2::rc::{Id, Owned, Shared, WeakId}; use objc2::runtime::{Object, Sel}; use objc2::{class, declare_class, msg_send, msg_send_id, sel, ClassType}; use super::appkit::{ NSApp, NSCursor, NSEvent, NSEventModifierFlags, NSEventPhase, NSResponder, NSTrackingRectTag, NSView, }; use crate::platform::macos::{OptionAsAlt, WindowExtMacOS}; use crate::{ dpi::{LogicalPosition, LogicalSize}, event::{ DeviceEvent, ElementState, Event, Ime, KeyboardInput, ModifiersState, MouseButton, MouseScrollDelta, TouchPhase, VirtualKeyCode, WindowEvent, }, platform_impl::platform::{ app_state::AppState, event::{ char_to_keycode, check_function_keys, event_mods, modifier_event, scancode_to_keycode, EventWrapper, }, util, window::WinitWindow, DEVICE_ID, }, window::WindowId, }; #[derive(Debug)] pub struct CursorState { pub visible: bool, pub(super) cursor: Id<NSCursor, Shared>, } impl Default for CursorState { fn default() -> Self { Self { visible: true, cursor: Default::default(), } } } #[derive(Debug, Eq, PartialEq, Clone, Copy)] enum ImeState { /// The IME events are disabled, so only `ReceivedCharacter` is being sent to the user. Disabled, /// The ground state of enabled IME input. It means that both Preedit and regular keyboard /// input could be start from it. Ground, /// The IME is in preedit. Preedit, /// The text was just commited, so the next input from the keyboard must be ignored. Commited, } #[derive(Debug)] pub(super) struct ViewState { pub cursor_state: Mutex<CursorState>, ime_position: LogicalPosition<f64>, pub(super) modifiers: ModifiersState, tracking_rect: Option<NSTrackingRectTag>, ime_state: ImeState, input_source: String, /// True iff the application wants IME events. /// /// Can be set using `set_ime_allowed` ime_allowed: bool, /// True if the current key event should be forwarded /// to the application, even during IME forward_key_to_app: bool, } fn get_characters(event: &NSEvent, ignore_modifiers: bool) -> String { if ignore_modifiers { event.charactersIgnoringModifiers() } else { event.characters() } .expect("expected characters to be non-null") .to_string() } // As defined in: https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/CORPCHAR.TXT fn is_corporate_character(c: char) -> bool { matches!(c, '\u{F700}'..='\u{F747}' | '\u{F802}'..='\u{F84F}' | '\u{F850}' | '\u{F85C}' | '\u{F85D}' | '\u{F85F}' | '\u{F860}'..='\u{F86B}' | '\u{F870}'..='\u{F8FF}' ) } // Retrieves a layout-independent keycode given an event. fn retrieve_keycode(event: &NSEvent) -> Option<VirtualKeyCode> { #[inline] fn get_code(ev: &NSEvent, raw: bool) -> Option<VirtualKeyCode> { let characters = get_characters(ev, raw); characters.chars().next().and_then(char_to_keycode) } // Cmd switches Roman letters for Dvorak-QWERTY layout, so we try modified characters first. // If we don't get a match, then we fall back to unmodified characters. let code = get_code(event, false).or_else(|| get_code(event, true)); // We've checked all layout related keys, so fall through to scancode. // Reaching this code means that the key is layout-independent (e.g. Backspace, Return). // // We're additionally checking here for F21-F24 keys, since their keycode // can vary, but we know that they are encoded // in characters property. code.or_else(|| { let scancode = event.scancode(); scancode_to_keycode(scancode).or_else(|| check_function_keys(&get_characters(event, true))) }) } declare_class!( #[derive(Debug)] #[allow(non_snake_case)] pub(super) struct WinitView { // Weak reference because the window keeps a strong reference to the view _ns_window: IvarDrop<Box<WeakId<WinitWindow>>>, pub(super) state: IvarDrop<Box<ViewState>>, marked_text: IvarDrop<Id<NSMutableAttributedString, Owned>>, accepts_first_mouse: bool, } unsafe impl ClassType for WinitView { #[inherits(NSResponder, NSObject)] type Super = NSView; } unsafe impl WinitView { #[sel(initWithId:acceptsFirstMouse:)] fn init_with_id( &mut self, window: &WinitWindow, accepts_first_mouse: bool, ) -> Option<&mut Self> { let this: Option<&mut Self> = unsafe { msg_send![super(self), init] }; this.map(|this| { let state = ViewState { cursor_state: Default::default(), ime_position: LogicalPosition::new(0.0, 0.0), modifiers: Default::default(), tracking_rect: None, ime_state: ImeState::Disabled, input_source: String::new(), ime_allowed: false, forward_key_to_app: false, }; Ivar::write( &mut this._ns_window, Box::new(WeakId::new(&window.retain())), ); Ivar::write(&mut this.state, Box::new(state)); Ivar::write(&mut this.marked_text, NSMutableAttributedString::new()); Ivar::write(&mut this.accepts_first_mouse, accepts_first_mouse); this.setPostsFrameChangedNotifications(true); let notification_center: &Object = unsafe { msg_send![class!(NSNotificationCenter), defaultCenter] }; // About frame change let frame_did_change_notification_name = NSString::from_str("NSViewFrameDidChangeNotification"); #[allow(clippy::let_unit_value)] unsafe { let _: () = msg_send![ notification_center, addObserver: &*this, selector: sel!(frameDidChange:), name: &*frame_did_change_notification_name, object: &*this, ]; } this.state.input_source = this.current_input_source(); this }) } } unsafe impl WinitView { #[sel(viewDidMoveToWindow)] fn view_did_move_to_window(&mut self) { trace_scope!("viewDidMoveToWindow"); if let Some(tracking_rect) = self.state.tracking_rect.take() { self.removeTrackingRect(tracking_rect); } let rect = self.visibleRect(); let tracking_rect = self.add_tracking_rect(rect, false); self.state.tracking_rect = Some(tracking_rect); } #[sel(frameDidChange:)] fn frame_did_change(&mut self, _event: &NSEvent) { trace_scope!("frameDidChange:"); if let Some(tracking_rect) = self.state.tracking_rect.take() { self.removeTrackingRect(tracking_rect); } let rect = self.visibleRect(); let tracking_rect = self.add_tracking_rect(rect, false); self.state.tracking_rect = Some(tracking_rect); // Emit resize event here rather than from windowDidResize because: // 1. When a new window is created as a tab, the frame size may change without a window resize occurring. // 2. Even when a window resize does occur on a new tabbed window, it contains the wrong size (includes tab height). let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64); let size = logical_size.to_physical::<u32>(self.scale_factor()); self.queue_event(WindowEvent::Resized(size)); } #[sel(drawRect:)] fn draw_rect(&mut self, rect: NSRect) { trace_scope!("drawRect:"); AppState::handle_redraw(self.window_id()); #[allow(clippy::let_unit_value)] unsafe { let _: () = msg_send![super(self), drawRect: rect]; } } #[sel(acceptsFirstResponder)] fn accepts_first_responder(&self) -> bool { trace_scope!("acceptsFirstResponder"); true } // This is necessary to prevent a beefy terminal error on MacBook Pros: // IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem // TODO: Add an API extension for using `NSTouchBar` #[sel(touchBar)] fn touch_bar(&self) -> bool { trace_scope!("touchBar"); false } #[sel(resetCursorRects)] fn reset_cursor_rects(&self) { trace_scope!("resetCursorRects"); let bounds = self.bounds(); let cursor_state = self.state.cursor_state.lock().unwrap(); // We correctly invoke `addCursorRect` only from inside `resetCursorRects` if cursor_state.visible { self.addCursorRect(bounds, &cursor_state.cursor); } else { self.addCursorRect(bounds, &NSCursor::invisible()); } } } unsafe impl Protocol<NSTextInputClient> for WinitView { #[sel(hasMarkedText)] fn has_marked_text(&self) -> bool { trace_scope!("hasMarkedText"); self.marked_text.len_utf16() > 0 } #[sel(markedRange)] fn marked_range(&self) -> NSRange { trace_scope!("markedRange"); let length = self.marked_text.len_utf16(); if length > 0 { NSRange::new(0, length) } else { util::EMPTY_RANGE } } #[sel(selectedRange)] fn selected_range(&self) -> NSRange { trace_scope!("selectedRange"); util::EMPTY_RANGE } #[sel(setMarkedText:selectedRange:replacementRange:)] fn set_marked_text( &mut self, string: &NSObject, _selected_range: NSRange, _replacement_range: NSRange, ) { trace_scope!("setMarkedText:selectedRange:replacementRange:"); // SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`. let (marked_text, preedit_string) = if string.is_kind_of::<NSAttributedString>() { let string: *const NSObject = string; let string: *const NSAttributedString = string.cast(); let string = unsafe { &*string }; ( NSMutableAttributedString::from_attributed_nsstring(string), string.string().to_string(), ) } else { let string: *const NSObject = string; let string: *const NSString = string.cast(); let string = unsafe { &*string }; ( NSMutableAttributedString::from_nsstring(string), string.to_string(), ) }; // Update marked text. *self.marked_text = marked_text; // Notify IME is active if application still doesn't know it. if self.state.ime_state == ImeState::Disabled { self.state.input_source = self.current_input_source(); self.queue_event(WindowEvent::Ime(Ime::Enabled)); } if self.hasMarkedText() { self.state.ime_state = ImeState::Preedit; } else { // In case the preedit was cleared, set IME into the Ground state. self.state.ime_state = ImeState::Ground; } // Empty string basically means that there's no preedit, so indicate that by sending // `None` cursor range. let cursor_range = if preedit_string.is_empty() { None } else { Some((preedit_string.len(), preedit_string.len())) }; // Send WindowEvent for updating marked text self.queue_event(WindowEvent::Ime(Ime::Preedit(preedit_string, cursor_range))); } #[sel(unmarkText)] fn unmark_text(&mut self) { trace_scope!("unmarkText"); *self.marked_text = NSMutableAttributedString::new(); let input_context = self.inputContext().expect("input context"); input_context.discardMarkedText(); self.queue_event(WindowEvent::Ime(Ime::Preedit(String::new(), None))); if self.is_ime_enabled() { // Leave the Preedit self.state self.state.ime_state = ImeState::Ground; } else { warn!("Expected to have IME enabled when receiving unmarkText"); } } #[sel(validAttributesForMarkedText)] fn valid_attributes_for_marked_text(&self) -> *const NSArray<NSAttributedStringKey> { trace_scope!("validAttributesForMarkedText"); Id::autorelease_return(NSArray::new()) } #[sel(attributedSubstringForProposedRange:actualRange:)] fn attributed_substring_for_proposed_range( &self, _range: NSRange, _actual_range: *mut c_void, // *mut NSRange ) -> *const NSAttributedString { trace_scope!("attributedSubstringForProposedRange:actualRange:"); ptr::null() } #[sel(characterIndexForPoint:)] fn character_index_for_point(&self, _point: NSPoint) -> NSUInteger { trace_scope!("characterIndexForPoint:"); 0 } #[sel(firstRectForCharacterRange:actualRange:)] fn first_rect_for_character_range( &self, _range: NSRange, _actual_range: *mut c_void, // *mut NSRange ) -> NSRect { trace_scope!("firstRectForCharacterRange:actualRange:"); let window = self.window(); let content_rect = window.contentRectForFrameRect(window.frame()); let base_x = content_rect.origin.x as f64; let base_y = (content_rect.origin.y + content_rect.size.height) as f64; let x = base_x + self.state.ime_position.x; let y = base_y - self.state.ime_position.y; // This is not ideal: We _should_ return a different position based on // the currently selected character (which varies depending on the type // and size of the character), but in the current `winit` API there is // no way to express this. Same goes for the `NSSize`. NSRect::new(NSPoint::new(x as _, y as _), NSSize::new(0.0, 0.0)) } #[sel(insertText:replacementRange:)] fn insert_text(&mut self, string: &NSObject, _replacement_range: NSRange) { trace_scope!("insertText:replacementRange:"); // SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`. let string = if string.is_kind_of::<NSAttributedString>() { let string: *const NSObject = string; let string: *const NSAttributedString = string.cast(); unsafe { &*string }.string().to_string() } else { let string: *const NSObject = string; let string: *const NSString = string.cast(); unsafe { &*string }.to_string() }; let is_control = string.chars().next().map_or(false, |c| c.is_control()); // Commit only if we have marked text. if self.hasMarkedText() && self.is_ime_enabled() && !is_control { self.queue_event(WindowEvent::Ime(Ime::Preedit(String::new(), None))); self.queue_event(WindowEvent::Ime(Ime::Commit(string))); self.state.ime_state = ImeState::Commited; } } // Basically, we're sent this message whenever a keyboard event that doesn't generate a "human // readable" character happens, i.e. newlines, tabs, and Ctrl+C. #[sel(doCommandBySelector:)] fn do_command_by_selector(&mut self, _command: Sel) { trace_scope!("doCommandBySelector:"); // We shouldn't forward any character from just commited text, since we'll end up sending // it twice with some IMEs like Korean one. We'll also always send `Enter` in that case, // which is not desired given it was used to confirm IME input. if self.state.ime_state == ImeState::Commited { return; } self.state.forward_key_to_app = true; if self.hasMarkedText() && self.state.ime_state == ImeState::Preedit { // Leave preedit so that we also report the key-up for this key. self.state.ime_state = ImeState::Ground; } } } unsafe impl WinitView { #[sel(keyDown:)] fn key_down(&mut self, event: &NSEvent) { trace_scope!("keyDown:"); let input_source = self.current_input_source(); if self.state.input_source != input_source && self.is_ime_enabled() { self.state.ime_state = ImeState::Disabled; self.state.input_source = input_source; self.queue_event(WindowEvent::Ime(Ime::Disabled)); } // Get the characters from the event. let ev_mods = event_mods(event); let ignore_alt_characters = match self.window().option_as_alt() { OptionAsAlt::OnlyLeft if event.lalt_pressed() => true, OptionAsAlt::OnlyRight if event.ralt_pressed() => true, OptionAsAlt::Both if ev_mods.alt() => true, _ => false, } && !ev_mods.ctrl() && !ev_mods.logo(); let characters = get_characters(event, ignore_alt_characters); let old_ime_state = self.state.ime_state; self.state.forward_key_to_app = false; // The `interpretKeyEvents` function might call // `setMarkedText`, `insertText`, and `doCommandBySelector`. // It's important that we call this before queuing the KeyboardInput, because // we must send the `KeyboardInput` event during IME if it triggered // `doCommandBySelector`. (doCommandBySelector means that the keyboard input // is not handled by IME and should be handled by the application) if self.state.ime_allowed { let new_event = if ignore_alt_characters { replace_event_chars(event, &characters) } else { event.copy() }; let events_for_nsview = NSArray::from_slice(&[new_event]); unsafe { self.interpretKeyEvents(&events_for_nsview) }; // If the text was commited we must treat the next keyboard event as IME related. if self.state.ime_state == ImeState::Commited { // Remove any marked text, so normal input can continue. *self.marked_text = NSMutableAttributedString::new(); } } let scancode = event.scancode() as u32; let virtual_keycode = retrieve_keycode(event); self.update_potentially_stale_modifiers(event); let had_ime_input = match self.state.ime_state { ImeState::Commited => { // Allow normal input after the commit. self.state.ime_state = ImeState::Ground; true } ImeState::Preedit => true, // `key_down` could result in preedit clear, so compare old and current state. _ => old_ime_state != self.state.ime_state, }; if !had_ime_input || self.state.forward_key_to_app { #[allow(deprecated)] self.queue_event(WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { state: ElementState::Pressed, scancode, virtual_keycode, modifiers: ev_mods, }, is_synthetic: false, }); for character in characters.chars().filter(|c| !is_corporate_character(*c)) { self.queue_event(WindowEvent::ReceivedCharacter(character)); } } } #[sel(keyUp:)] fn key_up(&mut self, event: &NSEvent) { trace_scope!("keyUp:"); let scancode = event.scancode() as u32; let virtual_keycode = retrieve_keycode(event); self.update_potentially_stale_modifiers(event); // We want to send keyboard input when we are currently in the ground state. if matches!(self.state.ime_state, ImeState::Ground | ImeState::Disabled) { #[allow(deprecated)] self.queue_event(WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { state: ElementState::Released, scancode, virtual_keycode, modifiers: event_mods(event), }, is_synthetic: false, }); } } #[sel(flagsChanged:)] fn flags_changed(&mut self, event: &NSEvent) { trace_scope!("flagsChanged:"); if let Some(window_event) = modifier_event( event, NSEventModifierFlags::NSShiftKeyMask, self.state.modifiers.shift(), ) { self.state.modifiers.toggle(ModifiersState::SHIFT); self.queue_event(window_event); } if let Some(window_event) = modifier_event( event, NSEventModifierFlags::NSControlKeyMask, self.state.modifiers.ctrl(), ) { self.state.modifiers.toggle(ModifiersState::CTRL); self.queue_event(window_event); } if let Some(window_event) = modifier_event( event, NSEventModifierFlags::NSCommandKeyMask, self.state.modifiers.logo(), ) { self.state.modifiers.toggle(ModifiersState::LOGO); self.queue_event(window_event); } if let Some(window_event) = modifier_event( event, NSEventModifierFlags::NSAlternateKeyMask, self.state.modifiers.alt(), ) { self.state.modifiers.toggle(ModifiersState::ALT); self.queue_event(window_event); } self.queue_event(WindowEvent::ModifiersChanged(self.state.modifiers)); } #[sel(insertTab:)] fn insert_tab(&self, _sender: *const Object) { trace_scope!("insertTab:"); let window = self.window(); if let Some(first_responder) = window.firstResponder() { if *first_responder == ***self { window.selectNextKeyView(Some(self)) } } } #[sel(insertBackTab:)] fn insert_back_tab(&self, _sender: *const Object) { trace_scope!("insertBackTab:"); let window = self.window(); if let Some(first_responder) = window.firstResponder() { if *first_responder == ***self { window.selectPreviousKeyView(Some(self)) } } } // Allows us to receive Cmd-. (the shortcut for closing a dialog) // https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6 #[sel(cancelOperation:)] fn cancel_operation(&mut self, _sender: *const Object) { trace_scope!("cancelOperation:"); let scancode = 0x2f; let virtual_keycode = scancode_to_keycode(scancode); debug_assert_eq!(virtual_keycode, Some(VirtualKeyCode::Period)); let event = NSApp() .currentEvent() .expect("could not find current event"); self.update_potentially_stale_modifiers(&event); #[allow(deprecated)] self.queue_event(WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { state: ElementState::Pressed, scancode: scancode as _, virtual_keycode, modifiers: event_mods(&event), }, is_synthetic: false, }); } #[sel(mouseDown:)] fn mouse_down(&mut self, event: &NSEvent) { trace_scope!("mouseDown:"); self.mouse_motion(event); self.mouse_click(event, ElementState::Pressed); } #[sel(mouseUp:)] fn mouse_up(&mut self, event: &NSEvent) { trace_scope!("mouseUp:"); self.mouse_motion(event); self.mouse_click(event, ElementState::Released); } #[sel(rightMouseDown:)] fn right_mouse_down(&mut self, event: &NSEvent) { trace_scope!("rightMouseDown:"); self.mouse_motion(event); self.mouse_click(event, ElementState::Pressed); } #[sel(rightMouseUp:)] fn right_mouse_up(&mut self, event: &NSEvent) { trace_scope!("rightMouseUp:"); self.mouse_motion(event); self.mouse_click(event, ElementState::Released); } #[sel(otherMouseDown:)] fn other_mouse_down(&mut self, event: &NSEvent) { trace_scope!("otherMouseDown:"); self.mouse_motion(event); self.mouse_click(event, ElementState::Pressed); } #[sel(otherMouseUp:)] fn other_mouse_up(&mut self, event: &NSEvent) { trace_scope!("otherMouseUp:"); self.mouse_motion(event); self.mouse_click(event, ElementState::Released); } // No tracing on these because that would be overly verbose #[sel(mouseMoved:)] fn mouse_moved(&mut self, event: &NSEvent) { self.mouse_motion(event); } #[sel(mouseDragged:)] fn mouse_dragged(&mut self, event: &NSEvent) { self.mouse_motion(event); } #[sel(rightMouseDragged:)] fn right_mouse_dragged(&mut self, event: &NSEvent) { self.mouse_motion(event); } #[sel(otherMouseDragged:)] fn other_mouse_dragged(&mut self, event: &NSEvent) { self.mouse_motion(event); } #[sel(mouseEntered:)] fn mouse_entered(&self, _event: &NSEvent) { trace_scope!("mouseEntered:"); self.queue_event(WindowEvent::CursorEntered { device_id: DEVICE_ID, }); } #[sel(mouseExited:)] fn mouse_exited(&self, _event: &NSEvent) { trace_scope!("mouseExited:"); self.queue_event(WindowEvent::CursorLeft { device_id: DEVICE_ID, }); } #[sel(scrollWheel:)] fn scroll_wheel(&mut self, event: &NSEvent) { trace_scope!("scrollWheel:"); self.mouse_motion(event); let delta = { let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY()); if event.hasPreciseScrollingDeltas() { let delta = LogicalPosition::new(x, y).to_physical(self.scale_factor()); MouseScrollDelta::PixelDelta(delta) } else { MouseScrollDelta::LineDelta(x as f32, y as f32) } }; // The "momentum phase," if any, has higher priority than touch phase (the two should // be mutually exclusive anyhow, which is why the API is rather incoherent). If no momentum // phase is recorded (or rather, the started/ended cases of the momentum phase) then we // report the touch phase. let phase = match event.momentumPhase() { NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => { TouchPhase::Started } NSEventPhase::NSEventPhaseEnded | NSEventPhase::NSEventPhaseCancelled => { TouchPhase::Ended } _ => match event.phase() { NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => { TouchPhase::Started } NSEventPhase::NSEventPhaseEnded | NSEventPhase::NSEventPhaseCancelled => { TouchPhase::Ended } _ => TouchPhase::Moved, }, }; self.update_potentially_stale_modifiers(event); self.queue_device_event(DeviceEvent::MouseWheel { delta }); self.queue_event(WindowEvent::MouseWheel { device_id: DEVICE_ID, delta, phase, modifiers: event_mods(event), }); } #[sel(magnifyWithEvent:)] fn magnify_with_event(&self, event: &NSEvent) { trace_scope!("magnifyWithEvent:"); let phase = match event.phase() { NSEventPhase::NSEventPhaseBegan => TouchPhase::Started, NSEventPhase::NSEventPhaseChanged => TouchPhase::Moved, NSEventPhase::NSEventPhaseCancelled => TouchPhase::Cancelled, NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended, _ => return, }; self.queue_event(WindowEvent::TouchpadMagnify { device_id: DEVICE_ID, delta: event.magnification(), phase, }); } #[sel(smartMagnifyWithEvent:)] fn smart_magnify_with_event(&self, _event: &NSEvent) { trace_scope!("smartMagnifyWithEvent:"); self.queue_event(WindowEvent::SmartMagnify { device_id: DEVICE_ID, }); } #[sel(rotateWithEvent:)] fn rotate_with_event(&self, event: &NSEvent) { trace_scope!("rotateWithEvent:"); let phase = match event.phase() { NSEventPhase::NSEventPhaseBegan => TouchPhase::Started, NSEventPhase::NSEventPhaseChanged => TouchPhase::Moved, NSEventPhase::NSEventPhaseCancelled => TouchPhase::Cancelled, NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended, _ => return, }; self.queue_event(WindowEvent::TouchpadRotate { device_id: DEVICE_ID, delta: event.rotation(), phase, }); } #[sel(pressureChangeWithEvent:)] fn pressure_change_with_event(&mut self, event: &NSEvent) { trace_scope!("pressureChangeWithEvent:"); self.mouse_motion(event); self.queue_event(WindowEvent::TouchpadPressure { device_id: DEVICE_ID, pressure: event.pressure(), stage: event.stage() as i64, }); } // Allows us to receive Ctrl-Tab and Ctrl-Esc. // Note that this *doesn't* help with any missing Cmd inputs. // https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816 #[sel(_wantsKeyDownForEvent:)] fn wants_key_down_for_event(&self, _event: &NSEvent) -> bool { trace_scope!("_wantsKeyDownForEvent:"); true } #[sel(acceptsFirstMouse:)] fn accepts_first_mouse(&self, _event: &NSEvent) -> bool { trace_scope!("acceptsFirstMouse:"); *self.accepts_first_mouse } } ); impl WinitView { pub(super) fn new(window: &WinitWindow, accepts_first_mouse: bool) -> Id<Self, Shared> { unsafe { msg_send_id![ msg_send_id![Self::class(), alloc], initWithId: window, acceptsFirstMouse: accepts_first_mouse, ] } } fn window(&self) -> Id<WinitWindow, Shared> { // TODO: Simply use `window` property on `NSView`. // That only returns a window _after_ the view has been attached though! // (which is incompatible with `frameDidChange:`) // // unsafe { msg_send_id![self, window] } self._ns_window.load().expect("view to have a window") } fn window_id(&self) -> WindowId { WindowId(self.window().id()) } fn queue_event(&self, event: WindowEvent<'static>) { let event = Event::WindowEvent { window_id: self.window_id(), event, }; AppState::queue_event(EventWrapper::StaticEvent(event)); } fn queue_device_event(&self, event: DeviceEvent) { let event = Event::DeviceEvent { device_id: DEVICE_ID, event, }; AppState::queue_event(EventWrapper::StaticEvent(event)); } fn scale_factor(&self) -> f64 { self.window().backingScaleFactor() as f64 } fn is_ime_enabled(&self) -> bool { !matches!(self.state.ime_state, ImeState::Disabled) } fn current_input_source(&self) -> String { self.inputContext() .expect("input context") .selectedKeyboardInputSource() .map(|input_source| input_source.to_string()) .unwrap_or_else(String::new) } pub(super) fn set_ime_allowed(&mut self, ime_allowed: bool) { if self.state.ime_allowed == ime_allowed { return; } self.state.ime_allowed = ime_allowed; if self.state.ime_allowed { return; } // Clear markedText *self.marked_text = NSMutableAttributedString::new(); if self.state.ime_state != ImeState::Disabled { self.state.ime_state = ImeState::Disabled; self.queue_event(WindowEvent::Ime(Ime::Disabled)); } } pub(super) fn set_ime_position(&mut self, position: LogicalPosition<f64>) { self.state.ime_position = position; let input_context = self.inputContext().expect("input context"); input_context.invalidateCharacterCoordinates(); } // Update `state.modifiers` if `event` has something different fn update_potentially_stale_modifiers(&mut self, event: &NSEvent) { let event_modifiers = event_mods(event); if self.state.modifiers != event_modifiers { self.state.modifiers = event_modifiers; self.queue_event(WindowEvent::ModifiersChanged(self.state.modifiers)); } } fn mouse_click(&mut self, event: &NSEvent, button_state: ElementState) { let button = mouse_button(event); self.update_potentially_stale_modifiers(event); self.queue_event(WindowEvent::MouseInput { device_id: DEVICE_ID, state: button_state, button, modifiers: event_mods(event), }); } fn mouse_motion(&mut self, event: &NSEvent) { let window_point = event.locationInWindow(); let view_point = self.convertPoint_fromView(window_point, None); let view_rect = self.frame(); if view_point.x.is_sign_negative() || view_point.y.is_sign_negative() || view_point.x > view_rect.size.width || view_point.y > view_rect.size.height { let mouse_buttons_down = NSEvent::pressedMouseButtons(); if mouse_buttons_down == 0 { // Point is outside of the client area (view) and no buttons are pressed return; } } let x = view_point.x as f64; let y = view_rect.size.height as f64 - view_point.y as f64; let logical_position = LogicalPosition::new(x, y); self.update_potentially_stale_modifiers(event); self.queue_event(WindowEvent::CursorMoved { device_id: DEVICE_ID, position: logical_position.to_physical(self.scale_factor()), modifiers: event_mods(event), }); } } /// Get the mouse button from the NSEvent. fn mouse_button(event: &NSEvent) -> MouseButton { // The buttonNumber property only makes sense for the mouse events: // NSLeftMouse.../NSRightMouse.../NSOtherMouse... // For the other events, it's always set to 0. match event.buttonNumber() { 0 => MouseButton::Left, 1 => MouseButton::Right, 2 => MouseButton::Middle, n => MouseButton::Other(n as u16), } } fn replace_event_chars(event: &NSEvent, characters: &str) -> Id<NSEvent, Shared> { let ns_chars = NSString::from_str(characters); let chars_ignoring_mods = event.charactersIgnoringModifiers().unwrap(); NSEvent::keyEventWithType( event.type_(), event.locationInWindow(), event.modifierFlags(), event.timestamp(), event.window_number(), None, &ns_chars, &chars_ignoring_mods, event.is_a_repeat(), event.scancode(), ) }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/window.rs
Rust
#![allow(clippy::unnecessary_cast)] use std::{ collections::VecDeque, f64, ops, os::raw::c_void, sync::{ atomic::{AtomicBool, Ordering}, Mutex, MutexGuard, }, }; use raw_window_handle::{ AppKitDisplayHandle, AppKitWindowHandle, RawDisplayHandle, RawWindowHandle, }; use crate::{ dpi::{ LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size, Size::Logical, }, error::{ExternalError, NotSupportedError, OsError as RootOsError}, event::WindowEvent, icon::Icon, platform::macos::{OptionAsAlt, WindowExtMacOS}, platform_impl::platform::{ app_state::AppState, appkit::NSWindowOrderingMode, ffi, monitor::{self, MonitorHandle, VideoMode}, util, view::WinitView, window_delegate::WinitWindowDelegate, Fullscreen, OsError, }, window::{ CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, WindowButtons, WindowId as RootWindowId, WindowLevel, }, }; use core_graphics::display::{CGDisplay, CGPoint}; use objc2::declare::{Ivar, IvarDrop}; use objc2::foundation::{ is_main_thread, CGFloat, NSArray, NSCopying, NSInteger, NSObject, NSPoint, NSRect, NSSize, NSString, }; use objc2::rc::{autoreleasepool, Id, Owned, Shared}; use objc2::{declare_class, msg_send, msg_send_id, sel, ClassType}; use super::appkit::{ NSApp, NSAppKitVersion, NSAppearance, NSApplicationPresentationOptions, NSBackingStoreType, NSColor, NSCursor, NSFilenamesPboardType, NSRequestUserAttentionType, NSResponder, NSScreen, NSView, NSWindow, NSWindowButton, NSWindowLevel, NSWindowSharingType, NSWindowStyleMask, NSWindowTitleVisibility, }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WindowId(pub usize); impl WindowId { pub const unsafe fn dummy() -> Self { Self(0) } } impl From<WindowId> for u64 { fn from(window_id: WindowId) -> Self { window_id.0 as u64 } } impl From<u64> for WindowId { fn from(raw_id: u64) -> Self { Self(raw_id as usize) } } #[derive(Clone)] pub struct PlatformSpecificWindowBuilderAttributes { pub movable_by_window_background: bool, pub titlebar_transparent: bool, pub title_hidden: bool, pub titlebar_hidden: bool, pub titlebar_buttons_hidden: bool, pub fullsize_content_view: bool, pub disallow_hidpi: bool, pub has_shadow: bool, pub accepts_first_mouse: bool, pub option_as_alt: OptionAsAlt, } impl Default for PlatformSpecificWindowBuilderAttributes { #[inline] fn default() -> Self { Self { movable_by_window_background: false, titlebar_transparent: false, title_hidden: false, titlebar_hidden: false, titlebar_buttons_hidden: false, fullsize_content_view: false, disallow_hidpi: false, has_shadow: true, accepts_first_mouse: true, option_as_alt: Default::default(), } } } declare_class!( #[derive(Debug)] pub(crate) struct WinitWindow { // TODO: Fix unnecessary boxing here // SAFETY: These are initialized in WinitWindow::new, right after it is created. shared_state: IvarDrop<Box<Mutex<SharedState>>>, decorations: IvarDrop<Box<AtomicBool>>, } unsafe impl ClassType for WinitWindow { #[inherits(NSResponder, NSObject)] type Super = NSWindow; } unsafe impl WinitWindow { #[sel(canBecomeMainWindow)] fn can_become_main_window(&self) -> bool { trace_scope!("canBecomeMainWindow"); true } #[sel(canBecomeKeyWindow)] fn can_become_key_window(&self) -> bool { trace_scope!("canBecomeKeyWindow"); true } } ); #[derive(Debug, Default)] pub struct SharedState { pub resizable: bool, /// This field tracks the current fullscreen state of the window /// (as seen by `WindowDelegate`). pub(crate) fullscreen: Option<Fullscreen>, // This is true between windowWillEnterFullScreen and windowDidEnterFullScreen // or windowWillExitFullScreen and windowDidExitFullScreen. // We must not toggle fullscreen when this is true. pub in_fullscreen_transition: bool, // If it is attempted to toggle fullscreen when in_fullscreen_transition is true, // Set target_fullscreen and do after fullscreen transition is end. pub(crate) target_fullscreen: Option<Option<Fullscreen>>, pub maximized: bool, pub standard_frame: Option<NSRect>, pub(crate) is_simple_fullscreen: bool, pub saved_style: Option<NSWindowStyleMask>, /// Presentation options saved before entering `set_simple_fullscreen`, and /// restored upon exiting it. Also used when transitioning from Borderless to /// Exclusive fullscreen in `set_fullscreen` because we need to disable the menu /// bar in exclusive fullscreen but want to restore the original options when /// transitioning back to borderless fullscreen. save_presentation_opts: Option<NSApplicationPresentationOptions>, pub current_theme: Option<Theme>, /// The current resize incerments for the window content. pub(crate) resize_increments: NSSize, /// The state of the `Option` as `Alt`. pub(crate) option_as_alt: OptionAsAlt, } impl SharedState { pub fn saved_standard_frame(&self) -> NSRect { self.standard_frame .unwrap_or_else(|| NSRect::new(NSPoint::new(50.0, 50.0), NSSize::new(800.0, 600.0))) } } pub(crate) struct SharedStateMutexGuard<'a> { guard: MutexGuard<'a, SharedState>, called_from_fn: &'static str, } impl<'a> SharedStateMutexGuard<'a> { #[inline] fn new(guard: MutexGuard<'a, SharedState>, called_from_fn: &'static str) -> Self { trace!("Locked shared state in `{}`", called_from_fn); Self { guard, called_from_fn, } } } impl ops::Deref for SharedStateMutexGuard<'_> { type Target = SharedState; #[inline] fn deref(&self) -> &Self::Target { self.guard.deref() } } impl ops::DerefMut for SharedStateMutexGuard<'_> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.guard.deref_mut() } } impl Drop for SharedStateMutexGuard<'_> { #[inline] fn drop(&mut self) { trace!("Unlocked shared state in `{}`", self.called_from_fn); } } impl WinitWindow { #[allow(clippy::type_complexity)] pub(crate) fn new( attrs: WindowAttributes, pl_attrs: PlatformSpecificWindowBuilderAttributes, ) -> Result<(Id<Self, Shared>, Id<WinitWindowDelegate, Shared>), RootOsError> { trace_scope!("WinitWindow::new"); if !is_main_thread() { panic!("Windows can only be created on the main thread on macOS"); } let this = autoreleasepool(|_| { let screen = match attrs.fullscreen.clone().map(Into::into) { Some(Fullscreen::Borderless(Some(monitor))) | Some(Fullscreen::Exclusive(VideoMode { monitor, .. })) => { monitor.ns_screen().or_else(NSScreen::main) } Some(Fullscreen::Borderless(None)) => NSScreen::main(), None => None, }; let frame = match &screen { Some(screen) => screen.frame(), None => { let scale_factor = NSScreen::main() .map(|screen| screen.backingScaleFactor() as f64) .unwrap_or(1.0); let (width, height) = match attrs.inner_size { Some(size) => { let logical = size.to_logical(scale_factor); (logical.width, logical.height) } None => (800.0, 600.0), }; let (left, bottom) = match attrs.position { Some(position) => { let logical = util::window_position(position.to_logical(scale_factor)); // macOS wants the position of the bottom left corner, // but caller is setting the position of top left corner (logical.x, logical.y - height) } // This value is ignored by calling win.center() below None => (0.0, 0.0), }; NSRect::new(NSPoint::new(left, bottom), NSSize::new(width, height)) } }; let mut masks = if (!attrs.decorations && screen.is_none()) || pl_attrs.titlebar_hidden { // Resizable without a titlebar or borders // if decorations is set to false, ignore pl_attrs // // if the titlebar is hidden, ignore other pl_attrs NSWindowStyleMask::NSBorderlessWindowMask | NSWindowStyleMask::NSResizableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask } else { // default case, resizable window with titlebar and titlebar buttons NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask | NSWindowStyleMask::NSResizableWindowMask | NSWindowStyleMask::NSTitledWindowMask }; if !attrs.resizable { masks &= !NSWindowStyleMask::NSResizableWindowMask; } if !attrs.enabled_buttons.contains(WindowButtons::MINIMIZE) { masks &= !NSWindowStyleMask::NSMiniaturizableWindowMask; } if !attrs.enabled_buttons.contains(WindowButtons::CLOSE) { masks &= !NSWindowStyleMask::NSClosableWindowMask; } if pl_attrs.fullsize_content_view { masks |= NSWindowStyleMask::NSFullSizeContentViewWindowMask; } let this: Option<Id<Self, Owned>> = unsafe { msg_send_id![ msg_send_id![WinitWindow::class(), alloc], initWithContentRect: frame, styleMask: masks, backing: NSBackingStoreType::NSBackingStoreBuffered, defer: false, ] }; this.map(|mut this| { let resize_increments = match attrs .resize_increments .map(|i| i.to_logical::<f64>(this.scale_factor())) { Some(LogicalSize { width, height }) if width >= 1. && height >= 1. => { NSSize::new(width, height) } _ => NSSize::new(1., 1.), }; // Properly initialize the window's variables // // Ideally this should be done in an `init` method, // but for convenience we do it here instead. let state = SharedState { resizable: attrs.resizable, maximized: attrs.maximized, resize_increments, ..Default::default() }; Ivar::write(&mut this.shared_state, Box::new(Mutex::new(state))); Ivar::write( &mut this.decorations, Box::new(AtomicBool::new(attrs.decorations)), ); this.setReleasedWhenClosed(false); this.setTitle(&NSString::from_str(&attrs.title)); this.setAcceptsMouseMovedEvents(true); if attrs.content_protected { this.setSharingType(NSWindowSharingType::NSWindowSharingNone); } if pl_attrs.titlebar_transparent { this.setTitlebarAppearsTransparent(true); } if pl_attrs.title_hidden { this.setTitleVisibility(NSWindowTitleVisibility::Hidden); } if pl_attrs.titlebar_buttons_hidden { for titlebar_button in &[ #[allow(deprecated)] NSWindowButton::FullScreen, NSWindowButton::Miniaturize, NSWindowButton::Close, NSWindowButton::Zoom, ] { if let Some(button) = this.standardWindowButton(*titlebar_button) { button.setHidden(true); } } } if pl_attrs.movable_by_window_background { this.setMovableByWindowBackground(true); } if !attrs.enabled_buttons.contains(WindowButtons::MAXIMIZE) { if let Some(button) = this.standardWindowButton(NSWindowButton::Zoom) { button.setEnabled(false); } } if !pl_attrs.has_shadow { this.setHasShadow(false); } if attrs.position.is_none() { this.center(); } this.set_option_as_alt(pl_attrs.option_as_alt); Id::into_shared(this) }) }) .ok_or_else(|| os_error!(OsError::CreationError("Couldn't create `NSWindow`")))?; match attrs.parent_window { Some(RawWindowHandle::AppKit(handle)) => { // SAFETY: Caller ensures the pointer is valid or NULL let parent: Id<NSWindow, Shared> = match unsafe { Id::retain(handle.ns_window.cast()) } { Some(window) => window, None => { // SAFETY: Caller ensures the pointer is valid or NULL let parent_view: Id<NSView, Shared> = match unsafe { Id::retain(handle.ns_view.cast()) } { Some(view) => view, None => { return Err(os_error!(OsError::CreationError( "raw window handle should be non-empty" ))) } }; parent_view.window().ok_or_else(|| { os_error!(OsError::CreationError( "parent view should be installed in a window" )) })? } }; // SAFETY: We know that there are no parent -> child -> parent cycles since the only place in `winit` // where we allow making a window a child window is right here, just after it's been created. unsafe { parent.addChildWindow(&this, NSWindowOrderingMode::NSWindowAbove) }; } Some(raw) => panic!("Invalid raw window handle {raw:?} on macOS"), None => (), } let view = WinitView::new(&this, pl_attrs.accepts_first_mouse); // The default value of `setWantsBestResolutionOpenGLSurface:` was `false` until // macos 10.14 and `true` after 10.15, we should set it to `YES` or `NO` to avoid // always the default system value in favour of the user's code view.setWantsBestResolutionOpenGLSurface(!pl_attrs.disallow_hidpi); // On Mojave, views automatically become layer-backed shortly after being added to // a window. Changing the layer-backedness of a view breaks the association between // the view and its associated OpenGL context. To work around this, on Mojave we // explicitly make the view layer-backed up front so that AppKit doesn't do it // itself and break the association with its context. if NSAppKitVersion::current().floor() > NSAppKitVersion::NSAppKitVersionNumber10_12 { view.setWantsLayer(true); } // Configure the new view as the "key view" for the window this.setContentView(&view); this.setInitialFirstResponder(&view); if attrs.transparent { this.setOpaque(false); this.setBackgroundColor(&NSColor::clear()); } if let Some(dim) = attrs.min_inner_size { this.set_min_inner_size(Some(dim)); } if let Some(dim) = attrs.max_inner_size { this.set_max_inner_size(Some(dim)); } this.set_window_level(attrs.window_level); // register for drag and drop operations. this.registerForDraggedTypes(&NSArray::from_slice(&[ unsafe { NSFilenamesPboardType }.copy() ])); match attrs.preferred_theme { Some(theme) => { set_ns_theme(Some(theme)); let mut state = this.lock_shared_state("WinitWindow::new"); state.current_theme = Some(theme); } None => { let mut state = this.lock_shared_state("WinitWindow::new"); state.current_theme = Some(get_ns_theme()); } } let delegate = WinitWindowDelegate::new(&this, attrs.fullscreen.is_some()); // XXX Send `Focused(false)` right after creating the window delegate, so we won't // obscure the real focused events on the startup. delegate.queue_event(WindowEvent::Focused(false)); // Set fullscreen mode after we setup everything this.set_fullscreen(attrs.fullscreen.map(Into::into)); // Setting the window as key has to happen *after* we set the fullscreen // state, since otherwise we'll briefly see the window at normal size // before it transitions. if attrs.visible { if attrs.active { // Tightly linked with `app_state::window_activation_hack` this.makeKeyAndOrderFront(None); } else { this.orderFront(None); } } if attrs.maximized { this.set_maximized(attrs.maximized); } Ok((this, delegate)) } pub(super) fn retain(&self) -> Id<WinitWindow, Shared> { // SAFETY: The pointer is valid, and the window is always `Shared` // TODO(madsmtm): Remove the need for unsafety here unsafe { Id::retain(self as *const Self as *mut Self).unwrap() } } pub(super) fn view(&self) -> Id<WinitView, Shared> { // SAFETY: The view inside WinitWindow is always `WinitView` unsafe { Id::cast(self.contentView()) } } #[track_caller] pub(crate) fn lock_shared_state( &self, called_from_fn: &'static str, ) -> SharedStateMutexGuard<'_> { SharedStateMutexGuard::new(self.shared_state.lock().unwrap(), called_from_fn) } fn set_style_mask_sync(&self, mask: NSWindowStyleMask) { util::set_style_mask_sync(self, mask); } pub fn id(&self) -> WindowId { WindowId(self as *const Self as usize) } pub fn set_title(&self, title: &str) { util::set_title_sync(self, title); } pub fn set_transparent(&self, transparent: bool) { self.setOpaque(!transparent) } pub fn set_visible(&self, visible: bool) { match visible { true => util::make_key_and_order_front_sync(self), false => util::order_out_sync(self), } } #[inline] pub fn is_visible(&self) -> Option<bool> { Some(self.isVisible()) } pub fn request_redraw(&self) { AppState::queue_redraw(RootWindowId(self.id())); } pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { let frame_rect = self.frame(); let position = LogicalPosition::new( frame_rect.origin.x as f64, util::bottom_left_to_top_left(frame_rect), ); let scale_factor = self.scale_factor(); Ok(position.to_physical(scale_factor)) } pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { let content_rect = self.contentRectForFrameRect(self.frame()); let position = LogicalPosition::new( content_rect.origin.x as f64, util::bottom_left_to_top_left(content_rect), ); let scale_factor = self.scale_factor(); Ok(position.to_physical(scale_factor)) } pub fn set_outer_position(&self, position: Position) { let scale_factor = self.scale_factor(); let position = position.to_logical(scale_factor); util::set_frame_top_left_point_sync(self, util::window_position(position)); } #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { let frame = self.contentView().frame(); let logical: LogicalSize<f64> = (frame.size.width as f64, frame.size.height as f64).into(); let scale_factor = self.scale_factor(); logical.to_physical(scale_factor) } #[inline] pub fn outer_size(&self) -> PhysicalSize<u32> { let frame = self.frame(); let logical: LogicalSize<f64> = (frame.size.width as f64, frame.size.height as f64).into(); let scale_factor = self.scale_factor(); logical.to_physical(scale_factor) } #[inline] pub fn set_inner_size(&self, size: Size) { let scale_factor = self.scale_factor(); util::set_content_size_sync(self, size.to_logical(scale_factor)); } pub fn set_min_inner_size(&self, dimensions: Option<Size>) { let dimensions = dimensions.unwrap_or(Logical(LogicalSize { width: 0.0, height: 0.0, })); let min_size = dimensions.to_logical::<CGFloat>(self.scale_factor()); let mut current_rect = self.frame(); let content_rect = self.contentRectForFrameRect(current_rect); // Convert from client area size to window size let min_size = NSSize::new( min_size.width + (current_rect.size.width - content_rect.size.width), // this tends to be 0 min_size.height + (current_rect.size.height - content_rect.size.height), ); self.setMinSize(min_size); // If necessary, resize the window to match constraint if current_rect.size.width < min_size.width { current_rect.size.width = min_size.width; self.setFrame_display(current_rect, false) } if current_rect.size.height < min_size.height { // The origin point of a rectangle is at its bottom left in Cocoa. // To ensure the window's top-left point remains the same: current_rect.origin.y += current_rect.size.height - min_size.height; current_rect.size.height = min_size.height; self.setFrame_display(current_rect, false) } } pub fn set_max_inner_size(&self, dimensions: Option<Size>) { let dimensions = dimensions.unwrap_or(Logical(LogicalSize { width: std::f32::MAX as f64, height: std::f32::MAX as f64, })); let scale_factor = self.scale_factor(); let max_size = dimensions.to_logical::<CGFloat>(scale_factor); let mut current_rect = self.frame(); let content_rect = self.contentRectForFrameRect(current_rect); // Convert from client area size to window size let max_size = NSSize::new( max_size.width + (current_rect.size.width - content_rect.size.width), // this tends to be 0 max_size.height + (current_rect.size.height - content_rect.size.height), ); self.setMaxSize(max_size); // If necessary, resize the window to match constraint if current_rect.size.width > max_size.width { current_rect.size.width = max_size.width; self.setFrame_display(current_rect, false) } if current_rect.size.height > max_size.height { // The origin point of a rectangle is at its bottom left in Cocoa. // To ensure the window's top-left point remains the same: current_rect.origin.y += current_rect.size.height - max_size.height; current_rect.size.height = max_size.height; self.setFrame_display(current_rect, false) } } pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { let increments = self .lock_shared_state("set_resize_increments") .resize_increments; let (w, h) = (increments.width, increments.height); if w > 1.0 || h > 1.0 { Some(LogicalSize::new(w, h).to_physical(self.scale_factor())) } else { None } } pub fn set_resize_increments(&self, increments: Option<Size>) { // XXX the resize increments are only used during live resizes. let mut shared_state_lock = self.lock_shared_state("set_resize_increments"); shared_state_lock.resize_increments = increments .map(|increments| { let logical = increments.to_logical::<f64>(self.scale_factor()); NSSize::new(logical.width.max(1.0), logical.height.max(1.0)) }) .unwrap_or_else(|| NSSize::new(1.0, 1.0)); } pub(crate) fn set_resize_increments_inner(&self, size: NSSize) { // It was concluded (#2411) that there is never a use-case for // "outer" resize increments, hence we set "inner" ones here. // ("outer" in macOS being just resizeIncrements, and "inner" - contentResizeIncrements) // This is consistent with X11 size hints behavior self.setContentResizeIncrements(size); } #[inline] pub fn set_resizable(&self, resizable: bool) { let fullscreen = { let mut shared_state_lock = self.lock_shared_state("set_resizable"); shared_state_lock.resizable = resizable; shared_state_lock.fullscreen.is_some() }; if !fullscreen { let mut mask = self.styleMask(); if resizable { mask |= NSWindowStyleMask::NSResizableWindowMask; } else { mask &= !NSWindowStyleMask::NSResizableWindowMask; } self.set_style_mask_sync(mask); } // Otherwise, we don't change the mask until we exit fullscreen. } #[inline] pub fn is_resizable(&self) -> bool { self.isResizable() } #[inline] pub fn set_enabled_buttons(&self, buttons: WindowButtons) { let mut mask = self.styleMask(); if buttons.contains(WindowButtons::CLOSE) { mask |= NSWindowStyleMask::NSClosableWindowMask; } else { mask &= !NSWindowStyleMask::NSClosableWindowMask; } if buttons.contains(WindowButtons::MINIMIZE) { mask |= NSWindowStyleMask::NSMiniaturizableWindowMask; } else { mask &= !NSWindowStyleMask::NSMiniaturizableWindowMask; } // This must happen before the button's "enabled" status has been set, // hence we do it synchronously. self.set_style_mask_sync(mask); // We edit the button directly instead of using `NSResizableWindowMask`, // since that mask also affect the resizability of the window (which is // controllable by other means in `winit`). if let Some(button) = self.standardWindowButton(NSWindowButton::Zoom) { button.setEnabled(buttons.contains(WindowButtons::MAXIMIZE)); } } #[inline] pub fn enabled_buttons(&self) -> WindowButtons { let mut buttons = WindowButtons::empty(); if self.isMiniaturizable() { buttons |= WindowButtons::MINIMIZE; } if self .standardWindowButton(NSWindowButton::Zoom) .map(|b| b.isEnabled()) .unwrap_or(true) { buttons |= WindowButtons::MAXIMIZE; } if self.hasCloseBox() { buttons |= WindowButtons::CLOSE; } buttons } pub fn set_cursor_icon(&self, icon: CursorIcon) { let view = self.view(); let mut cursor_state = view.state.cursor_state.lock().unwrap(); cursor_state.cursor = NSCursor::from_icon(icon); drop(cursor_state); self.invalidateCursorRectsForView(&view); } #[inline] pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { let associate_mouse_cursor = match mode { CursorGrabMode::Locked => false, CursorGrabMode::None => true, CursorGrabMode::Confined => { return Err(ExternalError::NotSupported(NotSupportedError::new())) } }; // TODO: Do this for real https://stackoverflow.com/a/40922095/5435443 CGDisplay::associate_mouse_and_mouse_cursor_position(associate_mouse_cursor) .map_err(|status| ExternalError::Os(os_error!(OsError::CGError(status)))) } #[inline] pub fn set_cursor_visible(&self, visible: bool) { let view = self.view(); let mut cursor_state = view.state.cursor_state.lock().unwrap(); if visible != cursor_state.visible { cursor_state.visible = visible; drop(cursor_state); self.invalidateCursorRectsForView(&view); } } #[inline] pub fn scale_factor(&self) -> f64 { self.backingScaleFactor() as f64 } #[inline] pub fn set_cursor_position(&self, cursor_position: Position) -> Result<(), ExternalError> { let physical_window_position = self.inner_position().unwrap(); let scale_factor = self.scale_factor(); let window_position = physical_window_position.to_logical::<CGFloat>(scale_factor); let logical_cursor_position = cursor_position.to_logical::<CGFloat>(scale_factor); let point = CGPoint { x: logical_cursor_position.x + window_position.x, y: logical_cursor_position.y + window_position.y, }; CGDisplay::warp_mouse_cursor_position(point) .map_err(|e| ExternalError::Os(os_error!(OsError::CGError(e))))?; CGDisplay::associate_mouse_and_mouse_cursor_position(true) .map_err(|e| ExternalError::Os(os_error!(OsError::CGError(e))))?; Ok(()) } #[inline] pub fn drag_window(&self) -> Result<(), ExternalError> { let event = NSApp().currentEvent(); self.performWindowDragWithEvent(event.as_deref()); Ok(()) } #[inline] pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } #[inline] pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { util::set_ignore_mouse_events_sync(self, !hittest); Ok(()) } pub(crate) fn is_zoomed(&self) -> bool { // because `isZoomed` doesn't work if the window's borderless, // we make it resizable temporalily. let curr_mask = self.styleMask(); let required = NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSResizableWindowMask; let needs_temp_mask = !curr_mask.contains(required); if needs_temp_mask { self.set_style_mask_sync(required); } let is_zoomed = self.isZoomed(); // Roll back temp styles if needs_temp_mask { self.set_style_mask_sync(curr_mask); } is_zoomed } fn saved_style(&self, shared_state: &mut SharedState) -> NSWindowStyleMask { let base_mask = shared_state .saved_style .take() .unwrap_or_else(|| self.styleMask()); if shared_state.resizable { base_mask | NSWindowStyleMask::NSResizableWindowMask } else { base_mask & !NSWindowStyleMask::NSResizableWindowMask } } /// This is called when the window is exiting fullscreen, whether by the /// user clicking on the green fullscreen button or programmatically by /// `toggleFullScreen:` pub(crate) fn restore_state_from_fullscreen(&self) { let mut shared_state_lock = self.lock_shared_state("restore_state_from_fullscreen"); shared_state_lock.fullscreen = None; let maximized = shared_state_lock.maximized; let mask = self.saved_style(&mut shared_state_lock); drop(shared_state_lock); self.set_style_mask_sync(mask); self.set_maximized(maximized); } #[inline] pub fn set_minimized(&self, minimized: bool) { let is_minimized = self.isMiniaturized(); if is_minimized == minimized { return; } if minimized { self.miniaturize(Some(self)); } else { self.deminiaturize(Some(self)); } } #[inline] pub fn is_minimized(&self) -> Option<bool> { Some(self.isMiniaturized()) } #[inline] pub fn set_maximized(&self, maximized: bool) { let is_zoomed = self.is_zoomed(); if is_zoomed == maximized { return; }; util::set_maximized_sync(self, is_zoomed, maximized); } #[inline] pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { let shared_state_lock = self.lock_shared_state("fullscreen"); shared_state_lock.fullscreen.clone() } #[inline] pub fn is_maximized(&self) -> bool { self.is_zoomed() } #[inline] pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { let mut shared_state_lock = self.lock_shared_state("set_fullscreen"); if shared_state_lock.is_simple_fullscreen { return; } if shared_state_lock.in_fullscreen_transition { // We can't set fullscreen here. // Set fullscreen after transition. shared_state_lock.target_fullscreen = Some(fullscreen); return; } let old_fullscreen = shared_state_lock.fullscreen.clone(); if fullscreen == old_fullscreen { return; } drop(shared_state_lock); // If the fullscreen is on a different monitor, we must move the window // to that monitor before we toggle fullscreen (as `toggleFullScreen` // does not take a screen parameter, but uses the current screen) if let Some(ref fullscreen) = fullscreen { let new_screen = match fullscreen { Fullscreen::Borderless(Some(monitor)) => monitor.clone(), Fullscreen::Borderless(None) => { if let Some(monitor) = self.current_monitor_inner() { monitor } else { return; } } Fullscreen::Exclusive(video_mode) => video_mode.monitor(), } .ns_screen() .unwrap(); let old_screen = self.screen().unwrap(); if old_screen != new_screen { let mut screen_frame = new_screen.frame(); // The coordinate system here has its origin at bottom-left // and Y goes up screen_frame.origin.y += screen_frame.size.height; util::set_frame_top_left_point_sync(self, screen_frame.origin); } } if let Some(Fullscreen::Exclusive(ref video_mode)) = fullscreen { // Note: `enterFullScreenMode:withOptions:` seems to do the exact // same thing as we're doing here (captures the display, sets the // video mode, and hides the menu bar and dock), with the exception // of that I couldn't figure out how to set the display mode with // it. I think `enterFullScreenMode:withOptions:` is still using the // older display mode API where display modes were of the type // `CFDictionary`, but this has changed, so we can't obtain the // correct parameter for this any longer. Apple's code samples for // this function seem to just pass in "YES" for the display mode // parameter, which is not consistent with the docs saying that it // takes a `NSDictionary`.. let display_id = video_mode.monitor().native_identifier(); let mut fade_token = ffi::kCGDisplayFadeReservationInvalidToken; if matches!(old_fullscreen, Some(Fullscreen::Borderless(_))) { let app = NSApp(); let mut shared_state_lock = self.lock_shared_state("set_fullscreen"); shared_state_lock.save_presentation_opts = Some(app.presentationOptions()); } unsafe { // Fade to black (and wait for the fade to complete) to hide the // flicker from capturing the display and switching display mode if ffi::CGAcquireDisplayFadeReservation(5.0, &mut fade_token) == ffi::kCGErrorSuccess { ffi::CGDisplayFade( fade_token, 0.3, ffi::kCGDisplayBlendNormal, ffi::kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, ffi::TRUE, ); } assert_eq!(ffi::CGDisplayCapture(display_id), ffi::kCGErrorSuccess); } unsafe { let result = ffi::CGDisplaySetDisplayMode( display_id, video_mode.native_mode.0, std::ptr::null(), ); assert!(result == ffi::kCGErrorSuccess, "failed to set video mode"); // After the display has been configured, fade back in // asynchronously if fade_token != ffi::kCGDisplayFadeReservationInvalidToken { ffi::CGDisplayFade( fade_token, 0.6, ffi::kCGDisplayBlendSolidColor, ffi::kCGDisplayBlendNormal, 0.0, 0.0, 0.0, ffi::FALSE, ); ffi::CGReleaseDisplayFadeReservation(fade_token); } } } self.lock_shared_state("set_fullscreen").fullscreen = fullscreen.clone(); match (&old_fullscreen, &fullscreen) { (&None, &Some(_)) => { util::toggle_full_screen_sync(self, old_fullscreen.is_none()); } (&Some(Fullscreen::Borderless(_)), &None) => { // State is restored by `window_did_exit_fullscreen` util::toggle_full_screen_sync(self, old_fullscreen.is_none()); } (&Some(Fullscreen::Exclusive(ref video_mode)), &None) => { unsafe { util::restore_display_mode_sync(video_mode.monitor().native_identifier()) }; // Rest of the state is restored by `window_did_exit_fullscreen` util::toggle_full_screen_sync(self, old_fullscreen.is_none()); } (&Some(Fullscreen::Borderless(_)), &Some(Fullscreen::Exclusive(_))) => { // If we're already in fullscreen mode, calling // `CGDisplayCapture` will place the shielding window on top of // our window, which results in a black display and is not what // we want. So, we must place our window on top of the shielding // window. Unfortunately, this also makes our window be on top // of the menu bar, and this looks broken, so we must make sure // that the menu bar is disabled. This is done in the window // delegate in `window:willUseFullScreenPresentationOptions:`. let app = NSApp(); self.lock_shared_state("set_fullscreen") .save_presentation_opts = Some(app.presentationOptions()); let presentation_options = NSApplicationPresentationOptions::NSApplicationPresentationFullScreen | NSApplicationPresentationOptions::NSApplicationPresentationHideDock | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; app.setPresentationOptions(presentation_options); let window_level = NSWindowLevel(unsafe { ffi::CGShieldingWindowLevel() } as NSInteger + 1); self.setLevel(window_level); } (&Some(Fullscreen::Exclusive(ref video_mode)), &Some(Fullscreen::Borderless(_))) => { let presentation_options = self .lock_shared_state("set_fullscreen") .save_presentation_opts .unwrap_or_else(|| { NSApplicationPresentationOptions::NSApplicationPresentationFullScreen | NSApplicationPresentationOptions::NSApplicationPresentationAutoHideDock | NSApplicationPresentationOptions::NSApplicationPresentationAutoHideMenuBar }); NSApp().setPresentationOptions(presentation_options); unsafe { util::restore_display_mode_sync(video_mode.monitor().native_identifier()) }; // Restore the normal window level following the Borderless fullscreen // `CGShieldingWindowLevel() + 1` hack. self.setLevel(NSWindowLevel::Normal); } _ => {} }; } #[inline] pub fn set_decorations(&self, decorations: bool) { if decorations != self.decorations.load(Ordering::Acquire) { self.decorations.store(decorations, Ordering::Release); let (fullscreen, resizable) = { let shared_state_lock = self.lock_shared_state("set_decorations"); ( shared_state_lock.fullscreen.is_some(), shared_state_lock.resizable, ) }; // If we're in fullscreen mode, we wait to apply decoration changes // until we're in `window_did_exit_fullscreen`. if fullscreen { return; } let new_mask = { let mut new_mask = if decorations { NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask | NSWindowStyleMask::NSResizableWindowMask | NSWindowStyleMask::NSTitledWindowMask } else { NSWindowStyleMask::NSBorderlessWindowMask | NSWindowStyleMask::NSResizableWindowMask }; if !resizable { new_mask &= !NSWindowStyleMask::NSResizableWindowMask; } new_mask }; self.set_style_mask_sync(new_mask); } } #[inline] pub fn is_decorated(&self) -> bool { self.decorations.load(Ordering::Acquire) } #[inline] pub fn set_window_level(&self, level: WindowLevel) { let level = match level { WindowLevel::AlwaysOnTop => NSWindowLevel::Floating, WindowLevel::AlwaysOnBottom => NSWindowLevel::BELOW_NORMAL, WindowLevel::Normal => NSWindowLevel::Normal, }; util::set_level_sync(self, level); } #[inline] pub fn set_window_icon(&self, _icon: Option<Icon>) { // macOS doesn't have window icons. Though, there is // `setRepresentedFilename`, but that's semantically distinct and should // only be used when the window is in some way representing a specific // file/directory. For instance, Terminal.app uses this for the CWD. // Anyway, that should eventually be implemented as // `WindowBuilderExt::with_represented_file` or something, and doesn't // have anything to do with `set_window_icon`. // https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/WinPanel/Tasks/SettingWindowTitle.html } #[inline] pub fn set_ime_position(&self, spot: Position) { let scale_factor = self.scale_factor(); let logical_spot = spot.to_logical(scale_factor); util::set_ime_position_sync(self, logical_spot); } #[inline] pub fn set_ime_allowed(&self, allowed: bool) { // TODO(madsmtm): Remove the need for this unsafe { Id::from_shared(self.view()) }.set_ime_allowed(allowed); } #[inline] pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} #[inline] pub fn focus_window(&self) { let is_minimized = self.isMiniaturized(); let is_visible = self.isVisible(); if !is_minimized && is_visible { NSApp().activateIgnoringOtherApps(true); util::make_key_and_order_front_sync(self); } } #[inline] pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { let ns_request_type = request_type.map(|ty| match ty { UserAttentionType::Critical => NSRequestUserAttentionType::NSCriticalRequest, UserAttentionType::Informational => NSRequestUserAttentionType::NSInformationalRequest, }); if let Some(ty) = ns_request_type { NSApp().requestUserAttention(ty); } } #[inline] // Allow directly accessing the current monitor internally without unwrapping. pub(crate) fn current_monitor_inner(&self) -> Option<MonitorHandle> { let display_id = self.screen()?.display_id(); Some(MonitorHandle::new(display_id)) } #[inline] pub fn current_monitor(&self) -> Option<MonitorHandle> { self.current_monitor_inner() } #[inline] pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { monitor::available_monitors() } #[inline] pub fn primary_monitor(&self) -> Option<MonitorHandle> { let monitor = monitor::primary_monitor(); Some(monitor) } #[inline] pub fn raw_window_handle(&self) -> RawWindowHandle { let mut window_handle = AppKitWindowHandle::empty(); window_handle.ns_window = self.ns_window(); window_handle.ns_view = self.ns_view(); RawWindowHandle::AppKit(window_handle) } #[inline] pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::AppKit(AppKitDisplayHandle::empty()) } fn toggle_style_mask(&self, mask: NSWindowStyleMask, on: bool) { let current_style_mask = self.styleMask(); if on { util::set_style_mask_sync(self, current_style_mask | mask); } else { util::set_style_mask_sync(self, current_style_mask & (!mask)); } } #[inline] pub fn theme(&self) -> Option<Theme> { self.lock_shared_state("theme").current_theme } #[inline] pub fn has_focus(&self) -> bool { self.isKeyWindow() } pub fn set_theme(&self, theme: Option<Theme>) { set_ns_theme(theme); self.lock_shared_state("set_theme").current_theme = theme.or_else(|| Some(get_ns_theme())); } #[inline] pub fn set_content_protected(&self, protected: bool) { self.setSharingType(if protected { NSWindowSharingType::NSWindowSharingNone } else { NSWindowSharingType::NSWindowSharingReadOnly }) } pub fn title(&self) -> String { self.title_().to_string() } } impl WindowExtMacOS for WinitWindow { #[inline] fn ns_window(&self) -> *mut c_void { self as *const Self as *mut _ } #[inline] fn ns_view(&self) -> *mut c_void { Id::as_ptr(&self.contentView()) as *mut _ } #[inline] fn simple_fullscreen(&self) -> bool { self.lock_shared_state("simple_fullscreen") .is_simple_fullscreen } #[inline] fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { let mut shared_state_lock = self.lock_shared_state("set_simple_fullscreen"); let app = NSApp(); let is_native_fullscreen = shared_state_lock.fullscreen.is_some(); let is_simple_fullscreen = shared_state_lock.is_simple_fullscreen; // Do nothing if native fullscreen is active. if is_native_fullscreen || (fullscreen && is_simple_fullscreen) || (!fullscreen && !is_simple_fullscreen) { return false; } if fullscreen { // Remember the original window's settings // Exclude title bar shared_state_lock.standard_frame = Some(self.contentRectForFrameRect(self.frame())); shared_state_lock.saved_style = Some(self.styleMask()); shared_state_lock.save_presentation_opts = Some(app.presentationOptions()); // Tell our window's state that we're in fullscreen shared_state_lock.is_simple_fullscreen = true; // Drop shared state lock before calling app.setPresentationOptions, because // it will call our windowDidChangeScreen listener which reacquires the lock drop(shared_state_lock); // Simulate pre-Lion fullscreen by hiding the dock and menu bar let presentation_options = NSApplicationPresentationOptions::NSApplicationPresentationAutoHideDock | NSApplicationPresentationOptions::NSApplicationPresentationAutoHideMenuBar; app.setPresentationOptions(presentation_options); // Hide the titlebar self.toggle_style_mask(NSWindowStyleMask::NSTitledWindowMask, false); // Set the window frame to the screen frame size let screen = self.screen().expect("expected screen to be available"); self.setFrame_display(screen.frame(), true); // Fullscreen windows can't be resized, minimized, or moved self.toggle_style_mask(NSWindowStyleMask::NSMiniaturizableWindowMask, false); self.toggle_style_mask(NSWindowStyleMask::NSResizableWindowMask, false); self.setMovable(false); true } else { let new_mask = self.saved_style(&mut shared_state_lock); self.set_style_mask_sync(new_mask); shared_state_lock.is_simple_fullscreen = false; let save_presentation_opts = shared_state_lock.save_presentation_opts; let frame = shared_state_lock.saved_standard_frame(); // Drop shared state lock before calling app.setPresentationOptions, because // it will call our windowDidChangeScreen listener which reacquires the lock drop(shared_state_lock); if let Some(presentation_opts) = save_presentation_opts { app.setPresentationOptions(presentation_opts); } self.setFrame_display(frame, true); self.setMovable(true); true } } #[inline] fn has_shadow(&self) -> bool { self.hasShadow() } #[inline] fn set_has_shadow(&self, has_shadow: bool) { self.setHasShadow(has_shadow) } fn is_document_edited(&self) -> bool { self.isDocumentEdited() } fn set_document_edited(&self, edited: bool) { self.setDocumentEdited(edited) } fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) { let mut shared_state_lock = self.shared_state.lock().unwrap(); shared_state_lock.option_as_alt = option_as_alt; } fn option_as_alt(&self) -> OptionAsAlt { let shared_state_lock = self.shared_state.lock().unwrap(); shared_state_lock.option_as_alt } } pub(super) fn get_ns_theme() -> Theme { let app = NSApp(); let has_theme: bool = unsafe { msg_send![&app, respondsToSelector: sel!(effectiveAppearance)] }; if !has_theme { return Theme::Light; } let appearance = app.effectiveAppearance(); let name = appearance.bestMatchFromAppearancesWithNames(&NSArray::from_slice(&[ NSString::from_str("NSAppearanceNameAqua"), NSString::from_str("NSAppearanceNameDarkAqua"), ])); match &*name.to_string() { "NSAppearanceNameDarkAqua" => Theme::Dark, _ => Theme::Light, } } fn set_ns_theme(theme: Option<Theme>) { let app = NSApp(); let has_theme: bool = unsafe { msg_send![&app, respondsToSelector: sel!(effectiveAppearance)] }; if has_theme { let appearance = theme.map(|t| { let name = match t { Theme::Dark => NSString::from_str("NSAppearanceNameDarkAqua"), Theme::Light => NSString::from_str("NSAppearanceNameAqua"), }; NSAppearance::appearanceNamed(&name) }); app.setAppearance(appearance.as_ref().map(|a| a.as_ref())); } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/macos/window_delegate.rs
Rust
#![allow(clippy::unnecessary_cast)] use std::ptr; use objc2::declare::{Ivar, IvarDrop}; use objc2::foundation::{NSArray, NSObject, NSSize, NSString}; use objc2::rc::{autoreleasepool, Id, Shared}; use objc2::runtime::Object; use objc2::{class, declare_class, msg_send, msg_send_id, sel, ClassType}; use super::appkit::{ NSApplicationPresentationOptions, NSFilenamesPboardType, NSPasteboard, NSWindowOcclusionState, }; use crate::{ dpi::{LogicalPosition, LogicalSize}, event::{Event, ModifiersState, WindowEvent}, platform_impl::platform::{ app_state::AppState, event::{EventProxy, EventWrapper}, util, window::{get_ns_theme, WinitWindow}, Fullscreen, }, window::WindowId, }; declare_class!( #[derive(Debug)] pub(crate) struct WinitWindowDelegate { window: IvarDrop<Id<WinitWindow, Shared>>, // TODO: It's possible for delegate methods to be called asynchronously, // causing data races / `RefCell` panics. // This is set when WindowBuilder::with_fullscreen was set, // see comments of `window_did_fail_to_enter_fullscreen` initial_fullscreen: bool, // During `windowDidResize`, we use this to only send Moved if the position changed. // TODO: Remove unnecessary boxing here previous_position: IvarDrop<Option<Box<(f64, f64)>>>, // Used to prevent redundant events. previous_scale_factor: f64, } unsafe impl ClassType for WinitWindowDelegate { type Super = NSObject; } unsafe impl WinitWindowDelegate { #[sel(initWithWindow:initialFullscreen:)] fn init_with_winit( &mut self, window: &WinitWindow, initial_fullscreen: bool, ) -> Option<&mut Self> { let this: Option<&mut Self> = unsafe { msg_send![self, init] }; this.map(|this| { let scale_factor = window.scale_factor(); Ivar::write(&mut this.window, window.retain()); Ivar::write(&mut this.initial_fullscreen, initial_fullscreen); Ivar::write(&mut this.previous_position, None); Ivar::write(&mut this.previous_scale_factor, scale_factor); if scale_factor != 1.0 { this.queue_static_scale_factor_changed_event(); } this.window.setDelegate(Some(this)); // Enable theme change event let notification_center: Id<Object, Shared> = unsafe { msg_send_id![class!(NSDistributedNotificationCenter), defaultCenter] }; let notification_name = NSString::from_str("AppleInterfaceThemeChangedNotification"); let _: () = unsafe { msg_send![ &notification_center, addObserver: &*this selector: sel!(effectiveAppearanceDidChange:) name: &*notification_name object: ptr::null::<Object>() ] }; this }) } } // NSWindowDelegate + NSDraggingDestination protocols unsafe impl WinitWindowDelegate { #[sel(windowShouldClose:)] fn window_should_close(&self, _: Option<&Object>) -> bool { trace_scope!("windowShouldClose:"); self.queue_event(WindowEvent::CloseRequested); false } #[sel(windowWillClose:)] fn window_will_close(&self, _: Option<&Object>) { trace_scope!("windowWillClose:"); // `setDelegate:` retains the previous value and then autoreleases it autoreleasepool(|_| { // Since El Capitan, we need to be careful that delegate methods can't // be called after the window closes. self.window.setDelegate(None); }); self.queue_event(WindowEvent::Destroyed); } #[sel(windowDidResize:)] fn window_did_resize(&mut self, _: Option<&Object>) { trace_scope!("windowDidResize:"); // NOTE: WindowEvent::Resized is reported in frameDidChange. self.emit_move_event(); } #[sel(windowWillStartLiveResize:)] fn window_will_start_live_resize(&mut self, _: Option<&Object>) { trace_scope!("windowWillStartLiveResize:"); let increments = self .window .lock_shared_state("window_will_enter_fullscreen") .resize_increments; self.window.set_resize_increments_inner(increments); } #[sel(windowDidEndLiveResize:)] fn window_did_end_live_resize(&mut self, _: Option<&Object>) { trace_scope!("windowDidEndLiveResize:"); self.window.set_resize_increments_inner(NSSize::new(1., 1.)); } // This won't be triggered if the move was part of a resize. #[sel(windowDidMove:)] fn window_did_move(&mut self, _: Option<&Object>) { trace_scope!("windowDidMove:"); self.emit_move_event(); } #[sel(windowDidChangeBackingProperties:)] fn window_did_change_backing_properties(&mut self, _: Option<&Object>) { trace_scope!("windowDidChangeBackingProperties:"); self.queue_static_scale_factor_changed_event(); } #[sel(windowDidBecomeKey:)] fn window_did_become_key(&self, _: Option<&Object>) { trace_scope!("windowDidBecomeKey:"); // TODO: center the cursor if the window had mouse grab when it // lost focus self.queue_event(WindowEvent::Focused(true)); } #[sel(windowDidResignKey:)] fn window_did_resign_key(&self, _: Option<&Object>) { trace_scope!("windowDidResignKey:"); // It happens rather often, e.g. when the user is Cmd+Tabbing, that the // NSWindowDelegate will receive a didResignKey event despite no event // being received when the modifiers are released. This is because // flagsChanged events are received by the NSView instead of the // NSWindowDelegate, and as a result a tracked modifiers state can quite // easily fall out of synchrony with reality. This requires us to emit // a synthetic ModifiersChanged event when we lose focus. // TODO(madsmtm): Remove the need for this unsafety let mut view = unsafe { Id::from_shared(self.window.view()) }; // Both update the state and emit a ModifiersChanged event. if !view.state.modifiers.is_empty() { view.state.modifiers = ModifiersState::empty(); self.queue_event(WindowEvent::ModifiersChanged(view.state.modifiers)); } self.queue_event(WindowEvent::Focused(false)); } /// Invoked when the dragged image enters destination bounds or frame #[sel(draggingEntered:)] fn dragging_entered(&self, sender: *mut Object) -> bool { trace_scope!("draggingEntered:"); use std::path::PathBuf; let pb: Id<NSPasteboard, Shared> = unsafe { msg_send_id![sender, draggingPasteboard] }; let filenames = pb.propertyListForType(unsafe { NSFilenamesPboardType }); let filenames: Id<NSArray<NSString>, Shared> = unsafe { Id::cast(filenames) }; filenames.into_iter().for_each(|file| { let path = PathBuf::from(file.to_string()); self.queue_event(WindowEvent::HoveredFile(path)); }); true } /// Invoked when the image is released #[sel(prepareForDragOperation:)] fn prepare_for_drag_operation(&self, _: Option<&Object>) -> bool { trace_scope!("prepareForDragOperation:"); true } /// Invoked after the released image has been removed from the screen #[sel(performDragOperation:)] fn perform_drag_operation(&self, sender: *mut Object) -> bool { trace_scope!("performDragOperation:"); use std::path::PathBuf; let pb: Id<NSPasteboard, Shared> = unsafe { msg_send_id![sender, draggingPasteboard] }; let filenames = pb.propertyListForType(unsafe { NSFilenamesPboardType }); let filenames: Id<NSArray<NSString>, Shared> = unsafe { Id::cast(filenames) }; filenames.into_iter().for_each(|file| { let path = PathBuf::from(file.to_string()); self.queue_event(WindowEvent::DroppedFile(path)); }); true } /// Invoked when the dragging operation is complete #[sel(concludeDragOperation:)] fn conclude_drag_operation(&self, _: Option<&Object>) { trace_scope!("concludeDragOperation:"); } /// Invoked when the dragging operation is cancelled #[sel(draggingExited:)] fn dragging_exited(&self, _: Option<&Object>) { trace_scope!("draggingExited:"); self.queue_event(WindowEvent::HoveredFileCancelled); } /// Invoked when before enter fullscreen #[sel(windowWillEnterFullScreen:)] fn window_will_enter_fullscreen(&self, _: Option<&Object>) { trace_scope!("windowWillEnterFullScreen:"); let mut shared_state = self .window .lock_shared_state("window_will_enter_fullscreen"); shared_state.maximized = self.window.is_zoomed(); let fullscreen = shared_state.fullscreen.as_ref(); match fullscreen { // Exclusive mode sets the state in `set_fullscreen` as the user // can't enter exclusive mode by other means (like the // fullscreen button on the window decorations) Some(Fullscreen::Exclusive(_)) => (), // `window_will_enter_fullscreen` was triggered and we're already // in fullscreen, so we must've reached here by `set_fullscreen` // as it updates the state Some(Fullscreen::Borderless(_)) => (), // Otherwise, we must've reached fullscreen by the user clicking // on the green fullscreen button. Update state! None => { let current_monitor = self.window.current_monitor_inner(); shared_state.fullscreen = Some(Fullscreen::Borderless(current_monitor)) } } shared_state.in_fullscreen_transition = true; } /// Invoked when before exit fullscreen #[sel(windowWillExitFullScreen:)] fn window_will_exit_fullscreen(&self, _: Option<&Object>) { trace_scope!("windowWillExitFullScreen:"); let mut shared_state = self.window.lock_shared_state("window_will_exit_fullscreen"); shared_state.in_fullscreen_transition = true; } #[sel(window:willUseFullScreenPresentationOptions:)] fn window_will_use_fullscreen_presentation_options( &self, _: Option<&Object>, proposed_options: NSApplicationPresentationOptions, ) -> NSApplicationPresentationOptions { trace_scope!("window:willUseFullScreenPresentationOptions:"); // Generally, games will want to disable the menu bar and the dock. Ideally, // this would be configurable by the user. Unfortunately because of our // `CGShieldingWindowLevel() + 1` hack (see `set_fullscreen`), our window is // placed on top of the menu bar in exclusive fullscreen mode. This looks // broken so we always disable the menu bar in exclusive fullscreen. We may // still want to make this configurable for borderless fullscreen. Right now // we don't, for consistency. If we do, it should be documented that the // user-provided options are ignored in exclusive fullscreen. let mut options = proposed_options; let shared_state = self .window .lock_shared_state("window_will_use_fullscreen_presentation_options"); if let Some(Fullscreen::Exclusive(_)) = shared_state.fullscreen { options = NSApplicationPresentationOptions::NSApplicationPresentationFullScreen | NSApplicationPresentationOptions::NSApplicationPresentationHideDock | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; } options } /// Invoked when entered fullscreen #[sel(windowDidEnterFullScreen:)] fn window_did_enter_fullscreen(&mut self, _: Option<&Object>) { trace_scope!("windowDidEnterFullScreen:"); *self.initial_fullscreen = false; let mut shared_state = self.window.lock_shared_state("window_did_enter_fullscreen"); shared_state.in_fullscreen_transition = false; let target_fullscreen = shared_state.target_fullscreen.take(); drop(shared_state); if let Some(target_fullscreen) = target_fullscreen { self.window.set_fullscreen(target_fullscreen); } } /// Invoked when exited fullscreen #[sel(windowDidExitFullScreen:)] fn window_did_exit_fullscreen(&self, _: Option<&Object>) { trace_scope!("windowDidExitFullScreen:"); self.window.restore_state_from_fullscreen(); let mut shared_state = self.window.lock_shared_state("window_did_exit_fullscreen"); shared_state.in_fullscreen_transition = false; let target_fullscreen = shared_state.target_fullscreen.take(); drop(shared_state); if let Some(target_fullscreen) = target_fullscreen { self.window.set_fullscreen(target_fullscreen); } } /// Invoked when fail to enter fullscreen /// /// When this window launch from a fullscreen app (e.g. launch from VS Code /// terminal), it creates a new virtual destkop and a transition animation. /// This animation takes one second and cannot be disable without /// elevated privileges. In this animation time, all toggleFullscreen events /// will be failed. In this implementation, we will try again by using /// performSelector:withObject:afterDelay: until window_did_enter_fullscreen. /// It should be fine as we only do this at initialzation (i.e with_fullscreen /// was set). /// /// From Apple doc: /// In some cases, the transition to enter full-screen mode can fail, /// due to being in the midst of handling some other animation or user gesture. /// This method indicates that there was an error, and you should clean up any /// work you may have done to prepare to enter full-screen mode. #[sel(windowDidFailToEnterFullScreen:)] fn window_did_fail_to_enter_fullscreen(&self, _: Option<&Object>) { trace_scope!("windowDidFailToEnterFullScreen:"); let mut shared_state = self .window .lock_shared_state("window_did_fail_to_enter_fullscreen"); shared_state.in_fullscreen_transition = false; shared_state.target_fullscreen = None; if *self.initial_fullscreen { #[allow(clippy::let_unit_value)] unsafe { let _: () = msg_send![ &*self.window, performSelector: sel!(toggleFullScreen:), withObject: ptr::null::<Object>(), afterDelay: 0.5, ]; }; } else { self.window.restore_state_from_fullscreen(); } } // Invoked when the occlusion state of the window changes #[sel(windowDidChangeOcclusionState:)] fn window_did_change_occlusion_state(&self, _: Option<&Object>) { trace_scope!("windowDidChangeOcclusionState:"); self.queue_event(WindowEvent::Occluded( !self .window .occlusionState() .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible), )) } // Observe theme change #[sel(effectiveAppearanceDidChange:)] fn effective_appearance_did_change(&self, sender: Option<&Object>) { trace_scope!("Triggered `effectiveAppearanceDidChange:`"); unsafe { msg_send![ self, performSelectorOnMainThread: sel!(effectiveAppearanceDidChangedOnMainThread:), withObject: sender, waitUntilDone: false, ] } } #[sel(effectiveAppearanceDidChangedOnMainThread:)] fn effective_appearance_did_changed_on_main_thread(&self, _: Option<&Object>) { let theme = get_ns_theme(); let mut shared_state = self .window .lock_shared_state("effective_appearance_did_change"); let current_theme = shared_state.current_theme; shared_state.current_theme = Some(theme); drop(shared_state); if current_theme != Some(theme) { self.queue_event(WindowEvent::ThemeChanged(theme)); } } #[sel(windowDidChangeScreen:)] fn window_did_change_screen(&self, _: Option<&Object>) { trace_scope!("windowDidChangeScreen:"); let is_simple_fullscreen = self .window .lock_shared_state("window_did_change_screen") .is_simple_fullscreen; if is_simple_fullscreen { if let Some(screen) = self.window.screen() { self.window.setFrame_display(screen.frame(), true); } } } } ); impl WinitWindowDelegate { pub fn new(window: &WinitWindow, initial_fullscreen: bool) -> Id<Self, Shared> { unsafe { msg_send_id![ msg_send_id![Self::class(), alloc], initWithWindow: window, initialFullscreen: initial_fullscreen, ] } } pub(crate) fn queue_event(&self, event: WindowEvent<'static>) { let event = Event::WindowEvent { window_id: WindowId(self.window.id()), event, }; AppState::queue_event(EventWrapper::StaticEvent(event)); } fn queue_static_scale_factor_changed_event(&mut self) { let scale_factor = self.window.scale_factor(); if scale_factor == *self.previous_scale_factor { return; }; *self.previous_scale_factor = scale_factor; let wrapper = EventWrapper::EventProxy(EventProxy::DpiChangedProxy { window: self.window.clone(), suggested_size: self.view_size(), scale_factor, }); AppState::queue_event(wrapper); } fn emit_move_event(&mut self) { let rect = self.window.frame(); let x = rect.origin.x as f64; let y = util::bottom_left_to_top_left(rect); if self.previous_position.as_deref() != Some(&(x, y)) { *self.previous_position = Some(Box::new((x, y))); let scale_factor = self.window.scale_factor(); let physical_pos = LogicalPosition::<f64>::from((x, y)).to_physical(scale_factor); self.queue_event(WindowEvent::Moved(physical_pos)); } } fn view_size(&self) -> LogicalSize<f64> { let size = self.window.contentView().frame().size; LogicalSize::new(size.width as f64, size.height as f64) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/mod.rs
Rust
use crate::monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}; use crate::window::Fullscreen as RootFullscreen; #[cfg(windows_platform)] #[path = "windows/mod.rs"] mod platform; #[cfg(any(x11_platform, wayland_platform))] #[path = "linux/mod.rs"] mod platform; #[cfg(macos_platform)] #[path = "macos/mod.rs"] mod platform; #[cfg(android_platform)] #[path = "android/mod.rs"] mod platform; #[cfg(ios_platform)] #[path = "ios/mod.rs"] mod platform; #[cfg(wasm_platform)] #[path = "web/mod.rs"] mod platform; #[cfg(orbital_platform)] #[path = "orbital/mod.rs"] mod platform; pub use self::platform::*; /// Helper for converting between platform-specific and generic VideoMode/MonitorHandle #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Fullscreen { Exclusive(VideoMode), Borderless(Option<MonitorHandle>), } impl From<RootFullscreen> for Fullscreen { fn from(f: RootFullscreen) -> Self { match f { RootFullscreen::Exclusive(mode) => Self::Exclusive(mode.video_mode), RootFullscreen::Borderless(Some(handle)) => Self::Borderless(Some(handle.inner)), RootFullscreen::Borderless(None) => Self::Borderless(None), } } } impl From<Fullscreen> for RootFullscreen { fn from(f: Fullscreen) -> Self { match f { Fullscreen::Exclusive(video_mode) => Self::Exclusive(RootVideoMode { video_mode }), Fullscreen::Borderless(Some(inner)) => { Self::Borderless(Some(RootMonitorHandle { inner })) } Fullscreen::Borderless(None) => Self::Borderless(None), } } } #[cfg(all( not(ios_platform), not(windows_platform), not(macos_platform), not(android_platform), not(x11_platform), not(wayland_platform), not(wasm_platform), not(orbital_platform), ))] compile_error!("The platform you're compiling for is not supported by winit");
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/orbital/event_loop.rs
Rust
use std::{ collections::VecDeque, mem, slice, sync::{mpsc, Arc, Mutex}, time::Instant, }; use orbclient::{ ButtonEvent, EventOption, FocusEvent, HoverEvent, KeyEvent, MouseEvent, MoveEvent, QuitEvent, ResizeEvent, ScrollEvent, TextInputEvent, }; use raw_window_handle::{OrbitalDisplayHandle, RawDisplayHandle}; use crate::{ event::{self, StartCause, VirtualKeyCode}, event_loop::{self, ControlFlow}, window::WindowId as RootWindowId, }; use super::{ DeviceId, MonitorHandle, PlatformSpecificEventLoopAttributes, RedoxSocket, TimeSocket, WindowId, WindowProperties, }; fn convert_scancode(scancode: u8) -> Option<VirtualKeyCode> { match scancode { orbclient::K_A => Some(VirtualKeyCode::A), orbclient::K_B => Some(VirtualKeyCode::B), orbclient::K_C => Some(VirtualKeyCode::C), orbclient::K_D => Some(VirtualKeyCode::D), orbclient::K_E => Some(VirtualKeyCode::E), orbclient::K_F => Some(VirtualKeyCode::F), orbclient::K_G => Some(VirtualKeyCode::G), orbclient::K_H => Some(VirtualKeyCode::H), orbclient::K_I => Some(VirtualKeyCode::I), orbclient::K_J => Some(VirtualKeyCode::J), orbclient::K_K => Some(VirtualKeyCode::K), orbclient::K_L => Some(VirtualKeyCode::L), orbclient::K_M => Some(VirtualKeyCode::M), orbclient::K_N => Some(VirtualKeyCode::N), orbclient::K_O => Some(VirtualKeyCode::O), orbclient::K_P => Some(VirtualKeyCode::P), orbclient::K_Q => Some(VirtualKeyCode::Q), orbclient::K_R => Some(VirtualKeyCode::R), orbclient::K_S => Some(VirtualKeyCode::S), orbclient::K_T => Some(VirtualKeyCode::T), orbclient::K_U => Some(VirtualKeyCode::U), orbclient::K_V => Some(VirtualKeyCode::V), orbclient::K_W => Some(VirtualKeyCode::W), orbclient::K_X => Some(VirtualKeyCode::X), orbclient::K_Y => Some(VirtualKeyCode::Y), orbclient::K_Z => Some(VirtualKeyCode::Z), orbclient::K_0 => Some(VirtualKeyCode::Key0), orbclient::K_1 => Some(VirtualKeyCode::Key1), orbclient::K_2 => Some(VirtualKeyCode::Key2), orbclient::K_3 => Some(VirtualKeyCode::Key3), orbclient::K_4 => Some(VirtualKeyCode::Key4), orbclient::K_5 => Some(VirtualKeyCode::Key5), orbclient::K_6 => Some(VirtualKeyCode::Key6), orbclient::K_7 => Some(VirtualKeyCode::Key7), orbclient::K_8 => Some(VirtualKeyCode::Key8), orbclient::K_9 => Some(VirtualKeyCode::Key9), orbclient::K_TICK => Some(VirtualKeyCode::Grave), orbclient::K_MINUS => Some(VirtualKeyCode::Minus), orbclient::K_EQUALS => Some(VirtualKeyCode::Equals), orbclient::K_BACKSLASH => Some(VirtualKeyCode::Backslash), orbclient::K_BRACE_OPEN => Some(VirtualKeyCode::LBracket), orbclient::K_BRACE_CLOSE => Some(VirtualKeyCode::RBracket), orbclient::K_SEMICOLON => Some(VirtualKeyCode::Semicolon), orbclient::K_QUOTE => Some(VirtualKeyCode::Apostrophe), orbclient::K_COMMA => Some(VirtualKeyCode::Comma), orbclient::K_PERIOD => Some(VirtualKeyCode::Period), orbclient::K_SLASH => Some(VirtualKeyCode::Slash), orbclient::K_BKSP => Some(VirtualKeyCode::Back), orbclient::K_SPACE => Some(VirtualKeyCode::Space), orbclient::K_TAB => Some(VirtualKeyCode::Tab), //orbclient::K_CAPS => Some(VirtualKeyCode::CAPS), orbclient::K_LEFT_SHIFT => Some(VirtualKeyCode::LShift), orbclient::K_RIGHT_SHIFT => Some(VirtualKeyCode::RShift), orbclient::K_CTRL => Some(VirtualKeyCode::LControl), orbclient::K_ALT => Some(VirtualKeyCode::LAlt), orbclient::K_ENTER => Some(VirtualKeyCode::Return), orbclient::K_ESC => Some(VirtualKeyCode::Escape), orbclient::K_F1 => Some(VirtualKeyCode::F1), orbclient::K_F2 => Some(VirtualKeyCode::F2), orbclient::K_F3 => Some(VirtualKeyCode::F3), orbclient::K_F4 => Some(VirtualKeyCode::F4), orbclient::K_F5 => Some(VirtualKeyCode::F5), orbclient::K_F6 => Some(VirtualKeyCode::F6), orbclient::K_F7 => Some(VirtualKeyCode::F7), orbclient::K_F8 => Some(VirtualKeyCode::F8), orbclient::K_F9 => Some(VirtualKeyCode::F9), orbclient::K_F10 => Some(VirtualKeyCode::F10), orbclient::K_HOME => Some(VirtualKeyCode::Home), orbclient::K_UP => Some(VirtualKeyCode::Up), orbclient::K_PGUP => Some(VirtualKeyCode::PageUp), orbclient::K_LEFT => Some(VirtualKeyCode::Left), orbclient::K_RIGHT => Some(VirtualKeyCode::Right), orbclient::K_END => Some(VirtualKeyCode::End), orbclient::K_DOWN => Some(VirtualKeyCode::Down), orbclient::K_PGDN => Some(VirtualKeyCode::PageDown), orbclient::K_DEL => Some(VirtualKeyCode::Delete), orbclient::K_F11 => Some(VirtualKeyCode::F11), orbclient::K_F12 => Some(VirtualKeyCode::F12), _ => None, } } fn element_state(pressed: bool) -> event::ElementState { if pressed { event::ElementState::Pressed } else { event::ElementState::Released } } bitflags! { #[derive(Default)] struct KeyboardModifierState: u8 { const LSHIFT = 1 << 0; const RSHIFT = 1 << 1; const LCTRL = 1 << 2; const RCTRL = 1 << 3; const LALT = 1 << 4; const RALT = 1 << 5; const LSUPER = 1 << 6; const RSUPER = 1 << 7; } } bitflags! { #[derive(Default)] struct MouseButtonState: u8 { const LEFT = 1 << 0; const MIDDLE = 1 << 1; const RIGHT = 1 << 2; } } #[derive(Default)] struct EventState { keyboard: KeyboardModifierState, mouse: MouseButtonState, resize_opt: Option<(u32, u32)>, } impl EventState { fn key(&mut self, vk: VirtualKeyCode, pressed: bool) { match vk { VirtualKeyCode::LShift => self.keyboard.set(KeyboardModifierState::LSHIFT, pressed), VirtualKeyCode::RShift => self.keyboard.set(KeyboardModifierState::RSHIFT, pressed), VirtualKeyCode::LControl => self.keyboard.set(KeyboardModifierState::LCTRL, pressed), VirtualKeyCode::RControl => self.keyboard.set(KeyboardModifierState::RCTRL, pressed), VirtualKeyCode::LAlt => self.keyboard.set(KeyboardModifierState::LALT, pressed), VirtualKeyCode::RAlt => self.keyboard.set(KeyboardModifierState::RALT, pressed), VirtualKeyCode::LWin => self.keyboard.set(KeyboardModifierState::LSUPER, pressed), VirtualKeyCode::RWin => self.keyboard.set(KeyboardModifierState::RSUPER, pressed), _ => (), } } fn mouse( &mut self, left: bool, middle: bool, right: bool, ) -> Option<(event::MouseButton, event::ElementState)> { if self.mouse.contains(MouseButtonState::LEFT) != left { self.mouse.set(MouseButtonState::LEFT, left); return Some((event::MouseButton::Left, element_state(left))); } if self.mouse.contains(MouseButtonState::MIDDLE) != middle { self.mouse.set(MouseButtonState::MIDDLE, middle); return Some((event::MouseButton::Middle, element_state(middle))); } if self.mouse.contains(MouseButtonState::RIGHT) != right { self.mouse.set(MouseButtonState::RIGHT, right); return Some((event::MouseButton::Right, element_state(right))); } None } fn modifiers(&self) -> event::ModifiersState { let mut modifiers = event::ModifiersState::empty(); if self .keyboard .intersects(KeyboardModifierState::LSHIFT | KeyboardModifierState::RSHIFT) { modifiers |= event::ModifiersState::SHIFT; } if self .keyboard .intersects(KeyboardModifierState::LCTRL | KeyboardModifierState::RCTRL) { modifiers |= event::ModifiersState::CTRL; } if self .keyboard .intersects(KeyboardModifierState::LALT | KeyboardModifierState::RALT) { modifiers |= event::ModifiersState::ALT; } if self .keyboard .intersects(KeyboardModifierState::LSUPER | KeyboardModifierState::RSUPER) { modifiers |= event::ModifiersState::LOGO } modifiers } } pub struct EventLoop<T: 'static> { windows: Vec<(Arc<RedoxSocket>, EventState)>, window_target: event_loop::EventLoopWindowTarget<T>, } impl<T: 'static> EventLoop<T> { pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Self { let (user_events_sender, user_events_receiver) = mpsc::channel(); let event_socket = Arc::new(RedoxSocket::event().unwrap()); let wake_socket = Arc::new(TimeSocket::open().unwrap()); event_socket .write(&syscall::Event { id: wake_socket.0.fd, flags: syscall::EventFlags::EVENT_READ, data: wake_socket.0.fd, }) .unwrap(); Self { windows: Vec::new(), window_target: event_loop::EventLoopWindowTarget { p: EventLoopWindowTarget { user_events_sender, user_events_receiver, creates: Mutex::new(VecDeque::new()), redraws: Arc::new(Mutex::new(VecDeque::new())), destroys: Arc::new(Mutex::new(VecDeque::new())), event_socket, wake_socket, }, _marker: std::marker::PhantomData, }, } } pub fn run<F>(mut self, event_handler: F) -> ! where F: 'static + FnMut(event::Event<'_, T>, &event_loop::EventLoopWindowTarget<T>, &mut ControlFlow), { let exit_code = self.run_return(event_handler); ::std::process::exit(exit_code); } fn process_event<F>( window_id: WindowId, event_option: EventOption, event_state: &mut EventState, mut event_handler: F, ) where F: FnMut(event::Event<'_, T>), { match event_option { EventOption::Key(KeyEvent { character: _, scancode, pressed, }) => { if scancode != 0 { let vk_opt = convert_scancode(scancode); if let Some(vk) = vk_opt { event_state.key(vk, pressed); } event_handler( #[allow(deprecated)] event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::KeyboardInput { device_id: event::DeviceId(DeviceId), input: event::KeyboardInput { scancode: scancode as u32, state: element_state(pressed), virtual_keycode: vk_opt, modifiers: event_state.modifiers(), }, is_synthetic: false, }, }, ); } } EventOption::TextInput(TextInputEvent { character }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::ReceivedCharacter(character), }); } EventOption::Mouse(MouseEvent { x, y }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::CursorMoved { device_id: event::DeviceId(DeviceId), position: (x, y).into(), modifiers: event_state.modifiers(), }, }); } EventOption::Button(ButtonEvent { left, middle, right, }) => { while let Some((button, state)) = event_state.mouse(left, middle, right) { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::MouseInput { device_id: event::DeviceId(DeviceId), state, button, modifiers: event_state.modifiers(), }, }); } } EventOption::Scroll(ScrollEvent { x, y }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::MouseWheel { device_id: event::DeviceId(DeviceId), delta: event::MouseScrollDelta::LineDelta(x as f32, y as f32), phase: event::TouchPhase::Moved, modifiers: event_state.modifiers(), }, }); } EventOption::Quit(QuitEvent {}) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::CloseRequested, }); } EventOption::Focus(FocusEvent { focused }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::Focused(focused), }); } EventOption::Move(MoveEvent { x, y }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::Moved((x, y).into()), }); } EventOption::Resize(ResizeEvent { width, height }) => { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::Resized((width, height).into()), }); // Acknowledge resize after event loop. event_state.resize_opt = Some((width, height)); } //TODO: Clipboard EventOption::Hover(HoverEvent { entered }) => { if entered { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::CursorEntered { device_id: event::DeviceId(DeviceId), }, }); } else { event_handler(event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::CursorLeft { device_id: event::DeviceId(DeviceId), }, }); } } other => { warn!("unhandled event: {:?}", other); } } } pub fn run_return<F>(&mut self, mut event_handler_inner: F) -> i32 where F: FnMut(event::Event<'_, T>, &event_loop::EventLoopWindowTarget<T>, &mut ControlFlow), { // Wrapper for event handler function that prevents ExitWithCode from being unset. let mut event_handler = move |event: event::Event<'_, T>, window_target: &event_loop::EventLoopWindowTarget<T>, control_flow: &mut ControlFlow| { if let ControlFlow::ExitWithCode(code) = control_flow { event_handler_inner( event, window_target, &mut ControlFlow::ExitWithCode(*code), ); } else { event_handler_inner(event, window_target, control_flow); } }; let mut control_flow = ControlFlow::default(); let mut start_cause = StartCause::Init; let code = loop { event_handler( event::Event::NewEvents(start_cause), &self.window_target, &mut control_flow, ); if start_cause == StartCause::Init { event_handler( event::Event::Resumed, &self.window_target, &mut control_flow, ); } // Handle window creates. while let Some(window) = { let mut creates = self.window_target.p.creates.lock().unwrap(); creates.pop_front() } { let window_id = WindowId { fd: window.fd as u64, }; let mut buf: [u8; 4096] = [0; 4096]; let path = window.fpath(&mut buf).expect("failed to read properties"); let properties = WindowProperties::new(path); self.windows.push((window, EventState::default())); // Send resize event on create to indicate first size. event_handler( event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::Resized((properties.w, properties.h).into()), }, &self.window_target, &mut control_flow, ); // Send resize event on create to indicate first position. event_handler( event::Event::WindowEvent { window_id: RootWindowId(window_id), event: event::WindowEvent::Moved((properties.x, properties.y).into()), }, &self.window_target, &mut control_flow, ); } // Handle window destroys. while let Some(destroy_id) = { let mut destroys = self.window_target.p.destroys.lock().unwrap(); destroys.pop_front() } { event_handler( event::Event::WindowEvent { window_id: RootWindowId(destroy_id), event: event::WindowEvent::Destroyed, }, &self.window_target, &mut control_flow, ); self.windows .retain(|(window, _event_state)| window.fd as u64 != destroy_id.fd); } // Handle window events. let mut i = 0; // While loop is used here because the same window may be processed more than once. while let Some((window, event_state)) = self.windows.get_mut(i) { let window_id = WindowId { fd: window.fd as u64, }; let mut event_buf = [0u8; 16 * mem::size_of::<orbclient::Event>()]; let count = syscall::read(window.fd, &mut event_buf).expect("failed to read window events"); // Safety: orbclient::Event is a packed struct designed to be transferred over a socket. let events = unsafe { slice::from_raw_parts( event_buf.as_ptr() as *const orbclient::Event, count / mem::size_of::<orbclient::Event>(), ) }; for orbital_event in events { Self::process_event( window_id, orbital_event.to_option(), event_state, |event| event_handler(event, &self.window_target, &mut control_flow), ); } if count == event_buf.len() { // If event buf was full, process same window again to ensure all events are drained. continue; } // Acknowledge the latest resize event. if let Some((w, h)) = event_state.resize_opt.take() { window .write(format!("S,{w},{h}").as_bytes()) .expect("failed to acknowledge resize"); // Require redraw after resize. let mut redraws = self.window_target.p.redraws.lock().unwrap(); if !redraws.contains(&window_id) { redraws.push_back(window_id); } } // Move to next window. i += 1; } while let Ok(event) = self.window_target.p.user_events_receiver.try_recv() { event_handler( event::Event::UserEvent(event), &self.window_target, &mut control_flow, ); } event_handler( event::Event::MainEventsCleared, &self.window_target, &mut control_flow, ); // To avoid deadlocks the redraws lock is not held during event processing. while let Some(window_id) = { let mut redraws = self.window_target.p.redraws.lock().unwrap(); redraws.pop_front() } { event_handler( event::Event::RedrawRequested(RootWindowId(window_id)), &self.window_target, &mut control_flow, ); } event_handler( event::Event::RedrawEventsCleared, &self.window_target, &mut control_flow, ); let requested_resume = match control_flow { ControlFlow::Poll => { start_cause = StartCause::Poll; continue; } ControlFlow::Wait => None, ControlFlow::WaitUntil(instant) => Some(instant), ControlFlow::ExitWithCode(code) => break code, }; // Re-using wake socket caused extra wake events before because there were leftover // timeouts, and then new timeouts were added each time a spurious timeout expired. let timeout_socket = TimeSocket::open().unwrap(); self.window_target .p .event_socket .write(&syscall::Event { id: timeout_socket.0.fd, flags: syscall::EventFlags::EVENT_READ, data: 0, }) .unwrap(); let start = Instant::now(); if let Some(instant) = requested_resume { let mut time = timeout_socket.current_time().unwrap(); if let Some(duration) = instant.checked_duration_since(start) { time.tv_sec += duration.as_secs() as i64; time.tv_nsec += duration.subsec_nanos() as i32; // Normalize timespec so tv_nsec is not greater than one second. while time.tv_nsec >= 1_000_000_000 { time.tv_sec += 1; time.tv_nsec -= 1_000_000_000; } } timeout_socket.timeout(&time).unwrap(); } // Wait for event if needed. let mut event = syscall::Event::default(); self.window_target.p.event_socket.read(&mut event).unwrap(); // TODO: handle spurious wakeups (redraw caused wakeup but redraw already handled) match requested_resume { Some(requested_resume) if event.id == timeout_socket.0.fd => { // If the event is from the special timeout socket, report that resume // time was reached. start_cause = StartCause::ResumeTimeReached { start, requested_resume, }; } _ => { // Normal window event or spurious timeout. start_cause = StartCause::WaitCancelled { start, requested_resume, }; } } }; event_handler( event::Event::LoopDestroyed, &self.window_target, &mut control_flow, ); code } pub fn window_target(&self) -> &event_loop::EventLoopWindowTarget<T> { &self.window_target } pub fn create_proxy(&self) -> EventLoopProxy<T> { EventLoopProxy { user_events_sender: self.window_target.p.user_events_sender.clone(), wake_socket: self.window_target.p.wake_socket.clone(), } } } pub struct EventLoopProxy<T: 'static> { user_events_sender: mpsc::Sender<T>, wake_socket: Arc<TimeSocket>, } impl<T> EventLoopProxy<T> { pub fn send_event(&self, event: T) -> Result<(), event_loop::EventLoopClosed<T>> { self.user_events_sender .send(event) .map_err(|mpsc::SendError(x)| event_loop::EventLoopClosed(x))?; self.wake_socket.wake().unwrap(); Ok(()) } } impl<T> Clone for EventLoopProxy<T> { fn clone(&self) -> Self { Self { user_events_sender: self.user_events_sender.clone(), wake_socket: self.wake_socket.clone(), } } } impl<T> Unpin for EventLoopProxy<T> {} pub struct EventLoopWindowTarget<T: 'static> { pub(super) user_events_sender: mpsc::Sender<T>, pub(super) user_events_receiver: mpsc::Receiver<T>, pub(super) creates: Mutex<VecDeque<Arc<RedoxSocket>>>, pub(super) redraws: Arc<Mutex<VecDeque<WindowId>>>, pub(super) destroys: Arc<Mutex<VecDeque<WindowId>>>, pub(super) event_socket: Arc<RedoxSocket>, pub(super) wake_socket: Arc<TimeSocket>, } impl<T: 'static> EventLoopWindowTarget<T> { pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle) } pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { let mut v = VecDeque::with_capacity(1); v.push_back(MonitorHandle); v } pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Orbital(OrbitalDisplayHandle::empty()) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/orbital/mod.rs
Rust
#![cfg(target_os = "redox")] use std::str; use crate::dpi::{PhysicalPosition, PhysicalSize}; pub use self::event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget}; mod event_loop; pub use self::window::Window; mod window; struct RedoxSocket { fd: usize, } impl RedoxSocket { fn event() -> syscall::Result<Self> { Self::open_raw("event:") } fn orbital(properties: &WindowProperties<'_>) -> syscall::Result<Self> { Self::open_raw(&format!("{properties}")) } // Paths should be checked to ensure they are actually sockets and not normal files. If a // non-socket path is used, it could cause read and write to not function as expected. For // example, the seek would change in a potentially unpredictable way if either read or write // were called at the same time by multiple threads. fn open_raw(path: &str) -> syscall::Result<Self> { let fd = syscall::open(path, syscall::O_RDWR | syscall::O_CLOEXEC)?; Ok(Self { fd }) } fn read(&self, buf: &mut [u8]) -> syscall::Result<()> { let count = syscall::read(self.fd, buf)?; if count == buf.len() { Ok(()) } else { Err(syscall::Error::new(syscall::EINVAL)) } } fn write(&self, buf: &[u8]) -> syscall::Result<()> { let count = syscall::write(self.fd, buf)?; if count == buf.len() { Ok(()) } else { Err(syscall::Error::new(syscall::EINVAL)) } } fn fpath<'a>(&self, buf: &'a mut [u8]) -> syscall::Result<&'a str> { let count = syscall::fpath(self.fd, buf)?; str::from_utf8(&buf[..count]).map_err(|_err| syscall::Error::new(syscall::EINVAL)) } } impl Drop for RedoxSocket { fn drop(&mut self) { let _ = syscall::close(self.fd); } } pub struct TimeSocket(RedoxSocket); impl TimeSocket { fn open() -> syscall::Result<Self> { RedoxSocket::open_raw("time:4").map(Self) } // Read current time. fn current_time(&self) -> syscall::Result<syscall::TimeSpec> { let mut timespec = syscall::TimeSpec::default(); self.0.read(&mut timespec)?; Ok(timespec) } // Write a timeout. fn timeout(&self, timespec: &syscall::TimeSpec) -> syscall::Result<()> { self.0.write(timespec) } // Wake immediately. fn wake(&self) -> syscall::Result<()> { // Writing a default TimeSpec will always trigger a time event. self.timeout(&syscall::TimeSpec::default()) } } #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) struct PlatformSpecificEventLoopAttributes {} #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct WindowId { fd: u64, } impl WindowId { pub const fn dummy() -> Self { WindowId { fd: u64::max_value(), } } } impl From<WindowId> for u64 { fn from(id: WindowId) -> Self { id.fd } } impl From<u64> for WindowId { fn from(fd: u64) -> Self { Self { fd } } } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct DeviceId; impl DeviceId { pub const fn dummy() -> Self { DeviceId } } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct PlatformSpecificWindowBuilderAttributes; struct WindowProperties<'a> { flags: &'a str, x: i32, y: i32, w: u32, h: u32, title: &'a str, } impl<'a> WindowProperties<'a> { fn new(path: &'a str) -> Self { // orbital:flags/x/y/w/h/t let mut parts = path.splitn(6, '/'); let flags = parts.next().unwrap_or(""); let x = parts .next() .map_or(0, |part| part.parse::<i32>().unwrap_or(0)); let y = parts .next() .map_or(0, |part| part.parse::<i32>().unwrap_or(0)); let w = parts .next() .map_or(0, |part| part.parse::<u32>().unwrap_or(0)); let h = parts .next() .map_or(0, |part| part.parse::<u32>().unwrap_or(0)); let title = parts.next().unwrap_or(""); Self { flags, x, y, w, h, title, } } } impl<'a> fmt::Display for WindowProperties<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "orbital:{}/{}/{}/{}/{}/{}", self.flags, self.x, self.y, self.w, self.h, self.title ) } } #[derive(Default, Clone, Debug)] pub struct OsError; use std::fmt::{self, Display, Formatter}; impl Display for OsError { fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(fmt, "Redox OS Error") } } pub(crate) use crate::icon::NoIcon as PlatformIcon; #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct MonitorHandle; impl MonitorHandle { pub fn name(&self) -> Option<String> { Some("Redox Device".to_owned()) } pub fn size(&self) -> PhysicalSize<u32> { PhysicalSize::new(0, 0) // TODO } pub fn position(&self) -> PhysicalPosition<i32> { (0, 0).into() } pub fn scale_factor(&self) -> f64 { 1.0 // TODO } pub fn refresh_rate_millihertz(&self) -> Option<u32> { // FIXME no way to get real refresh rate for now. None } pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> { let size = self.size().into(); // FIXME this is not the real refresh rate // (it is guaranteed to support 32 bit color though) std::iter::once(VideoMode { size, bit_depth: 32, refresh_rate_millihertz: 60000, monitor: self.clone(), }) } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct VideoMode { size: (u32, u32), bit_depth: u16, refresh_rate_millihertz: u32, monitor: MonitorHandle, } impl VideoMode { pub fn size(&self) -> PhysicalSize<u32> { self.size.into() } pub fn bit_depth(&self) -> u16 { self.bit_depth } pub fn refresh_rate_millihertz(&self) -> u32 { self.refresh_rate_millihertz } pub fn monitor(&self) -> MonitorHandle { self.monitor.clone() } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/orbital/window.rs
Rust
use std::{ collections::VecDeque, sync::{Arc, Mutex}, }; use raw_window_handle::{ OrbitalDisplayHandle, OrbitalWindowHandle, RawDisplayHandle, RawWindowHandle, }; use crate::{ dpi::{PhysicalPosition, PhysicalSize, Position, Size}, error, platform_impl::Fullscreen, window, window::ImePurpose, }; use super::{ EventLoopWindowTarget, MonitorHandle, PlatformSpecificWindowBuilderAttributes, RedoxSocket, TimeSocket, WindowId, WindowProperties, }; // These values match the values uses in the `window_new` function in orbital: // https://gitlab.redox-os.org/redox-os/orbital/-/blob/master/src/scheme.rs const ORBITAL_FLAG_ASYNC: char = 'a'; const ORBITAL_FLAG_BACK: char = 'b'; const ORBITAL_FLAG_FRONT: char = 'f'; const ORBITAL_FLAG_BORDERLESS: char = 'l'; const ORBITAL_FLAG_RESIZABLE: char = 'r'; const ORBITAL_FLAG_TRANSPARENT: char = 't'; pub struct Window { window_socket: Arc<RedoxSocket>, redraws: Arc<Mutex<VecDeque<WindowId>>>, destroys: Arc<Mutex<VecDeque<WindowId>>>, wake_socket: Arc<TimeSocket>, } impl Window { pub(crate) fn new<T: 'static>( el: &EventLoopWindowTarget<T>, attrs: window::WindowAttributes, _: PlatformSpecificWindowBuilderAttributes, ) -> Result<Self, error::OsError> { let scale = MonitorHandle.scale_factor(); let (x, y) = if let Some(pos) = attrs.position { pos.to_physical::<i32>(scale).into() } else { // These coordinates are a special value to center the window. (-1, -1) }; let (w, h): (u32, u32) = if let Some(size) = attrs.inner_size { size.to_physical::<u32>(scale).into() } else { (1024, 768) }; //TODO: min/max inner_size // Async by default. let mut flag_str = ORBITAL_FLAG_ASYNC.to_string(); if attrs.resizable { flag_str.push(ORBITAL_FLAG_RESIZABLE); } //TODO: maximized, fullscreen, visible if attrs.transparent { flag_str.push(ORBITAL_FLAG_TRANSPARENT); } if !attrs.decorations { flag_str.push(ORBITAL_FLAG_BORDERLESS); } match attrs.window_level { window::WindowLevel::AlwaysOnBottom => { flag_str.push(ORBITAL_FLAG_BACK); } window::WindowLevel::Normal => {} window::WindowLevel::AlwaysOnTop => { flag_str.push(ORBITAL_FLAG_FRONT); } } //TODO: window_icon // Open window. let window = RedoxSocket::orbital(&WindowProperties { flags: &flag_str, x, y, w, h, title: &attrs.title, }) .expect("failed to open window"); // Add to event socket. el.event_socket .write(&syscall::Event { id: window.fd, flags: syscall::EventFlags::EVENT_READ, data: window.fd, }) .unwrap(); let window_socket = Arc::new(window); // Notify event thread that this window was created, it will send some default events. { let mut creates = el.creates.lock().unwrap(); creates.push_back(window_socket.clone()); } el.wake_socket.wake().unwrap(); Ok(Self { window_socket, redraws: el.redraws.clone(), destroys: el.destroys.clone(), wake_socket: el.wake_socket.clone(), }) } #[inline] pub fn id(&self) -> WindowId { WindowId { fd: self.window_socket.fd as u64, } } #[inline] pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle) } #[inline] pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { let mut v = VecDeque::with_capacity(1); v.push_back(MonitorHandle); v } #[inline] pub fn current_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle) } #[inline] pub fn scale_factor(&self) -> f64 { MonitorHandle.scale_factor() } #[inline] pub fn request_redraw(&self) { let window_id = self.id(); let mut redraws = self.redraws.lock().unwrap(); if !redraws.contains(&window_id) { redraws.push_back(window_id); self.wake_socket.wake().unwrap(); } } #[inline] pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { 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); Ok((properties.x, properties.y).into()) } #[inline] pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { //TODO: adjust for window decorations self.inner_position() } #[inline] pub fn set_outer_position(&self, position: Position) { //TODO: adjust for window decorations let (x, y): (i32, i32) = position.to_physical::<i32>(self.scale_factor()).into(); self.window_socket .write(format!("P,{x},{y}").as_bytes()) .expect("failed to set position"); } #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { 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] pub fn set_inner_size(&self, size: Size) { let (w, h): (u32, u32) = size.to_physical::<u32>(self.scale_factor()).into(); self.window_socket .write(format!("S,{w},{h}").as_bytes()) .expect("failed to set size"); } #[inline] pub fn outer_size(&self) -> PhysicalSize<u32> { //TODO: adjust for window decorations self.inner_size() } #[inline] pub fn set_min_inner_size(&self, _: Option<Size>) {} #[inline] pub fn set_max_inner_size(&self, _: Option<Size>) {} #[inline] pub fn title(&self) -> String { let mut buf: [u8; 4096] = [0; 4096]; let path = self .window_socket .fpath(&mut buf) .expect("failed to read properties"); let properties = WindowProperties::new(path); properties.title.to_string() } #[inline] pub fn set_title(&self, title: &str) { self.window_socket .write(format!("T,{title}").as_bytes()) .expect("failed to set title"); } #[inline] pub fn set_transparent(&self, _transparent: bool) {} #[inline] pub fn set_visible(&self, _visibility: bool) {} #[inline] pub fn is_visible(&self) -> Option<bool> { None } #[inline] pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { None } #[inline] pub fn set_resize_increments(&self, _increments: Option<Size>) {} #[inline] pub fn set_resizable(&self, _resizeable: bool) {} #[inline] pub fn is_resizable(&self) -> bool { 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.flags.contains(ORBITAL_FLAG_RESIZABLE) } #[inline] pub fn set_minimized(&self, _minimized: bool) {} #[inline] pub fn is_minimized(&self) -> Option<bool> { None } #[inline] pub fn set_maximized(&self, _maximized: bool) {} #[inline] pub fn is_maximized(&self) -> bool { false } #[inline] pub(crate) fn set_fullscreen(&self, _monitor: Option<Fullscreen>) {} #[inline] pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { None } #[inline] pub fn set_decorations(&self, _decorations: bool) {} #[inline] pub fn is_decorated(&self) -> bool { 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.flags.contains(ORBITAL_FLAG_BORDERLESS) } #[inline] pub fn set_window_level(&self, _level: window::WindowLevel) {} #[inline] pub fn set_window_icon(&self, _window_icon: Option<crate::icon::Icon>) {} #[inline] pub fn set_ime_position(&self, _position: Position) {} #[inline] pub fn set_ime_allowed(&self, _allowed: bool) {} #[inline] pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} #[inline] pub fn focus_window(&self) {} #[inline] pub fn request_user_attention(&self, _request_type: Option<window::UserAttentionType>) {} #[inline] pub fn set_cursor_icon(&self, _: window::CursorIcon) {} #[inline] pub fn set_cursor_position(&self, _: Position) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } #[inline] pub fn set_cursor_grab(&self, _: window::CursorGrabMode) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } #[inline] pub fn set_cursor_visible(&self, _: bool) {} #[inline] pub fn drag_window(&self) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } #[inline] pub fn drag_resize_window( &self, _direction: window::ResizeDirection, ) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } #[inline] pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), error::ExternalError> { Err(error::ExternalError::NotSupported( error::NotSupportedError::new(), )) } #[inline] pub fn raw_window_handle(&self) -> RawWindowHandle { let mut handle = OrbitalWindowHandle::empty(); handle.window = self.window_socket.fd as *mut _; RawWindowHandle::Orbital(handle) } #[inline] pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Orbital(OrbitalDisplayHandle::empty()) } #[inline] pub fn set_enabled_buttons(&self, _buttons: window::WindowButtons) {} #[inline] pub fn enabled_buttons(&self) -> window::WindowButtons { window::WindowButtons::all() } #[inline] pub fn theme(&self) -> Option<window::Theme> { None } #[inline] pub fn has_focus(&self) -> bool { false } #[inline] pub fn set_theme(&self, _theme: Option<window::Theme>) {} } impl Drop for Window { fn drop(&mut self) { { let mut destroys = self.destroys.lock().unwrap(); destroys.push_back(self.id()); } self.wake_socket.wake().unwrap(); } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/device.rs
Rust
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DeviceId(pub i32); impl DeviceId { pub const unsafe fn dummy() -> Self { Self(0) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/error.rs
Rust
use std::fmt; #[derive(Debug)] pub struct OsError(pub String); impl fmt::Display for OsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/event_loop/mod.rs
Rust
mod proxy; mod runner; mod state; mod window_target; pub use self::proxy::EventLoopProxy; pub use self::window_target::EventLoopWindowTarget; use super::{backend, device, window}; use crate::event::Event; use crate::event_loop::{ControlFlow, EventLoopWindowTarget as RootEventLoopWindowTarget}; use std::marker::PhantomData; pub struct EventLoop<T: 'static> { elw: RootEventLoopWindowTarget<T>, } #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub(crate) struct PlatformSpecificEventLoopAttributes {} impl<T> EventLoop<T> { pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Self { EventLoop { elw: RootEventLoopWindowTarget { p: EventLoopWindowTarget::new(), _marker: PhantomData, }, } } pub fn run<F>(self, event_handler: F) -> ! where F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow), { self.spawn(event_handler); // Throw an exception to break out of Rust execution and use unreachable to tell the // compiler this function won't return, giving it a return type of '!' backend::throw( "Using exceptions for control flow, don't mind me. This isn't actually an error!", ); unreachable!(); } pub fn spawn<F>(self, mut event_handler: F) where F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow), { let target = RootEventLoopWindowTarget { p: self.elw.p.clone(), _marker: PhantomData, }; self.elw.p.run(Box::new(move |event, flow| { event_handler(event, &target, flow) })); } pub fn create_proxy(&self) -> EventLoopProxy<T> { self.elw.p.proxy() } pub fn window_target(&self) -> &RootEventLoopWindowTarget<T> { &self.elw } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/event_loop/proxy.rs
Rust
use super::runner; use crate::event::Event; use crate::event_loop::EventLoopClosed; pub struct EventLoopProxy<T: 'static> { runner: runner::Shared<T>, } impl<T: 'static> EventLoopProxy<T> { pub fn new(runner: runner::Shared<T>) -> Self { Self { runner } } pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { self.runner.send_event(Event::UserEvent(event)); Ok(()) } } impl<T: 'static> Clone for EventLoopProxy<T> { fn clone(&self) -> Self { Self { runner: self.runner.clone(), } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/event_loop/runner.rs
Rust
use super::{super::ScaleChangeArgs, backend, state::State}; use crate::event::{Event, StartCause}; use crate::event_loop::ControlFlow; use crate::window::WindowId; use instant::{Duration, Instant}; use std::{ cell::RefCell, clone::Clone, collections::{HashSet, VecDeque}, iter, ops::Deref, rc::{Rc, Weak}, }; pub struct Shared<T: 'static>(Rc<Execution<T>>); pub(super) type EventHandler<T> = dyn FnMut(Event<'_, T>, &mut ControlFlow); impl<T> Clone for Shared<T> { fn clone(&self) -> Self { Shared(self.0.clone()) } } pub struct Execution<T: 'static> { runner: RefCell<RunnerEnum<T>>, events: RefCell<VecDeque<Event<'static, T>>>, id: RefCell<u32>, all_canvases: RefCell<Vec<(WindowId, Weak<RefCell<backend::Canvas>>)>>, redraw_pending: RefCell<HashSet<WindowId>>, destroy_pending: RefCell<VecDeque<WindowId>>, scale_change_detector: RefCell<Option<backend::ScaleChangeDetector>>, unload_event_handle: RefCell<Option<backend::UnloadEventHandle>>, } enum RunnerEnum<T: 'static> { /// The `EventLoop` is created but not being run. Pending, /// The `EventLoop` is being run. Running(Runner<T>), /// The `EventLoop` is exited after being started with `EventLoop::run`. Since /// `EventLoop::run` takes ownership of the `EventLoop`, we can be certain /// that this event loop will never be run again. Destroyed, } impl<T: 'static> RunnerEnum<T> { fn maybe_runner(&self) -> Option<&Runner<T>> { match self { RunnerEnum::Running(runner) => Some(runner), _ => None, } } } struct Runner<T: 'static> { state: State, event_handler: Box<EventHandler<T>>, } impl<T: 'static> Runner<T> { pub fn new(event_handler: Box<EventHandler<T>>) -> Self { Runner { state: State::Init, event_handler, } } /// Returns the corresponding `StartCause` for the current `state`, or `None` /// when in `Exit` state. fn maybe_start_cause(&self) -> Option<StartCause> { Some(match self.state { State::Init => StartCause::Init, State::Poll { .. } => StartCause::Poll, State::Wait { start } => StartCause::WaitCancelled { start, requested_resume: None, }, State::WaitUntil { start, end, .. } => StartCause::WaitCancelled { start, requested_resume: Some(end), }, State::Exit => return None, }) } fn handle_single_event(&mut self, event: Event<'_, T>, control: &mut ControlFlow) { let is_closed = matches!(*control, ControlFlow::ExitWithCode(_)); (self.event_handler)(event, control); // Maintain closed state, even if the callback changes it if is_closed { *control = ControlFlow::Exit; } } } impl<T: 'static> Shared<T> { pub fn new() -> Self { Shared(Rc::new(Execution { runner: RefCell::new(RunnerEnum::Pending), events: RefCell::new(VecDeque::new()), id: RefCell::new(0), all_canvases: RefCell::new(Vec::new()), redraw_pending: RefCell::new(HashSet::new()), destroy_pending: RefCell::new(VecDeque::new()), scale_change_detector: RefCell::new(None), unload_event_handle: RefCell::new(None), })) } pub fn add_canvas(&self, id: WindowId, canvas: &Rc<RefCell<backend::Canvas>>) { self.0 .all_canvases .borrow_mut() .push((id, Rc::downgrade(canvas))); } pub fn notify_destroy_window(&self, id: WindowId) { self.0.destroy_pending.borrow_mut().push_back(id); } // Set the event callback to use for the event loop runner // This the event callback is a fairly thin layer over the user-provided callback that closes // over a RootEventLoopWindowTarget reference pub fn set_listener(&self, event_handler: Box<EventHandler<T>>) { { let mut runner = self.0.runner.borrow_mut(); assert!(matches!(*runner, RunnerEnum::Pending)); *runner = RunnerEnum::Running(Runner::new(event_handler)); } self.init(); let close_instance = self.clone(); *self.0.unload_event_handle.borrow_mut() = Some(backend::on_unload(move || close_instance.handle_unload())); } pub(crate) fn set_on_scale_change<F>(&self, handler: F) where F: 'static + FnMut(ScaleChangeArgs), { *self.0.scale_change_detector.borrow_mut() = Some(backend::ScaleChangeDetector::new(handler)); } // Generate a strictly increasing ID // This is used to differentiate windows when handling events pub fn generate_id(&self) -> u32 { let mut id = self.0.id.borrow_mut(); *id += 1; *id } pub fn request_redraw(&self, id: WindowId) { self.0.redraw_pending.borrow_mut().insert(id); } pub fn init(&self) { // NB: For consistency all platforms must emit a 'resumed' event even though web // applications don't themselves have a formal suspend/resume lifecycle. self.run_until_cleared([Event::NewEvents(StartCause::Init), Event::Resumed].into_iter()); } // Run the polling logic for the Poll ControlFlow, which involves clearing the queue pub fn poll(&self) { let start_cause = Event::NewEvents(StartCause::Poll); self.run_until_cleared(iter::once(start_cause)); } // Run the logic for waking from a WaitUntil, which involves clearing the queue // Generally there shouldn't be events built up when this is called pub fn resume_time_reached(&self, start: Instant, requested_resume: Instant) { let start_cause = Event::NewEvents(StartCause::ResumeTimeReached { start, requested_resume, }); self.run_until_cleared(iter::once(start_cause)); } // Add an event to the event loop runner, from the user or an event handler // // It will determine if the event should be immediately sent to the user or buffered for later pub fn send_event(&self, event: Event<'static, T>) { self.send_events(iter::once(event)); } // Add a series of events to the event loop runner // // It will determine if the event should be immediately sent to the user or buffered for later pub fn send_events(&self, events: impl Iterator<Item = Event<'static, T>>) { // If the event loop is closed, it should discard any new events if self.is_closed() { return; } // If we can run the event processing right now, or need to queue this and wait for later let mut process_immediately = true; match self.0.runner.try_borrow().as_ref().map(Deref::deref) { Ok(RunnerEnum::Running(ref runner)) => { // If we're currently polling, queue this and wait for the poll() method to be called if let State::Poll { .. } = runner.state { process_immediately = false; } } Ok(RunnerEnum::Pending) => { // The runner still hasn't been attached: queue this event and wait for it to be process_immediately = false; } // Some other code is mutating the runner, which most likely means // the event loop is running and busy. So we queue this event for // it to be processed later. Err(_) => { process_immediately = false; } // This is unreachable since `self.is_closed() == true`. Ok(RunnerEnum::Destroyed) => unreachable!(), } if !process_immediately { // Queue these events to look at later self.0.events.borrow_mut().extend(events); return; } // At this point, we know this is a fresh set of events // Now we determine why new events are incoming, and handle the events let start_cause = match (self.0.runner.borrow().maybe_runner()) .unwrap_or_else(|| { unreachable!("The runner cannot process events when it is not attached") }) .maybe_start_cause() { Some(c) => c, // If we're in the exit state, don't do event processing None => return, }; // Take the start event, then the events provided to this function, and run an iteration of // the event loop let start_event = Event::NewEvents(start_cause); let events = iter::once(start_event).chain(events); self.run_until_cleared(events); } // Process the destroy-pending windows. This should only be called from // `run_until_cleared` and `handle_scale_changed`, somewhere between emitting // `NewEvents` and `MainEventsCleared`. fn process_destroy_pending_windows(&self, control: &mut ControlFlow) { while let Some(id) = self.0.destroy_pending.borrow_mut().pop_front() { self.0 .all_canvases .borrow_mut() .retain(|&(item_id, _)| item_id != id); self.handle_event( Event::WindowEvent { window_id: id, event: crate::event::WindowEvent::Destroyed, }, control, ); self.0.redraw_pending.borrow_mut().remove(&id); } } // Given the set of new events, run the event loop until the main events and redraw events are // cleared // // This will also process any events that have been queued or that are queued during processing fn run_until_cleared(&self, events: impl Iterator<Item = Event<'static, T>>) { let mut control = self.current_control_flow(); for event in events { self.handle_event(event, &mut control); } self.process_destroy_pending_windows(&mut control); self.handle_event(Event::MainEventsCleared, &mut control); // Collect all of the redraw events to avoid double-locking the RefCell let redraw_events: Vec<WindowId> = self.0.redraw_pending.borrow_mut().drain().collect(); for window_id in redraw_events { self.handle_event(Event::RedrawRequested(window_id), &mut control); } self.handle_event(Event::RedrawEventsCleared, &mut control); self.apply_control_flow(control); // If the event loop is closed, it has been closed this iteration and now the closing // event should be emitted if self.is_closed() { self.handle_loop_destroyed(&mut control); } } pub fn handle_scale_changed(&self, old_scale: f64, new_scale: f64) { // If there aren't any windows, then there is nothing to do here. if self.0.all_canvases.borrow().is_empty() { return; } let start_cause = match (self.0.runner.borrow().maybe_runner()) .unwrap_or_else(|| unreachable!("`scale_changed` should not happen without a runner")) .maybe_start_cause() { Some(c) => c, // If we're in the exit state, don't do event processing None => return, }; let mut control = self.current_control_flow(); // Handle the start event and all other events in the queue. self.handle_event(Event::NewEvents(start_cause), &mut control); // It is possible for windows to be dropped before this point. We don't // want to send `ScaleFactorChanged` for destroyed windows, so we process // the destroy-pending windows here. self.process_destroy_pending_windows(&mut control); // Now handle the `ScaleFactorChanged` events. for &(id, ref canvas) in &*self.0.all_canvases.borrow() { let canvas = match canvas.upgrade() { Some(rc) => rc.borrow().raw().clone(), // This shouldn't happen, but just in case... None => continue, }; // First, we send the `ScaleFactorChanged` event: let current_size = crate::dpi::PhysicalSize { width: canvas.width(), height: canvas.height(), }; let logical_size = current_size.to_logical::<f64>(old_scale); let mut new_size = logical_size.to_physical(new_scale); self.handle_single_event_sync( Event::WindowEvent { window_id: id, event: crate::event::WindowEvent::ScaleFactorChanged { scale_factor: new_scale, new_inner_size: &mut new_size, }, }, &mut control, ); // Then we resize the canvas to the new size and send a `Resized` event: backend::set_canvas_size(&canvas, crate::dpi::Size::Physical(new_size)); self.handle_single_event_sync( Event::WindowEvent { window_id: id, event: crate::event::WindowEvent::Resized(new_size), }, &mut control, ); } // Process the destroy-pending windows again. self.process_destroy_pending_windows(&mut control); self.handle_event(Event::MainEventsCleared, &mut control); // Discard all the pending redraw as we shall just redraw all windows. self.0.redraw_pending.borrow_mut().clear(); for &(window_id, _) in &*self.0.all_canvases.borrow() { self.handle_event(Event::RedrawRequested(window_id), &mut control); } self.handle_event(Event::RedrawEventsCleared, &mut control); self.apply_control_flow(control); // If the event loop is closed, it has been closed this iteration and now the closing // event should be emitted if self.is_closed() { self.handle_loop_destroyed(&mut control); } } fn handle_unload(&self) { self.apply_control_flow(ControlFlow::Exit); let mut control = self.current_control_flow(); // We don't call `handle_loop_destroyed` here because we don't need to // perform cleanup when the web browser is going to destroy the page. self.handle_event(Event::LoopDestroyed, &mut control); } // handle_single_event_sync takes in an event and handles it synchronously. // // It should only ever be called from `scale_changed`. fn handle_single_event_sync(&self, event: Event<'_, T>, control: &mut ControlFlow) { if self.is_closed() { *control = ControlFlow::Exit; } match *self.0.runner.borrow_mut() { RunnerEnum::Running(ref mut runner) => { runner.handle_single_event(event, control); } _ => panic!("Cannot handle event synchronously without a runner"), } } // handle_event takes in events and either queues them or applies a callback // // It should only ever be called from `run_until_cleared` and `scale_changed`. fn handle_event(&self, event: Event<'static, T>, control: &mut ControlFlow) { if self.is_closed() { *control = ControlFlow::Exit; } match *self.0.runner.borrow_mut() { RunnerEnum::Running(ref mut runner) => { runner.handle_single_event(event, control); } // If an event is being handled without a runner somehow, add it to the event queue so // it will eventually be processed RunnerEnum::Pending => self.0.events.borrow_mut().push_back(event), // If the Runner has been destroyed, there is nothing to do. RunnerEnum::Destroyed => return, } let is_closed = matches!(*control, ControlFlow::ExitWithCode(_)); // Don't take events out of the queue if the loop is closed or the runner doesn't exist // If the runner doesn't exist and this method recurses, it will recurse infinitely if !is_closed && self.0.runner.borrow().maybe_runner().is_some() { // Take an event out of the queue and handle it // Make sure not to let the borrow_mut live during the next handle_event let event = { self.0.events.borrow_mut().pop_front() }; if let Some(event) = event { self.handle_event(event, control); } } } // Apply the new ControlFlow that has been selected by the user // Start any necessary timeouts etc fn apply_control_flow(&self, control_flow: ControlFlow) { let new_state = match control_flow { ControlFlow::Poll => { let cloned = self.clone(); State::Poll { request: backend::AnimationFrameRequest::new(move || cloned.poll()), } } ControlFlow::Wait => State::Wait { start: Instant::now(), }, ControlFlow::WaitUntil(end) => { let start = Instant::now(); let delay = if end <= start { Duration::from_millis(0) } else { end - start }; let cloned = self.clone(); State::WaitUntil { start, end, timeout: backend::Timeout::new( move || cloned.resume_time_reached(start, end), delay, ), } } ControlFlow::ExitWithCode(_) => State::Exit, }; if let RunnerEnum::Running(ref mut runner) = *self.0.runner.borrow_mut() { runner.state = new_state; } } fn handle_loop_destroyed(&self, control: &mut ControlFlow) { self.handle_event(Event::LoopDestroyed, control); let all_canvases = std::mem::take(&mut *self.0.all_canvases.borrow_mut()); *self.0.scale_change_detector.borrow_mut() = None; *self.0.unload_event_handle.borrow_mut() = None; // Dropping the `Runner` drops the event handler closure, which will in // turn drop all `Window`s moved into the closure. *self.0.runner.borrow_mut() = RunnerEnum::Destroyed; for (_, canvas) in all_canvases { // In case any remaining `Window`s are still not dropped, we will need // to explicitly remove the event handlers associated with their canvases. if let Some(canvas) = canvas.upgrade() { let mut canvas = canvas.borrow_mut(); canvas.remove_listeners(); } } // At this point, the `self.0` `Rc` should only be strongly referenced // by the following: // * `self`, i.e. the item which triggered this event loop wakeup, which // is usually a `wasm-bindgen` `Closure`, which will be dropped after // returning to the JS glue code. // * The `EventLoopWindowTarget` leaked inside `EventLoop::run` due to the // JS exception thrown at the end. // * For each undropped `Window`: // * The `register_redraw_request` closure. // * The `destroy_fn` closure. } // Check if the event loop is currently closed fn is_closed(&self) -> bool { match self.0.runner.try_borrow().as_ref().map(Deref::deref) { Ok(RunnerEnum::Running(runner)) => runner.state.is_exit(), // The event loop is not closed since it is not initialized. Ok(RunnerEnum::Pending) => false, // The event loop is closed since it has been destroyed. Ok(RunnerEnum::Destroyed) => true, // Some other code is mutating the runner, which most likely means // the event loop is running and busy. Err(_) => false, } } // Get the current control flow state fn current_control_flow(&self) -> ControlFlow { match *self.0.runner.borrow() { RunnerEnum::Running(ref runner) => runner.state.control_flow(), RunnerEnum::Pending => ControlFlow::Poll, RunnerEnum::Destroyed => ControlFlow::Exit, } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/event_loop/state.rs
Rust
use super::backend; use crate::event_loop::ControlFlow; use instant::Instant; #[derive(Debug)] pub enum State { Init, WaitUntil { timeout: backend::Timeout, start: Instant, end: Instant, }, Wait { start: Instant, }, Poll { request: backend::AnimationFrameRequest, }, Exit, } impl State { pub fn is_exit(&self) -> bool { matches!(self, State::Exit) } pub fn control_flow(&self) -> ControlFlow { match self { State::Init => ControlFlow::Poll, State::WaitUntil { end, .. } => ControlFlow::WaitUntil(*end), State::Wait { .. } => ControlFlow::Wait, State::Poll { .. } => ControlFlow::Poll, State::Exit => ControlFlow::Exit, } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/event_loop/window_target.rs
Rust
use std::cell::RefCell; use std::clone::Clone; use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque}; use std::rc::Rc; use raw_window_handle::{RawDisplayHandle, WebDisplayHandle}; use super::{ super::monitor::MonitorHandle, backend, device::DeviceId, proxy::EventLoopProxy, runner, window::WindowId, }; use crate::dpi::{PhysicalSize, Size}; use crate::event::{ DeviceEvent, DeviceId as RootDeviceId, ElementState, Event, KeyboardInput, Touch, TouchPhase, WindowEvent, }; use crate::window::{Theme, WindowId as RootWindowId}; pub struct EventLoopWindowTarget<T: 'static> { pub(crate) runner: runner::Shared<T>, } impl<T> Clone for EventLoopWindowTarget<T> { fn clone(&self) -> Self { Self { runner: self.runner.clone(), } } } impl<T> EventLoopWindowTarget<T> { pub fn new() -> Self { Self { runner: runner::Shared::new(), } } pub fn proxy(&self) -> EventLoopProxy<T> { EventLoopProxy::new(self.runner.clone()) } pub fn run(&self, event_handler: Box<runner::EventHandler<T>>) { self.runner.set_listener(event_handler); let runner = self.runner.clone(); self.runner.set_on_scale_change(move |arg| { runner.handle_scale_changed(arg.old_scale, arg.new_scale) }); } pub fn generate_id(&self) -> WindowId { WindowId(self.runner.generate_id()) } pub fn register( &self, canvas: &Rc<RefCell<backend::Canvas>>, id: WindowId, prevent_default: bool, has_focus: Rc<RefCell<bool>>, ) { self.runner.add_canvas(RootWindowId(id), canvas); let mut canvas = canvas.borrow_mut(); canvas.set_attribute("data-raw-handle", &id.0.to_string()); canvas.on_touch_start(prevent_default); canvas.on_touch_end(prevent_default); let runner = self.runner.clone(); let has_focus_clone = has_focus.clone(); canvas.on_blur(move || { *has_focus_clone.borrow_mut() = false; runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Focused(false), }); }); let runner = self.runner.clone(); let has_focus_clone = has_focus.clone(); canvas.on_focus(move || { *has_focus_clone.borrow_mut() = true; runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Focused(true), }); }); let runner = self.runner.clone(); canvas.on_keyboard_press( move |scancode, virtual_keycode, modifiers| { #[allow(deprecated)] runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::KeyboardInput { device_id: RootDeviceId(unsafe { DeviceId::dummy() }), input: KeyboardInput { scancode, state: ElementState::Pressed, virtual_keycode, modifiers, }, is_synthetic: false, }, }); }, prevent_default, ); let runner = self.runner.clone(); canvas.on_keyboard_release( move |scancode, virtual_keycode, modifiers| { #[allow(deprecated)] runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::KeyboardInput { device_id: RootDeviceId(unsafe { DeviceId::dummy() }), input: KeyboardInput { scancode, state: ElementState::Released, virtual_keycode, modifiers, }, is_synthetic: false, }, }); }, prevent_default, ); let runner = self.runner.clone(); canvas.on_received_character( move |char_code| { runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::ReceivedCharacter(char_code), }); }, prevent_default, ); let runner = self.runner.clone(); canvas.on_cursor_leave(move |pointer_id| { runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CursorLeft { device_id: RootDeviceId(DeviceId(pointer_id)), }, }); }); let runner = self.runner.clone(); canvas.on_cursor_enter(move |pointer_id| { runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CursorEntered { device_id: RootDeviceId(DeviceId(pointer_id)), }, }); }); let runner = self.runner.clone(); let runner_touch = self.runner.clone(); canvas.on_cursor_move( move |pointer_id, position, delta, modifiers| { runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CursorMoved { device_id: RootDeviceId(DeviceId(pointer_id)), position, modifiers, }, }); runner.send_event(Event::DeviceEvent { device_id: RootDeviceId(DeviceId(pointer_id)), event: DeviceEvent::MouseMotion { delta: (delta.x, delta.y), }, }); }, move |device_id, location, force| { runner_touch.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Touch(Touch { id: device_id as u64, device_id: RootDeviceId(DeviceId(device_id)), phase: TouchPhase::Moved, force: Some(force), location, }), }); }, prevent_default, ); let runner = self.runner.clone(); let runner_touch = self.runner.clone(); canvas.on_mouse_press( move |pointer_id, position, button, modifiers| { *has_focus.borrow_mut() = true; // A mouse down event may come in without any prior CursorMoved events, // therefore we should send a CursorMoved event to make sure that the // user code has the correct cursor position. runner.send_events( std::iter::once(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Focused(true), }) .chain(std::iter::once(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::CursorMoved { device_id: RootDeviceId(DeviceId(pointer_id)), position, modifiers, }, })) .chain(std::iter::once(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::MouseInput { device_id: RootDeviceId(DeviceId(pointer_id)), state: ElementState::Pressed, button, modifiers, }, })), ); }, move |device_id, location, force| { runner_touch.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Touch(Touch { id: device_id as u64, device_id: RootDeviceId(DeviceId(device_id)), phase: TouchPhase::Started, force: Some(force), location, }), }); }, ); let runner = self.runner.clone(); let runner_touch = self.runner.clone(); canvas.on_mouse_release( move |pointer_id, button, modifiers| { runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::MouseInput { device_id: RootDeviceId(DeviceId(pointer_id)), state: ElementState::Released, button, modifiers, }, }); }, move |device_id, location, force| { runner_touch.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Touch(Touch { id: device_id as u64, device_id: RootDeviceId(DeviceId(device_id)), phase: TouchPhase::Ended, force: Some(force), location, }), }); }, ); let runner = self.runner.clone(); canvas.on_mouse_wheel( move |pointer_id, delta, modifiers| { runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::MouseWheel { device_id: RootDeviceId(DeviceId(pointer_id)), delta, phase: TouchPhase::Moved, modifiers, }, }); }, prevent_default, ); let runner = self.runner.clone(); let raw = canvas.raw().clone(); // The size to restore to after exiting fullscreen. let mut intended_size = PhysicalSize { width: raw.width(), height: raw.height(), }; canvas.on_fullscreen_change(move || { // If the canvas is marked as fullscreen, it is moving *into* fullscreen // If it is not, it is moving *out of* fullscreen let new_size = if backend::is_fullscreen(&raw) { intended_size = PhysicalSize { width: raw.width(), height: raw.height(), }; backend::window_size().to_physical(backend::scale_factor()) } else { intended_size }; backend::set_canvas_size(&raw, Size::Physical(new_size)); runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Resized(new_size), }); runner.request_redraw(RootWindowId(id)); }); let runner = self.runner.clone(); canvas.on_touch_cancel(move |device_id, location, force| { runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::Touch(Touch { id: device_id as u64, device_id: RootDeviceId(DeviceId(device_id)), phase: TouchPhase::Cancelled, force: Some(force), location, }), }); }); let runner = self.runner.clone(); canvas.on_dark_mode(move |is_dark_mode| { let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; runner.send_event(Event::WindowEvent { window_id: RootWindowId(id), event: WindowEvent::ThemeChanged(theme), }); }); } pub fn available_monitors(&self) -> VecDequeIter<MonitorHandle> { VecDeque::new().into_iter() } pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle) } pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Web(WebDisplayHandle::empty()) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/mod.rs
Rust
// Brief introduction to the internals of the web backend: // The web backend used to support both wasm-bindgen and stdweb as methods of binding to the // environment. Because they are both supporting the same underlying APIs, the actual web bindings // are cordoned off into backend abstractions, which present the thinnest unifying layer possible. // // When adding support for new events or interactions with the browser, first consult trusted // documentation (such as MDN) to ensure it is well-standardised and supported across many browsers. // Once you have decided on the relevant web APIs, add support to both backends. // // The backend is used by the rest of the module to implement Winit's business logic, which forms // the rest of the code. 'device', 'error', 'monitor', and 'window' define web-specific structures // for winit's cross-platform structures. They are all relatively simple translations. // // The event_loop module handles listening for and processing events. 'Proxy' implements // EventLoopProxy and 'WindowTarget' implements EventLoopWindowTarget. WindowTarget also handles // registering the event handlers. The 'Execution' struct in the 'runner' module handles taking // incoming events (from the registered handlers) and ensuring they are passed to the user in a // compliant way. mod device; mod error; mod event_loop; mod monitor; mod window; #[path = "web_sys/mod.rs"] mod backend; pub use self::device::DeviceId; pub use self::error::OsError; pub(crate) use self::event_loop::{ EventLoop, EventLoopProxy, EventLoopWindowTarget, PlatformSpecificEventLoopAttributes, }; pub use self::monitor::{MonitorHandle, VideoMode}; pub use self::window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId}; pub(crate) use crate::icon::NoIcon as PlatformIcon; pub(self) use crate::platform_impl::Fullscreen; #[derive(Clone, Copy)] pub(crate) struct ScaleChangeArgs { old_scale: f64, new_scale: f64, }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/monitor.rs
Rust
use crate::dpi::{PhysicalPosition, PhysicalSize}; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct MonitorHandle; impl MonitorHandle { pub fn scale_factor(&self) -> f64 { 1.0 } pub fn position(&self) -> PhysicalPosition<i32> { PhysicalPosition { x: 0, y: 0 } } pub fn name(&self) -> Option<String> { None } pub fn refresh_rate_millihertz(&self) -> Option<u32> { None } pub fn size(&self) -> PhysicalSize<u32> { PhysicalSize { width: 0, height: 0, } } pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> { std::iter::empty() } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct VideoMode; impl VideoMode { pub fn size(&self) -> PhysicalSize<u32> { unimplemented!(); } pub fn bit_depth(&self) -> u16 { unimplemented!(); } pub fn refresh_rate_millihertz(&self) -> u32 { 32000 } pub fn monitor(&self) -> MonitorHandle { MonitorHandle } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/canvas.rs
Rust
use super::event; use super::event_handle::EventListenerHandle; use super::media_query_handle::MediaQueryListHandle; use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}; use crate::error::OsError as RootOE; use crate::event::{ Force, ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode, }; use crate::platform_impl::{OsError, PlatformSpecificWindowBuilderAttributes}; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::{closure::Closure, JsCast}; use web_sys::{ AddEventListenerOptions, Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, MediaQueryListEvent, MouseEvent, WheelEvent, }; mod mouse_handler; mod pointer_handler; #[allow(dead_code)] pub struct Canvas { common: Common, on_touch_start: Option<EventListenerHandle<dyn FnMut(Event)>>, on_touch_end: Option<EventListenerHandle<dyn FnMut(Event)>>, on_focus: Option<EventListenerHandle<dyn FnMut(FocusEvent)>>, on_blur: Option<EventListenerHandle<dyn FnMut(FocusEvent)>>, on_keyboard_release: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>, on_keyboard_press: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>, on_received_character: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>, on_mouse_wheel: Option<EventListenerHandle<dyn FnMut(WheelEvent)>>, on_fullscreen_change: Option<EventListenerHandle<dyn FnMut(Event)>>, on_dark_mode: Option<MediaQueryListHandle>, mouse_state: MouseState, } struct Common { /// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained. raw: HtmlCanvasElement, wants_fullscreen: Rc<RefCell<bool>>, } impl Canvas { pub fn create(attr: PlatformSpecificWindowBuilderAttributes) -> Result<Self, RootOE> { let canvas = match attr.canvas { Some(canvas) => canvas, None => { let window = web_sys::window() .ok_or_else(|| os_error!(OsError("Failed to obtain window".to_owned())))?; let document = window .document() .ok_or_else(|| os_error!(OsError("Failed to obtain document".to_owned())))?; document .create_element("canvas") .map_err(|_| os_error!(OsError("Failed to create canvas element".to_owned())))? .unchecked_into() } }; // A tabindex is needed in order to capture local keyboard events. // A "0" value means that the element should be focusable in // sequential keyboard navigation, but its order is defined by the // document's source order. // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex if attr.focusable { canvas .set_attribute("tabindex", "0") .map_err(|_| os_error!(OsError("Failed to set a tabindex".to_owned())))?; } let mouse_state = if has_pointer_event() { MouseState::HasPointerEvent(pointer_handler::PointerHandler::new()) } else { MouseState::NoPointerEvent(mouse_handler::MouseHandler::new()) }; Ok(Canvas { common: Common { raw: canvas, wants_fullscreen: Rc::new(RefCell::new(false)), }, on_touch_start: None, on_touch_end: None, on_blur: None, on_focus: None, on_keyboard_release: None, on_keyboard_press: None, on_received_character: None, on_mouse_wheel: None, on_fullscreen_change: None, on_dark_mode: None, mouse_state, }) } pub fn set_cursor_lock(&self, lock: bool) -> Result<(), RootOE> { if lock { self.raw().request_pointer_lock(); } else { let window = web_sys::window() .ok_or_else(|| os_error!(OsError("Failed to obtain window".to_owned())))?; let document = window .document() .ok_or_else(|| os_error!(OsError("Failed to obtain document".to_owned())))?; document.exit_pointer_lock(); } Ok(()) } pub fn set_attribute(&self, attribute: &str, value: &str) { self.common .raw .set_attribute(attribute, value) .unwrap_or_else(|err| panic!("error: {err:?}\nSet attribute: {attribute}")) } pub fn position(&self) -> LogicalPosition<f64> { let bounds = self.common.raw.get_bounding_client_rect(); LogicalPosition { x: bounds.x(), y: bounds.y(), } } pub fn size(&self) -> PhysicalSize<u32> { PhysicalSize { width: self.common.raw.width(), height: self.common.raw.height(), } } pub fn raw(&self) -> &HtmlCanvasElement { &self.common.raw } pub fn on_touch_start(&mut self, prevent_default: bool) { self.on_touch_start = Some(self.common.add_event("touchstart", move |event: Event| { if prevent_default { event.prevent_default(); } })); } pub fn on_touch_end(&mut self, prevent_default: bool) { self.on_touch_end = Some(self.common.add_event("touchend", move |event: Event| { if prevent_default { event.prevent_default(); } })); } pub fn on_blur<F>(&mut self, mut handler: F) where F: 'static + FnMut(), { self.on_blur = Some(self.common.add_event("blur", move |_: FocusEvent| { handler(); })); } pub fn on_focus<F>(&mut self, mut handler: F) where F: 'static + FnMut(), { self.on_focus = Some(self.common.add_event("focus", move |_: FocusEvent| { handler(); })); } pub fn on_keyboard_release<F>(&mut self, mut handler: F, prevent_default: bool) where F: 'static + FnMut(ScanCode, Option<VirtualKeyCode>, ModifiersState), { self.on_keyboard_release = Some(self.common.add_user_event( "keyup", move |event: KeyboardEvent| { if prevent_default { event.prevent_default(); } handler( event::scan_code(&event), event::virtual_key_code(&event), event::keyboard_modifiers(&event), ); }, )); } pub fn on_keyboard_press<F>(&mut self, mut handler: F, prevent_default: bool) where F: 'static + FnMut(ScanCode, Option<VirtualKeyCode>, ModifiersState), { self.on_keyboard_press = Some(self.common.add_user_event( "keydown", move |event: KeyboardEvent| { // event.prevent_default() would suppress subsequent on_received_character() calls. That // suppression is correct for key sequences like Tab/Shift-Tab, Ctrl+R, PgUp/Down to // scroll, etc. We should not do it for key sequences that result in meaningful character // input though. if prevent_default { let event_key = &event.key(); let is_key_string = event_key.len() == 1 || !event_key.is_ascii(); let is_shortcut_modifiers = (event.ctrl_key() || event.alt_key()) && !event.get_modifier_state("AltGr"); if !is_key_string || is_shortcut_modifiers { event.prevent_default(); } } handler( event::scan_code(&event), event::virtual_key_code(&event), event::keyboard_modifiers(&event), ); }, )); } pub fn on_received_character<F>(&mut self, mut handler: F, prevent_default: bool) where F: 'static + FnMut(char), { // TODO: Use `beforeinput`. // // The `keypress` event is deprecated, but there does not seem to be a // viable/compatible alternative as of now. `beforeinput` is still widely // unsupported. self.on_received_character = Some(self.common.add_user_event( "keypress", move |event: KeyboardEvent| { // Suppress further handling to stop keys like the space key from scrolling the page. if prevent_default { event.prevent_default(); } handler(event::codepoint(&event)); }, )); } pub fn on_cursor_leave<F>(&mut self, handler: F) where F: 'static + FnMut(i32), { match &mut self.mouse_state { MouseState::HasPointerEvent(h) => h.on_cursor_leave(&self.common, handler), MouseState::NoPointerEvent(h) => h.on_cursor_leave(&self.common, handler), } } pub fn on_cursor_enter<F>(&mut self, handler: F) where F: 'static + FnMut(i32), { match &mut self.mouse_state { MouseState::HasPointerEvent(h) => h.on_cursor_enter(&self.common, handler), MouseState::NoPointerEvent(h) => h.on_cursor_enter(&self.common, handler), } } pub fn on_mouse_release<M, T>(&mut self, mouse_handler: M, touch_handler: T) where M: 'static + FnMut(i32, MouseButton, ModifiersState), T: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { match &mut self.mouse_state { MouseState::HasPointerEvent(h) => { h.on_mouse_release(&self.common, mouse_handler, touch_handler) } MouseState::NoPointerEvent(h) => h.on_mouse_release(&self.common, mouse_handler), } } pub fn on_mouse_press<M, T>(&mut self, mouse_handler: M, touch_handler: T) where M: 'static + FnMut(i32, PhysicalPosition<f64>, MouseButton, ModifiersState), T: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { match &mut self.mouse_state { MouseState::HasPointerEvent(h) => { h.on_mouse_press(&self.common, mouse_handler, touch_handler) } MouseState::NoPointerEvent(h) => h.on_mouse_press(&self.common, mouse_handler), } } pub fn on_cursor_move<M, T>( &mut self, mouse_handler: M, touch_handler: T, prevent_default: bool, ) where M: 'static + FnMut(i32, PhysicalPosition<f64>, PhysicalPosition<f64>, ModifiersState), T: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { match &mut self.mouse_state { MouseState::HasPointerEvent(h) => { h.on_cursor_move(&self.common, mouse_handler, touch_handler, prevent_default) } MouseState::NoPointerEvent(h) => h.on_cursor_move(&self.common, mouse_handler), } } pub fn on_touch_cancel<F>(&mut self, handler: F) where F: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { if let MouseState::HasPointerEvent(h) = &mut self.mouse_state { h.on_touch_cancel(&self.common, handler) } } pub fn on_mouse_wheel<F>(&mut self, mut handler: F, prevent_default: bool) where F: 'static + FnMut(i32, MouseScrollDelta, ModifiersState), { self.on_mouse_wheel = Some(self.common.add_event("wheel", move |event: WheelEvent| { if prevent_default { event.prevent_default(); } if let Some(delta) = event::mouse_scroll_delta(&event) { handler(0, delta, event::mouse_modifiers(&event)); } })); } pub fn on_fullscreen_change<F>(&mut self, mut handler: F) where F: 'static + FnMut(), { self.on_fullscreen_change = Some( self.common .add_event("fullscreenchange", move |_: Event| handler()), ); } pub fn on_dark_mode<F>(&mut self, mut handler: F) where F: 'static + FnMut(bool), { let closure = Closure::wrap( Box::new(move |event: MediaQueryListEvent| handler(event.matches())) as Box<dyn FnMut(_)>, ); self.on_dark_mode = MediaQueryListHandle::new("(prefers-color-scheme: dark)", closure); } pub fn request_fullscreen(&self) { self.common.request_fullscreen() } pub fn is_fullscreen(&self) -> bool { self.common.is_fullscreen() } pub fn remove_listeners(&mut self) { self.on_focus = None; self.on_blur = None; self.on_keyboard_release = None; self.on_keyboard_press = None; self.on_received_character = None; self.on_mouse_wheel = None; self.on_fullscreen_change = None; self.on_dark_mode = None; match &mut self.mouse_state { MouseState::HasPointerEvent(h) => h.remove_listeners(), MouseState::NoPointerEvent(h) => h.remove_listeners(), } } } impl Common { fn add_event<E, F>( &self, event_name: &'static str, mut handler: F, ) -> EventListenerHandle<dyn FnMut(E)> where E: 'static + AsRef<web_sys::Event> + wasm_bindgen::convert::FromWasmAbi, F: 'static + FnMut(E), { let closure = Closure::wrap(Box::new(move |event: E| { { let event_ref = event.as_ref(); event_ref.stop_propagation(); event_ref.cancel_bubble(); } handler(event); }) as Box<dyn FnMut(E)>); EventListenerHandle::new(&self.raw, event_name, closure) } // The difference between add_event and add_user_event is that the latter has a special meaning // for browser security. A user event is a deliberate action by the user (like a mouse or key // press) and is the only time things like a fullscreen request may be successfully completed.) fn add_user_event<E, F>( &self, event_name: &'static str, mut handler: F, ) -> EventListenerHandle<dyn FnMut(E)> where E: 'static + AsRef<web_sys::Event> + wasm_bindgen::convert::FromWasmAbi, F: 'static + FnMut(E), { let wants_fullscreen = self.wants_fullscreen.clone(); let canvas = self.raw.clone(); self.add_event(event_name, move |event: E| { handler(event); if *wants_fullscreen.borrow() { canvas .request_fullscreen() .expect("Failed to enter fullscreen"); *wants_fullscreen.borrow_mut() = false; } }) } // This function is used exclusively for mouse events (not pointer events). // Due to the need for mouse capturing, the mouse event handlers are added // to the window instead of the canvas element, which requires special // handling to control event propagation. fn add_window_mouse_event<F>( &self, event_name: &'static str, mut handler: F, ) -> EventListenerHandle<dyn FnMut(MouseEvent)> where F: 'static + FnMut(MouseEvent), { let wants_fullscreen = self.wants_fullscreen.clone(); let canvas = self.raw.clone(); let window = web_sys::window().expect("Failed to obtain window"); let closure = Closure::wrap(Box::new(move |event: MouseEvent| { handler(event); if *wants_fullscreen.borrow() { canvas .request_fullscreen() .expect("Failed to enter fullscreen"); *wants_fullscreen.borrow_mut() = false; } }) as Box<dyn FnMut(_)>); let listener = EventListenerHandle::with_options( &window, event_name, closure, AddEventListenerOptions::new().capture(true), ); listener } pub fn request_fullscreen(&self) { *self.wants_fullscreen.borrow_mut() = true; } pub fn is_fullscreen(&self) -> bool { super::is_fullscreen(&self.raw) } } /// Pointer events are supported or not. enum MouseState { HasPointerEvent(pointer_handler::PointerHandler), NoPointerEvent(mouse_handler::MouseHandler), } /// Returns whether pointer events are supported. /// Used to decide whether to use pointer events /// or plain mouse events. Note that Safari /// doesn't support pointer events now. fn has_pointer_event() -> bool { if let Some(window) = web_sys::window() { window.get("PointerEvent").is_some() } else { false } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/canvas/mouse_handler.rs
Rust
use super::event; use super::EventListenerHandle; use crate::dpi::PhysicalPosition; use crate::event::{ModifiersState, MouseButton}; use std::cell::RefCell; use std::rc::Rc; use web_sys::{EventTarget, MouseEvent}; type MouseLeaveHandler = Rc<RefCell<Option<Box<dyn FnMut(i32)>>>>; #[allow(dead_code)] pub(super) struct MouseHandler { on_mouse_leave: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>, on_mouse_enter: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>, on_mouse_move: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>, on_mouse_press: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>, on_mouse_release: Option<EventListenerHandle<dyn FnMut(MouseEvent)>>, on_mouse_leave_handler: MouseLeaveHandler, mouse_capture_state: Rc<RefCell<MouseCaptureState>>, } #[derive(PartialEq, Eq)] pub(super) enum MouseCaptureState { NotCaptured, Captured, OtherElement, } impl MouseHandler { pub fn new() -> Self { Self { on_mouse_leave: None, on_mouse_enter: None, on_mouse_move: None, on_mouse_press: None, on_mouse_release: None, on_mouse_leave_handler: Rc::new(RefCell::new(None)), mouse_capture_state: Rc::new(RefCell::new(MouseCaptureState::NotCaptured)), } } pub fn on_cursor_leave<F>(&mut self, canvas_common: &super::Common, handler: F) where F: 'static + FnMut(i32), { *self.on_mouse_leave_handler.borrow_mut() = Some(Box::new(handler)); let on_mouse_leave_handler = self.on_mouse_leave_handler.clone(); let mouse_capture_state = self.mouse_capture_state.clone(); self.on_mouse_leave = Some(canvas_common.add_event("mouseout", move |_: MouseEvent| { // If the mouse is being captured, it is always considered // to be "within" the the canvas, until the capture has been // released, therefore we don't send cursor leave events. if *mouse_capture_state.borrow() != MouseCaptureState::Captured { if let Some(handler) = on_mouse_leave_handler.borrow_mut().as_mut() { handler(0); } } })); } pub fn on_cursor_enter<F>(&mut self, canvas_common: &super::Common, mut handler: F) where F: 'static + FnMut(i32), { let mouse_capture_state = self.mouse_capture_state.clone(); self.on_mouse_enter = Some(canvas_common.add_event("mouseover", move |_: MouseEvent| { // We don't send cursor leave events when the mouse is being // captured, therefore we do the same with cursor enter events. if *mouse_capture_state.borrow() != MouseCaptureState::Captured { handler(0); } })); } pub fn on_mouse_release<F>(&mut self, canvas_common: &super::Common, mut handler: F) where F: 'static + FnMut(i32, MouseButton, ModifiersState), { let on_mouse_leave_handler = self.on_mouse_leave_handler.clone(); let mouse_capture_state = self.mouse_capture_state.clone(); let canvas = canvas_common.raw.clone(); self.on_mouse_release = Some(canvas_common.add_window_mouse_event( "mouseup", move |event: MouseEvent| { let canvas = canvas.clone(); let mut mouse_capture_state = mouse_capture_state.borrow_mut(); match &*mouse_capture_state { // Shouldn't happen but we'll just ignore it. MouseCaptureState::NotCaptured => return, MouseCaptureState::OtherElement => { if event.buttons() == 0 { // No buttons are pressed anymore so reset // the capturing state. *mouse_capture_state = MouseCaptureState::NotCaptured; } return; } MouseCaptureState::Captured => {} } event.stop_propagation(); handler( 0, event::mouse_button(&event), event::mouse_modifiers(&event), ); if event .target() .map_or(false, |target| target != EventTarget::from(canvas)) { // Since we do not send cursor leave events while the // cursor is being captured, we instead send it after // the capture has been released. if let Some(handler) = on_mouse_leave_handler.borrow_mut().as_mut() { handler(0); } } if event.buttons() == 0 { // No buttons are pressed anymore so reset // the capturing state. *mouse_capture_state = MouseCaptureState::NotCaptured; } }, )); } pub fn on_mouse_press<F>(&mut self, canvas_common: &super::Common, mut handler: F) where F: 'static + FnMut(i32, PhysicalPosition<f64>, MouseButton, ModifiersState), { let mouse_capture_state = self.mouse_capture_state.clone(); let canvas = canvas_common.raw.clone(); self.on_mouse_press = Some(canvas_common.add_window_mouse_event( "mousedown", move |event: MouseEvent| { let canvas = canvas.clone(); let mut mouse_capture_state = mouse_capture_state.borrow_mut(); match &*mouse_capture_state { MouseCaptureState::NotCaptured if event .target() .map_or(false, |target| target != EventTarget::from(canvas)) => { // The target isn't our canvas which means the // mouse is pressed outside of it. *mouse_capture_state = MouseCaptureState::OtherElement; return; } MouseCaptureState::OtherElement => return, _ => {} } *mouse_capture_state = MouseCaptureState::Captured; event.stop_propagation(); handler( 0, event::mouse_position(&event).to_physical(super::super::scale_factor()), event::mouse_button(&event), event::mouse_modifiers(&event), ); }, )); } pub fn on_cursor_move<F>(&mut self, canvas_common: &super::Common, mut handler: F) where F: 'static + FnMut(i32, PhysicalPosition<f64>, PhysicalPosition<f64>, ModifiersState), { let mouse_capture_state = self.mouse_capture_state.clone(); let canvas = canvas_common.raw.clone(); self.on_mouse_move = Some(canvas_common.add_window_mouse_event( "mousemove", move |event: MouseEvent| { let canvas = canvas.clone(); let mouse_capture_state = mouse_capture_state.borrow(); let is_over_canvas = event .target() .map_or(false, |target| target == EventTarget::from(canvas.clone())); match &*mouse_capture_state { // Don't handle hover events outside of canvas. MouseCaptureState::NotCaptured | MouseCaptureState::OtherElement if !is_over_canvas => {} // If hovering over the canvas, just send the cursor move event. MouseCaptureState::NotCaptured | MouseCaptureState::OtherElement | MouseCaptureState::Captured => { if *mouse_capture_state == MouseCaptureState::Captured { event.stop_propagation(); } let mouse_pos = if is_over_canvas { event::mouse_position(&event) } else { // Since the mouse is not on the canvas, we cannot // use `offsetX`/`offsetY`. event::mouse_position_by_client(&event, &canvas) }; let mouse_delta = event::mouse_delta(&event); handler( 0, mouse_pos.to_physical(super::super::scale_factor()), mouse_delta.to_physical(super::super::scale_factor()), event::mouse_modifiers(&event), ); } } }, )); } pub fn remove_listeners(&mut self) { self.on_mouse_leave = None; self.on_mouse_enter = None; self.on_mouse_move = None; self.on_mouse_press = None; self.on_mouse_release = None; *self.on_mouse_leave_handler.borrow_mut() = None; } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/canvas/pointer_handler.rs
Rust
use super::event; use super::EventListenerHandle; use crate::dpi::PhysicalPosition; use crate::event::Force; use crate::event::{ModifiersState, MouseButton}; use web_sys::PointerEvent; #[allow(dead_code)] pub(super) struct PointerHandler { on_cursor_leave: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, on_cursor_enter: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, on_cursor_move: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, on_pointer_press: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, on_pointer_release: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, on_touch_cancel: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, } impl PointerHandler { pub fn new() -> Self { Self { on_cursor_leave: None, on_cursor_enter: None, on_cursor_move: None, on_pointer_press: None, on_pointer_release: None, on_touch_cancel: None, } } pub fn on_cursor_leave<F>(&mut self, canvas_common: &super::Common, mut handler: F) where F: 'static + FnMut(i32), { self.on_cursor_leave = Some(canvas_common.add_event( "pointerout", move |event: PointerEvent| { // touch events are handled separately // handling them here would produce duplicate mouse events, inconsistent with // other platforms. if event.pointer_type() == "touch" { return; } handler(event.pointer_id()); }, )); } pub fn on_cursor_enter<F>(&mut self, canvas_common: &super::Common, mut handler: F) where F: 'static + FnMut(i32), { self.on_cursor_enter = Some(canvas_common.add_event( "pointerover", move |event: PointerEvent| { // touch events are handled separately // handling them here would produce duplicate mouse events, inconsistent with // other platforms. if event.pointer_type() == "touch" { return; } handler(event.pointer_id()); }, )); } pub fn on_mouse_release<M, T>( &mut self, canvas_common: &super::Common, mut mouse_handler: M, mut touch_handler: T, ) where M: 'static + FnMut(i32, MouseButton, ModifiersState), T: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { let canvas = canvas_common.raw.clone(); self.on_pointer_release = Some(canvas_common.add_user_event( "pointerup", move |event: PointerEvent| { if event.pointer_type() == "touch" { touch_handler( event.pointer_id(), event::touch_position(&event, &canvas) .to_physical(super::super::scale_factor()), Force::Normalized(event.pressure() as f64), ); } else { mouse_handler( event.pointer_id(), event::mouse_button(&event), event::mouse_modifiers(&event), ); } }, )); } pub fn on_mouse_press<M, T>( &mut self, canvas_common: &super::Common, mut mouse_handler: M, mut touch_handler: T, ) where M: 'static + FnMut(i32, PhysicalPosition<f64>, MouseButton, ModifiersState), T: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { let canvas = canvas_common.raw.clone(); self.on_pointer_press = Some(canvas_common.add_user_event( "pointerdown", move |event: PointerEvent| { if event.pointer_type() == "touch" { touch_handler( event.pointer_id(), event::touch_position(&event, &canvas) .to_physical(super::super::scale_factor()), Force::Normalized(event.pressure() as f64), ); } else { mouse_handler( event.pointer_id(), event::mouse_position(&event).to_physical(super::super::scale_factor()), event::mouse_button(&event), event::mouse_modifiers(&event), ); // Error is swallowed here since the error would occur every time the mouse is // clicked when the cursor is grabbed, and there is probably not a situation where // this could fail, that we care if it fails. let _e = canvas.set_pointer_capture(event.pointer_id()); } }, )); } pub fn on_cursor_move<M, T>( &mut self, canvas_common: &super::Common, mut mouse_handler: M, mut touch_handler: T, prevent_default: bool, ) where M: 'static + FnMut(i32, PhysicalPosition<f64>, PhysicalPosition<f64>, ModifiersState), T: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { let canvas = canvas_common.raw.clone(); self.on_cursor_move = Some(canvas_common.add_event( "pointermove", move |event: PointerEvent| { if event.pointer_type() == "touch" { if prevent_default { // prevent scroll on mobile web event.prevent_default(); } touch_handler( event.pointer_id(), event::touch_position(&event, &canvas) .to_physical(super::super::scale_factor()), Force::Normalized(event.pressure() as f64), ); } else { mouse_handler( event.pointer_id(), event::mouse_position(&event).to_physical(super::super::scale_factor()), event::mouse_delta(&event).to_physical(super::super::scale_factor()), event::mouse_modifiers(&event), ); } }, )); } pub fn on_touch_cancel<F>(&mut self, canvas_common: &super::Common, mut handler: F) where F: 'static + FnMut(i32, PhysicalPosition<f64>, Force), { let canvas = canvas_common.raw.clone(); self.on_touch_cancel = Some(canvas_common.add_event( "pointercancel", move |event: PointerEvent| { if event.pointer_type() == "touch" { handler( event.pointer_id(), event::touch_position(&event, &canvas) .to_physical(super::super::scale_factor()), Force::Normalized(event.pressure() as f64), ); } }, )); } pub fn remove_listeners(&mut self) { self.on_cursor_leave = None; self.on_cursor_enter = None; self.on_cursor_move = None; self.on_pointer_press = None; self.on_pointer_release = None; self.on_touch_cancel = None; } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/event.rs
Rust
use crate::dpi::LogicalPosition; use crate::event::{ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode}; use std::convert::TryInto; use web_sys::{HtmlCanvasElement, KeyboardEvent, MouseEvent, PointerEvent, WheelEvent}; pub fn mouse_button(event: &MouseEvent) -> MouseButton { match event.button() { 0 => MouseButton::Left, 1 => MouseButton::Middle, 2 => MouseButton::Right, i => MouseButton::Other((i - 3).try_into().expect("very large mouse button value")), } } pub fn mouse_modifiers(event: &MouseEvent) -> ModifiersState { let mut m = ModifiersState::empty(); m.set(ModifiersState::SHIFT, event.shift_key()); m.set(ModifiersState::CTRL, event.ctrl_key()); m.set(ModifiersState::ALT, event.alt_key()); m.set(ModifiersState::LOGO, event.meta_key()); m } pub fn mouse_position(event: &MouseEvent) -> LogicalPosition<f64> { LogicalPosition { x: event.offset_x() as f64, y: event.offset_y() as f64, } } pub fn mouse_delta(event: &MouseEvent) -> LogicalPosition<f64> { LogicalPosition { x: event.movement_x() as f64, y: event.movement_y() as f64, } } pub fn mouse_position_by_client( event: &MouseEvent, canvas: &HtmlCanvasElement, ) -> LogicalPosition<f64> { let bounding_client_rect = canvas.get_bounding_client_rect(); LogicalPosition { x: event.client_x() as f64 - bounding_client_rect.x(), y: event.client_y() as f64 - bounding_client_rect.y(), } } pub fn mouse_scroll_delta(event: &WheelEvent) -> Option<MouseScrollDelta> { let x = -event.delta_x(); let y = -event.delta_y(); match event.delta_mode() { WheelEvent::DOM_DELTA_LINE => Some(MouseScrollDelta::LineDelta(x as f32, y as f32)), WheelEvent::DOM_DELTA_PIXEL => { let delta = LogicalPosition::new(x, y).to_physical(super::scale_factor()); Some(MouseScrollDelta::PixelDelta(delta)) } _ => None, } } pub fn scan_code(event: &KeyboardEvent) -> ScanCode { match event.key_code() { 0 => event.char_code(), i => i, } } pub fn virtual_key_code(event: &KeyboardEvent) -> Option<VirtualKeyCode> { Some(match &event.code()[..] { "Digit1" => VirtualKeyCode::Key1, "Digit2" => VirtualKeyCode::Key2, "Digit3" => VirtualKeyCode::Key3, "Digit4" => VirtualKeyCode::Key4, "Digit5" => VirtualKeyCode::Key5, "Digit6" => VirtualKeyCode::Key6, "Digit7" => VirtualKeyCode::Key7, "Digit8" => VirtualKeyCode::Key8, "Digit9" => VirtualKeyCode::Key9, "Digit0" => VirtualKeyCode::Key0, "KeyA" => VirtualKeyCode::A, "KeyB" => VirtualKeyCode::B, "KeyC" => VirtualKeyCode::C, "KeyD" => VirtualKeyCode::D, "KeyE" => VirtualKeyCode::E, "KeyF" => VirtualKeyCode::F, "KeyG" => VirtualKeyCode::G, "KeyH" => VirtualKeyCode::H, "KeyI" => VirtualKeyCode::I, "KeyJ" => VirtualKeyCode::J, "KeyK" => VirtualKeyCode::K, "KeyL" => VirtualKeyCode::L, "KeyM" => VirtualKeyCode::M, "KeyN" => VirtualKeyCode::N, "KeyO" => VirtualKeyCode::O, "KeyP" => VirtualKeyCode::P, "KeyQ" => VirtualKeyCode::Q, "KeyR" => VirtualKeyCode::R, "KeyS" => VirtualKeyCode::S, "KeyT" => VirtualKeyCode::T, "KeyU" => VirtualKeyCode::U, "KeyV" => VirtualKeyCode::V, "KeyW" => VirtualKeyCode::W, "KeyX" => VirtualKeyCode::X, "KeyY" => VirtualKeyCode::Y, "KeyZ" => VirtualKeyCode::Z, "Escape" => VirtualKeyCode::Escape, "F1" => VirtualKeyCode::F1, "F2" => VirtualKeyCode::F2, "F3" => VirtualKeyCode::F3, "F4" => VirtualKeyCode::F4, "F5" => VirtualKeyCode::F5, "F6" => VirtualKeyCode::F6, "F7" => VirtualKeyCode::F7, "F8" => VirtualKeyCode::F8, "F9" => VirtualKeyCode::F9, "F10" => VirtualKeyCode::F10, "F11" => VirtualKeyCode::F11, "F12" => VirtualKeyCode::F12, "F13" => VirtualKeyCode::F13, "F14" => VirtualKeyCode::F14, "F15" => VirtualKeyCode::F15, "F16" => VirtualKeyCode::F16, "F17" => VirtualKeyCode::F17, "F18" => VirtualKeyCode::F18, "F19" => VirtualKeyCode::F19, "F20" => VirtualKeyCode::F20, "F21" => VirtualKeyCode::F21, "F22" => VirtualKeyCode::F22, "F23" => VirtualKeyCode::F23, "F24" => VirtualKeyCode::F24, "PrintScreen" => VirtualKeyCode::Snapshot, "ScrollLock" => VirtualKeyCode::Scroll, "Pause" => VirtualKeyCode::Pause, "Insert" => VirtualKeyCode::Insert, "Home" => VirtualKeyCode::Home, "Delete" => VirtualKeyCode::Delete, "End" => VirtualKeyCode::End, "PageDown" => VirtualKeyCode::PageDown, "PageUp" => VirtualKeyCode::PageUp, "ArrowLeft" => VirtualKeyCode::Left, "ArrowUp" => VirtualKeyCode::Up, "ArrowRight" => VirtualKeyCode::Right, "ArrowDown" => VirtualKeyCode::Down, "Backspace" => VirtualKeyCode::Back, "Enter" => VirtualKeyCode::Return, "Space" => VirtualKeyCode::Space, "Compose" => VirtualKeyCode::Compose, "Caret" => VirtualKeyCode::Caret, "NumLock" => VirtualKeyCode::Numlock, "Numpad0" => VirtualKeyCode::Numpad0, "Numpad1" => VirtualKeyCode::Numpad1, "Numpad2" => VirtualKeyCode::Numpad2, "Numpad3" => VirtualKeyCode::Numpad3, "Numpad4" => VirtualKeyCode::Numpad4, "Numpad5" => VirtualKeyCode::Numpad5, "Numpad6" => VirtualKeyCode::Numpad6, "Numpad7" => VirtualKeyCode::Numpad7, "Numpad8" => VirtualKeyCode::Numpad8, "Numpad9" => VirtualKeyCode::Numpad9, "AbntC1" => VirtualKeyCode::AbntC1, "AbntC2" => VirtualKeyCode::AbntC2, "NumpadAdd" => VirtualKeyCode::NumpadAdd, "Quote" => VirtualKeyCode::Apostrophe, "Apps" => VirtualKeyCode::Apps, "At" => VirtualKeyCode::At, "Ax" => VirtualKeyCode::Ax, "Backslash" => VirtualKeyCode::Backslash, "Calculator" => VirtualKeyCode::Calculator, "Capital" => VirtualKeyCode::Capital, "Semicolon" => VirtualKeyCode::Semicolon, "Comma" => VirtualKeyCode::Comma, "Convert" => VirtualKeyCode::Convert, "NumpadDecimal" => VirtualKeyCode::NumpadDecimal, "NumpadDivide" => VirtualKeyCode::NumpadDivide, "Equal" => VirtualKeyCode::Equals, "Backquote" => VirtualKeyCode::Grave, "Kana" => VirtualKeyCode::Kana, "Kanji" => VirtualKeyCode::Kanji, "AltLeft" => VirtualKeyCode::LAlt, "BracketLeft" => VirtualKeyCode::LBracket, "ControlLeft" => VirtualKeyCode::LControl, "ShiftLeft" => VirtualKeyCode::LShift, "MetaLeft" => VirtualKeyCode::LWin, "Mail" => VirtualKeyCode::Mail, "MediaSelect" => VirtualKeyCode::MediaSelect, "MediaStop" => VirtualKeyCode::MediaStop, "Minus" => VirtualKeyCode::Minus, "NumpadMultiply" => VirtualKeyCode::NumpadMultiply, "Mute" => VirtualKeyCode::Mute, "LaunchMyComputer" => VirtualKeyCode::MyComputer, "NavigateForward" => VirtualKeyCode::NavigateForward, "NavigateBackward" => VirtualKeyCode::NavigateBackward, "NextTrack" => VirtualKeyCode::NextTrack, "NoConvert" => VirtualKeyCode::NoConvert, "NumpadComma" => VirtualKeyCode::NumpadComma, "NumpadEnter" => VirtualKeyCode::NumpadEnter, "NumpadEquals" => VirtualKeyCode::NumpadEquals, "OEM102" => VirtualKeyCode::OEM102, "Period" => VirtualKeyCode::Period, "PlayPause" => VirtualKeyCode::PlayPause, "Power" => VirtualKeyCode::Power, "PrevTrack" => VirtualKeyCode::PrevTrack, "AltRight" => VirtualKeyCode::RAlt, "BracketRight" => VirtualKeyCode::RBracket, "ControlRight" => VirtualKeyCode::RControl, "ShiftRight" => VirtualKeyCode::RShift, "MetaRight" => VirtualKeyCode::RWin, "Slash" => VirtualKeyCode::Slash, "Sleep" => VirtualKeyCode::Sleep, "Stop" => VirtualKeyCode::Stop, "NumpadSubtract" => VirtualKeyCode::NumpadSubtract, "Sysrq" => VirtualKeyCode::Sysrq, "Tab" => VirtualKeyCode::Tab, "Underline" => VirtualKeyCode::Underline, "Unlabeled" => VirtualKeyCode::Unlabeled, "AudioVolumeDown" => VirtualKeyCode::VolumeDown, "AudioVolumeUp" => VirtualKeyCode::VolumeUp, "Wake" => VirtualKeyCode::Wake, "WebBack" => VirtualKeyCode::WebBack, "WebFavorites" => VirtualKeyCode::WebFavorites, "WebForward" => VirtualKeyCode::WebForward, "WebHome" => VirtualKeyCode::WebHome, "WebRefresh" => VirtualKeyCode::WebRefresh, "WebSearch" => VirtualKeyCode::WebSearch, "WebStop" => VirtualKeyCode::WebStop, "Yen" => VirtualKeyCode::Yen, _ => return None, }) } pub fn keyboard_modifiers(event: &KeyboardEvent) -> ModifiersState { let mut m = ModifiersState::empty(); m.set(ModifiersState::SHIFT, event.shift_key()); m.set(ModifiersState::CTRL, event.ctrl_key()); m.set(ModifiersState::ALT, event.alt_key()); m.set(ModifiersState::LOGO, event.meta_key()); m } pub fn codepoint(event: &KeyboardEvent) -> char { // `event.key()` always returns a non-empty `String`. Therefore, this should // never panic. // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key event.key().chars().next().unwrap() } pub fn touch_position(event: &PointerEvent, _canvas: &HtmlCanvasElement) -> LogicalPosition<f64> { // TODO: Should this handle more, like `mouse_position_by_client` does? LogicalPosition { x: event.client_x() as f64, y: event.client_y() as f64, } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/event_handle.rs
Rust
use wasm_bindgen::{prelude::Closure, JsCast}; use web_sys::{AddEventListenerOptions, EventListenerOptions, EventTarget}; pub(super) struct EventListenerHandle<T: ?Sized> { target: EventTarget, event_type: &'static str, listener: Closure<T>, options: EventListenerOptions, } impl<T: ?Sized> EventListenerHandle<T> { pub fn new<U>(target: &U, event_type: &'static str, listener: Closure<T>) -> Self where U: Clone + Into<EventTarget>, { let target = target.clone().into(); target .add_event_listener_with_callback(event_type, listener.as_ref().unchecked_ref()) .expect("Failed to add event listener"); EventListenerHandle { target, event_type, listener, options: EventListenerOptions::new(), } } pub fn with_options<U>( target: &U, event_type: &'static str, listener: Closure<T>, options: &AddEventListenerOptions, ) -> Self where U: Clone + Into<EventTarget>, { let target = target.clone().into(); target .add_event_listener_with_callback_and_add_event_listener_options( event_type, listener.as_ref().unchecked_ref(), options, ) .expect("Failed to add event listener"); EventListenerHandle { target, event_type, listener, options: options.clone().unchecked_into(), } } } impl<T: ?Sized> Drop for EventListenerHandle<T> { fn drop(&mut self) { self.target .remove_event_listener_with_callback_and_event_listener_options( self.event_type, self.listener.as_ref().unchecked_ref(), &self.options, ) .unwrap_or_else(|e| { web_sys::console::error_2( &format!("Error removing event listener {}", self.event_type).into(), &e, ) }); } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/media_query_handle.rs
Rust
use wasm_bindgen::{prelude::Closure, JsCast}; use web_sys::{MediaQueryList, MediaQueryListEvent}; pub(super) struct MediaQueryListHandle { mql: MediaQueryList, listener: Option<Closure<dyn FnMut(MediaQueryListEvent)>>, } impl MediaQueryListHandle { pub fn new( media_query: &str, listener: Closure<dyn FnMut(MediaQueryListEvent)>, ) -> Option<Self> { let window = web_sys::window().expect("Failed to obtain window"); let mql = window .match_media(media_query) .ok() .flatten() .and_then(|mql| { mql.add_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref())) .map(|_| mql) .ok() }); mql.map(|mql| Self { mql, listener: Some(listener), }) } pub fn mql(&self) -> &MediaQueryList { &self.mql } /// Removes the listener and returns the original listener closure, which /// can be reused. pub fn remove(mut self) -> Closure<dyn FnMut(MediaQueryListEvent)> { let listener = self.listener.take().unwrap_or_else(|| unreachable!()); remove_listener(&self.mql, &listener); listener } } impl Drop for MediaQueryListHandle { fn drop(&mut self) { if let Some(listener) = self.listener.take() { remove_listener(&self.mql, &listener); } } } fn remove_listener(mql: &MediaQueryList, listener: &Closure<dyn FnMut(MediaQueryListEvent)>) { mql.remove_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref())) .unwrap_or_else(|e| { web_sys::console::error_2(&"Error removing media query listener".into(), &e) }); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/mod.rs
Rust
mod canvas; mod event; mod event_handle; mod media_query_handle; mod scaling; mod timeout; pub use self::canvas::Canvas; pub use self::scaling::ScaleChangeDetector; pub use self::timeout::{AnimationFrameRequest, Timeout}; use crate::dpi::{LogicalSize, Size}; use crate::platform::web::WindowExtWebSys; use crate::window::Window; use wasm_bindgen::closure::Closure; use web_sys::{window, BeforeUnloadEvent, Element, HtmlCanvasElement}; pub fn throw(msg: &str) { wasm_bindgen::throw_str(msg); } pub fn exit_fullscreen() { let window = web_sys::window().expect("Failed to obtain window"); let document = window.document().expect("Failed to obtain document"); document.exit_fullscreen(); } pub struct UnloadEventHandle { _listener: event_handle::EventListenerHandle<dyn FnMut(BeforeUnloadEvent)>, } pub fn on_unload(mut handler: impl FnMut() + 'static) -> UnloadEventHandle { let window = web_sys::window().expect("Failed to obtain window"); let closure = Closure::wrap( Box::new(move |_: BeforeUnloadEvent| handler()) as Box<dyn FnMut(BeforeUnloadEvent)> ); let listener = event_handle::EventListenerHandle::new(&window, "beforeunload", closure); UnloadEventHandle { _listener: listener, } } impl WindowExtWebSys for Window { fn canvas(&self) -> HtmlCanvasElement { self.window.canvas().raw().clone() } fn is_dark_mode(&self) -> bool { let window = web_sys::window().expect("Failed to obtain window"); window .match_media("(prefers-color-scheme: dark)") .ok() .flatten() .map(|media| media.matches()) .unwrap_or(false) } } pub fn window_size() -> LogicalSize<f64> { let window = web_sys::window().expect("Failed to obtain window"); let width = window .inner_width() .expect("Failed to get width") .as_f64() .expect("Failed to get width as f64"); let height = window .inner_height() .expect("Failed to get height") .as_f64() .expect("Failed to get height as f64"); LogicalSize { width, height } } pub fn scale_factor() -> f64 { let window = web_sys::window().expect("Failed to obtain window"); window.device_pixel_ratio() } pub fn set_canvas_size(raw: &HtmlCanvasElement, size: Size) { let scale_factor = scale_factor(); let physical_size = size.to_physical::<u32>(scale_factor); let logical_size = size.to_logical::<f64>(scale_factor); raw.set_width(physical_size.width); raw.set_height(physical_size.height); set_canvas_style_property(raw, "width", &format!("{}px", logical_size.width)); set_canvas_style_property(raw, "height", &format!("{}px", logical_size.height)); } pub fn set_canvas_style_property(raw: &HtmlCanvasElement, property: &str, value: &str) { let style = raw.style(); style .set_property(property, value) .unwrap_or_else(|err| panic!("error: {err:?}\nFailed to set {property}")) } pub fn is_fullscreen(canvas: &HtmlCanvasElement) -> bool { let window = window().expect("Failed to obtain window"); let document = window.document().expect("Failed to obtain document"); match document.fullscreen_element() { Some(elem) => { let raw: Element = canvas.clone().into(); raw == elem } None => false, } } pub type RawCanvasType = HtmlCanvasElement;
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/scaling.rs
Rust
use super::super::ScaleChangeArgs; use super::media_query_handle::MediaQueryListHandle; use std::{cell::RefCell, rc::Rc}; use wasm_bindgen::prelude::Closure; use web_sys::MediaQueryListEvent; pub struct ScaleChangeDetector(Rc<RefCell<ScaleChangeDetectorInternal>>); impl ScaleChangeDetector { pub(crate) fn new<F>(handler: F) -> Self where F: 'static + FnMut(ScaleChangeArgs), { Self(ScaleChangeDetectorInternal::new(handler)) } } /// This is a helper type to help manage the `MediaQueryList` used for detecting /// changes of the `devicePixelRatio`. struct ScaleChangeDetectorInternal { callback: Box<dyn FnMut(ScaleChangeArgs)>, mql: Option<MediaQueryListHandle>, last_scale: f64, } impl ScaleChangeDetectorInternal { fn new<F>(handler: F) -> Rc<RefCell<Self>> where F: 'static + FnMut(ScaleChangeArgs), { let current_scale = super::scale_factor(); let new_self = Rc::new(RefCell::new(Self { callback: Box::new(handler), mql: None, last_scale: current_scale, })); let weak_self = Rc::downgrade(&new_self); let closure = Closure::wrap(Box::new(move |event: MediaQueryListEvent| { if let Some(rc_self) = weak_self.upgrade() { rc_self.borrow_mut().handler(event); } }) as Box<dyn FnMut(_)>); let mql = Self::create_mql(closure); { let mut borrowed_self = new_self.borrow_mut(); borrowed_self.mql = mql; } new_self } fn create_mql( closure: Closure<dyn FnMut(MediaQueryListEvent)>, ) -> Option<MediaQueryListHandle> { let current_scale = super::scale_factor(); // This media query initially matches the current `devicePixelRatio`. // We add 0.0001 to the lower and upper bounds such that it won't fail // due to floating point precision limitations. let media_query = format!( "(min-resolution: {min_scale:.4}dppx) and (max-resolution: {max_scale:.4}dppx), (-webkit-min-device-pixel-ratio: {min_scale:.4}) and (-webkit-max-device-pixel-ratio: {max_scale:.4})", min_scale = current_scale - 0.0001, max_scale= current_scale + 0.0001, ); let mql = MediaQueryListHandle::new(&media_query, closure); if let Some(mql) = &mql { assert!(mql.mql().matches()); } mql } fn handler(&mut self, _event: MediaQueryListEvent) { let mql = self .mql .take() .expect("DevicePixelRatioChangeDetector::mql should not be None"); let closure = mql.remove(); let new_scale = super::scale_factor(); (self.callback)(ScaleChangeArgs { old_scale: self.last_scale, new_scale, }); let new_mql = Self::create_mql(closure); self.mql = new_mql; self.last_scale = new_scale; } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/web_sys/timeout.rs
Rust
use std::cell::Cell; use std::rc::Rc; use std::time::Duration; use wasm_bindgen::closure::Closure; use wasm_bindgen::JsCast; #[derive(Debug)] pub struct Timeout { handle: i32, _closure: Closure<dyn FnMut()>, } impl Timeout { pub fn new<F>(f: F, duration: Duration) -> Timeout where F: 'static + FnMut(), { let window = web_sys::window().expect("Failed to obtain window"); let closure = Closure::wrap(Box::new(f) as Box<dyn FnMut()>); let handle = window .set_timeout_with_callback_and_timeout_and_arguments_0( closure.as_ref().unchecked_ref(), duration.as_millis() as i32, ) .expect("Failed to set timeout"); Timeout { handle, _closure: closure, } } } impl Drop for Timeout { fn drop(&mut self) { let window = web_sys::window().expect("Failed to obtain window"); window.clear_timeout_with_handle(self.handle); } } #[derive(Debug)] pub struct AnimationFrameRequest { handle: i32, // track callback state, because `cancelAnimationFrame` is slow fired: Rc<Cell<bool>>, _closure: Closure<dyn FnMut()>, } impl AnimationFrameRequest { pub fn new<F>(mut f: F) -> AnimationFrameRequest where F: 'static + FnMut(), { let window = web_sys::window().expect("Failed to obtain window"); let fired = Rc::new(Cell::new(false)); let c_fired = fired.clone(); let closure = Closure::wrap(Box::new(move || { (*c_fired).set(true); f(); }) as Box<dyn FnMut()>); let handle = window .request_animation_frame(closure.as_ref().unchecked_ref()) .expect("Failed to request animation frame"); AnimationFrameRequest { handle, fired, _closure: closure, } } } impl Drop for AnimationFrameRequest { fn drop(&mut self) { if !(*self.fired).get() { let window = web_sys::window().expect("Failed to obtain window"); window .cancel_animation_frame(self.handle) .expect("Failed to cancel animation frame"); } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/web/window.rs
Rust
use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; use crate::error::{ExternalError, NotSupportedError, OsError as RootOE}; use crate::event; use crate::icon::Icon; use crate::window::{ CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, WindowButtons, WindowId as RootWI, WindowLevel, }; use raw_window_handle::{RawDisplayHandle, RawWindowHandle, WebDisplayHandle, WebWindowHandle}; use super::{backend, monitor::MonitorHandle, EventLoopWindowTarget, Fullscreen}; use std::cell::{Ref, RefCell}; use std::collections::vec_deque::IntoIter as VecDequeIter; use std::collections::VecDeque; use std::rc::Rc; pub struct Window { canvas: Rc<RefCell<backend::Canvas>>, previous_pointer: RefCell<&'static str>, id: WindowId, register_redraw_request: Box<dyn Fn()>, resize_notify_fn: Box<dyn Fn(PhysicalSize<u32>)>, destroy_fn: Option<Box<dyn FnOnce()>>, has_focus: Rc<RefCell<bool>>, } impl Window { pub(crate) fn new<T>( target: &EventLoopWindowTarget<T>, attr: WindowAttributes, platform_attr: PlatformSpecificWindowBuilderAttributes, ) -> Result<Self, RootOE> { let runner = target.runner.clone(); let id = target.generate_id(); let prevent_default = platform_attr.prevent_default; let canvas = backend::Canvas::create(platform_attr)?; let canvas = Rc::new(RefCell::new(canvas)); let register_redraw_request = Box::new(move || runner.request_redraw(RootWI(id))); let has_focus = Rc::new(RefCell::new(false)); target.register(&canvas, id, prevent_default, has_focus.clone()); let runner = target.runner.clone(); let resize_notify_fn = Box::new(move |new_size| { runner.send_event(event::Event::WindowEvent { window_id: RootWI(id), event: event::WindowEvent::Resized(new_size), }); }); let runner = target.runner.clone(); let destroy_fn = Box::new(move || runner.notify_destroy_window(RootWI(id))); let window = Window { canvas, previous_pointer: RefCell::new("auto"), id, register_redraw_request, resize_notify_fn, destroy_fn: Some(destroy_fn), has_focus, }; backend::set_canvas_size( window.canvas.borrow().raw(), attr.inner_size.unwrap_or(Size::Logical(LogicalSize { width: 1024.0, height: 768.0, })), ); window.set_title(&attr.title); window.set_maximized(attr.maximized); window.set_visible(attr.visible); window.set_window_icon(attr.window_icon); Ok(window) } pub fn canvas(&self) -> Ref<'_, backend::Canvas> { self.canvas.borrow() } pub fn set_title(&self, title: &str) { self.canvas.borrow().set_attribute("alt", title); } pub fn set_transparent(&self, _transparent: bool) {} pub fn set_visible(&self, _visible: bool) { // Intentionally a no-op } #[inline] pub fn is_visible(&self) -> Option<bool> { None } pub fn request_redraw(&self) { (self.register_redraw_request)(); } pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { Ok(self .canvas .borrow() .position() .to_physical(self.scale_factor())) } pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { // Note: the canvas element has no window decorations, so this is equal to `outer_position`. self.outer_position() } pub fn set_outer_position(&self, position: Position) { let position = position.to_logical::<f64>(self.scale_factor()); let canvas = self.canvas.borrow(); canvas.set_attribute("position", "fixed"); canvas.set_attribute("left", &position.x.to_string()); canvas.set_attribute("top", &position.y.to_string()); } #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { self.canvas.borrow().size() } #[inline] pub fn outer_size(&self) -> PhysicalSize<u32> { // Note: the canvas element has no window decorations, so this is equal to `inner_size`. self.inner_size() } #[inline] pub fn set_inner_size(&self, size: Size) { let old_size = self.inner_size(); backend::set_canvas_size(self.canvas.borrow().raw(), size); let new_size = self.inner_size(); if old_size != new_size { (self.resize_notify_fn)(new_size); } } #[inline] pub fn set_min_inner_size(&self, _dimensions: Option<Size>) { // Intentionally a no-op: users can't resize canvas elements } #[inline] pub fn set_max_inner_size(&self, _dimensions: Option<Size>) { // Intentionally a no-op: users can't resize canvas elements } #[inline] pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { None } #[inline] pub fn set_resize_increments(&self, _increments: Option<Size>) { // Intentionally a no-op: users can't resize canvas elements } #[inline] pub fn set_resizable(&self, _resizable: bool) { // Intentionally a no-op: users can't resize canvas elements } pub fn is_resizable(&self) -> bool { true } #[inline] pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {} #[inline] pub fn enabled_buttons(&self) -> WindowButtons { WindowButtons::all() } #[inline] pub fn scale_factor(&self) -> f64 { super::backend::scale_factor() } #[inline] pub fn set_cursor_icon(&self, cursor: CursorIcon) { let text = match cursor { CursorIcon::Default => "auto", CursorIcon::Crosshair => "crosshair", CursorIcon::Hand => "pointer", CursorIcon::Arrow => "default", CursorIcon::Move => "move", CursorIcon::Text => "text", CursorIcon::Wait => "wait", CursorIcon::Help => "help", CursorIcon::Progress => "progress", CursorIcon::NotAllowed => "not-allowed", CursorIcon::ContextMenu => "context-menu", CursorIcon::Cell => "cell", CursorIcon::VerticalText => "vertical-text", CursorIcon::Alias => "alias", CursorIcon::Copy => "copy", CursorIcon::NoDrop => "no-drop", CursorIcon::Grab => "grab", CursorIcon::Grabbing => "grabbing", CursorIcon::AllScroll => "all-scroll", CursorIcon::ZoomIn => "zoom-in", CursorIcon::ZoomOut => "zoom-out", CursorIcon::EResize => "e-resize", CursorIcon::NResize => "n-resize", CursorIcon::NeResize => "ne-resize", CursorIcon::NwResize => "nw-resize", CursorIcon::SResize => "s-resize", CursorIcon::SeResize => "se-resize", CursorIcon::SwResize => "sw-resize", CursorIcon::WResize => "w-resize", CursorIcon::EwResize => "ew-resize", CursorIcon::NsResize => "ns-resize", CursorIcon::NeswResize => "nesw-resize", CursorIcon::NwseResize => "nwse-resize", CursorIcon::ColResize => "col-resize", CursorIcon::RowResize => "row-resize", }; *self.previous_pointer.borrow_mut() = text; backend::set_canvas_style_property(self.canvas.borrow().raw(), "cursor", text); } #[inline] pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } #[inline] pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { let lock = match mode { CursorGrabMode::None => false, CursorGrabMode::Locked => true, CursorGrabMode::Confined => { return Err(ExternalError::NotSupported(NotSupportedError::new())) } }; self.canvas .borrow() .set_cursor_lock(lock) .map_err(ExternalError::Os) } #[inline] pub fn set_cursor_visible(&self, visible: bool) { if !visible { self.canvas.borrow().set_attribute("cursor", "none"); } else { self.canvas .borrow() .set_attribute("cursor", &self.previous_pointer.borrow()); } } #[inline] pub fn drag_window(&self) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } #[inline] pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } #[inline] pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } #[inline] pub fn set_minimized(&self, _minimized: bool) { // Intentionally a no-op, as canvases cannot be 'minimized' } #[inline] pub fn is_minimized(&self) -> Option<bool> { // Canvas cannot be 'minimized' Some(false) } #[inline] pub fn set_maximized(&self, _maximized: bool) { // Intentionally a no-op, as canvases cannot be 'maximized' } #[inline] pub fn is_maximized(&self) -> bool { // Canvas cannot be 'maximized' false } #[inline] pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { if self.canvas.borrow().is_fullscreen() { Some(Fullscreen::Borderless(Some(self.current_monitor_inner()))) } else { None } } #[inline] pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { if fullscreen.is_some() { self.canvas.borrow().request_fullscreen(); } else if self.canvas.borrow().is_fullscreen() { backend::exit_fullscreen(); } } #[inline] pub fn set_decorations(&self, _decorations: bool) { // Intentionally a no-op, no canvas decorations } pub fn is_decorated(&self) -> bool { true } #[inline] pub fn set_window_level(&self, _level: WindowLevel) { // Intentionally a no-op, no window ordering } #[inline] pub fn set_window_icon(&self, _window_icon: Option<Icon>) { // Currently an intentional no-op } #[inline] pub fn set_ime_position(&self, _position: Position) { // Currently a no-op as it does not seem there is good support for this on web } #[inline] pub fn set_ime_allowed(&self, _allowed: bool) { // Currently not implemented } #[inline] pub fn set_ime_purpose(&self, _purpose: ImePurpose) { // Currently not implemented } #[inline] pub fn focus_window(&self) { // Currently a no-op as it does not seem there is good support for this on web } #[inline] pub fn request_user_attention(&self, _request_type: Option<UserAttentionType>) { // Currently an intentional no-op } #[inline] // Allow directly accessing the current monitor internally without unwrapping. fn current_monitor_inner(&self) -> MonitorHandle { MonitorHandle } #[inline] pub fn current_monitor(&self) -> Option<MonitorHandle> { Some(self.current_monitor_inner()) } #[inline] pub fn available_monitors(&self) -> VecDequeIter<MonitorHandle> { VecDeque::new().into_iter() } #[inline] pub fn primary_monitor(&self) -> Option<MonitorHandle> { Some(MonitorHandle) } #[inline] pub fn id(&self) -> WindowId { self.id } #[inline] pub fn raw_window_handle(&self) -> RawWindowHandle { let mut window_handle = WebWindowHandle::empty(); window_handle.id = self.id.0; RawWindowHandle::Web(window_handle) } #[inline] pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Web(WebDisplayHandle::empty()) } #[inline] pub fn set_theme(&self, _theme: Option<Theme>) {} #[inline] pub fn theme(&self) -> Option<Theme> { web_sys::window() .and_then(|window| { window .match_media("(prefers-color-scheme: dark)") .ok() .flatten() }) .map(|media_query_list| { if media_query_list.matches() { Theme::Dark } else { Theme::Light } }) } #[inline] pub fn has_focus(&self) -> bool { *self.has_focus.borrow() } pub fn title(&self) -> String { String::new() } } impl Drop for Window { fn drop(&mut self) { if let Some(destroy_fn) = self.destroy_fn.take() { destroy_fn(); } } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WindowId(pub(crate) u32); impl WindowId { pub const unsafe fn dummy() -> Self { Self(0) } } impl From<WindowId> for u64 { fn from(window_id: WindowId) -> Self { window_id.0 as u64 } } impl From<u64> for WindowId { fn from(raw_id: u64) -> Self { Self(raw_id as u32) } } #[derive(Clone)] pub struct PlatformSpecificWindowBuilderAttributes { pub(crate) canvas: Option<backend::RawCanvasType>, pub(crate) prevent_default: bool, pub(crate) focusable: bool, } impl Default for PlatformSpecificWindowBuilderAttributes { fn default() -> Self { Self { canvas: None, prevent_default: true, focusable: true, } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/dark_mode.rs
Rust
/// This is a simple implementation of support for Windows Dark Mode, /// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode use std::{ffi::c_void, ptr}; use once_cell::sync::Lazy; use windows_sys::{ core::PCSTR, Win32::{ Foundation::{BOOL, HWND, NTSTATUS, S_OK}, System::{ LibraryLoader::{GetProcAddress, LoadLibraryA}, SystemInformation::OSVERSIONINFOW, }, UI::{ Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTA}, Controls::SetWindowTheme, WindowsAndMessaging::{SystemParametersInfoA, SPI_GETHIGHCONTRAST}, }, }, }; use crate::window::Theme; use super::util; static WIN10_BUILD_VERSION: Lazy<Option<u32>> = Lazy::new(|| { type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> NTSTATUS; let handle = get_function!("ntdll.dll", RtlGetVersion); if let Some(rtl_get_version) = handle { unsafe { let mut vi = OSVERSIONINFOW { dwOSVersionInfoSize: 0, dwMajorVersion: 0, dwMinorVersion: 0, dwBuildNumber: 0, dwPlatformId: 0, szCSDVersion: [0; 128], }; let status = (rtl_get_version)(&mut vi); if status >= 0 && vi.dwMajorVersion == 10 && vi.dwMinorVersion == 0 { Some(vi.dwBuildNumber) } else { None } } } else { None } }); static DARK_MODE_SUPPORTED: Lazy<bool> = Lazy::new(|| { // We won't try to do anything for windows versions < 17763 // (Windows 10 October 2018 update) match *WIN10_BUILD_VERSION { Some(v) => v >= 17763, None => false, } }); static DARK_THEME_NAME: Lazy<Vec<u16>> = Lazy::new(|| util::encode_wide("DarkMode_Explorer")); static LIGHT_THEME_NAME: Lazy<Vec<u16>> = Lazy::new(|| util::encode_wide("")); /// Attempt to set a theme on a window, if necessary. /// Returns the theme that was picked pub fn try_theme(hwnd: HWND, preferred_theme: Option<Theme>) -> Theme { if *DARK_MODE_SUPPORTED { let is_dark_mode = match preferred_theme { Some(theme) => theme == Theme::Dark, None => should_use_dark_mode(), }; let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; let theme_name = match theme { Theme::Dark => DARK_THEME_NAME.as_ptr(), Theme::Light => LIGHT_THEME_NAME.as_ptr(), }; let status = unsafe { SetWindowTheme(hwnd, theme_name, ptr::null()) }; if status == S_OK && set_dark_mode_for_window(hwnd, is_dark_mode) { return theme; } } Theme::Light } fn set_dark_mode_for_window(hwnd: HWND, is_dark_mode: bool) -> bool { // Uses Windows undocumented API SetWindowCompositionAttribute, // as seen in win32-darkmode example linked at top of file. type SetWindowCompositionAttribute = unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL; #[allow(clippy::upper_case_acronyms)] type WINDOWCOMPOSITIONATTRIB = u32; const WCA_USEDARKMODECOLORS: WINDOWCOMPOSITIONATTRIB = 26; #[allow(non_snake_case)] #[allow(clippy::upper_case_acronyms)] #[repr(C)] struct WINDOWCOMPOSITIONATTRIBDATA { Attrib: WINDOWCOMPOSITIONATTRIB, pvData: *mut c_void, cbData: usize, } static SET_WINDOW_COMPOSITION_ATTRIBUTE: Lazy<Option<SetWindowCompositionAttribute>> = Lazy::new(|| get_function!("user32.dll", SetWindowCompositionAttribute)); if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE { unsafe { // SetWindowCompositionAttribute needs a bigbool (i32), not bool. let mut is_dark_mode_bigbool = BOOL::from(is_dark_mode); let mut data = WINDOWCOMPOSITIONATTRIBDATA { Attrib: WCA_USEDARKMODECOLORS, pvData: &mut is_dark_mode_bigbool as *mut _ as _, cbData: std::mem::size_of_val(&is_dark_mode_bigbool) as _, }; let status = set_window_composition_attribute(hwnd, &mut data); status != false.into() } } else { false } } fn should_use_dark_mode() -> bool { should_apps_use_dark_mode() && !is_high_contrast() } fn should_apps_use_dark_mode() -> bool { type ShouldAppsUseDarkMode = unsafe extern "system" fn() -> bool; static SHOULD_APPS_USE_DARK_MODE: Lazy<Option<ShouldAppsUseDarkMode>> = Lazy::new(|| unsafe { const UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL: PCSTR = 132 as PCSTR; let module = LoadLibraryA("uxtheme.dll\0".as_ptr()); if module == 0 { return None; } let handle = GetProcAddress(module, UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL); handle.map(|handle| std::mem::transmute(handle)) }); SHOULD_APPS_USE_DARK_MODE .map(|should_apps_use_dark_mode| unsafe { (should_apps_use_dark_mode)() }) .unwrap_or(false) } fn is_high_contrast() -> bool { let mut hc = HIGHCONTRASTA { cbSize: 0, dwFlags: 0, lpszDefaultScheme: ptr::null_mut(), }; let ok = unsafe { SystemParametersInfoA( SPI_GETHIGHCONTRAST, std::mem::size_of_val(&hc) as _, &mut hc as *mut _ as _, 0, ) }; ok != false.into() && util::has_flag(hc.dwFlags, HCF_HIGHCONTRASTON) }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/definitions.rs
Rust
#![allow(non_snake_case)] #![allow(non_upper_case_globals)] use std::ffi::c_void; use windows_sys::{ core::{IUnknown, GUID, HRESULT}, Win32::{ Foundation::{BOOL, HWND, POINTL}, System::Com::{ IAdviseSink, IDataObject, IEnumFORMATETC, IEnumSTATDATA, FORMATETC, STGMEDIUM, }, }, }; #[repr(C)] pub struct IUnknownVtbl { pub QueryInterface: unsafe extern "system" fn( This: *mut IUnknown, riid: *const GUID, ppvObject: *mut *mut c_void, ) -> HRESULT, pub AddRef: unsafe extern "system" fn(This: *mut IUnknown) -> u32, pub Release: unsafe extern "system" fn(This: *mut IUnknown) -> u32, } #[repr(C)] pub struct IDataObjectVtbl { pub parent: IUnknownVtbl, pub GetData: unsafe extern "system" fn( This: *mut IDataObject, pformatetcIn: *const FORMATETC, pmedium: *mut STGMEDIUM, ) -> HRESULT, pub GetDataHere: unsafe extern "system" fn( This: *mut IDataObject, pformatetc: *const FORMATETC, pmedium: *mut STGMEDIUM, ) -> HRESULT, QueryGetData: unsafe extern "system" fn(This: *mut IDataObject, pformatetc: *const FORMATETC) -> HRESULT, pub GetCanonicalFormatEtc: unsafe extern "system" fn( This: *mut IDataObject, pformatetcIn: *const FORMATETC, pformatetcOut: *mut FORMATETC, ) -> HRESULT, pub SetData: unsafe extern "system" fn( This: *mut IDataObject, pformatetc: *const FORMATETC, pformatetcOut: *const FORMATETC, fRelease: BOOL, ) -> HRESULT, pub EnumFormatEtc: unsafe extern "system" fn( This: *mut IDataObject, dwDirection: u32, ppenumFormatEtc: *mut *mut IEnumFORMATETC, ) -> HRESULT, pub DAdvise: unsafe extern "system" fn( This: *mut IDataObject, pformatetc: *const FORMATETC, advf: u32, pAdvSInk: *const IAdviseSink, pdwConnection: *mut u32, ) -> HRESULT, pub DUnadvise: unsafe extern "system" fn(This: *mut IDataObject, dwConnection: u32) -> HRESULT, pub EnumDAdvise: unsafe extern "system" fn( This: *mut IDataObject, ppenumAdvise: *const *const IEnumSTATDATA, ) -> HRESULT, } #[repr(C)] pub struct IDropTargetVtbl { pub parent: IUnknownVtbl, pub DragEnter: unsafe extern "system" fn( This: *mut IDropTarget, pDataObj: *const IDataObject, grfKeyState: u32, pt: *const POINTL, pdwEffect: *mut u32, ) -> HRESULT, pub DragOver: unsafe extern "system" fn( This: *mut IDropTarget, grfKeyState: u32, pt: *const POINTL, pdwEffect: *mut u32, ) -> HRESULT, pub DragLeave: unsafe extern "system" fn(This: *mut IDropTarget) -> HRESULT, pub Drop: unsafe extern "system" fn( This: *mut IDropTarget, pDataObj: *const IDataObject, grfKeyState: u32, pt: *const POINTL, pdwEffect: *mut u32, ) -> HRESULT, } #[repr(C)] pub struct IDropTarget { pub lpVtbl: *const IDropTargetVtbl, } #[repr(C)] pub struct ITaskbarListVtbl { pub parent: IUnknownVtbl, pub HrInit: unsafe extern "system" fn(This: *mut ITaskbarList) -> HRESULT, pub AddTab: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, pub DeleteTab: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, pub ActivateTab: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, pub SetActiveAlt: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, } #[repr(C)] pub struct ITaskbarList { pub lpVtbl: *const ITaskbarListVtbl, } #[repr(C)] pub struct ITaskbarList2Vtbl { pub parent: ITaskbarListVtbl, pub MarkFullscreenWindow: unsafe extern "system" fn( This: *mut ITaskbarList2, hwnd: HWND, fFullscreen: BOOL, ) -> HRESULT, } #[repr(C)] pub struct ITaskbarList2 { pub lpVtbl: *const ITaskbarList2Vtbl, } pub const CLSID_TaskbarList: GUID = GUID { data1: 0x56fdf344, data2: 0xfd6d, data3: 0x11d0, data4: [0x95, 0x8a, 0x00, 0x60, 0x97, 0xc9, 0xa0, 0x90], }; pub const IID_ITaskbarList: GUID = GUID { data1: 0x56FDF342, data2: 0xFD6D, data3: 0x11D0, data4: [0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90], }; pub const IID_ITaskbarList2: GUID = GUID { data1: 0x602d4995, data2: 0xb13a, data3: 0x429b, data4: [0xa6, 0x6e, 0x19, 0x35, 0xe4, 0x4f, 0x43, 0x17], };
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/dpi.rs
Rust
#![allow(non_snake_case, unused_unsafe)] use std::sync::Once; use windows_sys::Win32::{ Foundation::{HWND, S_OK}, Graphics::Gdi::{ GetDC, GetDeviceCaps, MonitorFromWindow, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST, }, UI::{ HiDpi::{ DPI_AWARENESS_CONTEXT, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE, MDT_EFFECTIVE_DPI, PROCESS_PER_MONITOR_DPI_AWARE, }, WindowsAndMessaging::IsProcessDPIAware, }, }; use crate::platform_impl::platform::util::{ ENABLE_NON_CLIENT_DPI_SCALING, GET_DPI_FOR_MONITOR, GET_DPI_FOR_WINDOW, SET_PROCESS_DPI_AWARE, SET_PROCESS_DPI_AWARENESS, SET_PROCESS_DPI_AWARENESS_CONTEXT, }; const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2: DPI_AWARENESS_CONTEXT = -4; pub fn become_dpi_aware() { static ENABLE_DPI_AWARENESS: Once = Once::new(); ENABLE_DPI_AWARENESS.call_once(|| { unsafe { if let Some(SetProcessDpiAwarenessContext) = *SET_PROCESS_DPI_AWARENESS_CONTEXT { // We are on Windows 10 Anniversary Update (1607) or later. if SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) == false.into() { // V2 only works with Windows 10 Creators Update (1703). Try using the older // V1 if we can't set V2. SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); } } else if let Some(SetProcessDpiAwareness) = *SET_PROCESS_DPI_AWARENESS { // We are on Windows 8.1 or later. SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); } else if let Some(SetProcessDPIAware) = *SET_PROCESS_DPI_AWARE { // We are on Vista or later. SetProcessDPIAware(); } } }); } pub fn enable_non_client_dpi_scaling(hwnd: HWND) { unsafe { if let Some(EnableNonClientDpiScaling) = *ENABLE_NON_CLIENT_DPI_SCALING { EnableNonClientDpiScaling(hwnd); } } } pub fn get_monitor_dpi(hmonitor: HMONITOR) -> Option<u32> { unsafe { if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { // We are on Windows 8.1 or later. let mut dpi_x = 0; let mut dpi_y = 0; if GetDpiForMonitor(hmonitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { // MSDN says that "the values of *dpiX and *dpiY are identical. You only need to // record one of the values to determine the DPI and respond appropriately". // https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510(v=vs.85).aspx return Some(dpi_x); } } } None } pub const BASE_DPI: u32 = 96; pub fn dpi_to_scale_factor(dpi: u32) -> f64 { dpi as f64 / BASE_DPI as f64 } pub unsafe fn hwnd_dpi(hwnd: HWND) -> u32 { let hdc = GetDC(hwnd); if hdc == 0 { panic!("[winit] `GetDC` returned null!"); } if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW { // We are on Windows 10 Anniversary Update (1607) or later. match GetDpiForWindow(hwnd) { 0 => BASE_DPI, // 0 is returned if hwnd is invalid dpi => dpi, } } else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { // We are on Windows 8.1 or later. let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); if monitor == 0 { return BASE_DPI; } let mut dpi_x = 0; let mut dpi_y = 0; if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { dpi_x } else { BASE_DPI } } else { // We are on Vista or later. if IsProcessDPIAware() != false.into() { // If the process is DPI aware, then scaling must be handled by the application using // this DPI value. GetDeviceCaps(hdc, LOGPIXELSX) as u32 } else { // If the process is DPI unaware, then scaling is performed by the OS; we thus return // 96 (scale factor 1.0) to prevent the window from being re-scaled by both the // application and the WM. BASE_DPI } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/drop_handler.rs
Rust
use std::{ ffi::{c_void, OsString}, os::windows::ffi::OsStringExt, path::PathBuf, ptr, sync::atomic::{AtomicUsize, Ordering}, }; use windows_sys::{ core::{IUnknown, GUID, HRESULT}, Win32::{ Foundation::{DV_E_FORMATETC, HWND, POINTL, S_OK}, System::{ Com::{IDataObject, DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL}, Ole::{CF_HDROP, DROPEFFECT_COPY, DROPEFFECT_NONE}, }, UI::Shell::{DragFinish, DragQueryFileW, HDROP}, }, }; use crate::platform_impl::platform::{ definitions::{IDataObjectVtbl, IDropTarget, IDropTargetVtbl, IUnknownVtbl}, WindowId, }; use crate::{event::Event, window::WindowId as RootWindowId}; #[repr(C)] pub struct FileDropHandlerData { pub interface: IDropTarget, refcount: AtomicUsize, window: HWND, send_event: Box<dyn Fn(Event<'static, ()>)>, cursor_effect: u32, hovered_is_valid: bool, /* If the currently hovered item is not valid there must not be any `HoveredFileCancelled` emitted */ } pub struct FileDropHandler { pub data: *mut FileDropHandlerData, } #[allow(non_snake_case)] impl FileDropHandler { pub fn new(window: HWND, send_event: Box<dyn Fn(Event<'static, ()>)>) -> FileDropHandler { let data = Box::new(FileDropHandlerData { interface: IDropTarget { lpVtbl: &DROP_TARGET_VTBL as *const IDropTargetVtbl, }, refcount: AtomicUsize::new(1), window, send_event, cursor_effect: DROPEFFECT_NONE, hovered_is_valid: false, }); FileDropHandler { data: Box::into_raw(data), } } // Implement IUnknown pub unsafe extern "system" fn QueryInterface( _this: *mut IUnknown, _riid: *const GUID, _ppvObject: *mut *mut c_void, ) -> HRESULT { // This function doesn't appear to be required for an `IDropTarget`. // An implementation would be nice however. unimplemented!(); } pub unsafe extern "system" fn AddRef(this: *mut IUnknown) -> u32 { let drop_handler_data = Self::from_interface(this); let count = drop_handler_data.refcount.fetch_add(1, Ordering::Release) + 1; count as u32 } pub unsafe extern "system" fn Release(this: *mut IUnknown) -> u32 { let drop_handler = Self::from_interface(this); let count = drop_handler.refcount.fetch_sub(1, Ordering::Release) - 1; if count == 0 { // Destroy the underlying data drop(Box::from_raw(drop_handler as *mut FileDropHandlerData)); } count as u32 } pub unsafe extern "system" fn DragEnter( this: *mut IDropTarget, pDataObj: *const IDataObject, _grfKeyState: u32, _pt: *const POINTL, pdwEffect: *mut u32, ) -> HRESULT { use crate::event::WindowEvent::HoveredFile; let drop_handler = Self::from_interface(this); let hdrop = Self::iterate_filenames(pDataObj, |filename| { drop_handler.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(drop_handler.window)), event: HoveredFile(filename), }); }); drop_handler.hovered_is_valid = hdrop.is_some(); drop_handler.cursor_effect = if drop_handler.hovered_is_valid { DROPEFFECT_COPY } else { DROPEFFECT_NONE }; *pdwEffect = drop_handler.cursor_effect; S_OK } pub unsafe extern "system" fn DragOver( this: *mut IDropTarget, _grfKeyState: u32, _pt: *const POINTL, pdwEffect: *mut u32, ) -> HRESULT { let drop_handler = Self::from_interface(this); *pdwEffect = drop_handler.cursor_effect; S_OK } pub unsafe extern "system" fn DragLeave(this: *mut IDropTarget) -> HRESULT { use crate::event::WindowEvent::HoveredFileCancelled; let drop_handler = Self::from_interface(this); if drop_handler.hovered_is_valid { drop_handler.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(drop_handler.window)), event: HoveredFileCancelled, }); } S_OK } pub unsafe extern "system" fn Drop( this: *mut IDropTarget, pDataObj: *const IDataObject, _grfKeyState: u32, _pt: *const POINTL, _pdwEffect: *mut u32, ) -> HRESULT { use crate::event::WindowEvent::DroppedFile; let drop_handler = Self::from_interface(this); let hdrop = Self::iterate_filenames(pDataObj, |filename| { drop_handler.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(drop_handler.window)), event: DroppedFile(filename), }); }); if let Some(hdrop) = hdrop { DragFinish(hdrop); } S_OK } unsafe fn from_interface<'a, InterfaceT>(this: *mut InterfaceT) -> &'a mut FileDropHandlerData { &mut *(this as *mut _) } unsafe fn iterate_filenames<F>(data_obj: *const IDataObject, callback: F) -> Option<HDROP> where F: Fn(PathBuf), { let drop_format = FORMATETC { cfFormat: CF_HDROP, ptd: ptr::null_mut(), dwAspect: DVASPECT_CONTENT, lindex: -1, tymed: TYMED_HGLOBAL as u32, }; let mut medium = std::mem::zeroed(); let get_data_fn = (*(*data_obj).cast::<IDataObjectVtbl>()).GetData; let get_data_result = get_data_fn(data_obj as *mut _, &drop_format, &mut medium); if get_data_result >= 0 { let hdrop = medium.Anonymous.hGlobal; // The second parameter (0xFFFFFFFF) instructs the function to return the item count let item_count = DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); for i in 0..item_count { // Get the length of the path string NOT including the terminating null character. // Previously, this was using a fixed size array of MAX_PATH length, but the // Windows API allows longer paths under certain circumstances. let character_count = DragQueryFileW(hdrop, i, ptr::null_mut(), 0) as usize; let str_len = character_count + 1; // Fill path_buf with the null-terminated file name let mut path_buf = Vec::with_capacity(str_len); DragQueryFileW(hdrop, i, path_buf.as_mut_ptr(), str_len as u32); path_buf.set_len(str_len); callback(OsString::from_wide(&path_buf[0..character_count]).into()); } Some(hdrop) } else if get_data_result == DV_E_FORMATETC { // If the dropped item is not a file this error will occur. // In this case it is OK to return without taking further action. debug!("Error occured while processing dropped/hovered item: item is not a file."); None } else { debug!("Unexpected error occured while processing dropped/hovered item."); None } } } impl FileDropHandlerData { fn send_event(&self, event: Event<'static, ()>) { (self.send_event)(event); } } impl Drop for FileDropHandler { fn drop(&mut self) { unsafe { FileDropHandler::Release(self.data as *mut IUnknown); } } } static DROP_TARGET_VTBL: IDropTargetVtbl = IDropTargetVtbl { parent: IUnknownVtbl { QueryInterface: FileDropHandler::QueryInterface, AddRef: FileDropHandler::AddRef, Release: FileDropHandler::Release, }, DragEnter: FileDropHandler::DragEnter, DragOver: FileDropHandler::DragOver, DragLeave: FileDropHandler::DragLeave, Drop: FileDropHandler::Drop, };
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/event.rs
Rust
use std::{ char, sync::atomic::{AtomicBool, AtomicIsize, Ordering}, }; use windows_sys::Win32::{ Foundation::{LPARAM, WPARAM}, UI::{ Input::KeyboardAndMouse::{ GetKeyState, GetKeyboardLayout, GetKeyboardState, MapVirtualKeyA, ToUnicodeEx, MAPVK_VK_TO_CHAR, MAPVK_VSC_TO_VK_EX, VIRTUAL_KEY, VK_0, VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9, VK_A, VK_ADD, VK_APPS, VK_B, VK_BACK, VK_BROWSER_BACK, VK_BROWSER_FAVORITES, VK_BROWSER_FORWARD, VK_BROWSER_HOME, VK_BROWSER_REFRESH, VK_BROWSER_SEARCH, VK_BROWSER_STOP, VK_C, VK_CAPITAL, VK_CONTROL, VK_CONVERT, VK_D, VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_E, VK_END, VK_ESCAPE, VK_F, VK_F1, VK_F10, VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16, VK_F17, VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, VK_F23, VK_F24, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_G, VK_H, VK_HOME, VK_I, VK_INSERT, VK_J, VK_K, VK_KANA, VK_KANJI, VK_L, VK_LAUNCH_MAIL, VK_LAUNCH_MEDIA_SELECT, VK_LCONTROL, VK_LEFT, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_M, VK_MEDIA_NEXT_TRACK, VK_MEDIA_PLAY_PAUSE, VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MENU, VK_MULTIPLY, VK_N, VK_NEXT, VK_NONCONVERT, VK_NUMLOCK, VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_O, VK_OEM_1, VK_OEM_102, VK_OEM_2, VK_OEM_3, VK_OEM_4, VK_OEM_5, VK_OEM_6, VK_OEM_7, VK_OEM_COMMA, VK_OEM_MINUS, VK_OEM_PERIOD, VK_OEM_PLUS, VK_P, VK_PAUSE, VK_PRIOR, VK_Q, VK_R, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_S, VK_SCROLL, VK_SHIFT, VK_SLEEP, VK_SNAPSHOT, VK_SPACE, VK_SUBTRACT, VK_T, VK_TAB, VK_U, VK_UP, VK_V, VK_VOLUME_DOWN, VK_VOLUME_MUTE, VK_VOLUME_UP, VK_W, VK_X, VK_Y, VK_Z, }, TextServices::HKL, }, }; use crate::event::{ModifiersState, ScanCode, VirtualKeyCode}; use super::util::has_flag; fn key_pressed(vkey: VIRTUAL_KEY) -> bool { unsafe { has_flag(GetKeyState(vkey as i32), 1 << 15) } } pub fn get_key_mods() -> ModifiersState { let filter_out_altgr = layout_uses_altgr() && key_pressed(VK_RMENU); let mut mods = ModifiersState::empty(); mods.set(ModifiersState::SHIFT, key_pressed(VK_SHIFT)); mods.set( ModifiersState::CTRL, key_pressed(VK_CONTROL) && !filter_out_altgr, ); mods.set( ModifiersState::ALT, key_pressed(VK_MENU) && !filter_out_altgr, ); mods.set( ModifiersState::LOGO, key_pressed(VK_LWIN) || key_pressed(VK_RWIN), ); mods } bitflags! { #[derive(Default)] pub struct ModifiersStateSide: u32 { const LSHIFT = 0b010; const RSHIFT = 0b001; const LCTRL = 0b010 << 3; const RCTRL = 0b001 << 3; const LALT = 0b010 << 6; const RALT = 0b001 << 6; const LLOGO = 0b010 << 9; const RLOGO = 0b001 << 9; } } impl ModifiersStateSide { pub fn filter_out_altgr(&self) -> ModifiersStateSide { match layout_uses_altgr() && self.contains(Self::RALT) { false => *self, true => *self & !(Self::LCTRL | Self::RCTRL | Self::LALT | Self::RALT), } } } impl From<ModifiersStateSide> for ModifiersState { fn from(side: ModifiersStateSide) -> Self { let mut state = ModifiersState::default(); state.set( Self::SHIFT, side.intersects(ModifiersStateSide::LSHIFT | ModifiersStateSide::RSHIFT), ); state.set( Self::CTRL, side.intersects(ModifiersStateSide::LCTRL | ModifiersStateSide::RCTRL), ); state.set( Self::ALT, side.intersects(ModifiersStateSide::LALT | ModifiersStateSide::RALT), ); state.set( Self::LOGO, side.intersects(ModifiersStateSide::LLOGO | ModifiersStateSide::RLOGO), ); state } } pub fn get_pressed_keys() -> impl Iterator<Item = VIRTUAL_KEY> { let mut keyboard_state = vec![0u8; 256]; unsafe { GetKeyboardState(keyboard_state.as_mut_ptr()) }; keyboard_state .into_iter() .enumerate() .filter(|(_, p)| (*p & (1 << 7)) != 0) // whether or not a key is pressed is communicated via the high-order bit .map(|(i, _)| i as u16) } unsafe fn get_char(keyboard_state: &[u8; 256], v_key: u32, hkl: HKL) -> Option<char> { let mut unicode_bytes = [0u16; 5]; let len = ToUnicodeEx( v_key, 0, keyboard_state.as_ptr(), unicode_bytes.as_mut_ptr(), unicode_bytes.len() as _, 0, hkl, ); if len >= 1 { char::decode_utf16(unicode_bytes.iter().cloned()) .next() .and_then(|c| c.ok()) } else { None } } /// Figures out if the keyboard layout has an AltGr key instead of an Alt key. /// /// Unfortunately, the Windows API doesn't give a way for us to conveniently figure that out. So, /// we use a technique blatantly stolen from [the Firefox source code][source]: iterate over every /// possible virtual key and compare the `char` output when AltGr is pressed vs when it isn't. If /// pressing AltGr outputs characters that are different from the standard characters, the layout /// uses AltGr. Otherwise, it doesn't. /// /// [source]: https://github.com/mozilla/gecko-dev/blob/265e6721798a455604328ed5262f430cfcc37c2f/widget/windows/KeyboardLayout.cpp#L4356-L4416 fn layout_uses_altgr() -> bool { unsafe { static ACTIVE_LAYOUT: AtomicIsize = AtomicIsize::new(0); static USES_ALTGR: AtomicBool = AtomicBool::new(false); let hkl = GetKeyboardLayout(0); let old_hkl = ACTIVE_LAYOUT.swap(hkl, Ordering::SeqCst); if hkl == old_hkl { return USES_ALTGR.load(Ordering::SeqCst); } let mut keyboard_state_altgr = [0u8; 256]; // AltGr is an alias for Ctrl+Alt for... some reason. Whatever it is, those are the keypresses // we have to emulate to do an AltGr test. keyboard_state_altgr[VK_MENU as usize] = 0x80; keyboard_state_altgr[VK_CONTROL as usize] = 0x80; let keyboard_state_empty = [0u8; 256]; for v_key in 0..=255 { let key_noaltgr = get_char(&keyboard_state_empty, v_key, hkl); let key_altgr = get_char(&keyboard_state_altgr, v_key, hkl); if let (Some(noaltgr), Some(altgr)) = (key_noaltgr, key_altgr) { if noaltgr != altgr { USES_ALTGR.store(true, Ordering::SeqCst); return true; } } } USES_ALTGR.store(false, Ordering::SeqCst); false } } pub fn vkey_to_winit_vkey(vkey: VIRTUAL_KEY) -> Option<VirtualKeyCode> { // VK_* codes are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx match vkey { //VK_LBUTTON => Some(VirtualKeyCode::Lbutton), //VK_RBUTTON => Some(VirtualKeyCode::Rbutton), //VK_CANCEL => Some(VirtualKeyCode::Cancel), //VK_MBUTTON => Some(VirtualKeyCode::Mbutton), //VK_XBUTTON1 => Some(VirtualKeyCode::Xbutton1), //VK_XBUTTON2 => Some(VirtualKeyCode::Xbutton2), VK_BACK => Some(VirtualKeyCode::Back), VK_TAB => Some(VirtualKeyCode::Tab), //VK_CLEAR => Some(VirtualKeyCode::Clear), VK_RETURN => Some(VirtualKeyCode::Return), VK_LSHIFT => Some(VirtualKeyCode::LShift), VK_RSHIFT => Some(VirtualKeyCode::RShift), VK_LCONTROL => Some(VirtualKeyCode::LControl), VK_RCONTROL => Some(VirtualKeyCode::RControl), VK_LMENU => Some(VirtualKeyCode::LAlt), VK_RMENU => Some(VirtualKeyCode::RAlt), VK_PAUSE => Some(VirtualKeyCode::Pause), VK_CAPITAL => Some(VirtualKeyCode::Capital), VK_KANA => Some(VirtualKeyCode::Kana), //VK_HANGUEL => Some(VirtualKeyCode::Hanguel), //VK_HANGUL => Some(VirtualKeyCode::Hangul), //VK_JUNJA => Some(VirtualKeyCode::Junja), //VK_FINAL => Some(VirtualKeyCode::Final), //VK_HANJA => Some(VirtualKeyCode::Hanja), VK_KANJI => Some(VirtualKeyCode::Kanji), VK_ESCAPE => Some(VirtualKeyCode::Escape), VK_CONVERT => Some(VirtualKeyCode::Convert), VK_NONCONVERT => Some(VirtualKeyCode::NoConvert), //VK_ACCEPT => Some(VirtualKeyCode::Accept), //VK_MODECHANGE => Some(VirtualKeyCode::Modechange), VK_SPACE => Some(VirtualKeyCode::Space), VK_PRIOR => Some(VirtualKeyCode::PageUp), VK_NEXT => Some(VirtualKeyCode::PageDown), VK_END => Some(VirtualKeyCode::End), VK_HOME => Some(VirtualKeyCode::Home), VK_LEFT => Some(VirtualKeyCode::Left), VK_UP => Some(VirtualKeyCode::Up), VK_RIGHT => Some(VirtualKeyCode::Right), VK_DOWN => Some(VirtualKeyCode::Down), //VK_SELECT => Some(VirtualKeyCode::Select), //VK_PRINT => Some(VirtualKeyCode::Print), //VK_EXECUTE => Some(VirtualKeyCode::Execute), VK_SNAPSHOT => Some(VirtualKeyCode::Snapshot), VK_INSERT => Some(VirtualKeyCode::Insert), VK_DELETE => Some(VirtualKeyCode::Delete), //VK_HELP => Some(VirtualKeyCode::Help), VK_0 => Some(VirtualKeyCode::Key0), VK_1 => Some(VirtualKeyCode::Key1), VK_2 => Some(VirtualKeyCode::Key2), VK_3 => Some(VirtualKeyCode::Key3), VK_4 => Some(VirtualKeyCode::Key4), VK_5 => Some(VirtualKeyCode::Key5), VK_6 => Some(VirtualKeyCode::Key6), VK_7 => Some(VirtualKeyCode::Key7), VK_8 => Some(VirtualKeyCode::Key8), VK_9 => Some(VirtualKeyCode::Key9), VK_A => Some(VirtualKeyCode::A), VK_B => Some(VirtualKeyCode::B), VK_C => Some(VirtualKeyCode::C), VK_D => Some(VirtualKeyCode::D), VK_E => Some(VirtualKeyCode::E), VK_F => Some(VirtualKeyCode::F), VK_G => Some(VirtualKeyCode::G), VK_H => Some(VirtualKeyCode::H), VK_I => Some(VirtualKeyCode::I), VK_J => Some(VirtualKeyCode::J), VK_K => Some(VirtualKeyCode::K), VK_L => Some(VirtualKeyCode::L), VK_M => Some(VirtualKeyCode::M), VK_N => Some(VirtualKeyCode::N), VK_O => Some(VirtualKeyCode::O), VK_P => Some(VirtualKeyCode::P), VK_Q => Some(VirtualKeyCode::Q), VK_R => Some(VirtualKeyCode::R), VK_S => Some(VirtualKeyCode::S), VK_T => Some(VirtualKeyCode::T), VK_U => Some(VirtualKeyCode::U), VK_V => Some(VirtualKeyCode::V), VK_W => Some(VirtualKeyCode::W), VK_X => Some(VirtualKeyCode::X), VK_Y => Some(VirtualKeyCode::Y), VK_Z => Some(VirtualKeyCode::Z), VK_LWIN => Some(VirtualKeyCode::LWin), VK_RWIN => Some(VirtualKeyCode::RWin), VK_APPS => Some(VirtualKeyCode::Apps), VK_SLEEP => Some(VirtualKeyCode::Sleep), VK_NUMPAD0 => Some(VirtualKeyCode::Numpad0), VK_NUMPAD1 => Some(VirtualKeyCode::Numpad1), VK_NUMPAD2 => Some(VirtualKeyCode::Numpad2), VK_NUMPAD3 => Some(VirtualKeyCode::Numpad3), VK_NUMPAD4 => Some(VirtualKeyCode::Numpad4), VK_NUMPAD5 => Some(VirtualKeyCode::Numpad5), VK_NUMPAD6 => Some(VirtualKeyCode::Numpad6), VK_NUMPAD7 => Some(VirtualKeyCode::Numpad7), VK_NUMPAD8 => Some(VirtualKeyCode::Numpad8), VK_NUMPAD9 => Some(VirtualKeyCode::Numpad9), VK_MULTIPLY => Some(VirtualKeyCode::NumpadMultiply), VK_ADD => Some(VirtualKeyCode::NumpadAdd), //VK_SEPARATOR => Some(VirtualKeyCode::Separator), VK_SUBTRACT => Some(VirtualKeyCode::NumpadSubtract), VK_DECIMAL => Some(VirtualKeyCode::NumpadDecimal), VK_DIVIDE => Some(VirtualKeyCode::NumpadDivide), VK_F1 => Some(VirtualKeyCode::F1), VK_F2 => Some(VirtualKeyCode::F2), VK_F3 => Some(VirtualKeyCode::F3), VK_F4 => Some(VirtualKeyCode::F4), VK_F5 => Some(VirtualKeyCode::F5), VK_F6 => Some(VirtualKeyCode::F6), VK_F7 => Some(VirtualKeyCode::F7), VK_F8 => Some(VirtualKeyCode::F8), VK_F9 => Some(VirtualKeyCode::F9), VK_F10 => Some(VirtualKeyCode::F10), VK_F11 => Some(VirtualKeyCode::F11), VK_F12 => Some(VirtualKeyCode::F12), VK_F13 => Some(VirtualKeyCode::F13), VK_F14 => Some(VirtualKeyCode::F14), VK_F15 => Some(VirtualKeyCode::F15), VK_F16 => Some(VirtualKeyCode::F16), VK_F17 => Some(VirtualKeyCode::F17), VK_F18 => Some(VirtualKeyCode::F18), VK_F19 => Some(VirtualKeyCode::F19), VK_F20 => Some(VirtualKeyCode::F20), VK_F21 => Some(VirtualKeyCode::F21), VK_F22 => Some(VirtualKeyCode::F22), VK_F23 => Some(VirtualKeyCode::F23), VK_F24 => Some(VirtualKeyCode::F24), VK_NUMLOCK => Some(VirtualKeyCode::Numlock), VK_SCROLL => Some(VirtualKeyCode::Scroll), VK_BROWSER_BACK => Some(VirtualKeyCode::NavigateBackward), VK_BROWSER_FORWARD => Some(VirtualKeyCode::NavigateForward), VK_BROWSER_REFRESH => Some(VirtualKeyCode::WebRefresh), VK_BROWSER_STOP => Some(VirtualKeyCode::WebStop), VK_BROWSER_SEARCH => Some(VirtualKeyCode::WebSearch), VK_BROWSER_FAVORITES => Some(VirtualKeyCode::WebFavorites), VK_BROWSER_HOME => Some(VirtualKeyCode::WebHome), VK_VOLUME_MUTE => Some(VirtualKeyCode::Mute), VK_VOLUME_DOWN => Some(VirtualKeyCode::VolumeDown), VK_VOLUME_UP => Some(VirtualKeyCode::VolumeUp), VK_MEDIA_NEXT_TRACK => Some(VirtualKeyCode::NextTrack), VK_MEDIA_PREV_TRACK => Some(VirtualKeyCode::PrevTrack), VK_MEDIA_STOP => Some(VirtualKeyCode::MediaStop), VK_MEDIA_PLAY_PAUSE => Some(VirtualKeyCode::PlayPause), VK_LAUNCH_MAIL => Some(VirtualKeyCode::Mail), VK_LAUNCH_MEDIA_SELECT => Some(VirtualKeyCode::MediaSelect), /*VK_LAUNCH_APP1 => Some(VirtualKeyCode::Launch_app1), VK_LAUNCH_APP2 => Some(VirtualKeyCode::Launch_app2),*/ VK_OEM_PLUS => Some(VirtualKeyCode::Equals), VK_OEM_COMMA => Some(VirtualKeyCode::Comma), VK_OEM_MINUS => Some(VirtualKeyCode::Minus), VK_OEM_PERIOD => Some(VirtualKeyCode::Period), VK_OEM_1 => map_text_keys(vkey), VK_OEM_2 => map_text_keys(vkey), VK_OEM_3 => map_text_keys(vkey), VK_OEM_4 => map_text_keys(vkey), VK_OEM_5 => map_text_keys(vkey), VK_OEM_6 => map_text_keys(vkey), VK_OEM_7 => map_text_keys(vkey), /* VK_OEM_8 => Some(VirtualKeyCode::Oem_8), */ VK_OEM_102 => Some(VirtualKeyCode::OEM102), /*VK_PROCESSKEY => Some(VirtualKeyCode::Processkey), VK_PACKET => Some(VirtualKeyCode::Packet), VK_ATTN => Some(VirtualKeyCode::Attn), VK_CRSEL => Some(VirtualKeyCode::Crsel), VK_EXSEL => Some(VirtualKeyCode::Exsel), VK_EREOF => Some(VirtualKeyCode::Ereof), VK_PLAY => Some(VirtualKeyCode::Play), VK_ZOOM => Some(VirtualKeyCode::Zoom), VK_NONAME => Some(VirtualKeyCode::Noname), VK_PA1 => Some(VirtualKeyCode::Pa1), VK_OEM_CLEAR => Some(VirtualKeyCode::Oem_clear),*/ _ => None, } } pub fn handle_extended_keys( vkey: VIRTUAL_KEY, mut scancode: u32, extended: bool, ) -> Option<(VIRTUAL_KEY, u32)> { // Welcome to hell https://blog.molecular-matters.com/2011/09/05/properly-handling-keyboard-input/ scancode |= if extended { 0xE000 } else { 0x0000 }; let vkey = match vkey { VK_SHIFT => (unsafe { MapVirtualKeyA(scancode, MAPVK_VSC_TO_VK_EX) } as u16), VK_CONTROL => { if extended { VK_RCONTROL } else { VK_LCONTROL } } VK_MENU => { if extended { VK_RMENU } else { VK_LMENU } } _ => { match scancode { // When VK_PAUSE is pressed it emits a LeftControl + NumLock scancode event sequence, but reports VK_PAUSE // as the virtual key on both events, or VK_PAUSE on the first event or 0xFF when using raw input. // Don't emit anything for the LeftControl event in the pair... 0xE01D if vkey == VK_PAUSE => return None, // ...and emit the Pause event for the second event in the pair. 0x45 if vkey == VK_PAUSE || vkey == 0xFF => { scancode = 0xE059; VK_PAUSE } // VK_PAUSE has an incorrect vkey value when used with modifiers. VK_PAUSE also reports a different // scancode when used with modifiers than when used without 0xE046 => { scancode = 0xE059; VK_PAUSE } // VK_SCROLL has an incorrect vkey value when used with modifiers. 0x46 => VK_SCROLL, _ => vkey, } } }; Some((vkey, scancode)) } pub fn process_key_params( wparam: WPARAM, lparam: LPARAM, ) -> Option<(ScanCode, Option<VirtualKeyCode>)> { let scancode = ((lparam >> 16) & 0xff) as u32; let extended = (lparam & 0x01000000) != 0; handle_extended_keys(wparam as u16, scancode, extended) .map(|(vkey, scancode)| (scancode, vkey_to_winit_vkey(vkey))) } // This is needed as windows doesn't properly distinguish // some virtual key codes for different keyboard layouts fn map_text_keys(win_virtual_key: VIRTUAL_KEY) -> Option<VirtualKeyCode> { let char_key = unsafe { MapVirtualKeyA(win_virtual_key as u32, MAPVK_VK_TO_CHAR) } & 0x7FFF; match char::from_u32(char_key) { Some(';') => Some(VirtualKeyCode::Semicolon), Some('/') => Some(VirtualKeyCode::Slash), Some('`') => Some(VirtualKeyCode::Grave), Some('[') => Some(VirtualKeyCode::LBracket), Some(']') => Some(VirtualKeyCode::RBracket), Some('\'') => Some(VirtualKeyCode::Apostrophe), Some('\\') => Some(VirtualKeyCode::Backslash), _ => None, } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/event_loop.rs
Rust
#![allow(non_snake_case)] mod runner; use std::{ cell::Cell, collections::VecDeque, ffi::c_void, marker::PhantomData, mem, panic, ptr, rc::Rc, sync::{ atomic::{AtomicU32, Ordering}, mpsc::{self, Receiver, Sender}, Arc, Mutex, MutexGuard, }, thread, time::{Duration, Instant}, }; use once_cell::sync::Lazy; use raw_window_handle::{RawDisplayHandle, WindowsDisplayHandle}; use windows_sys::Win32::{ Devices::HumanInterfaceDevice::MOUSE_MOVE_RELATIVE, Foundation::{BOOL, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WAIT_TIMEOUT, WPARAM}, Graphics::Gdi::{ GetMonitorInfoW, GetUpdateRect, MonitorFromRect, MonitorFromWindow, RedrawWindow, ScreenToClient, ValidateRect, MONITORINFO, MONITOR_DEFAULTTONULL, RDW_INTERNALPAINT, SC_SCREENSAVE, }, Media::{timeBeginPeriod, timeEndPeriod, timeGetDevCaps, TIMECAPS, TIMERR_NOERROR}, System::{Ole::RevokeDragDrop, Threading::GetCurrentThreadId, WindowsProgramming::INFINITE}, UI::{ Controls::{HOVER_DEFAULT, WM_MOUSELEAVE}, Input::{ Ime::{GCS_COMPSTR, GCS_RESULTSTR, ISC_SHOWUICOMPOSITIONWINDOW}, KeyboardAndMouse::{ MapVirtualKeyA, ReleaseCapture, SetCapture, TrackMouseEvent, MAPVK_VK_TO_VSC, TME_LEAVE, TRACKMOUSEEVENT, }, Pointer::{ POINTER_FLAG_DOWN, POINTER_FLAG_UP, POINTER_FLAG_UPDATE, POINTER_INFO, POINTER_PEN_INFO, POINTER_TOUCH_INFO, }, Touch::{ CloseTouchInputHandle, GetTouchInputInfo, TOUCHEVENTF_DOWN, TOUCHEVENTF_MOVE, TOUCHEVENTF_UP, TOUCHINPUT, }, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE, }, WindowsAndMessaging::{ CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMenu, GetMessageW, LoadCursorW, MsgWaitForMultipleObjectsEx, PeekMessageW, PostMessageW, PostThreadMessageW, RegisterClassExW, RegisterWindowMessageA, SetCursor, SetWindowPos, TranslateMessage, CREATESTRUCTW, GIDC_ARRIVAL, GIDC_REMOVAL, GWL_STYLE, GWL_USERDATA, HTCAPTION, HTCLIENT, MINMAXINFO, MNC_CLOSE, MSG, MWMO_INPUTAVAILABLE, NCCALCSIZE_PARAMS, PM_NOREMOVE, PM_QS_PAINT, PM_REMOVE, PT_PEN, PT_TOUCH, QS_ALLEVENTS, RI_KEY_E0, RI_KEY_E1, RI_MOUSE_WHEEL, SC_MINIMIZE, SC_RESTORE, SIZE_MAXIMIZED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WHEEL_DELTA, WINDOWPOS, WM_CAPTURECHANGED, WM_CHAR, WM_CLOSE, WM_CREATE, WM_DESTROY, WM_DPICHANGED, WM_DROPFILES, WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_GETMINMAXINFO, WM_IME_COMPOSITION, WM_IME_ENDCOMPOSITION, WM_IME_SETCONTEXT, WM_IME_STARTCOMPOSITION, WM_INPUT, WM_INPUT_DEVICE_CHANGE, WM_KEYDOWN, WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MENUCHAR, WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_NCACTIVATE, WM_NCCALCSIZE, WM_NCCREATE, WM_NCDESTROY, WM_NCLBUTTONDOWN, WM_PAINT, WM_POINTERDOWN, WM_POINTERUP, WM_POINTERUPDATE, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SETFOCUS, WM_SETTINGCHANGE, WM_SIZE, WM_SYSCHAR, WM_SYSCOMMAND, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TOUCH, WM_WINDOWPOSCHANGED, WM_WINDOWPOSCHANGING, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, WS_OVERLAPPED, WS_POPUP, WS_VISIBLE, }, }, }; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, event::{DeviceEvent, Event, Force, Ime, KeyboardInput, Touch, TouchPhase, WindowEvent}, event_loop::{ ControlFlow, DeviceEventFilter, EventLoopClosed, EventLoopWindowTarget as RootELW, }, platform_impl::platform::{ dark_mode::try_theme, dpi::{become_dpi_aware, dpi_to_scale_factor}, drop_handler::FileDropHandler, event::{self, handle_extended_keys, process_key_params, vkey_to_winit_vkey}, ime::ImeContext, monitor::{self, MonitorHandle}, raw_input, util, window::InitData, window_state::{CursorFlags, ImeState, WindowFlags, WindowState}, wrap_device_id, Fullscreen, WindowId, DEVICE_ID, }, window::WindowId as RootWindowId, }; use runner::{EventLoopRunner, EventLoopRunnerShared}; use super::window::set_skip_taskbar; type GetPointerFrameInfoHistory = unsafe extern "system" fn( pointerId: u32, entriesCount: *mut u32, pointerCount: *mut u32, pointerInfo: *mut POINTER_INFO, ) -> BOOL; type SkipPointerFrameMessages = unsafe extern "system" fn(pointerId: u32) -> BOOL; type GetPointerDeviceRects = unsafe extern "system" fn( device: HANDLE, pointerDeviceRect: *mut RECT, displayRect: *mut RECT, ) -> BOOL; type GetPointerTouchInfo = unsafe extern "system" fn(pointerId: u32, touchInfo: *mut POINTER_TOUCH_INFO) -> BOOL; type GetPointerPenInfo = unsafe extern "system" fn(pointId: u32, penInfo: *mut POINTER_PEN_INFO) -> BOOL; static GET_POINTER_FRAME_INFO_HISTORY: Lazy<Option<GetPointerFrameInfoHistory>> = Lazy::new(|| get_function!("user32.dll", GetPointerFrameInfoHistory)); static SKIP_POINTER_FRAME_MESSAGES: Lazy<Option<SkipPointerFrameMessages>> = Lazy::new(|| get_function!("user32.dll", SkipPointerFrameMessages)); static GET_POINTER_DEVICE_RECTS: Lazy<Option<GetPointerDeviceRects>> = Lazy::new(|| get_function!("user32.dll", GetPointerDeviceRects)); static GET_POINTER_TOUCH_INFO: Lazy<Option<GetPointerTouchInfo>> = Lazy::new(|| get_function!("user32.dll", GetPointerTouchInfo)); static GET_POINTER_PEN_INFO: Lazy<Option<GetPointerPenInfo>> = Lazy::new(|| get_function!("user32.dll", GetPointerPenInfo)); pub(crate) struct WindowData<T: 'static> { pub window_state: Arc<Mutex<WindowState>>, pub event_loop_runner: EventLoopRunnerShared<T>, pub _file_drop_handler: Option<FileDropHandler>, pub userdata_removed: Cell<bool>, pub recurse_depth: Cell<u32>, } impl<T> WindowData<T> { unsafe fn send_event(&self, event: Event<'_, T>) { self.event_loop_runner.send_event(event); } fn window_state_lock(&self) -> MutexGuard<'_, WindowState> { self.window_state.lock().unwrap() } } struct ThreadMsgTargetData<T: 'static> { event_loop_runner: EventLoopRunnerShared<T>, user_event_receiver: Receiver<T>, } impl<T> ThreadMsgTargetData<T> { unsafe fn send_event(&self, event: Event<'_, T>) { self.event_loop_runner.send_event(event); } } pub struct EventLoop<T: 'static> { thread_msg_sender: Sender<T>, window_target: RootELW<T>, msg_hook: Option<Box<dyn FnMut(*const c_void) -> bool + 'static>>, } pub(crate) struct PlatformSpecificEventLoopAttributes { pub(crate) any_thread: bool, pub(crate) dpi_aware: bool, pub(crate) msg_hook: Option<Box<dyn FnMut(*const c_void) -> bool + 'static>>, } impl Default for PlatformSpecificEventLoopAttributes { fn default() -> Self { Self { any_thread: false, dpi_aware: true, msg_hook: None, } } } pub struct EventLoopWindowTarget<T: 'static> { thread_id: u32, thread_msg_target: HWND, pub(crate) runner_shared: EventLoopRunnerShared<T>, } impl<T: 'static> EventLoop<T> { pub(crate) fn new(attributes: &mut PlatformSpecificEventLoopAttributes) -> Self { let thread_id = unsafe { GetCurrentThreadId() }; if !attributes.any_thread && thread_id != main_thread_id() { panic!( "Initializing the event loop outside of the main thread is a significant \ cross-platform compatibility hazard. If you absolutely need to create an \ EventLoop on a different thread, you can use the \ `EventLoopBuilderExtWindows::any_thread` function." ); } if attributes.dpi_aware { become_dpi_aware(); } let thread_msg_target = create_event_target_window::<T>(); thread::Builder::new() .name("winit wait thread".to_string()) .spawn(move || wait_thread(thread_id, thread_msg_target)) .expect("Failed to spawn winit wait thread"); let wait_thread_id = get_wait_thread_id(); let runner_shared = Rc::new(EventLoopRunner::new(thread_msg_target, wait_thread_id)); let thread_msg_sender = insert_event_target_window_data::<T>(thread_msg_target, runner_shared.clone()); raw_input::register_all_mice_and_keyboards_for_raw_input( thread_msg_target, Default::default(), ); EventLoop { thread_msg_sender, window_target: RootELW { p: EventLoopWindowTarget { thread_id, thread_msg_target, runner_shared, }, _marker: PhantomData, }, msg_hook: attributes.msg_hook.take(), } } pub fn window_target(&self) -> &RootELW<T> { &self.window_target } pub fn run<F>(mut self, event_handler: F) -> ! where F: 'static + FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow), { let exit_code = self.run_return(event_handler); ::std::process::exit(exit_code); } pub fn run_return<F>(&mut self, mut event_handler: F) -> i32 where F: FnMut(Event<'_, T>, &RootELW<T>, &mut ControlFlow), { let event_loop_windows_ref = &self.window_target; unsafe { self.window_target .p .runner_shared .set_event_handler(move |event, control_flow| { event_handler(event, event_loop_windows_ref, control_flow) }); } let runner = &self.window_target.p.runner_shared; let exit_code = unsafe { let mut msg = mem::zeroed(); runner.poll(); 'main: loop { if GetMessageW(&mut msg, 0, 0, 0) == false.into() { break 'main 0; } let handled = if let Some(callback) = self.msg_hook.as_deref_mut() { callback(&mut msg as *mut _ as *mut _) } else { false }; if !handled { TranslateMessage(&msg); DispatchMessageW(&msg); } if let Err(payload) = runner.take_panic_error() { runner.reset_runner(); panic::resume_unwind(payload); } if let ControlFlow::ExitWithCode(code) = runner.control_flow() { if !runner.handling_events() { break 'main code; } } } }; unsafe { runner.loop_destroyed(); } runner.reset_runner(); exit_code } pub fn create_proxy(&self) -> EventLoopProxy<T> { EventLoopProxy { target_window: self.window_target.p.thread_msg_target, event_send: self.thread_msg_sender.clone(), } } } impl<T> EventLoopWindowTarget<T> { #[inline(always)] pub(crate) fn create_thread_executor(&self) -> EventLoopThreadExecutor { EventLoopThreadExecutor { thread_id: self.thread_id, target_window: self.thread_msg_target, } } // TODO: Investigate opportunities for caching pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { monitor::available_monitors() } pub fn primary_monitor(&self) -> Option<MonitorHandle> { let monitor = monitor::primary_monitor(); Some(monitor) } pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Windows(WindowsDisplayHandle::empty()) } pub fn set_device_event_filter(&self, filter: DeviceEventFilter) { raw_input::register_all_mice_and_keyboards_for_raw_input(self.thread_msg_target, filter); } } /// Returns the id of the main thread. /// /// Windows has no real API to check if the current executing thread is the "main thread", unlike /// macOS. /// /// Windows will let us look up the current thread's id, but there's no API that lets us check what /// the id of the main thread is. We would somehow need to get the main thread's id before a /// developer could spin off any other threads inside of the main entrypoint in order to emulate the /// capabilities of other platforms. /// /// We can get the id of the main thread by using CRT initialization. CRT initialization can be used /// to setup global state within a program. The OS will call a list of function pointers which /// assign values to a static variable. To have get a hold of the main thread id, we need to place /// our function pointer inside of the `.CRT$XCU` section so it is called before the main /// entrypoint. /// /// Full details of CRT initialization can be found here: /// <https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-initialization?view=msvc-160> fn main_thread_id() -> u32 { static mut MAIN_THREAD_ID: u32 = 0; /// Function pointer used in CRT initialization section to set the above static field's value. // Mark as used so this is not removable. #[used] #[allow(non_upper_case_globals)] // Place the function pointer inside of CRT initialization section so it is loaded before // main entrypoint. // // See: https://doc.rust-lang.org/stable/reference/abi.html#the-link_section-attribute #[link_section = ".CRT$XCU"] static INIT_MAIN_THREAD_ID: unsafe fn() = { unsafe fn initer() { MAIN_THREAD_ID = GetCurrentThreadId(); } initer }; unsafe { MAIN_THREAD_ID } } fn get_wait_thread_id() -> u32 { unsafe { let mut msg = mem::zeroed(); let result = GetMessageW( &mut msg, -1, SEND_WAIT_THREAD_ID_MSG_ID.get(), SEND_WAIT_THREAD_ID_MSG_ID.get(), ); assert_eq!( msg.message, SEND_WAIT_THREAD_ID_MSG_ID.get(), "this shouldn't be possible. please open an issue with Winit. error code: {result}" ); msg.lParam as u32 } } static WAIT_PERIOD_MIN: Lazy<Option<u32>> = Lazy::new(|| unsafe { let mut caps = TIMECAPS { wPeriodMin: 0, wPeriodMax: 0, }; if timeGetDevCaps(&mut caps, mem::size_of::<TIMECAPS>() as u32) == TIMERR_NOERROR { Some(caps.wPeriodMin) } else { None } }); fn wait_thread(parent_thread_id: u32, msg_window_id: HWND) { unsafe { let mut msg: MSG; let cur_thread_id = GetCurrentThreadId(); PostThreadMessageW( parent_thread_id, SEND_WAIT_THREAD_ID_MSG_ID.get(), 0, cur_thread_id as LPARAM, ); let mut wait_until_opt = None; 'main: loop { // Zeroing out the message ensures that the `WaitUntilInstantBox` doesn't get // double-freed if `MsgWaitForMultipleObjectsEx` returns early and there aren't // additional messages to process. msg = mem::zeroed(); if wait_until_opt.is_some() { if PeekMessageW(&mut msg, 0, 0, 0, PM_REMOVE) != false.into() { TranslateMessage(&msg); DispatchMessageW(&msg); } } else if GetMessageW(&mut msg, 0, 0, 0) == false.into() { break 'main; } else { TranslateMessage(&msg); DispatchMessageW(&msg); } if msg.message == WAIT_UNTIL_MSG_ID.get() { wait_until_opt = Some(*WaitUntilInstantBox::from_raw(msg.lParam as *mut _)); } else if msg.message == CANCEL_WAIT_UNTIL_MSG_ID.get() { wait_until_opt = None; } if let Some(wait_until) = wait_until_opt { let now = Instant::now(); if now < wait_until { // Windows' scheduler has a default accuracy of several ms. This isn't good enough for // `WaitUntil`, so we request the Windows scheduler to use a higher accuracy if possible. // If we couldn't query the timer capabilities, then we use the default resolution. if let Some(period) = *WAIT_PERIOD_MIN { timeBeginPeriod(period); } // `MsgWaitForMultipleObjects` is bound by the granularity of the scheduler period. // Because of this, we try to reduce the requested time just enough to undershoot `wait_until` // by the smallest amount possible, and then we busy loop for the remaining time inside the // NewEvents message handler. let resume_reason = MsgWaitForMultipleObjectsEx( 0, ptr::null(), dur2timeout(wait_until - now).saturating_sub(WAIT_PERIOD_MIN.unwrap_or(1)), QS_ALLEVENTS, MWMO_INPUTAVAILABLE, ); if let Some(period) = *WAIT_PERIOD_MIN { timeEndPeriod(period); } if resume_reason == WAIT_TIMEOUT { PostMessageW(msg_window_id, PROCESS_NEW_EVENTS_MSG_ID.get(), 0, 0); wait_until_opt = None; } } else { PostMessageW(msg_window_id, PROCESS_NEW_EVENTS_MSG_ID.get(), 0, 0); wait_until_opt = None; } } } } } // Implementation taken from https://github.com/rust-lang/rust/blob/db5476571d9b27c862b95c1e64764b0ac8980e23/src/libstd/sys/windows/mod.rs fn dur2timeout(dur: Duration) -> u32 { // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the // timeouts in windows APIs are typically u32 milliseconds. To translate, we // have two pieces to take care of: // // * Nanosecond precision is rounded up // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE // (never time out). dur.as_secs() .checked_mul(1000) .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) .and_then(|ms| { if dur.subsec_nanos() % 1_000_000 > 0 { ms.checked_add(1) } else { Some(ms) } }) .map(|ms| { if ms > u32::MAX as u64 { INFINITE } else { ms as u32 } }) .unwrap_or(INFINITE) } impl<T> Drop for EventLoop<T> { fn drop(&mut self) { unsafe { DestroyWindow(self.window_target.p.thread_msg_target); } } } pub(crate) struct EventLoopThreadExecutor { thread_id: u32, target_window: HWND, } unsafe impl Send for EventLoopThreadExecutor {} unsafe impl Sync for EventLoopThreadExecutor {} impl EventLoopThreadExecutor { /// Check to see if we're in the parent event loop's thread. pub(super) fn in_event_loop_thread(&self) -> bool { let cur_thread_id = unsafe { GetCurrentThreadId() }; self.thread_id == cur_thread_id } /// Executes a function in the event loop thread. If we're already in the event loop thread, /// we just call the function directly. /// /// The `Inserted` can be used to inject a `WindowState` for the callback to use. The state is /// removed automatically if the callback receives a `WM_CLOSE` message for the window. /// /// Note that if you are using this to change some property of a window and updating /// `WindowState` then you should call this within the lock of `WindowState`. Otherwise the /// events may be sent to the other thread in different order to the one in which you set /// `WindowState`, leaving them out of sync. /// /// Note that we use a FnMut instead of a FnOnce because we're too lazy to create an equivalent /// to the unstable FnBox. pub(super) fn execute_in_thread<F>(&self, mut function: F) where F: FnMut() + Send + 'static, { unsafe { if self.in_event_loop_thread() { function(); } else { // We double-box because the first box is a fat pointer. let boxed2: ThreadExecFn = Box::new(Box::new(function)); let raw = Box::into_raw(boxed2); let res = PostMessageW(self.target_window, EXEC_MSG_ID.get(), raw as usize, 0); assert!( res != false.into(), "PostMessage failed; is the messages queue full?" ); } } } } type ThreadExecFn = Box<Box<dyn FnMut()>>; pub struct EventLoopProxy<T: 'static> { target_window: HWND, event_send: Sender<T>, } unsafe impl<T: Send + 'static> Send for EventLoopProxy<T> {} impl<T: 'static> Clone for EventLoopProxy<T> { fn clone(&self) -> Self { Self { target_window: self.target_window, event_send: self.event_send.clone(), } } } impl<T: 'static> EventLoopProxy<T> { pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { unsafe { if PostMessageW(self.target_window, USER_EVENT_MSG_ID.get(), 0, 0) != false.into() { self.event_send.send(event).ok(); Ok(()) } else { Err(EventLoopClosed(event)) } } } } type WaitUntilInstantBox = Box<Instant>; /// A lazily-initialized window message ID. pub struct LazyMessageId { /// The ID. id: AtomicU32, /// The name of the message. name: &'static str, } /// An invalid custom window ID. const INVALID_ID: u32 = 0x0; impl LazyMessageId { /// Create a new `LazyId`. const fn new(name: &'static str) -> Self { Self { id: AtomicU32::new(INVALID_ID), name, } } /// Get the message ID. pub fn get(&self) -> u32 { // Load the ID. let id = self.id.load(Ordering::Relaxed); if id != INVALID_ID { return id; } // Register the message. // SAFETY: We are sure that the pointer is a valid C string ending with '\0'. assert!(self.name.ends_with('\0')); let new_id = unsafe { RegisterWindowMessageA(self.name.as_ptr()) }; assert_ne!( new_id, 0, "RegisterWindowMessageA returned zero for '{}': {}", self.name, std::io::Error::last_os_error() ); // Store the new ID. Since `RegisterWindowMessageA` returns the same value for any given string, // the target value will always either be a). `INVALID_ID` or b). the correct ID. Therefore a // compare-and-swap operation here (or really any consideration) is never necessary. self.id.store(new_id, Ordering::Relaxed); new_id } } // Message sent by the `EventLoopProxy` when we want to wake up the thread. // WPARAM and LPARAM are unused. static USER_EVENT_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::WakeupMsg\0"); // Message sent when we want to execute a closure in the thread. // WPARAM contains a Box<Box<dyn FnMut()>> that must be retrieved with `Box::from_raw`, // and LPARAM is unused. static EXEC_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::ExecMsg\0"); static PROCESS_NEW_EVENTS_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::ProcessNewEvents\0"); /// lparam is the wait thread's message id. static SEND_WAIT_THREAD_ID_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::SendWaitThreadId\0"); /// lparam points to a `Box<Instant>` signifying the time `PROCESS_NEW_EVENTS_MSG_ID` should /// be sent. static WAIT_UNTIL_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::WaitUntil\0"); static CANCEL_WAIT_UNTIL_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::CancelWaitUntil\0"); // Message sent by a `Window` when it wants to be destroyed by the main thread. // WPARAM and LPARAM are unused. pub static DESTROY_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::DestroyMsg\0"); // WPARAM is a bool specifying the `WindowFlags::MARKER_RETAIN_STATE_ON_SIZE` flag. See the // documentation in the `window_state` module for more information. pub static SET_RETAIN_STATE_ON_SIZE_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::SetRetainMaximized\0"); static THREAD_EVENT_TARGET_WINDOW_CLASS: Lazy<Vec<u16>> = Lazy::new(|| util::encode_wide("Winit Thread Event Target")); /// When the taskbar is created, it registers a message with the "TaskbarCreated" string and then broadcasts this message to all top-level windows /// <https://docs.microsoft.com/en-us/windows/win32/shell/taskbar#taskbar-creation-notification> pub static TASKBAR_CREATED: LazyMessageId = LazyMessageId::new("TaskbarCreated\0"); fn create_event_target_window<T: 'static>() -> HWND { use windows_sys::Win32::UI::WindowsAndMessaging::CS_HREDRAW; use windows_sys::Win32::UI::WindowsAndMessaging::CS_VREDRAW; unsafe { let class = WNDCLASSEXW { cbSize: mem::size_of::<WNDCLASSEXW>() as u32, style: CS_HREDRAW | CS_VREDRAW, lpfnWndProc: Some(thread_event_target_callback::<T>), cbClsExtra: 0, cbWndExtra: 0, hInstance: util::get_instance_handle(), hIcon: 0, hCursor: 0, // must be null in order for cursor state to work properly hbrBackground: 0, lpszMenuName: ptr::null(), lpszClassName: THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(), hIconSm: 0, }; RegisterClassExW(&class); } unsafe { let window = CreateWindowExW( WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_LAYERED // WS_EX_TOOLWINDOW prevents this window from ever showing up in the taskbar, which // we want to avoid. If you remove this style, this window won't show up in the // taskbar *initially*, but it can show up at some later point. This can sometimes // happen on its own after several hours have passed, although this has proven // difficult to reproduce. Alternatively, it can be manually triggered by killing // `explorer.exe` and then starting the process back up. // It is unclear why the bug is triggered by waiting for several hours. | WS_EX_TOOLWINDOW, THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(), ptr::null(), WS_OVERLAPPED, 0, 0, 0, 0, 0, 0, util::get_instance_handle(), ptr::null(), ); super::set_window_long( window, GWL_STYLE, // The window technically has to be visible to receive WM_PAINT messages (which are used // for delivering events during resizes), but it isn't displayed to the user because of // the LAYERED style. (WS_VISIBLE | WS_POPUP) as isize, ); window } } fn insert_event_target_window_data<T>( thread_msg_target: HWND, event_loop_runner: EventLoopRunnerShared<T>, ) -> Sender<T> { let (tx, rx) = mpsc::channel(); let userdata = ThreadMsgTargetData { event_loop_runner, user_event_receiver: rx, }; let input_ptr = Box::into_raw(Box::new(userdata)); unsafe { super::set_window_long(thread_msg_target, GWL_USERDATA, input_ptr as isize) }; tx } /// Capture mouse input, allowing `window` to receive mouse events when the cursor is outside of /// the window. unsafe fn capture_mouse(window: HWND, window_state: &mut WindowState) { window_state.mouse.capture_count += 1; SetCapture(window); } /// Release mouse input, stopping windows on this thread from receiving mouse input when the cursor /// is outside the window. unsafe fn release_mouse(mut window_state: MutexGuard<'_, WindowState>) { window_state.mouse.capture_count = window_state.mouse.capture_count.saturating_sub(1); if window_state.mouse.capture_count == 0 { // ReleaseCapture() causes a WM_CAPTURECHANGED where we lock the window_state. drop(window_state); ReleaseCapture(); } } fn normalize_pointer_pressure(pressure: u32) -> Option<Force> { match pressure { 1..=1024 => Some(Force::Normalized(pressure as f64 / 1024.0)), _ => None, } } /// Flush redraw events for Winit's windows. /// /// Winit's API guarantees that all redraw events will be clustered together and dispatched all at /// once, but the standard Windows message loop doesn't always exhibit that behavior. If multiple /// windows have had redraws scheduled, but an input event is pushed to the message queue between /// the `WM_PAINT` call for the first window and the `WM_PAINT` call for the second window, Windows /// will dispatch the input event immediately instead of flushing all the redraw events. This /// function explicitly pulls all of Winit's redraw events out of the event queue so that they /// always all get processed in one fell swoop. /// /// Returns `true` if this invocation flushed all the redraw events. If this function is re-entrant, /// it won't flush the redraw events and will return `false`. #[must_use] unsafe fn flush_paint_messages<T: 'static>( except: Option<HWND>, runner: &EventLoopRunner<T>, ) -> bool { if !runner.redrawing() { runner.main_events_cleared(); let mut msg = mem::zeroed(); runner.owned_windows(|redraw_window| { if Some(redraw_window) == except { return; } if PeekMessageW( &mut msg, redraw_window, WM_PAINT, WM_PAINT, PM_REMOVE | PM_QS_PAINT, ) == false.into() { return; } TranslateMessage(&msg); DispatchMessageW(&msg); }); true } else { false } } unsafe fn process_control_flow<T: 'static>(runner: &EventLoopRunner<T>) { match runner.control_flow() { ControlFlow::Poll => { PostMessageW( runner.thread_msg_target(), PROCESS_NEW_EVENTS_MSG_ID.get(), 0, 0, ); } ControlFlow::Wait => (), ControlFlow::WaitUntil(until) => { PostThreadMessageW( runner.wait_thread_id(), WAIT_UNTIL_MSG_ID.get(), 0, Box::into_raw(WaitUntilInstantBox::new(until)) as isize, ); } ControlFlow::ExitWithCode(_) => (), } } /// Emit a `ModifiersChanged` event whenever modifiers have changed. fn update_modifiers<T>(window: HWND, userdata: &WindowData<T>) { use crate::event::WindowEvent::ModifiersChanged; let modifiers = event::get_key_mods(); let mut window_state = userdata.window_state_lock(); if window_state.modifiers_state != modifiers { window_state.modifiers_state = modifiers; // Drop lock drop(window_state); unsafe { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: ModifiersChanged(modifiers), }); } } } unsafe fn gain_active_focus<T>(window: HWND, userdata: &WindowData<T>) { use crate::event::{ElementState::Released, WindowEvent::Focused}; for windows_keycode in event::get_pressed_keys() { let scancode = MapVirtualKeyA(windows_keycode as u32, MAPVK_VK_TO_VSC); let virtual_keycode = event::vkey_to_winit_vkey(windows_keycode); update_modifiers(window, userdata); #[allow(deprecated)] userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { scancode, virtual_keycode, state: Released, modifiers: event::get_key_mods(), }, is_synthetic: true, }, }) } userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: Focused(true), }); } unsafe fn lose_active_focus<T>(window: HWND, userdata: &WindowData<T>) { use crate::event::{ ElementState::Released, ModifiersState, WindowEvent::{Focused, ModifiersChanged}, }; for windows_keycode in event::get_pressed_keys() { let scancode = MapVirtualKeyA(windows_keycode as u32, MAPVK_VK_TO_VSC); let virtual_keycode = event::vkey_to_winit_vkey(windows_keycode); #[allow(deprecated)] userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { scancode, virtual_keycode, state: Released, modifiers: event::get_key_mods(), }, is_synthetic: true, }, }) } userdata.window_state_lock().modifiers_state = ModifiersState::empty(); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: ModifiersChanged(ModifiersState::empty()), }); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: Focused(false), }); } /// Any window whose callback is configured to this function will have its events propagated /// through the events loop of the thread the window was created in. // // This is the callback that is called by `DispatchMessage` in the events loop. // // Returning 0 tells the Win32 API that the message has been processed. // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary pub(super) unsafe extern "system" fn public_window_callback<T: 'static>( window: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM, ) -> LRESULT { let userdata = super::get_window_long(window, GWL_USERDATA); let userdata_ptr = match (userdata, msg) { (0, WM_NCCREATE) => { let createstruct = &mut *(lparam as *mut CREATESTRUCTW); let initdata = &mut *(createstruct.lpCreateParams as *mut InitData<'_, T>); let result = match initdata.on_nccreate(window) { Some(userdata) => { super::set_window_long(window, GWL_USERDATA, userdata as _); DefWindowProcW(window, msg, wparam, lparam) } None => -1, // failed to create the window }; return result; } // Getting here should quite frankly be impossible, // but we'll make window creation fail here just in case. (0, WM_CREATE) => return -1, (_, WM_CREATE) => { let createstruct = &mut *(lparam as *mut CREATESTRUCTW); let initdata = createstruct.lpCreateParams; let initdata = &mut *(initdata as *mut InitData<'_, T>); initdata.on_create(); return DefWindowProcW(window, msg, wparam, lparam); } (0, _) => return DefWindowProcW(window, msg, wparam, lparam), _ => userdata as *mut WindowData<T>, }; let (result, userdata_removed, recurse_depth) = { let userdata = &*(userdata_ptr); userdata.recurse_depth.set(userdata.recurse_depth.get() + 1); let result = public_window_callback_inner(window, msg, wparam, lparam, userdata); let userdata_removed = userdata.userdata_removed.get(); let recurse_depth = userdata.recurse_depth.get() - 1; userdata.recurse_depth.set(recurse_depth); (result, userdata_removed, recurse_depth) }; if userdata_removed && recurse_depth == 0 { drop(Box::from_raw(userdata_ptr)); } result } unsafe fn public_window_callback_inner<T: 'static>( window: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM, userdata: &WindowData<T>, ) -> LRESULT { RedrawWindow( userdata.event_loop_runner.thread_msg_target(), ptr::null(), 0, RDW_INTERNALPAINT, ); // I decided to bind the closure to `callback` and pass it to catch_unwind rather than passing // the closure to catch_unwind directly so that the match body indendation wouldn't change and // the git blame and history would be preserved. let callback = || match msg { WM_NCCALCSIZE => { let window_flags = userdata.window_state_lock().window_flags; if wparam == 0 || window_flags.contains(WindowFlags::MARKER_DECORATIONS) { return DefWindowProcW(window, msg, wparam, lparam); } let params = &mut *(lparam as *mut NCCALCSIZE_PARAMS); if util::is_maximized(window) { // Limit the window size when maximized to the current monitor. // Otherwise it would include the non-existent decorations. // // Use `MonitorFromRect` instead of `MonitorFromWindow` to select // the correct monitor here. // See https://github.com/MicrosoftEdge/WebView2Feedback/issues/2549 let monitor = MonitorFromRect(&params.rgrc[0], MONITOR_DEFAULTTONULL); if let Ok(monitor_info) = monitor::get_monitor_info(monitor) { params.rgrc[0] = monitor_info.monitorInfo.rcWork; } } else if window_flags.contains(WindowFlags::MARKER_UNDECORATED_SHADOW) { // Extend the client area to cover the whole non-client area. // https://docs.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize#remarks // // HACK(msiglreith): To add the drop shadow we slightly tweak the non-client area. // This leads to a small black 1px border on the top. Adding a margin manually // on all 4 borders would result in the caption getting drawn by the DWM. // // Another option would be to allow the DWM to paint inside the client area. // Unfortunately this results in janky resize behavior, where the compositor is // ahead of the window surface. Currently, there seems no option to achieve this // with the Windows API. params.rgrc[0].top += 1; params.rgrc[0].bottom += 1; } 0 } WM_ENTERSIZEMOVE => { userdata .window_state_lock() .set_window_flags_in_place(|f| f.insert(WindowFlags::MARKER_IN_SIZE_MOVE)); 0 } WM_EXITSIZEMOVE => { let mut state = userdata.window_state_lock(); if state.dragging { state.dragging = false; PostMessageW(window, WM_LBUTTONUP, 0, lparam); } state.set_window_flags_in_place(|f| f.remove(WindowFlags::MARKER_IN_SIZE_MOVE)); 0 } WM_NCLBUTTONDOWN => { if wparam == HTCAPTION as _ { PostMessageW(window, WM_MOUSEMOVE, 0, lparam); } DefWindowProcW(window, msg, wparam, lparam) } WM_CLOSE => { use crate::event::WindowEvent::CloseRequested; userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: CloseRequested, }); 0 } WM_DESTROY => { use crate::event::WindowEvent::Destroyed; RevokeDragDrop(window); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: Destroyed, }); userdata.event_loop_runner.remove_window(window); 0 } WM_NCDESTROY => { super::set_window_long(window, GWL_USERDATA, 0); userdata.userdata_removed.set(true); 0 } WM_PAINT => { if userdata.event_loop_runner.should_buffer() { // this branch can happen in response to `UpdateWindow`, if win32 decides to // redraw the window outside the normal flow of the event loop. RedrawWindow(window, ptr::null(), 0, RDW_INTERNALPAINT); } else { let managing_redraw = flush_paint_messages(Some(window), &userdata.event_loop_runner); userdata.send_event(Event::RedrawRequested(RootWindowId(WindowId(window)))); if managing_redraw { userdata.event_loop_runner.redraw_events_cleared(); process_control_flow(&userdata.event_loop_runner); } } DefWindowProcW(window, msg, wparam, lparam) } WM_WINDOWPOSCHANGING => { let mut window_state = userdata.window_state_lock(); if let Some(ref mut fullscreen) = window_state.fullscreen { let window_pos = &mut *(lparam as *mut WINDOWPOS); let new_rect = RECT { left: window_pos.x, top: window_pos.y, right: window_pos.x + window_pos.cx, bottom: window_pos.y + window_pos.cy, }; const NOMOVE_OR_NOSIZE: u32 = SWP_NOMOVE | SWP_NOSIZE; let new_rect = if window_pos.flags & NOMOVE_OR_NOSIZE != 0 { let cur_rect = util::WindowArea::Outer.get_rect(window) .expect("Unexpected GetWindowRect failure; please report this error to https://github.com/rust-windowing/winit"); match window_pos.flags & NOMOVE_OR_NOSIZE { NOMOVE_OR_NOSIZE => None, SWP_NOMOVE => Some(RECT { left: cur_rect.left, top: cur_rect.top, right: cur_rect.left + window_pos.cx, bottom: cur_rect.top + window_pos.cy, }), SWP_NOSIZE => Some(RECT { left: window_pos.x, top: window_pos.y, right: window_pos.x - cur_rect.left + cur_rect.right, bottom: window_pos.y - cur_rect.top + cur_rect.bottom, }), _ => unreachable!(), } } else { Some(new_rect) }; if let Some(new_rect) = new_rect { let new_monitor = MonitorFromRect(&new_rect, MONITOR_DEFAULTTONULL); match fullscreen { Fullscreen::Borderless(ref mut fullscreen_monitor) => { if new_monitor != 0 && fullscreen_monitor .as_ref() .map(|monitor| new_monitor != monitor.hmonitor()) .unwrap_or(true) { if let Ok(new_monitor_info) = monitor::get_monitor_info(new_monitor) { let new_monitor_rect = new_monitor_info.monitorInfo.rcMonitor; window_pos.x = new_monitor_rect.left; window_pos.y = new_monitor_rect.top; window_pos.cx = new_monitor_rect.right - new_monitor_rect.left; window_pos.cy = new_monitor_rect.bottom - new_monitor_rect.top; } *fullscreen_monitor = Some(MonitorHandle::new(new_monitor)); } } Fullscreen::Exclusive(ref video_mode) => { let old_monitor = video_mode.monitor.hmonitor(); if let Ok(old_monitor_info) = monitor::get_monitor_info(old_monitor) { let old_monitor_rect = old_monitor_info.monitorInfo.rcMonitor; window_pos.x = old_monitor_rect.left; window_pos.y = old_monitor_rect.top; window_pos.cx = old_monitor_rect.right - old_monitor_rect.left; window_pos.cy = old_monitor_rect.bottom - old_monitor_rect.top; } } } } } 0 } // WM_MOVE supplies client area positions, so we send Moved here instead. WM_WINDOWPOSCHANGED => { use crate::event::WindowEvent::Moved; let windowpos = lparam as *const WINDOWPOS; if (*windowpos).flags & SWP_NOMOVE != SWP_NOMOVE { let physical_position = PhysicalPosition::new((*windowpos).x, (*windowpos).y); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: Moved(physical_position), }); } // This is necessary for us to still get sent WM_SIZE. DefWindowProcW(window, msg, wparam, lparam) } WM_SIZE => { use crate::event::WindowEvent::Resized; let w = super::loword(lparam as u32) as u32; let h = super::hiword(lparam as u32) as u32; let physical_size = PhysicalSize::new(w, h); let event = Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: Resized(physical_size), }; { let mut w = userdata.window_state_lock(); // See WindowFlags::MARKER_RETAIN_STATE_ON_SIZE docs for info on why this `if` check exists. if !w .window_flags() .contains(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE) { let maximized = wparam == SIZE_MAXIMIZED as usize; w.set_window_flags_in_place(|f| f.set(WindowFlags::MAXIMIZED, maximized)); } } userdata.send_event(event); 0 } WM_CHAR | WM_SYSCHAR => { use crate::event::WindowEvent::ReceivedCharacter; use std::char; let is_high_surrogate = (0xD800..=0xDBFF).contains(&wparam); let is_low_surrogate = (0xDC00..=0xDFFF).contains(&wparam); if is_high_surrogate { userdata.window_state_lock().high_surrogate = Some(wparam as u16); } else if is_low_surrogate { let high_surrogate = userdata.window_state_lock().high_surrogate.take(); if let Some(high_surrogate) = high_surrogate { let pair = [high_surrogate, wparam as u16]; if let Some(Ok(chr)) = char::decode_utf16(pair.iter().copied()).next() { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: ReceivedCharacter(chr), }); } } } else { userdata.window_state_lock().high_surrogate = None; if let Some(chr) = char::from_u32(wparam as u32) { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: ReceivedCharacter(chr), }); } } // todo(msiglreith): // Ideally, `WM_SYSCHAR` shouldn't emit a `ReceivedChar` event // indicating user text input. As we lack dedicated support // accelerators/keybindings these events will be additionally // emitted for downstream users. // This means certain key combinations (ie Alt + Space) will // trigger the default system behavior **and** emit a char event. if msg == WM_SYSCHAR { DefWindowProcW(window, msg, wparam, lparam) } else { 0 } } WM_MENUCHAR => (MNC_CLOSE << 16) as isize, WM_IME_STARTCOMPOSITION => { let ime_allowed = userdata.window_state_lock().ime_allowed; if ime_allowed { userdata.window_state_lock().ime_state = ImeState::Enabled; userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Enabled), }); } DefWindowProcW(window, msg, wparam, lparam) } WM_IME_COMPOSITION => { let ime_allowed_and_composing = { let w = userdata.window_state_lock(); w.ime_allowed && w.ime_state != ImeState::Disabled }; // Windows Hangul IME sends WM_IME_COMPOSITION after WM_IME_ENDCOMPOSITION, so // check whether composing. if ime_allowed_and_composing { let ime_context = ImeContext::current(window); if lparam == 0 { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Preedit(String::new(), None)), }); } // Google Japanese Input and ATOK have both flags, so // first, receive composing result if exist. if (lparam as u32 & GCS_RESULTSTR) != 0 { if let Some(text) = ime_context.get_composed_text() { userdata.window_state_lock().ime_state = ImeState::Enabled; userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Preedit(String::new(), None)), }); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Commit(text)), }); } } // Next, receive preedit range for next composing if exist. if (lparam as u32 & GCS_COMPSTR) != 0 { if let Some((text, first, last)) = ime_context.get_composing_text_and_cursor() { userdata.window_state_lock().ime_state = ImeState::Preedit; let cursor_range = first.map(|f| (f, last.unwrap_or(f))); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Preedit(text, cursor_range)), }); } } } // Not calling DefWindowProc to hide composing text drawn by IME. 0 } WM_IME_ENDCOMPOSITION => { let ime_allowed_or_composing = { let w = userdata.window_state_lock(); w.ime_allowed || w.ime_state != ImeState::Disabled }; if ime_allowed_or_composing { if userdata.window_state_lock().ime_state == ImeState::Preedit { // Windows Hangul IME sends WM_IME_COMPOSITION after WM_IME_ENDCOMPOSITION, so // trying receiving composing result and commit if exists. let ime_context = ImeContext::current(window); if let Some(text) = ime_context.get_composed_text() { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Preedit(String::new(), None)), }); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Commit(text)), }); } } userdata.window_state_lock().ime_state = ImeState::Disabled; userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Ime(Ime::Disabled), }); } DefWindowProcW(window, msg, wparam, lparam) } WM_IME_SETCONTEXT => { // Hide composing text drawn by IME. let wparam = wparam & (!ISC_SHOWUICOMPOSITIONWINDOW as usize); DefWindowProcW(window, msg, wparam, lparam) } // this is necessary for us to maintain minimize/restore state WM_SYSCOMMAND => { if wparam == SC_RESTORE as usize { let mut w = userdata.window_state_lock(); w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, false)); } if wparam == SC_MINIMIZE as usize { let mut w = userdata.window_state_lock(); w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, true)); } // Send `WindowEvent::Minimized` here if we decide to implement one if wparam == SC_SCREENSAVE as usize { let window_state = userdata.window_state_lock(); if window_state.fullscreen.is_some() { return 0; } } DefWindowProcW(window, msg, wparam, lparam) } WM_MOUSEMOVE => { use crate::event::WindowEvent::{CursorEntered, CursorMoved}; let mouse_was_outside_window = { let mut w = userdata.window_state_lock(); let was_outside_window = !w.mouse.cursor_flags().contains(CursorFlags::IN_WINDOW); w.mouse .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, true)) .ok(); was_outside_window }; if mouse_was_outside_window { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: CursorEntered { device_id: DEVICE_ID, }, }); // Calling TrackMouseEvent in order to receive mouse leave events. TrackMouseEvent(&mut TRACKMOUSEEVENT { cbSize: mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: window, dwHoverTime: HOVER_DEFAULT, }); } let x = super::get_x_lparam(lparam as u32) as f64; let y = super::get_y_lparam(lparam as u32) as f64; let position = PhysicalPosition::new(x, y); let cursor_moved; { // handle spurious WM_MOUSEMOVE messages // see https://devblogs.microsoft.com/oldnewthing/20031001-00/?p=42343 // and http://debugandconquer.blogspot.com/2015/08/the-cause-of-spurious-mouse-move.html let mut w = userdata.window_state_lock(); cursor_moved = w.mouse.last_position != Some(position); w.mouse.last_position = Some(position); } if cursor_moved { update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: CursorMoved { device_id: DEVICE_ID, position, modifiers: event::get_key_mods(), }, }); } 0 } WM_MOUSELEAVE => { use crate::event::WindowEvent::CursorLeft; { let mut w = userdata.window_state_lock(); w.mouse .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)) .ok(); } userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: CursorLeft { device_id: DEVICE_ID, }, }); 0 } WM_MOUSEWHEEL => { use crate::event::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = value as f32 / WHEEL_DELTA as f32; update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::MouseWheel { device_id: DEVICE_ID, delta: LineDelta(0.0, value), phase: TouchPhase::Moved, modifiers: event::get_key_mods(), }, }); 0 } WM_MOUSEHWHEEL => { use crate::event::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = -value as f32 / WHEEL_DELTA as f32; // NOTE: inverted! See https://github.com/rust-windowing/winit/pull/2105/ update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::MouseWheel { device_id: DEVICE_ID, delta: LineDelta(value, 0.0), phase: TouchPhase::Moved, modifiers: event::get_key_mods(), }, }); 0 } WM_KEYDOWN | WM_SYSKEYDOWN => { use crate::event::{ElementState::Pressed, VirtualKeyCode}; if let Some((scancode, vkey)) = process_key_params(wparam, lparam) { update_modifiers(window, userdata); #[allow(deprecated)] userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { state: Pressed, scancode, virtual_keycode: vkey, modifiers: event::get_key_mods(), }, is_synthetic: false, }, }); // Windows doesn't emit a delete character by default, but in order to make it // consistent with the other platforms we'll emit a delete character here. if vkey == Some(VirtualKeyCode::Delete) { userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::ReceivedCharacter('\u{7F}'), }); } } if msg == WM_SYSKEYDOWN { DefWindowProcW(window, msg, wparam, lparam) } else { 0 } } WM_KEYUP | WM_SYSKEYUP => { use crate::event::ElementState::Released; if let Some((scancode, vkey)) = process_key_params(wparam, lparam) { update_modifiers(window, userdata); #[allow(deprecated)] userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::KeyboardInput { device_id: DEVICE_ID, input: KeyboardInput { state: Released, scancode, virtual_keycode: vkey, modifiers: event::get_key_mods(), }, is_synthetic: false, }, }); } if msg == WM_SYSKEYUP && GetMenu(window) != 0 { // let Windows handle event if the window has a native menu, a modal event loop // is started here on Alt key up. DefWindowProcW(window, msg, wparam, lparam) } else { 0 } } WM_LBUTTONDOWN => { use crate::event::{ElementState::Pressed, MouseButton::Left, WindowEvent::MouseInput}; capture_mouse(window, &mut userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Left, modifiers: event::get_key_mods(), }, }); 0 } WM_LBUTTONUP => { use crate::event::{ ElementState::Released, MouseButton::Left, WindowEvent::MouseInput, }; release_mouse(userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Released, button: Left, modifiers: event::get_key_mods(), }, }); 0 } WM_RBUTTONDOWN => { use crate::event::{ ElementState::Pressed, MouseButton::Right, WindowEvent::MouseInput, }; capture_mouse(window, &mut userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Right, modifiers: event::get_key_mods(), }, }); 0 } WM_RBUTTONUP => { use crate::event::{ ElementState::Released, MouseButton::Right, WindowEvent::MouseInput, }; release_mouse(userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Released, button: Right, modifiers: event::get_key_mods(), }, }); 0 } WM_MBUTTONDOWN => { use crate::event::{ ElementState::Pressed, MouseButton::Middle, WindowEvent::MouseInput, }; capture_mouse(window, &mut userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Middle, modifiers: event::get_key_mods(), }, }); 0 } WM_MBUTTONUP => { use crate::event::{ ElementState::Released, MouseButton::Middle, WindowEvent::MouseInput, }; release_mouse(userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Released, button: Middle, modifiers: event::get_key_mods(), }, }); 0 } WM_XBUTTONDOWN => { use crate::event::{ ElementState::Pressed, MouseButton::Other, WindowEvent::MouseInput, }; let xbutton = super::get_xbutton_wparam(wparam as u32); capture_mouse(window, &mut userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Other(xbutton), modifiers: event::get_key_mods(), }, }); 0 } WM_XBUTTONUP => { use crate::event::{ ElementState::Released, MouseButton::Other, WindowEvent::MouseInput, }; let xbutton = super::get_xbutton_wparam(wparam as u32); release_mouse(userdata.window_state_lock()); update_modifiers(window, userdata); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: MouseInput { device_id: DEVICE_ID, state: Released, button: Other(xbutton), modifiers: event::get_key_mods(), }, }); 0 } WM_CAPTURECHANGED => { // lparam here is a handle to the window which is gaining mouse capture. // If it is the same as our window, then we're essentially retaining the capture. This // can happen if `SetCapture` is called on our window when it already has the mouse // capture. if lparam != window { userdata.window_state_lock().mouse.capture_count = 0; } 0 } WM_TOUCH => { let pcount = super::loword(wparam as u32) as usize; let mut inputs = Vec::with_capacity(pcount); let htouch = lparam; if GetTouchInputInfo( htouch, pcount as u32, inputs.as_mut_ptr(), mem::size_of::<TOUCHINPUT>() as i32, ) > 0 { inputs.set_len(pcount); for input in &inputs { let mut location = POINT { x: input.x / 100, y: input.y / 100, }; if ScreenToClient(window, &mut location) == false.into() { continue; } let x = location.x as f64 + (input.x % 100) as f64 / 100f64; let y = location.y as f64 + (input.y % 100) as f64 / 100f64; let location = PhysicalPosition::new(x, y); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Touch(Touch { phase: if util::has_flag(input.dwFlags, TOUCHEVENTF_DOWN) { TouchPhase::Started } else if util::has_flag(input.dwFlags, TOUCHEVENTF_UP) { TouchPhase::Ended } else if util::has_flag(input.dwFlags, TOUCHEVENTF_MOVE) { TouchPhase::Moved } else { continue; }, location, force: None, // WM_TOUCH doesn't support pressure information id: input.dwID as u64, device_id: DEVICE_ID, }), }); } } CloseTouchInputHandle(htouch); 0 } WM_POINTERDOWN | WM_POINTERUPDATE | WM_POINTERUP => { if let ( Some(GetPointerFrameInfoHistory), Some(SkipPointerFrameMessages), Some(GetPointerDeviceRects), ) = ( *GET_POINTER_FRAME_INFO_HISTORY, *SKIP_POINTER_FRAME_MESSAGES, *GET_POINTER_DEVICE_RECTS, ) { let pointer_id = super::loword(wparam as u32) as u32; let mut entries_count = 0u32; let mut pointers_count = 0u32; if GetPointerFrameInfoHistory( pointer_id, &mut entries_count, &mut pointers_count, ptr::null_mut(), ) == false.into() { return 0; } let pointer_info_count = (entries_count * pointers_count) as usize; let mut pointer_infos = Vec::with_capacity(pointer_info_count); if GetPointerFrameInfoHistory( pointer_id, &mut entries_count, &mut pointers_count, pointer_infos.as_mut_ptr(), ) == false.into() { return 0; } pointer_infos.set_len(pointer_info_count); // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getpointerframeinfohistory // The information retrieved appears in reverse chronological order, with the most recent entry in the first // row of the returned array for pointer_info in pointer_infos.iter().rev() { let mut device_rect = mem::MaybeUninit::uninit(); let mut display_rect = mem::MaybeUninit::uninit(); if GetPointerDeviceRects( pointer_info.sourceDevice, device_rect.as_mut_ptr(), display_rect.as_mut_ptr(), ) == false.into() { continue; } let device_rect = device_rect.assume_init(); let display_rect = display_rect.assume_init(); // For the most precise himetric to pixel conversion we calculate the ratio between the resolution // of the display device (pixel) and the touch device (himetric). let himetric_to_pixel_ratio_x = (display_rect.right - display_rect.left) as f64 / (device_rect.right - device_rect.left) as f64; let himetric_to_pixel_ratio_y = (display_rect.bottom - display_rect.top) as f64 / (device_rect.bottom - device_rect.top) as f64; // ptHimetricLocation's origin is 0,0 even on multi-monitor setups. // On multi-monitor setups we need to translate the himetric location to the rect of the // display device it's attached to. let x = display_rect.left as f64 + pointer_info.ptHimetricLocation.x as f64 * himetric_to_pixel_ratio_x; let y = display_rect.top as f64 + pointer_info.ptHimetricLocation.y as f64 * himetric_to_pixel_ratio_y; let mut location = POINT { x: x.floor() as i32, y: y.floor() as i32, }; if ScreenToClient(window, &mut location) == false.into() { continue; } let force = match pointer_info.pointerType { PT_TOUCH => { let mut touch_info = mem::MaybeUninit::uninit(); GET_POINTER_TOUCH_INFO.and_then(|GetPointerTouchInfo| { match GetPointerTouchInfo( pointer_info.pointerId, touch_info.as_mut_ptr(), ) { 0 => None, _ => normalize_pointer_pressure( touch_info.assume_init().pressure, ), } }) } PT_PEN => { let mut pen_info = mem::MaybeUninit::uninit(); GET_POINTER_PEN_INFO.and_then(|GetPointerPenInfo| { match GetPointerPenInfo( pointer_info.pointerId, pen_info.as_mut_ptr(), ) { 0 => None, _ => { normalize_pointer_pressure(pen_info.assume_init().pressure) } } }) } _ => None, }; let x = location.x as f64 + x.fract(); let y = location.y as f64 + y.fract(); let location = PhysicalPosition::new(x, y); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: WindowEvent::Touch(Touch { phase: if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_DOWN) { TouchPhase::Started } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UP) { TouchPhase::Ended } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UPDATE) { TouchPhase::Moved } else { continue; }, location, force, id: pointer_info.pointerId as u64, device_id: DEVICE_ID, }), }); } SkipPointerFrameMessages(pointer_id); } 0 } WM_NCACTIVATE => { let is_active = wparam != false.into(); let active_focus_changed = userdata.window_state_lock().set_active(is_active); if active_focus_changed { if is_active { gain_active_focus(window, userdata); } else { lose_active_focus(window, userdata); } } DefWindowProcW(window, msg, wparam, lparam) } WM_SETFOCUS => { let active_focus_changed = userdata.window_state_lock().set_focused(true); if active_focus_changed { gain_active_focus(window, userdata); } 0 } WM_KILLFOCUS => { let active_focus_changed = userdata.window_state_lock().set_focused(false); if active_focus_changed { lose_active_focus(window, userdata); } 0 } WM_SETCURSOR => { let set_cursor_to = { let window_state = userdata.window_state_lock(); // The return value for the preceding `WM_NCHITTEST` message is conveniently // provided through the low-order word of lParam. We use that here since // `WM_MOUSEMOVE` seems to come after `WM_SETCURSOR` for a given cursor movement. let in_client_area = super::loword(lparam as u32) as u32 == HTCLIENT; if in_client_area { Some(window_state.mouse.cursor) } else { None } }; match set_cursor_to { Some(cursor) => { let cursor = LoadCursorW(0, cursor.to_windows_cursor()); SetCursor(cursor); 0 } None => DefWindowProcW(window, msg, wparam, lparam), } } WM_DROPFILES => { // See `FileDropHandler` for implementation. 0 } WM_GETMINMAXINFO => { let mmi = lparam as *mut MINMAXINFO; let window_state = userdata.window_state_lock(); let window_flags = window_state.window_flags; if window_state.min_size.is_some() || window_state.max_size.is_some() { if let Some(min_size) = window_state.min_size { let min_size = min_size.to_physical(window_state.scale_factor); let (width, height): (u32, u32) = window_flags.adjust_size(window, min_size).into(); (*mmi).ptMinTrackSize = POINT { x: width as i32, y: height as i32, }; } if let Some(max_size) = window_state.max_size { let max_size = max_size.to_physical(window_state.scale_factor); let (width, height): (u32, u32) = window_flags.adjust_size(window, max_size).into(); (*mmi).ptMaxTrackSize = POINT { x: width as i32, y: height as i32, }; } } 0 } // Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change // DPI, therefore all applications are closed while DPI is changing. WM_DPICHANGED => { use crate::event::WindowEvent::ScaleFactorChanged; // This message actually provides two DPI values - x and y. However MSDN says that // "you only need to use either the X-axis or the Y-axis value when scaling your // application since they are the same". // https://msdn.microsoft.com/en-us/library/windows/desktop/dn312083(v=vs.85).aspx let new_dpi_x = super::loword(wparam as u32) as u32; let new_scale_factor = dpi_to_scale_factor(new_dpi_x); let old_scale_factor: f64; let (allow_resize, window_flags) = { let mut window_state = userdata.window_state_lock(); old_scale_factor = window_state.scale_factor; window_state.scale_factor = new_scale_factor; if new_scale_factor == old_scale_factor { return 0; } let allow_resize = window_state.fullscreen.is_none() && !window_state.window_flags().contains(WindowFlags::MAXIMIZED); (allow_resize, window_state.window_flags) }; // New size as suggested by Windows. let suggested_rect = *(lparam as *const RECT); // The window rect provided is the window's outer size, not it's inner size. However, // win32 doesn't provide an `UnadjustWindowRectEx` function to get the client rect from // the outer rect, so we instead adjust the window rect to get the decoration margins // and remove them from the outer size. let margin_left: i32; let margin_top: i32; // let margin_right: i32; // let margin_bottom: i32; { let adjusted_rect = window_flags .adjust_rect(window, suggested_rect) .unwrap_or(suggested_rect); margin_left = suggested_rect.left - adjusted_rect.left; margin_top = suggested_rect.top - adjusted_rect.top; // margin_right = adjusted_rect.right - suggested_rect.right; // margin_bottom = adjusted_rect.bottom - suggested_rect.bottom; } let old_physical_inner_rect = util::WindowArea::Inner .get_rect(window) .expect("failed to query (old) inner window area"); let old_physical_inner_size = PhysicalSize::new( (old_physical_inner_rect.right - old_physical_inner_rect.left) as u32, (old_physical_inner_rect.bottom - old_physical_inner_rect.top) as u32, ); // `allow_resize` prevents us from re-applying DPI adjustment to the restored size after // exiting fullscreen (the restored size is already DPI adjusted). let mut new_physical_inner_size = match allow_resize { // We calculate our own size because the default suggested rect doesn't do a great job // of preserving the window's logical size. true => old_physical_inner_size .to_logical::<f64>(old_scale_factor) .to_physical::<u32>(new_scale_factor), false => old_physical_inner_size, }; userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: ScaleFactorChanged { scale_factor: new_scale_factor, new_inner_size: &mut new_physical_inner_size, }, }); let dragging_window: bool; { let window_state = userdata.window_state_lock(); dragging_window = window_state .window_flags() .contains(WindowFlags::MARKER_IN_SIZE_MOVE); // Unset maximized if we're changing the window's size. if new_physical_inner_size != old_physical_inner_size { WindowState::set_window_flags(window_state, window, |f| { f.set(WindowFlags::MAXIMIZED, false) }); } } let new_outer_rect: RECT; { let suggested_ul = ( suggested_rect.left + margin_left, suggested_rect.top + margin_top, ); let mut conservative_rect = RECT { left: suggested_ul.0, top: suggested_ul.1, right: suggested_ul.0 + new_physical_inner_size.width as i32, bottom: suggested_ul.1 + new_physical_inner_size.height as i32, }; conservative_rect = window_flags .adjust_rect(window, conservative_rect) .unwrap_or(conservative_rect); // If we're dragging the window, offset the window so that the cursor's // relative horizontal position in the title bar is preserved. if dragging_window { let bias = { let cursor_pos = { let mut pos = mem::zeroed(); GetCursorPos(&mut pos); pos }; let suggested_cursor_horizontal_ratio = (cursor_pos.x - suggested_rect.left) as f64 / (suggested_rect.right - suggested_rect.left) as f64; (cursor_pos.x - (suggested_cursor_horizontal_ratio * (conservative_rect.right - conservative_rect.left) as f64) as i32) - conservative_rect.left }; conservative_rect.left += bias; conservative_rect.right += bias; } // Check to see if the new window rect is on the monitor with the new DPI factor. // If it isn't, offset the window so that it is. let new_dpi_monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONULL); let conservative_rect_monitor = MonitorFromRect(&conservative_rect, MONITOR_DEFAULTTONULL); new_outer_rect = if conservative_rect_monitor == new_dpi_monitor { conservative_rect } else { let get_monitor_rect = |monitor| { let mut monitor_info = MONITORINFO { cbSize: mem::size_of::<MONITORINFO>() as _, ..mem::zeroed() }; GetMonitorInfoW(monitor, &mut monitor_info); monitor_info.rcMonitor }; let wrong_monitor = conservative_rect_monitor; let wrong_monitor_rect = get_monitor_rect(wrong_monitor); let new_monitor_rect = get_monitor_rect(new_dpi_monitor); // The direction to nudge the window in to get the window onto the monitor with // the new DPI factor. We calculate this by seeing which monitor edges are // shared and nudging away from the wrong monitor based on those. #[allow(clippy::bool_to_int_with_if)] let delta_nudge_to_dpi_monitor = ( if wrong_monitor_rect.left == new_monitor_rect.right { -1 } else if wrong_monitor_rect.right == new_monitor_rect.left { 1 } else { 0 }, if wrong_monitor_rect.bottom == new_monitor_rect.top { 1 } else if wrong_monitor_rect.top == new_monitor_rect.bottom { -1 } else { 0 }, ); let abort_after_iterations = new_monitor_rect.right - new_monitor_rect.left + new_monitor_rect.bottom - new_monitor_rect.top; for _ in 0..abort_after_iterations { conservative_rect.left += delta_nudge_to_dpi_monitor.0; conservative_rect.right += delta_nudge_to_dpi_monitor.0; conservative_rect.top += delta_nudge_to_dpi_monitor.1; conservative_rect.bottom += delta_nudge_to_dpi_monitor.1; if MonitorFromRect(&conservative_rect, MONITOR_DEFAULTTONULL) == new_dpi_monitor { break; } } conservative_rect }; } SetWindowPos( window, 0, new_outer_rect.left, new_outer_rect.top, new_outer_rect.right - new_outer_rect.left, new_outer_rect.bottom - new_outer_rect.top, SWP_NOZORDER | SWP_NOACTIVATE, ); 0 } WM_SETTINGCHANGE => { use crate::event::WindowEvent::ThemeChanged; let preferred_theme = userdata.window_state_lock().preferred_theme; if preferred_theme.is_none() { let new_theme = try_theme(window, preferred_theme); let mut window_state = userdata.window_state_lock(); if window_state.current_theme != new_theme { window_state.current_theme = new_theme; drop(window_state); userdata.send_event(Event::WindowEvent { window_id: RootWindowId(WindowId(window)), event: ThemeChanged(new_theme), }); } } DefWindowProcW(window, msg, wparam, lparam) } _ => { if msg == DESTROY_MSG_ID.get() { DestroyWindow(window); 0 } else if msg == SET_RETAIN_STATE_ON_SIZE_MSG_ID.get() { let mut window_state = userdata.window_state_lock(); window_state.set_window_flags_in_place(|f| { f.set(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE, wparam != 0) }); 0 } else if msg == TASKBAR_CREATED.get() { let window_state = userdata.window_state_lock(); set_skip_taskbar(window, window_state.skip_taskbar); DefWindowProcW(window, msg, wparam, lparam) } else { DefWindowProcW(window, msg, wparam, lparam) } } }; userdata .event_loop_runner .catch_unwind(callback) .unwrap_or(-1) } unsafe extern "system" fn thread_event_target_callback<T: 'static>( window: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM, ) -> LRESULT { let userdata_ptr = super::get_window_long(window, GWL_USERDATA) as *mut ThreadMsgTargetData<T>; if userdata_ptr.is_null() { // `userdata_ptr` will always be null for the first `WM_GETMINMAXINFO`, as well as `WM_NCCREATE` and // `WM_CREATE`. return DefWindowProcW(window, msg, wparam, lparam); } let userdata = Box::from_raw(userdata_ptr); if msg != WM_PAINT { RedrawWindow(window, ptr::null(), 0, RDW_INTERNALPAINT); } let mut userdata_removed = false; // I decided to bind the closure to `callback` and pass it to catch_unwind rather than passing // the closure to catch_unwind directly so that the match body indendation wouldn't change and // the git blame and history would be preserved. let callback = || match msg { WM_NCDESTROY => { super::set_window_long(window, GWL_USERDATA, 0); userdata_removed = true; 0 } // Because WM_PAINT comes after all other messages, we use it during modal loops to detect // when the event queue has been emptied. See `process_event` for more details. WM_PAINT => { ValidateRect(window, ptr::null()); // If the WM_PAINT handler in `public_window_callback` has already flushed the redraw // events, `handling_events` will return false and we won't emit a second // `RedrawEventsCleared` event. if userdata.event_loop_runner.handling_events() { if userdata.event_loop_runner.should_buffer() { // This branch can be triggered when a nested win32 event loop is triggered // inside of the `event_handler` callback. RedrawWindow(window, ptr::null(), 0, RDW_INTERNALPAINT); } else { // This WM_PAINT handler will never be re-entrant because `flush_paint_messages` // doesn't call WM_PAINT for the thread event target (i.e. this window). assert!(flush_paint_messages(None, &userdata.event_loop_runner)); userdata.event_loop_runner.redraw_events_cleared(); process_control_flow(&userdata.event_loop_runner); } } // Default WM_PAINT behaviour. This makes sure modals and popups are shown immediatly when opening them. DefWindowProcW(window, msg, wparam, lparam) } WM_INPUT_DEVICE_CHANGE => { let event = match wparam as u32 { GIDC_ARRIVAL => DeviceEvent::Added, GIDC_REMOVAL => DeviceEvent::Removed, _ => unreachable!(), }; userdata.send_event(Event::DeviceEvent { device_id: wrap_device_id(lparam as u32), event, }); 0 } WM_INPUT => { use crate::event::{ DeviceEvent::{Button, Key, Motion, MouseMotion, MouseWheel}, ElementState::{Pressed, Released}, MouseScrollDelta::LineDelta, }; if let Some(data) = raw_input::get_raw_input_data(lparam) { let device_id = wrap_device_id(data.header.hDevice as u32); if data.header.dwType == RIM_TYPEMOUSE { let mouse = data.data.mouse; if util::has_flag(mouse.usFlags as u32, MOUSE_MOVE_RELATIVE) { let x = mouse.lLastX as f64; let y = mouse.lLastY as f64; if x != 0.0 { userdata.send_event(Event::DeviceEvent { device_id, event: Motion { axis: 0, value: x }, }); } if y != 0.0 { userdata.send_event(Event::DeviceEvent { device_id, event: Motion { axis: 1, value: y }, }); } if x != 0.0 || y != 0.0 { userdata.send_event(Event::DeviceEvent { device_id, event: MouseMotion { delta: (x, y) }, }); } } let mouse_button_flags = mouse.Anonymous.Anonymous.usButtonFlags; if util::has_flag(mouse_button_flags as u32, RI_MOUSE_WHEEL) { let delta = mouse.Anonymous.Anonymous.usButtonData as i16 as f32 / WHEEL_DELTA as f32; userdata.send_event(Event::DeviceEvent { device_id, event: MouseWheel { delta: LineDelta(0.0, delta), }, }); } let button_state = raw_input::get_raw_mouse_button_state(mouse_button_flags as u32); // Left, middle, and right, respectively. for (index, state) in button_state.iter().enumerate() { if let Some(state) = *state { // This gives us consistency with X11, since there doesn't // seem to be anything else reasonable to do for a mouse // button ID. let button = (index + 1) as u32; userdata.send_event(Event::DeviceEvent { device_id, event: Button { button, state }, }); } } } else if data.header.dwType == RIM_TYPEKEYBOARD { let keyboard = data.data.keyboard; let pressed = keyboard.Message == WM_KEYDOWN || keyboard.Message == WM_SYSKEYDOWN; let released = keyboard.Message == WM_KEYUP || keyboard.Message == WM_SYSKEYUP; if pressed || released { let state = if pressed { Pressed } else { Released }; let scancode = keyboard.MakeCode; let extended = util::has_flag(keyboard.Flags, RI_KEY_E0 as u16) | util::has_flag(keyboard.Flags, RI_KEY_E1 as u16); if let Some((vkey, scancode)) = handle_extended_keys(keyboard.VKey, scancode as u32, extended) { let virtual_keycode = vkey_to_winit_vkey(vkey); #[allow(deprecated)] userdata.send_event(Event::DeviceEvent { device_id, event: Key(KeyboardInput { scancode, state, virtual_keycode, modifiers: event::get_key_mods(), }), }); } } } } DefWindowProcW(window, msg, wparam, lparam) } _ if msg == USER_EVENT_MSG_ID.get() => { if let Ok(event) = userdata.user_event_receiver.recv() { userdata.send_event(Event::UserEvent(event)); } 0 } _ if msg == EXEC_MSG_ID.get() => { let mut function: ThreadExecFn = Box::from_raw(wparam as *mut _); function(); 0 } _ if msg == PROCESS_NEW_EVENTS_MSG_ID.get() => { PostThreadMessageW( userdata.event_loop_runner.wait_thread_id(), CANCEL_WAIT_UNTIL_MSG_ID.get(), 0, 0, ); // if the control_flow is WaitUntil, make sure the given moment has actually passed // before emitting NewEvents if let ControlFlow::WaitUntil(wait_until) = userdata.event_loop_runner.control_flow() { let mut msg = mem::zeroed(); while Instant::now() < wait_until { if PeekMessageW(&mut msg, 0, 0, 0, PM_NOREMOVE) != false.into() { // This works around a "feature" in PeekMessageW. If the message PeekMessageW // gets is a WM_PAINT message that had RDW_INTERNALPAINT set (i.e. doesn't // have an update region), PeekMessageW will remove that window from the // redraw queue even though we told it not to remove messages from the // queue. We fix it by re-dispatching an internal paint message to that // window. if msg.message == WM_PAINT { let mut rect = mem::zeroed(); if GetUpdateRect(msg.hwnd, &mut rect, false.into()) == false.into() { RedrawWindow(msg.hwnd, ptr::null(), 0, RDW_INTERNALPAINT); } } break; } } } userdata.event_loop_runner.poll(); 0 } _ => DefWindowProcW(window, msg, wparam, lparam), }; let result = userdata .event_loop_runner .catch_unwind(callback) .unwrap_or(-1); if userdata_removed { drop(userdata); } else { Box::into_raw(userdata); } result }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/event_loop/runner.rs
Rust
use std::{ any::Any, cell::{Cell, RefCell}, collections::{HashSet, VecDeque}, mem, panic, ptr, rc::Rc, time::Instant, }; use windows_sys::Win32::{ Foundation::HWND, Graphics::Gdi::{RedrawWindow, RDW_INTERNALPAINT}, }; use crate::{ dpi::PhysicalSize, event::{Event, StartCause, WindowEvent}, event_loop::ControlFlow, platform_impl::platform::{ event_loop::{WindowData, GWL_USERDATA}, get_window_long, }, window::WindowId, }; pub(crate) type EventLoopRunnerShared<T> = Rc<EventLoopRunner<T>>; type EventHandler<T> = Cell<Option<Box<dyn FnMut(Event<'_, T>, &mut ControlFlow)>>>; pub(crate) struct EventLoopRunner<T: 'static> { // The event loop's win32 handles pub(super) thread_msg_target: HWND, wait_thread_id: u32, control_flow: Cell<ControlFlow>, runner_state: Cell<RunnerState>, last_events_cleared: Cell<Instant>, event_handler: EventHandler<T>, event_buffer: RefCell<VecDeque<BufferedEvent<T>>>, owned_windows: Cell<HashSet<HWND>>, panic_error: Cell<Option<PanicError>>, } pub type PanicError = Box<dyn Any + Send + 'static>; /// See `move_state_to` function for details on how the state loop works. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum RunnerState { /// The event loop has just been created, and an `Init` event must be sent. Uninitialized, /// The event loop is idling. Idle, /// The event loop is handling the OS's events and sending them to the user's callback. /// `NewEvents` has been sent, and `MainEventsCleared` hasn't. HandlingMainEvents, /// The event loop is handling the redraw events and sending them to the user's callback. /// `MainEventsCleared` has been sent, and `RedrawEventsCleared` hasn't. HandlingRedrawEvents, /// The event loop has been destroyed. No other events will be emitted. Destroyed, } enum BufferedEvent<T: 'static> { Event(Event<'static, T>), ScaleFactorChanged(WindowId, f64, PhysicalSize<u32>), } impl<T> EventLoopRunner<T> { pub(crate) fn new(thread_msg_target: HWND, wait_thread_id: u32) -> EventLoopRunner<T> { EventLoopRunner { thread_msg_target, wait_thread_id, runner_state: Cell::new(RunnerState::Uninitialized), control_flow: Cell::new(ControlFlow::Poll), panic_error: Cell::new(None), last_events_cleared: Cell::new(Instant::now()), event_handler: Cell::new(None), event_buffer: RefCell::new(VecDeque::new()), owned_windows: Cell::new(HashSet::new()), } } pub(crate) unsafe fn set_event_handler<F>(&self, f: F) where F: FnMut(Event<'_, T>, &mut ControlFlow), { let old_event_handler = self.event_handler.replace(mem::transmute::< Option<Box<dyn FnMut(Event<'_, T>, &mut ControlFlow)>>, Option<Box<dyn FnMut(Event<'_, T>, &mut ControlFlow)>>, >(Some(Box::new(f)))); assert!(old_event_handler.is_none()); } pub(crate) fn reset_runner(&self) { let EventLoopRunner { thread_msg_target: _, wait_thread_id: _, runner_state, panic_error, control_flow, last_events_cleared: _, event_handler, event_buffer: _, owned_windows: _, } = self; runner_state.set(RunnerState::Uninitialized); panic_error.set(None); control_flow.set(ControlFlow::Poll); event_handler.set(None); } } /// State retrieval functions. impl<T> EventLoopRunner<T> { pub fn thread_msg_target(&self) -> HWND { self.thread_msg_target } pub fn wait_thread_id(&self) -> u32 { self.wait_thread_id } pub fn redrawing(&self) -> bool { self.runner_state.get() == RunnerState::HandlingRedrawEvents } pub fn take_panic_error(&self) -> Result<(), PanicError> { match self.panic_error.take() { Some(err) => Err(err), None => Ok(()), } } pub fn control_flow(&self) -> ControlFlow { self.control_flow.get() } pub fn handling_events(&self) -> bool { self.runner_state.get() != RunnerState::Idle } pub fn should_buffer(&self) -> bool { let handler = self.event_handler.take(); let should_buffer = handler.is_none(); self.event_handler.set(handler); should_buffer } } /// Misc. functions impl<T> EventLoopRunner<T> { pub fn catch_unwind<R>(&self, f: impl FnOnce() -> R) -> Option<R> { let panic_error = self.panic_error.take(); if panic_error.is_none() { let result = panic::catch_unwind(panic::AssertUnwindSafe(f)); // Check to see if the panic error was set in a re-entrant call to catch_unwind inside // of `f`. If it was, that error takes priority. If it wasn't, check if our call to // catch_unwind caught any panics and set panic_error appropriately. match self.panic_error.take() { None => match result { Ok(r) => Some(r), Err(e) => { self.panic_error.set(Some(e)); None } }, Some(e) => { self.panic_error.set(Some(e)); None } } } else { self.panic_error.set(panic_error); None } } pub fn register_window(&self, window: HWND) { let mut owned_windows = self.owned_windows.take(); owned_windows.insert(window); self.owned_windows.set(owned_windows); } pub fn remove_window(&self, window: HWND) { let mut owned_windows = self.owned_windows.take(); owned_windows.remove(&window); self.owned_windows.set(owned_windows); } pub fn owned_windows(&self, mut f: impl FnMut(HWND)) { let mut owned_windows = self.owned_windows.take(); for hwnd in &owned_windows { f(*hwnd); } let new_owned_windows = self.owned_windows.take(); owned_windows.extend(&new_owned_windows); self.owned_windows.set(owned_windows); } } /// Event dispatch functions. impl<T> EventLoopRunner<T> { pub(crate) unsafe fn poll(&self) { self.move_state_to(RunnerState::HandlingMainEvents); } pub(crate) unsafe fn send_event(&self, event: Event<'_, T>) { if let Event::RedrawRequested(_) = event { if self.runner_state.get() != RunnerState::HandlingRedrawEvents { warn!("RedrawRequested dispatched without explicit MainEventsCleared"); self.move_state_to(RunnerState::HandlingRedrawEvents); } self.call_event_handler(event); } else if self.should_buffer() { // If the runner is already borrowed, we're in the middle of an event loop invocation. Add // the event to a buffer to be processed later. self.event_buffer .borrow_mut() .push_back(BufferedEvent::from_event(event)) } else { self.move_state_to(RunnerState::HandlingMainEvents); self.call_event_handler(event); self.dispatch_buffered_events(); } } pub(crate) unsafe fn main_events_cleared(&self) { self.move_state_to(RunnerState::HandlingRedrawEvents); } pub(crate) unsafe fn redraw_events_cleared(&self) { self.move_state_to(RunnerState::Idle); } pub(crate) unsafe fn loop_destroyed(&self) { self.move_state_to(RunnerState::Destroyed); } unsafe fn call_event_handler(&self, event: Event<'_, T>) { self.catch_unwind(|| { let mut control_flow = self.control_flow.take(); let mut event_handler = self.event_handler.take() .expect("either event handler is re-entrant (likely), or no event handler is registered (very unlikely)"); if let ControlFlow::ExitWithCode(code) = control_flow { event_handler(event, &mut ControlFlow::ExitWithCode(code)); } else { event_handler(event, &mut control_flow); } assert!(self.event_handler.replace(Some(event_handler)).is_none()); self.control_flow.set(control_flow); }); } unsafe fn dispatch_buffered_events(&self) { loop { // We do this instead of using a `while let` loop because if we use a `while let` // loop the reference returned `borrow_mut()` doesn't get dropped until the end // of the loop's body and attempts to add events to the event buffer while in // `process_event` will fail. let buffered_event_opt = self.event_buffer.borrow_mut().pop_front(); match buffered_event_opt { Some(e) => e.dispatch_event(|e| self.call_event_handler(e)), None => break, } } } /// Dispatch control flow events (`NewEvents`, `MainEventsCleared`, `RedrawEventsCleared`, and /// `LoopDestroyed`) as necessary to bring the internal `RunnerState` to the new runner state. /// /// The state transitions are defined as follows: /// /// ```text /// Uninitialized /// | /// V /// HandlingMainEvents /// ^ | /// | V /// Idle <--- HandlingRedrawEvents /// | /// V /// Destroyed /// ``` /// /// Attempting to transition back to `Uninitialized` will result in a panic. Attempting to /// transition *from* `Destroyed` will also reuslt in a panic. Transitioning to the current /// state is a no-op. Even if the `new_runner_state` isn't the immediate next state in the /// runner state machine (e.g. `self.runner_state == HandlingMainEvents` and /// `new_runner_state == Idle`), the intermediate state transitions will still be executed. unsafe fn move_state_to(&self, new_runner_state: RunnerState) { use RunnerState::{ Destroyed, HandlingMainEvents, HandlingRedrawEvents, Idle, Uninitialized, }; match ( self.runner_state.replace(new_runner_state), new_runner_state, ) { (Uninitialized, Uninitialized) | (Idle, Idle) | (HandlingMainEvents, HandlingMainEvents) | (HandlingRedrawEvents, HandlingRedrawEvents) | (Destroyed, Destroyed) => (), // State transitions that initialize the event loop. (Uninitialized, HandlingMainEvents) => { self.call_new_events(true); } (Uninitialized, HandlingRedrawEvents) => { self.call_new_events(true); self.call_event_handler(Event::MainEventsCleared); } (Uninitialized, Idle) => { self.call_new_events(true); self.call_event_handler(Event::MainEventsCleared); self.call_redraw_events_cleared(); } (Uninitialized, Destroyed) => { self.call_new_events(true); self.call_event_handler(Event::MainEventsCleared); self.call_redraw_events_cleared(); self.call_event_handler(Event::LoopDestroyed); } (_, Uninitialized) => panic!("cannot move state to Uninitialized"), // State transitions that start the event handling process. (Idle, HandlingMainEvents) => { self.call_new_events(false); } (Idle, HandlingRedrawEvents) => { self.call_new_events(false); self.call_event_handler(Event::MainEventsCleared); } (Idle, Destroyed) => { self.call_event_handler(Event::LoopDestroyed); } (HandlingMainEvents, HandlingRedrawEvents) => { self.call_event_handler(Event::MainEventsCleared); } (HandlingMainEvents, Idle) => { warn!("RedrawEventsCleared emitted without explicit MainEventsCleared"); self.call_event_handler(Event::MainEventsCleared); self.call_redraw_events_cleared(); } (HandlingMainEvents, Destroyed) => { self.call_event_handler(Event::MainEventsCleared); self.call_redraw_events_cleared(); self.call_event_handler(Event::LoopDestroyed); } (HandlingRedrawEvents, Idle) => { self.call_redraw_events_cleared(); } (HandlingRedrawEvents, HandlingMainEvents) => { warn!("NewEvents emitted without explicit RedrawEventsCleared"); self.call_redraw_events_cleared(); self.call_new_events(false); } (HandlingRedrawEvents, Destroyed) => { self.call_redraw_events_cleared(); self.call_event_handler(Event::LoopDestroyed); } (Destroyed, _) => panic!("cannot move state from Destroyed"), } } unsafe fn call_new_events(&self, init: bool) { let start_cause = match (init, self.control_flow()) { (true, _) => StartCause::Init, (false, ControlFlow::Poll) => StartCause::Poll, (false, ControlFlow::ExitWithCode(_)) | (false, ControlFlow::Wait) => { StartCause::WaitCancelled { requested_resume: None, start: self.last_events_cleared.get(), } } (false, ControlFlow::WaitUntil(requested_resume)) => { if Instant::now() < requested_resume { StartCause::WaitCancelled { requested_resume: Some(requested_resume), start: self.last_events_cleared.get(), } } else { StartCause::ResumeTimeReached { requested_resume, start: self.last_events_cleared.get(), } } } }; self.call_event_handler(Event::NewEvents(start_cause)); // NB: For consistency all platforms must emit a 'resumed' event even though Windows // applications don't themselves have a formal suspend/resume lifecycle. if init { self.call_event_handler(Event::Resumed); } self.dispatch_buffered_events(); RedrawWindow(self.thread_msg_target, ptr::null(), 0, RDW_INTERNALPAINT); } unsafe fn call_redraw_events_cleared(&self) { self.call_event_handler(Event::RedrawEventsCleared); self.last_events_cleared.set(Instant::now()); } } impl<T> BufferedEvent<T> { pub fn from_event(event: Event<'_, T>) -> BufferedEvent<T> { match event { Event::WindowEvent { event: WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size, }, window_id, } => BufferedEvent::ScaleFactorChanged(window_id, scale_factor, *new_inner_size), event => BufferedEvent::Event(event.to_static().unwrap()), } } pub fn dispatch_event(self, dispatch: impl FnOnce(Event<'_, T>)) { match self { Self::Event(event) => dispatch(event), Self::ScaleFactorChanged(window_id, scale_factor, mut new_inner_size) => { dispatch(Event::WindowEvent { window_id, event: WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size: &mut new_inner_size, }, }); let window_flags = unsafe { let userdata = get_window_long(window_id.0.into(), GWL_USERDATA) as *mut WindowData<T>; (*userdata).window_state_lock().window_flags }; window_flags.set_size((window_id.0).0, new_inner_size); } } } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/icon.rs
Rust
use std::{fmt, io, mem, path::Path, sync::Arc}; use windows_sys::{ core::PCWSTR, Win32::{ Foundation::HWND, UI::WindowsAndMessaging::{ CreateIcon, DestroyIcon, LoadImageW, SendMessageW, HICON, ICON_BIG, ICON_SMALL, IMAGE_ICON, LR_DEFAULTSIZE, LR_LOADFROMFILE, WM_SETICON, }, }, }; use crate::dpi::PhysicalSize; use crate::icon::*; use super::util; impl Pixel { fn convert_to_bgra(&mut self) { mem::swap(&mut self.r, &mut self.b); } } impl RgbaIcon { fn into_windows_icon(self) -> Result<WinIcon, BadIcon> { let rgba = self.rgba; let pixel_count = rgba.len() / PIXEL_SIZE; let mut and_mask = Vec::with_capacity(pixel_count); let pixels = unsafe { std::slice::from_raw_parts_mut(rgba.as_ptr() as *mut Pixel, pixel_count) }; for pixel in pixels { and_mask.push(pixel.a.wrapping_sub(std::u8::MAX)); // invert alpha channel pixel.convert_to_bgra(); } assert_eq!(and_mask.len(), pixel_count); let handle = unsafe { CreateIcon( 0, self.width as i32, self.height as i32, 1, (PIXEL_SIZE * 8) as u8, and_mask.as_ptr(), rgba.as_ptr(), ) }; if handle != 0 { Ok(WinIcon::from_handle(handle)) } else { Err(BadIcon::OsError(io::Error::last_os_error())) } } } #[derive(Debug)] pub enum IconType { Small = ICON_SMALL as isize, Big = ICON_BIG as isize, } #[derive(Debug)] struct RaiiIcon { handle: HICON, } #[derive(Clone)] pub struct WinIcon { inner: Arc<RaiiIcon>, } unsafe impl Send for WinIcon {} impl WinIcon { pub fn as_raw_handle(&self) -> HICON { self.inner.handle } pub fn from_path<P: AsRef<Path>>( path: P, size: Option<PhysicalSize<u32>>, ) -> Result<Self, BadIcon> { // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size let (width, height) = size.map(Into::into).unwrap_or((0, 0)); let wide_path = util::encode_wide(path.as_ref()); let handle = unsafe { LoadImageW( 0, wide_path.as_ptr(), IMAGE_ICON, width, height, LR_DEFAULTSIZE | LR_LOADFROMFILE, ) }; if handle != 0 { Ok(WinIcon::from_handle(handle as HICON)) } else { Err(BadIcon::OsError(io::Error::last_os_error())) } } pub fn from_resource( resource_id: u16, size: Option<PhysicalSize<u32>>, ) -> Result<Self, BadIcon> { // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size let (width, height) = size.map(Into::into).unwrap_or((0, 0)); let handle = unsafe { LoadImageW( util::get_instance_handle(), resource_id as PCWSTR, IMAGE_ICON, width, height, LR_DEFAULTSIZE, ) }; if handle != 0 { Ok(WinIcon::from_handle(handle as HICON)) } else { Err(BadIcon::OsError(io::Error::last_os_error())) } } pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> { let rgba_icon = RgbaIcon::from_rgba(rgba, width, height)?; rgba_icon.into_windows_icon() } pub fn set_for_window(&self, hwnd: HWND, icon_type: IconType) { unsafe { SendMessageW(hwnd, WM_SETICON, icon_type as usize, self.as_raw_handle()); } } fn from_handle(handle: HICON) -> Self { Self { inner: Arc::new(RaiiIcon { handle }), } } } impl Drop for RaiiIcon { fn drop(&mut self) { unsafe { DestroyIcon(self.handle) }; } } impl fmt::Debug for WinIcon { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { (*self.inner).fmt(formatter) } } pub fn unset_for_window(hwnd: HWND, icon_type: IconType) { unsafe { SendMessageW(hwnd, WM_SETICON, icon_type as usize, 0); } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/ime.rs
Rust
use std::{ ffi::{c_void, OsString}, mem::zeroed, os::windows::prelude::OsStringExt, ptr::null_mut, }; use windows_sys::Win32::{ Foundation::POINT, Globalization::HIMC, UI::{ Input::Ime::{ ImmAssociateContextEx, ImmGetCompositionStringW, ImmGetContext, ImmReleaseContext, ImmSetCandidateWindow, ATTR_TARGET_CONVERTED, ATTR_TARGET_NOTCONVERTED, CANDIDATEFORM, CFS_EXCLUDE, GCS_COMPATTR, GCS_COMPSTR, GCS_CURSORPOS, GCS_RESULTSTR, IACE_CHILDREN, IACE_DEFAULT, }, WindowsAndMessaging::{GetSystemMetrics, SM_IMMENABLED}, }, }; use crate::{dpi::Position, platform::windows::HWND}; pub struct ImeContext { hwnd: HWND, himc: HIMC, } impl ImeContext { pub unsafe fn current(hwnd: HWND) -> Self { let himc = ImmGetContext(hwnd); ImeContext { hwnd, himc } } pub unsafe fn get_composing_text_and_cursor( &self, ) -> Option<(String, Option<usize>, Option<usize>)> { let text = self.get_composition_string(GCS_COMPSTR)?; let attrs = self.get_composition_data(GCS_COMPATTR).unwrap_or_default(); let mut first = None; let mut last = None; let mut boundary_before_char = 0; for (attr, chr) in attrs.into_iter().zip(text.chars()) { let char_is_targetted = attr as u32 == ATTR_TARGET_CONVERTED || attr as u32 == ATTR_TARGET_NOTCONVERTED; if first.is_none() && char_is_targetted { first = Some(boundary_before_char); } else if first.is_some() && last.is_none() && !char_is_targetted { last = Some(boundary_before_char); } boundary_before_char += chr.len_utf8(); } if first.is_some() && last.is_none() { last = Some(text.len()); } else if first.is_none() { // IME haven't split words and select any clause yet, so trying to retrieve normal cursor. let cursor = self.get_composition_cursor(&text); first = cursor; last = cursor; } Some((text, first, last)) } pub unsafe fn get_composed_text(&self) -> Option<String> { self.get_composition_string(GCS_RESULTSTR) } unsafe fn get_composition_cursor(&self, text: &str) -> Option<usize> { let cursor = ImmGetCompositionStringW(self.himc, GCS_CURSORPOS, null_mut(), 0); (cursor >= 0).then(|| text.chars().take(cursor as _).map(|c| c.len_utf8()).sum()) } unsafe fn get_composition_string(&self, gcs_mode: u32) -> Option<String> { let data = self.get_composition_data(gcs_mode)?; let (prefix, shorts, suffix) = data.align_to::<u16>(); if prefix.is_empty() && suffix.is_empty() { OsString::from_wide(shorts).into_string().ok() } else { None } } unsafe fn get_composition_data(&self, gcs_mode: u32) -> Option<Vec<u8>> { let size = match ImmGetCompositionStringW(self.himc, gcs_mode, null_mut(), 0) { 0 => return Some(Vec::new()), size if size < 0 => return None, size => size, }; let mut buf = Vec::<u8>::with_capacity(size as _); let size = ImmGetCompositionStringW( self.himc, gcs_mode, buf.as_mut_ptr() as *mut c_void, size as _, ); if size < 0 { None } else { buf.set_len(size as _); Some(buf) } } pub unsafe fn set_ime_position(&self, spot: Position, scale_factor: f64) { if !ImeContext::system_has_ime() { return; } let (x, y) = spot.to_physical::<i32>(scale_factor).into(); let candidate_form = CANDIDATEFORM { dwIndex: 0, dwStyle: CFS_EXCLUDE, ptCurrentPos: POINT { x, y }, rcArea: zeroed(), }; ImmSetCandidateWindow(self.himc, &candidate_form); } pub unsafe fn set_ime_allowed(hwnd: HWND, allowed: bool) { if !ImeContext::system_has_ime() { return; } if allowed { ImmAssociateContextEx(hwnd, 0, IACE_DEFAULT); } else { ImmAssociateContextEx(hwnd, 0, IACE_CHILDREN); } } unsafe fn system_has_ime() -> bool { GetSystemMetrics(SM_IMMENABLED) != 0 } } impl Drop for ImeContext { fn drop(&mut self) { unsafe { ImmReleaseContext(self.hwnd, self.himc) }; } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/mod.rs
Rust
#![cfg(windows_platform)] use windows_sys::Win32::{ Foundation::{HANDLE, HWND}, UI::WindowsAndMessaging::{HMENU, WINDOW_LONG_PTR_INDEX}, }; pub(crate) use self::{ event_loop::{ EventLoop, EventLoopProxy, EventLoopWindowTarget, PlatformSpecificEventLoopAttributes, }, icon::WinIcon, monitor::{MonitorHandle, VideoMode}, window::Window, }; pub use self::icon::WinIcon as PlatformIcon; pub(self) use crate::platform_impl::Fullscreen; use crate::event::DeviceId as RootDeviceId; use crate::icon::Icon; #[derive(Clone)] pub struct PlatformSpecificWindowBuilderAttributes { pub owner: Option<HWND>, pub menu: Option<HMENU>, pub taskbar_icon: Option<Icon>, pub no_redirection_bitmap: bool, pub drag_and_drop: bool, pub skip_taskbar: bool, pub decoration_shadow: bool, } impl Default for PlatformSpecificWindowBuilderAttributes { fn default() -> Self { Self { owner: None, menu: None, taskbar_icon: None, no_redirection_bitmap: false, drag_and_drop: true, skip_taskbar: false, decoration_shadow: false, } } } unsafe impl Send for PlatformSpecificWindowBuilderAttributes {} unsafe impl Sync for PlatformSpecificWindowBuilderAttributes {} // Cursor name in UTF-16. Used to set cursor in `WM_SETCURSOR`. #[derive(Debug, Clone, Copy)] pub struct Cursor(pub *const u16); unsafe impl Send for Cursor {} unsafe impl Sync for Cursor {} #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DeviceId(u32); impl DeviceId { pub const unsafe fn dummy() -> Self { DeviceId(0) } } impl DeviceId { pub fn persistent_identifier(&self) -> Option<String> { if self.0 != 0 { raw_input::get_raw_input_device_name(self.0 as HANDLE) } else { None } } } // Constant device ID, to be removed when this backend is updated to report real device IDs. const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId(0)); fn wrap_device_id(id: u32) -> RootDeviceId { RootDeviceId(DeviceId(id)) } pub type OsError = std::io::Error; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WindowId(HWND); unsafe impl Send for WindowId {} unsafe impl Sync for WindowId {} impl WindowId { pub const unsafe fn dummy() -> Self { WindowId(0) } } impl From<WindowId> for u64 { fn from(window_id: WindowId) -> Self { window_id.0 as u64 } } impl From<WindowId> for HWND { fn from(window_id: WindowId) -> Self { window_id.0 } } impl From<u64> for WindowId { fn from(raw_id: u64) -> Self { Self(raw_id as HWND) } } #[inline(always)] const fn get_xbutton_wparam(x: u32) -> u16 { hiword(x) } #[inline(always)] const fn get_x_lparam(x: u32) -> i16 { loword(x) as _ } #[inline(always)] const fn get_y_lparam(x: u32) -> i16 { hiword(x) as _ } #[inline(always)] const fn loword(x: u32) -> u16 { (x & 0xFFFF) as u16 } #[inline(always)] const fn hiword(x: u32) -> u16 { ((x >> 16) & 0xFFFF) as u16 } #[inline(always)] unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize { #[cfg(target_pointer_width = "64")] return windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW(hwnd, nindex); #[cfg(target_pointer_width = "32")] return windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongW(hwnd, nindex) as isize; } #[inline(always)] unsafe fn set_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX, dwnewlong: isize) -> isize { #[cfg(target_pointer_width = "64")] return windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW(hwnd, nindex, dwnewlong); #[cfg(target_pointer_width = "32")] return windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongW( hwnd, nindex, dwnewlong as i32, ) as isize; } #[macro_use] mod util; mod dark_mode; mod definitions; mod dpi; mod drop_handler; mod event; mod event_loop; mod icon; mod ime; mod monitor; mod raw_input; mod window; mod window_state;
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/monitor.rs
Rust
use std::{ collections::{BTreeSet, VecDeque}, hash::Hash, io, mem, ptr, }; use windows_sys::Win32::{ Foundation::{BOOL, HWND, LPARAM, POINT, RECT}, Graphics::Gdi::{ EnumDisplayMonitors, EnumDisplaySettingsExW, GetMonitorInfoW, MonitorFromPoint, MonitorFromWindow, DEVMODEW, DM_BITSPERPEL, DM_DISPLAYFREQUENCY, DM_PELSHEIGHT, DM_PELSWIDTH, ENUM_CURRENT_SETTINGS, HDC, HMONITOR, MONITORINFO, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTOPRIMARY, }, }; use super::util::decode_wide; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, monitor::VideoMode as RootVideoMode, platform_impl::platform::{ dpi::{dpi_to_scale_factor, get_monitor_dpi}, util::has_flag, window::Window, }, }; #[derive(Clone)] pub struct VideoMode { pub(crate) size: (u32, u32), pub(crate) bit_depth: u16, pub(crate) refresh_rate_millihertz: u32, pub(crate) monitor: MonitorHandle, // DEVMODEW is huge so we box it to avoid blowing up the size of winit::window::Fullscreen pub(crate) native_video_mode: Box<DEVMODEW>, } impl PartialEq for VideoMode { fn eq(&self, other: &Self) -> bool { self.size == other.size && self.bit_depth == other.bit_depth && self.refresh_rate_millihertz == other.refresh_rate_millihertz && self.monitor == other.monitor } } impl Eq for VideoMode {} impl std::hash::Hash for VideoMode { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.size.hash(state); self.bit_depth.hash(state); self.refresh_rate_millihertz.hash(state); self.monitor.hash(state); } } impl std::fmt::Debug for VideoMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("VideoMode") .field("size", &self.size) .field("bit_depth", &self.bit_depth) .field("refresh_rate_millihertz", &self.refresh_rate_millihertz) .field("monitor", &self.monitor) .finish() } } impl VideoMode { pub fn size(&self) -> PhysicalSize<u32> { self.size.into() } pub fn bit_depth(&self) -> u16 { self.bit_depth } pub fn refresh_rate_millihertz(&self) -> u32 { self.refresh_rate_millihertz } pub fn monitor(&self) -> MonitorHandle { self.monitor.clone() } } #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] pub struct MonitorHandle(HMONITOR); // Send is not implemented for HMONITOR, we have to wrap it and implement it manually. // For more info see: // https://github.com/retep998/winapi-rs/issues/360 // https://github.com/retep998/winapi-rs/issues/396 unsafe impl Send for MonitorHandle {} unsafe extern "system" fn monitor_enum_proc( hmonitor: HMONITOR, _hdc: HDC, _place: *mut RECT, data: LPARAM, ) -> BOOL { let monitors = data as *mut VecDeque<MonitorHandle>; (*monitors).push_back(MonitorHandle::new(hmonitor)); true.into() // continue enumeration } pub fn available_monitors() -> VecDeque<MonitorHandle> { let mut monitors: VecDeque<MonitorHandle> = VecDeque::new(); unsafe { EnumDisplayMonitors( 0, ptr::null(), Some(monitor_enum_proc), &mut monitors as *mut _ as LPARAM, ); } monitors } pub fn primary_monitor() -> MonitorHandle { const ORIGIN: POINT = POINT { x: 0, y: 0 }; let hmonitor = unsafe { MonitorFromPoint(ORIGIN, MONITOR_DEFAULTTOPRIMARY) }; MonitorHandle::new(hmonitor) } pub fn current_monitor(hwnd: HWND) -> MonitorHandle { let hmonitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) }; MonitorHandle::new(hmonitor) } impl Window { pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { available_monitors() } pub fn primary_monitor(&self) -> Option<MonitorHandle> { let monitor = primary_monitor(); Some(monitor) } } pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result<MONITORINFOEXW, io::Error> { let mut monitor_info: MONITORINFOEXW = unsafe { mem::zeroed() }; monitor_info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32; let status = unsafe { GetMonitorInfoW( hmonitor, &mut monitor_info as *mut MONITORINFOEXW as *mut MONITORINFO, ) }; if status == false.into() { Err(io::Error::last_os_error()) } else { Ok(monitor_info) } } impl MonitorHandle { pub(crate) fn new(hmonitor: HMONITOR) -> Self { MonitorHandle(hmonitor) } #[inline] pub fn name(&self) -> Option<String> { let monitor_info = get_monitor_info(self.0).unwrap(); Some( decode_wide(&monitor_info.szDevice) .to_string_lossy() .to_string(), ) } #[inline] pub fn native_identifier(&self) -> String { self.name().unwrap() } #[inline] pub fn hmonitor(&self) -> HMONITOR { self.0 } #[inline] pub fn size(&self) -> PhysicalSize<u32> { let rc_monitor = get_monitor_info(self.0).unwrap().monitorInfo.rcMonitor; PhysicalSize { width: (rc_monitor.right - rc_monitor.left) as u32, height: (rc_monitor.bottom - rc_monitor.top) as u32, } } #[inline] pub fn refresh_rate_millihertz(&self) -> Option<u32> { let monitor_info = get_monitor_info(self.0).ok()?; let device_name = monitor_info.szDevice.as_ptr(); unsafe { let mut mode: DEVMODEW = mem::zeroed(); mode.dmSize = mem::size_of_val(&mode) as u16; if EnumDisplaySettingsExW(device_name, ENUM_CURRENT_SETTINGS, &mut mode, 0) == false.into() { None } else { Some(mode.dmDisplayFrequency * 1000) } } } #[inline] pub fn position(&self) -> PhysicalPosition<i32> { let rc_monitor = get_monitor_info(self.0).unwrap().monitorInfo.rcMonitor; PhysicalPosition { x: rc_monitor.left, y: rc_monitor.top, } } #[inline] pub fn scale_factor(&self) -> f64 { dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96)) } #[inline] pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> { // EnumDisplaySettingsExW can return duplicate values (or some of the // fields are probably changing, but we aren't looking at those fields // anyway), so we're using a BTreeSet deduplicate let mut modes = BTreeSet::new(); let mut i = 0; loop { unsafe { let monitor_info = get_monitor_info(self.0).unwrap(); let device_name = monitor_info.szDevice.as_ptr(); let mut mode: DEVMODEW = mem::zeroed(); mode.dmSize = mem::size_of_val(&mode) as u16; if EnumDisplaySettingsExW(device_name, i, &mut mode, 0) == false.into() { break; } i += 1; const REQUIRED_FIELDS: u32 = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY; assert!(has_flag(mode.dmFields, REQUIRED_FIELDS)); // Use Ord impl of RootVideoMode modes.insert(RootVideoMode { video_mode: VideoMode { size: (mode.dmPelsWidth, mode.dmPelsHeight), bit_depth: mode.dmBitsPerPel as u16, refresh_rate_millihertz: mode.dmDisplayFrequency * 1000, monitor: self.clone(), native_video_mode: Box::new(mode), }, }); } } modes.into_iter().map(|mode| mode.video_mode) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/raw_input.rs
Rust
use std::{ mem::{self, size_of}, ptr, }; use windows_sys::Win32::{ Devices::HumanInterfaceDevice::{ HID_USAGE_GENERIC_KEYBOARD, HID_USAGE_GENERIC_MOUSE, HID_USAGE_PAGE_GENERIC, }, Foundation::{HANDLE, HWND}, UI::{ Input::{ GetRawInputData, GetRawInputDeviceInfoW, GetRawInputDeviceList, RegisterRawInputDevices, HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTDEVICELIST, RAWINPUTHEADER, RIDEV_DEVNOTIFY, RIDEV_INPUTSINK, RIDEV_REMOVE, RIDI_DEVICEINFO, RIDI_DEVICENAME, RID_DEVICE_INFO, RID_DEVICE_INFO_HID, RID_DEVICE_INFO_KEYBOARD, RID_DEVICE_INFO_MOUSE, RID_INPUT, RIM_TYPEHID, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE, }, WindowsAndMessaging::{ RI_MOUSE_LEFT_BUTTON_DOWN, RI_MOUSE_LEFT_BUTTON_UP, RI_MOUSE_MIDDLE_BUTTON_DOWN, RI_MOUSE_MIDDLE_BUTTON_UP, RI_MOUSE_RIGHT_BUTTON_DOWN, RI_MOUSE_RIGHT_BUTTON_UP, }, }, }; use crate::{event::ElementState, event_loop::DeviceEventFilter, platform_impl::platform::util}; #[allow(dead_code)] pub fn get_raw_input_device_list() -> Option<Vec<RAWINPUTDEVICELIST>> { let list_size = size_of::<RAWINPUTDEVICELIST>() as u32; let mut num_devices = 0; let status = unsafe { GetRawInputDeviceList(ptr::null_mut(), &mut num_devices, list_size) }; if status == u32::MAX { return None; } let mut buffer = Vec::with_capacity(num_devices as _); let num_stored = unsafe { GetRawInputDeviceList(buffer.as_mut_ptr(), &mut num_devices, list_size) }; if num_stored == u32::MAX { return None; } debug_assert_eq!(num_devices, num_stored); unsafe { buffer.set_len(num_devices as _) }; Some(buffer) } #[allow(dead_code)] pub enum RawDeviceInfo { Mouse(RID_DEVICE_INFO_MOUSE), Keyboard(RID_DEVICE_INFO_KEYBOARD), Hid(RID_DEVICE_INFO_HID), } impl From<RID_DEVICE_INFO> for RawDeviceInfo { fn from(info: RID_DEVICE_INFO) -> Self { unsafe { match info.dwType { RIM_TYPEMOUSE => RawDeviceInfo::Mouse(info.Anonymous.mouse), RIM_TYPEKEYBOARD => RawDeviceInfo::Keyboard(info.Anonymous.keyboard), RIM_TYPEHID => RawDeviceInfo::Hid(info.Anonymous.hid), _ => unreachable!(), } } } } #[allow(dead_code)] pub fn get_raw_input_device_info(handle: HANDLE) -> Option<RawDeviceInfo> { let mut info: RID_DEVICE_INFO = unsafe { mem::zeroed() }; let info_size = size_of::<RID_DEVICE_INFO>() as u32; info.cbSize = info_size; let mut minimum_size = 0; let status = unsafe { GetRawInputDeviceInfoW( handle, RIDI_DEVICEINFO, &mut info as *mut _ as _, &mut minimum_size, ) }; if status == u32::MAX || status == 0 { return None; } debug_assert_eq!(info_size, status); Some(info.into()) } pub fn get_raw_input_device_name(handle: HANDLE) -> Option<String> { let mut minimum_size = 0; let status = unsafe { GetRawInputDeviceInfoW(handle, RIDI_DEVICENAME, ptr::null_mut(), &mut minimum_size) }; if status != 0 { return None; } let mut name: Vec<u16> = Vec::with_capacity(minimum_size as _); let status = unsafe { GetRawInputDeviceInfoW( handle, RIDI_DEVICENAME, name.as_ptr() as _, &mut minimum_size, ) }; if status == u32::MAX || status == 0 { return None; } debug_assert_eq!(minimum_size, status); unsafe { name.set_len(minimum_size as _) }; util::decode_wide(&name).into_string().ok() } pub fn register_raw_input_devices(devices: &[RAWINPUTDEVICE]) -> bool { let device_size = size_of::<RAWINPUTDEVICE>() as u32; unsafe { RegisterRawInputDevices(devices.as_ptr(), devices.len() as u32, device_size) == true.into() } } pub fn register_all_mice_and_keyboards_for_raw_input( mut window_handle: HWND, filter: DeviceEventFilter, ) -> bool { // RIDEV_DEVNOTIFY: receive hotplug events // RIDEV_INPUTSINK: receive events even if we're not in the foreground // RIDEV_REMOVE: don't receive device events (requires NULL hwndTarget) let flags = match filter { DeviceEventFilter::Always => { window_handle = 0; RIDEV_REMOVE } DeviceEventFilter::Unfocused => RIDEV_DEVNOTIFY, DeviceEventFilter::Never => RIDEV_DEVNOTIFY | RIDEV_INPUTSINK, }; let devices: [RAWINPUTDEVICE; 2] = [ RAWINPUTDEVICE { usUsagePage: HID_USAGE_PAGE_GENERIC, usUsage: HID_USAGE_GENERIC_MOUSE, dwFlags: flags, hwndTarget: window_handle, }, RAWINPUTDEVICE { usUsagePage: HID_USAGE_PAGE_GENERIC, usUsage: HID_USAGE_GENERIC_KEYBOARD, dwFlags: flags, hwndTarget: window_handle, }, ]; register_raw_input_devices(&devices) } pub fn get_raw_input_data(handle: HRAWINPUT) -> Option<RAWINPUT> { let mut data: RAWINPUT = unsafe { mem::zeroed() }; let mut data_size = size_of::<RAWINPUT>() as u32; let header_size = size_of::<RAWINPUTHEADER>() as u32; let status = unsafe { GetRawInputData( handle, RID_INPUT, &mut data as *mut _ as _, &mut data_size, header_size, ) }; if status == u32::MAX || status == 0 { return None; } Some(data) } fn button_flags_to_element_state( button_flags: u32, down_flag: u32, up_flag: u32, ) -> Option<ElementState> { // We assume the same button won't be simultaneously pressed and released. if util::has_flag(button_flags, down_flag) { Some(ElementState::Pressed) } else if util::has_flag(button_flags, up_flag) { Some(ElementState::Released) } else { None } } pub fn get_raw_mouse_button_state(button_flags: u32) -> [Option<ElementState>; 3] { [ button_flags_to_element_state( button_flags, RI_MOUSE_LEFT_BUTTON_DOWN, RI_MOUSE_LEFT_BUTTON_UP, ), button_flags_to_element_state( button_flags, RI_MOUSE_MIDDLE_BUTTON_DOWN, RI_MOUSE_MIDDLE_BUTTON_UP, ), button_flags_to_element_state( button_flags, RI_MOUSE_RIGHT_BUTTON_DOWN, RI_MOUSE_RIGHT_BUTTON_UP, ), ] }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei