Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a safe method for cross-crate interop to winit #2744

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ And please only add new entries to the top of this list, right below the `# Unre
# Unreleased

- Bump MSRV from `1.60` to `1.64`.
- Implement the borrowed handle traits from the `raw-window-handle` crate.

# 0.28.3

Expand Down
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ wayland-dlopen = ["sctk/dlopen", "wayland-client/dlopen"]
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
android-native-activity = [ "android-activity/native-activity" ]
android-game-activity = [ "android-activity/game-activity" ]
android-native-activity = ["android-activity/native-activity"]
android-game-activity = ["android-activity/game-activity"]

[build-dependencies]
cfg_aliases = "0.1.1"
Expand All @@ -54,7 +54,7 @@ instant = { version = "0.1", features = ["wasm-bindgen"] }
log = "0.4"
mint = { version = "0.5.6", optional = true }
once_cell = "1.12"
raw_window_handle = { package = "raw-window-handle", version = "0.5" }
raw_window_handle = { package = "raw-window-handle", version = "0.5.2", features = ["std"] }
serde = { version = "1", optional = true, features = ["serde_derive"] }

[dev-dependencies]
Expand Down
47 changes: 47 additions & 0 deletions examples/borrowed_window.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//! Use borrowed window handles in `winit`.
notgull marked this conversation as resolved.
Show resolved Hide resolved

#![allow(clippy::single_match)]

use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::EventLoop,
window::WindowBuilder,
};

fn main() {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();

let window = WindowBuilder::new()
.with_title("A borrowed window!")
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
.build(&event_loop)
.unwrap();

event_loop.run(move |event, elwt, control_flow| {
control_flow.set_wait();
println!("{event:?}");

// Print the display handle.
println!("Display handle: {:?}", elwt.display_handle());

// Print the window handle.
match window.window_handle() {
Ok(handle) => println!("Window handle: {:?}", handle),
Err(_) => println!("Window handle: None"),
}

match event {
Event::WindowEvent {
event: WindowEvent::CloseRequested,
window_id,
} if window_id == window.id() => control_flow.set_exit(),
Event::MainEventsCleared => {
window.request_redraw();
}
_ => (),
}
});
}
118 changes: 117 additions & 1 deletion src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ use std::{error, fmt};

use instant::{Duration, Instant};
use once_cell::sync::OnceCell;
use raw_window_handle::{HasRawDisplayHandle, RawDisplayHandle};
use raw_window_handle::{
DisplayHandle, HandleError, HasDisplayHandle, HasRawDisplayHandle, RawDisplayHandle,
};

use crate::{event::Event, monitor::MonitorHandle, platform_impl};

Expand Down Expand Up @@ -48,6 +50,71 @@ pub struct EventLoopWindowTarget<T: 'static> {
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
}

/// Target that provides a handle to the display powering the event loop.
///
/// This type allows one to take advantage of the display's capabilities, such as
/// querying the display's resolution or DPI, without having to create a window. It
/// implements [`HasDisplayHandle`].
///
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can't query anything from it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the part about querying. "Capabilities" should be enough to describe what it can be used for.

/// The main reason why this type exists is to act as a persistent display handle
/// in cases where the [`Window`] type is not available. Let's say that your graphics
notgull marked this conversation as resolved.
Show resolved Hide resolved
/// framework has a type `Display<T>`, where `T` has to implement [`HasDisplayHandle`]
/// so that the graphics framework can query it for data and be sure that the display is
/// still alive. Also assume that `Display<T>` is somewhat expensive to construct, so
/// you cannot just create a new `Display<T>` every time you need to render.
/// Therefore, you need a *persistent* handle to the display to pass in as `T`. This
/// handle cannot be invalidated by the borrow checker during the lifetime of the
/// program; otherwise, you would have to drop the `Display<T>` and recreate it
/// every time you need to render, which would be very expensive.
///
/// The [`EventLoop`] type is either owned or borrowed mutably during event
/// handling. Therefore, neither [`EventLoop`], `&EventLoop` or a [`DisplayHandle`]
/// referencing an [`EventLoop`] can be used to provide a [`HasDisplayHandle`]
/// implementation. On the other hand, the [`EventLoopWindowTarget`] type disappears
/// between events so it can't be used as a persistent handle either. In certain
/// cases, you can use a [`Window`]; however, for certain graphics APIs (like OpenGL)
/// you need to be able to query the display before creating a window. In this case,
/// you end up with a "chicken and egg" problem; you need a display handle to create
/// a window, but you need a window to access the display handle.
///
/// ![A chicken](https://i.imgur.com/9a5K2nz.jpg)
///
/// <sub>Figure 1: A chicken, representing the window in the above metaphor. Note that
/// there are no eggs. "[Chicken February 2009-1]" by [Joaquim Alves Gaspar] is licensed
/// under [CC BY-SA 3.0].</sub>
notgull marked this conversation as resolved.
Show resolved Hide resolved
///
/// The `OwnedDisplayHandle` type breaks this cycle by providing a persistent handle
notgull marked this conversation as resolved.
Show resolved Hide resolved
/// to the display. It is not tied to any lifetime constraints, so it can't be
/// invalidated during event handling. It is also cheaply clonable, so you can
/// more easily pass it around to other parts of your program. Therefore, it can
/// be passed in as `T` to your graphics framework's `Display<T>` type without
/// worrying about the borrow checker.
///
/// To create an `OwnedDisplayHandle`, use the [`EventLoopWindowTarget::owned_display_handle`]
/// method.
///
/// ## Safety
///
/// The [`DisplayHandle`] returned by the `OwnedDisplayHandle` type is guaranteed to
/// remain valid as long as the `OwnedDisplayHandle` is alive. The internal display
/// handle is not immediately closed by the [`EventLoop`] being dropped as long as
/// the `OwnedDisplayHandle` is still alive. On all platforms, the underlying display
/// is either ref-counted or a ZST, so this is safe.
///
/// [Chicken February 2009-1]: https://commons.wikimedia.org/wiki/File:Chicken_February_2009-1.jpg
/// [Joaquim Alves Gaspar]: https://commons.wikimedia.org/wiki/User:Alvesgaspar
/// [CC BY-SA 3.0]: https://creativecommons.org/licenses/by-sa/3.0
/// [`EventLoop`]: EventLoop
/// [`Window`]: crate::window::Window
/// [`DisplayHandle`]: raw_window_handle::DisplayHandle
/// [`EventLoopWindowTarget`]: EventLoopWindowTarget
/// [`HasDisplayHandle`]: raw_window_handle::HasDisplayHandle
#[derive(Clone)]
pub struct OwnedDisplayHandle {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really understand the purpose of this type. The EventLoop itself is what should have the HasDisplayHandle impl, and its lifetime is what should be used. The fact that you're not using this type in examples at all suggests me that there's no clear case when it should be used(at least you should use it inside the examples).

The EventLoopWindowTarget must have the same lifetime as the EventLoop itself, because it's simply a field on EventLoop in all the backends.

The Clone is also sort of questionable, because it simply will discard the lifetime attached to it, given that there's only a way to get &OwnedDisplayHandle not the owned type on its own?

if that's intent on lifetime casting, different method should be used with unsafe bit on it(because it's simply mem::tranmsute like thingy of donig 'static lifetime).

Copy link
Member Author

@notgull notgull Apr 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason why this type exists is for the glutin case. The scenario is that you need an object that has a display handle before a window is created, since you need to query the display. You can't use EventLoop, &EventLoop or a DisplayHandle<'_> taken from an EventLoop because the EventLoop is owned/borrowed mutably for event handling. You can't use the EventLoopWindowTarget that is provided in the event handler, since it disappears between events, which means it can't be used persistently. Normally I'd use a Window, but for glutin (outside of Win32) you haven't created a Window yet.

Therefore I created this type to fill that hole. Something that implements HasDisplayHandle that can be used according to Rust's borrowing system. This way, it can be used in the display position without any unsafe hacks.

If the Clone is a deal breaker I can get rid of it. actually, it might be necessary for the borrowing rules to check out in this case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually, it might be necessary for the borrowing rules to check out in this case.

I just think that it's unsafe, so you might have different method like to_static, which casts away lifetime.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added documentation clarifying the purpose of OwnedWindowHandle and why it is safe.

pub(crate) p: platform_impl::OwnedDisplayHandle,
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
notgull marked this conversation as resolved.
Show resolved Hide resolved
}

/// Object that allows building the event loop.
///
/// This is used to make specifying options that affect the whole application
Expand Down Expand Up @@ -320,6 +387,12 @@ unsafe impl<T> HasRawDisplayHandle for EventLoop<T> {
}
}

impl<T> HasDisplayHandle for EventLoop<T> {
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
self.event_loop.window_target().display_handle()
}
}

impl<T> Deref for EventLoop<T> {
type Target = EventLoopWindowTarget<T>;
fn deref(&self) -> &EventLoopWindowTarget<T> {
Expand Down Expand Up @@ -367,6 +440,28 @@ impl<T> EventLoopWindowTarget<T> {
#[cfg(any(x11_platform, wayland_platform, windows))]
self.p.set_device_event_filter(_filter);
}

/// Get an owned handle to the current display.
///
/// This handle can be cheaply cloned and used, allowing one to fulfill the [`HasDisplayHandle`]
/// trait bound.
///
/// For more information, see documentation for [`OwnedDisplayHandle`] and the
/// [`HasDisplayHandle`] trait.
///
/// ## Example
///
/// ```no_run
/// use winit::event_loop::EventLoop;
///
/// let event_loop = EventLoop::new();
/// let display_handle = event_loop.owned_display_handle();
/// ```
///
/// [`HasDisplayHandle`]: raw_window_handle::HasDisplayHandle
pub fn owned_display_handle(&self) -> &OwnedDisplayHandle {
self.p.owned_display_handle()
}
}

unsafe impl<T> HasRawDisplayHandle for EventLoopWindowTarget<T> {
Expand All @@ -376,6 +471,27 @@ unsafe impl<T> HasRawDisplayHandle for EventLoopWindowTarget<T> {
}
}

impl<T> HasDisplayHandle for EventLoopWindowTarget<T> {
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
// SAFETY: The display handle is valid for as long as the window target is.
Ok(unsafe { DisplayHandle::borrow_raw(self.raw_display_handle()) })
}
}

unsafe impl HasRawDisplayHandle for OwnedDisplayHandle {
/// Returns a [`raw_window_handle::RawDisplayHandle`] for the event loop.
fn raw_display_handle(&self) -> RawDisplayHandle {
self.p.raw_display_handle()
}
}

impl HasDisplayHandle for OwnedDisplayHandle {
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
// SAFETY: The display handle is valid for as long as the window target is.
Ok(unsafe { DisplayHandle::borrow_raw(self.raw_display_handle()) })
}
}

/// Used to send custom events to [`EventLoop`].
pub struct EventLoopProxy<T: 'static> {
event_loop_proxy: platform_impl::EventLoopProxy<T>,
Expand Down
33 changes: 32 additions & 1 deletion src/platform_impl/android/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use android_activity::{
};
use once_cell::sync::Lazy;
use raw_window_handle::{
AndroidDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle,
Active, AndroidDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle,
};

use crate::platform_impl::Fullscreen;
Expand Down Expand Up @@ -340,6 +340,7 @@ impl<T: 'static> EventLoop<T> {
&redraw_flag,
android_app.create_waker(),
),
active: Arc::new(Active::new()),
_marker: std::marker::PhantomData,
},
_marker: std::marker::PhantomData,
Expand Down Expand Up @@ -378,6 +379,11 @@ impl<T: 'static> EventLoop<T> {

match event {
MainEvent::InitWindow { .. } => {
// SAFETY: The window is now active.
unsafe {
self.window_target.p.active.set_active();
}

sticky_exit_callback(
event::Event::Resumed,
self.window_target(),
Expand All @@ -392,6 +398,8 @@ impl<T: 'static> EventLoop<T> {
control_flow,
callback,
);

self.window_target.p.active.set_inactive();
}
MainEvent::WindowResized { .. } => resized = true,
MainEvent::RedrawNeeded { .. } => *pending_redraw = true,
Expand Down Expand Up @@ -821,6 +829,7 @@ impl<T> EventLoopProxy<T> {
pub struct EventLoopWindowTarget<T: 'static> {
app: AndroidApp,
redraw_requester: RedrawRequester,
active: Arc<Active>,
_marker: std::marker::PhantomData<T>,
}

Expand All @@ -838,6 +847,22 @@ impl<T: 'static> EventLoopWindowTarget<T> {
pub fn raw_display_handle(&self) -> RawDisplayHandle {
RawDisplayHandle::Android(AndroidDisplayHandle::empty())
}

pub fn owned_display_handle(&self) -> &event_loop::OwnedDisplayHandle {
&event_loop::OwnedDisplayHandle {
p: OwnedDisplayHandle,
_marker: std::marker::PhantomData,
}
}
}

#[derive(Clone)]
pub struct OwnedDisplayHandle;

impl OwnedDisplayHandle {
pub fn raw_display_handle(&self) -> RawDisplayHandle {
RawDisplayHandle::Android(AndroidDisplayHandle::empty())
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
Expand Down Expand Up @@ -876,6 +901,7 @@ pub struct PlatformSpecificWindowBuilderAttributes;
pub(crate) struct Window {
app: AndroidApp,
redraw_requester: RedrawRequester,
active: Arc<Active>,
}

impl Window {
Expand All @@ -889,6 +915,7 @@ impl Window {
Ok(Self {
app: el.app.clone(),
redraw_requester: el.redraw_requester.clone(),
active: el.active.clone(),
})
}

Expand Down Expand Up @@ -1084,6 +1111,10 @@ impl Window {
pub fn title(&self) -> String {
String::new()
}

pub(crate) fn active(&self) -> &Active {
&self.active
}
}

#[derive(Default, Clone, Debug)]
Expand Down
16 changes: 16 additions & 0 deletions src/platform_impl/ios/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,22 @@ impl<T: 'static> EventLoopWindowTarget<T> {
pub fn raw_display_handle(&self) -> RawDisplayHandle {
RawDisplayHandle::UiKit(UiKitDisplayHandle::empty())
}

pub fn owned_display_handle(&self) -> &crate::event_loop::OwnedDisplayHandle {
&crate::event_loop::OwnedDisplayHandle {
p: OwnedDisplayHandle,
_marker: PhantomData,
}
}
}

#[derive(Clone)]
pub struct OwnedDisplayHandle;

impl OwnedDisplayHandle {
pub fn raw_display_handle(&self) -> RawDisplayHandle {
RawDisplayHandle::UiKit(UiKitDisplayHandle::empty())
}
}

pub struct EventLoop<T: 'static> {
Expand Down
3 changes: 2 additions & 1 deletion src/platform_impl/ios/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ use std::fmt;

pub(crate) use self::{
event_loop::{
EventLoop, EventLoopProxy, EventLoopWindowTarget, PlatformSpecificEventLoopAttributes,
EventLoop, EventLoopProxy, EventLoopWindowTarget, OwnedDisplayHandle,
PlatformSpecificEventLoopAttributes,
},
monitor::{MonitorHandle, VideoMode},
window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId},
Expand Down
23 changes: 23 additions & 0 deletions src/platform_impl/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,14 @@ pub enum EventLoopProxy<T: 'static> {
Wayland(wayland::EventLoopProxy<T>),
}

#[derive(Clone)]
pub enum OwnedDisplayHandle {
#[cfg(x11_platform)]
X(x11::OwnedDisplayHandle),
#[cfg(wayland_platform)]
Wayland(wayland::OwnedDisplayHandle),
}

impl<T: 'static> Clone for EventLoopProxy<T> {
fn clone(&self) -> Self {
x11_or_wayland!(match self; EventLoopProxy(proxy) => proxy.clone(); as EventLoopProxy)
Expand Down Expand Up @@ -866,6 +874,21 @@ impl<T> EventLoopWindowTarget<T> {
pub fn raw_display_handle(&self) -> raw_window_handle::RawDisplayHandle {
x11_or_wayland!(match self; Self(evlp) => evlp.raw_display_handle())
}

pub fn owned_display_handle(&self) -> &crate::event_loop::OwnedDisplayHandle {
match self {
#[cfg(wayland_platform)]
EventLoopWindowTarget::Wayland(evlp) => evlp.owned_display_handle(),
#[cfg(x11_platform)]
EventLoopWindowTarget::X(evlp) => evlp.owned_display_handle(),
}
}
}

impl OwnedDisplayHandle {
pub fn raw_display_handle(&self) -> raw_window_handle::RawDisplayHandle {
x11_or_wayland!(match self; Self(evlp) => evlp.raw_display_handle())
}
}

fn sticky_exit_callback<T, F>(
Expand Down
Loading