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 8 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();
}
_ => (),
}
});
}
50 changes: 49 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,17 @@ 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`.
#[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 +333,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 +386,14 @@ 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.
pub fn owned_display_handle(&self) -> &OwnedDisplayHandle {
self.p.owned_display_handle()
}
}

unsafe impl<T> HasRawDisplayHandle for EventLoopWindowTarget<T> {
Expand All @@ -376,6 +403,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
31 changes: 30 additions & 1 deletion src/platform_impl/linux/wayland/event_loop/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ use sctk::WaylandSource;

use crate::dpi::{LogicalSize, PhysicalSize};
use crate::event::{Event, StartCause, WindowEvent};
use crate::event_loop::{ControlFlow, EventLoopWindowTarget as RootEventLoopWindowTarget};
use crate::event_loop::{
ControlFlow, EventLoopWindowTarget as RootEventLoopWindowTarget,
OwnedDisplayHandle as RootOwnedDisplayHandle,
};
use crate::platform_impl::platform::sticky_exit_callback;
use crate::platform_impl::EventLoopWindowTarget as PlatformEventLoopWindowTarget;

Expand All @@ -45,6 +48,9 @@ pub struct EventLoopWindowTarget<T> {
/// Wayland display.
pub display: Display,

/// Display handle.
pub display_handle: RootOwnedDisplayHandle,

/// Environment to handle object creation, etc.
pub env: Environment<WinitEnv>,

Expand Down Expand Up @@ -81,6 +87,10 @@ impl<T> EventLoopWindowTarget<T> {
display_handle.display = self.display.get_display_ptr() as *mut _;
RawDisplayHandle::Wayland(display_handle)
}

pub fn owned_display_handle(&self) -> &RootOwnedDisplayHandle {
&self.display_handle
}
}

pub struct EventLoop<T: 'static> {
Expand Down Expand Up @@ -183,6 +193,12 @@ impl<T: 'static> EventLoop<T> {
// Create event loop window target.
let event_loop_window_target = EventLoopWindowTarget {
display: display.clone(),
display_handle: RootOwnedDisplayHandle {
p: super::super::OwnedDisplayHandle::Wayland(OwnedDisplayHandle {
display: display.clone(),
}),
_marker: std::marker::PhantomData,
},
env,
state: RefCell::new(WinitState {
window_map,
Expand Down Expand Up @@ -601,6 +617,19 @@ impl<T: 'static> EventLoop<T> {
}
}

#[derive(Clone)]
pub struct OwnedDisplayHandle {
display: Display,
}

impl OwnedDisplayHandle {
pub fn raw_display_handle(&self) -> RawDisplayHandle {
let mut display_handle = WaylandDisplayHandle::empty();
display_handle.display = self.display.get_display_ptr() as *mut _;
RawDisplayHandle::Wayland(display_handle)
notgull marked this conversation as resolved.
Show resolved Hide resolved
}
}

// The default routine does floor, but we need round on Wayland.
fn logical_to_physical_rounded(size: LogicalSize<u32>, scale_factor: f64) -> PhysicalSize<u32> {
let width = size.width as f64 * scale_factor;
Expand Down
Loading