Skip to content
Merged
7 changes: 6 additions & 1 deletion winit-core/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,12 @@ impl WindowAttributes {
/// to the client area of its parent window. For more information, see
/// <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
/// - **X11**: A child window is confined to the client area of its parent window.
/// - **Android / iOS / Wayland / Web:** Unsupported.
/// - **Wayland:** The parent must be a window created by the same event loop. The child is
/// attached to it with `xdg_toplevel.set_parent`; where it is placed is up to the compositor.
/// When the parent is closed, its children are closed as well and receive
/// [`WindowEvent::Destroyed`]. They stay visible until the application drops them, and so
/// does the parent, which is only destroyed once all its children have been dropped.
/// - **Android / iOS / Web:** Unsupported.
#[inline]
pub unsafe fn with_parent_window(
mut self,
Expand Down
19 changes: 17 additions & 2 deletions winit-wayland/src/event_loop/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,13 @@ impl EventLoop {

for mut compositor_update in compositor_updates.drain(..) {
let window_id = compositor_update.window_id;

// Never send events for a window the event loop no longer manages: it already got
// `Destroyed`, and the lookups below expect the window to be present.
if !self.with_state(|state| state.windows.get_mut().contains_key(&window_id)) {
continue;
}

if compositor_update.scale_changed {
let (physical_size, scale_factor) = self.with_state(|state| {
let windows = state.windows.get_mut();
Expand Down Expand Up @@ -449,7 +456,11 @@ impl EventLoop {
for event in buffer_sink.drain() {
match event {
Event::WindowEvent { window_id, event } => {
app.window_event(&self.active_event_loop, window_id, event)
// Never send events for a window the event loop no longer manages: it
// already got `Destroyed`, or its creation failed.
if self.with_state(|state| state.windows.get_mut().contains_key(&window_id)) {
app.window_event(&self.active_event_loop, window_id, event)
}
},
Event::DeviceEvent { event } => {
app.device_event(&self.active_event_loop, None, event)
Expand All @@ -464,7 +475,11 @@ impl EventLoop {
for event in buffer_sink.drain() {
match event {
Event::WindowEvent { window_id, event } => {
app.window_event(&self.active_event_loop, window_id, event)
// Never send events for a window the event loop no longer manages: it
// already got `Destroyed`, or its creation failed.
if self.with_state(|state| state.windows.get_mut().contains_key(&window_id)) {
app.window_event(&self.active_event_loop, window_id, event)
}
},
Event::DeviceEvent { event } => {
app.device_event(&self.active_event_loop, None, event)
Expand Down
92 changes: 22 additions & 70 deletions winit-wayland/src/popup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::sync::{Arc, Mutex};
use dpi::{
LogicalPosition, LogicalSize, PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size,
};
use rwh_06::RawWindowHandle;
use sctk::shell::WaylandSurface;
use sctk::shell::xdg::popup::Popup as SctkPopup;
use sctk::shell::xdg::{XdgPositioner, XdgSurface};
Expand All @@ -21,10 +20,9 @@ use winit_core::window::{

use super::ActiveEventLoop;
use crate::WindowAttributesWayland;
use crate::window::Handles;
use crate::window::common::WindowCommon;
use crate::window::handles::WindowRequests;
use crate::window::state::{WindowState, WindowType};
use crate::window::state::{WindowParent, WindowState, WindowType};
use crate::window::{Handles, finish_window_setup};

#[derive(Debug)]
pub struct Popup {
Expand All @@ -36,24 +34,15 @@ impl Popup {
event_loop_window_target: &ActiveEventLoop,
mut attributes: WindowAttributes,
) -> Result<Self, CreateWindowError> {
let parent_window_handle = attributes
.parent_window()
.ok_or(InvalidInput::new("Popup without a parent is not supported"))?;
let RawWindowHandle::Wayland(parent_window_handle) = parent_window_handle else {
return Err(InvalidInput::new("A Popup requires a parent wayland window handle").into());
};

let queue_handle = event_loop_window_target.queue_handle.clone();
let mut state = event_loop_window_target.state.borrow_mut();
let parent = WindowParent::from_attributes(&state, &attributes)?
.ok_or(InvalidInput::new("Popup without a parent is not supported"))?;
let parent_state = parent.state.clone();
let monitors = state.monitors.clone();
let xdg_activation =
state.xdg_activation.as_ref().map(|activation_state| activation_state.global().clone());
let xdg_positioner = XdgPositioner::new(&state.xdg_shell).map_err(|e| os_error!(e))?;
let parent_window_id = WindowId::from_raw(parent_window_handle.surface.as_ptr() as usize);
let window_states = state.windows.borrow();
let Some(parent_window_state) = window_states.get(&parent_window_id) else {
return Err(InvalidInput::new("Unknown parent window id").into());
};

let WindowPositioner {
anchor,
Expand All @@ -65,7 +54,7 @@ impl Popup {
} = attributes.positioner.unwrap_or_default();
let grab_keyboard = attributes.active;

let mut parent_window_state = parent_window_state.lock().unwrap();
let parent_window_state = parent_state.lock().unwrap();

// Use the scale factor and xdg geometry of the parent.
let scale_factor = parent_window_state.scale_factor();
Expand Down Expand Up @@ -131,9 +120,7 @@ impl Popup {
&state.xdg_shell,
)
.map_err(|e| os_error!(e))?;
parent_window_state.add_child(super::make_wid(popup.wl_surface()));
drop(parent_window_state);
drop(window_states);

let mut popup_state = WindowState::new(
event_loop_window_target,
Expand All @@ -155,7 +142,7 @@ impl Popup {
attributes.preferred_theme,
false,
scale_factor,
Some(parent_window_id),
Some(parent),
);

// Set transparency hint.
Expand Down Expand Up @@ -199,48 +186,24 @@ impl Popup {

let popup_state = Arc::new(Mutex::new(popup_state));

let window_id = super::make_wid(popup.wl_surface());
state.windows.get_mut().insert(window_id, popup_state.clone());

let window_requests = WindowRequests {
redraw_requested: AtomicBool::new(true),
closed: AtomicBool::new(false),
};
let window_requests = Arc::new(window_requests);
state.window_requests.get_mut().insert(window_id, window_requests.clone());

// Setup the event sync to insert `WindowEvents` right from the window.
let window_events_sink = state.window_events_sink.clone();

let mut wayland_source = event_loop_window_target.wayland_dispatcher.as_source_mut();
let event_queue = wayland_source.queue();
// Do a roundtrip.
event_queue.roundtrip(&mut state).map_err(|err| os_error!(err))?;

// XXX Wait for the initial configure to arrive.
while !popup_state.lock().unwrap().is_configured() {
event_queue.blocking_dispatch(&mut state).map_err(|err| os_error!(err))?;
// The compositor may dismiss a popup (e.g. invalid grab serial) by sending
// popup_done before configure. Detect that and bail out instead of looping forever.
if state
.window_compositor_updates
.iter()
.any(|u| u.window_id == window_id && u.close_window)
{
return Err(os_error!(PopupError(
"Popup was dismissed by the compositor before configure"
))
.into());
}
}
let (window_id, window_requests) = finish_window_setup(
event_loop_window_target,
&mut state,
popup.wl_surface(),
&popup_state,
Some("Popup was dismissed by the compositor before configure"),
)?;

// Wake-up event loop, so it'll send initial redraw requested.
let event_loop_awakener = event_loop_window_target.event_loop_awakener.clone();
event_loop_awakener.ping();

parent_state.lock().unwrap().add_child(window_id);

Ok(Self {
common: WindowCommon {
state: Arc::downgrade(&popup_state),
state: popup_state,
window_id,
display: event_loop_window_target.handle.connection.display().clone(),
handles: Handles {
Expand All @@ -266,20 +229,15 @@ impl CoreWindow for Popup {
}

fn positioner(&self) -> WindowPositioner {
let Some(state) = self.common.state.upgrade() else { return WindowPositioner::default() };
if let WindowType::Popup { positioner, .. } = &state.lock().unwrap().window {
if let WindowType::Popup { positioner, .. } = &self.common.state.lock().unwrap().window {
*positioner
} else {
WindowPositioner::default()
}
}

fn set_positioner(&self, new_positioner: WindowPositioner) {
let Some(state) = self.common.state.upgrade() else {
return;
};

let mut state = state.lock().unwrap();
let mut state = self.common.state.lock().unwrap();
let scale_factor = state.scale_factor();

if let WindowType::Popup { popup, xdg_positioner, parent_origin, positioner, .. } =
Expand Down Expand Up @@ -341,12 +299,7 @@ impl CoreWindow for Popup {
}

fn outer_position(&self) -> Result<PhysicalPosition<i32>, RequestError> {
let s = self
.common
.state
.upgrade()
.ok_or_else(|| os_error!(PopupError("the popup has been destroyed")))?;
let state = s.lock().unwrap();
let state = self.common.state.lock().unwrap();
if let WindowType::Popup { last_configure: Some(configure), .. } = &state.window {
let (x, y) = configure.position;
return Ok(LogicalPosition::new(x, y).to_physical(state.scale_factor()));
Expand All @@ -355,8 +308,7 @@ impl CoreWindow for Popup {
}

fn set_outer_position(&self, position: Position) {
let Some(s) = self.common.state.upgrade() else { return };
let mut state = s.lock().unwrap();
let mut state = self.common.state.lock().unwrap();
let scale_factor = state.scale_factor();
if let WindowType::Popup { popup, xdg_positioner, positioner, parent_origin, .. } =
&mut state.window
Expand Down Expand Up @@ -652,7 +604,7 @@ fn from_constraint_adjustment(
ConstraintAdjustment::from_bits_retain(value.bits())
}

/// Constructing a popup failed: dismissed by OS
/// A request on a popup failed because the popup is gone or not yet configured.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct PopupError(&'static str);

Expand Down
93 changes: 51 additions & 42 deletions winit-wayland/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,30 +300,13 @@ impl WinitState {

updates[pos].close_window = true;
}
}

impl ShmHandler for WinitState {
fn shm_state(&mut self) -> &mut Shm {
&mut self.shm
}
}

impl WindowHandler for WinitState {
fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, window: &Window) {
let window_id = super::make_wid(window.wl_surface());
Self::queue_close(&mut self.window_compositor_updates, window_id);
}

fn configure(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
window: &Window,
configure: WindowConfigure,
_serial: u32,
) {
let window_id = super::make_wid(window.wl_surface());

/// Handle an `xdg_toplevel` configure event
fn configure_xdg_toplevel(&mut self, window_id: WindowId, configure: WindowConfigure) {
let Some(window) = self.windows.get_mut().get_mut(&window_id) else {
tracing::debug!("got configure for dead window {window_id:?}, ignoring it");
return;
};
let index = if let Some(index) =
self.window_compositor_updates.iter().position(|update| update.window_id == window_id)
{
Expand All @@ -334,17 +317,13 @@ impl WindowHandler for WinitState {
};

// Populate the configure to the window.
self.window_compositor_updates[index].resized |= self
.windows
.get_mut()
.get_mut(&window_id)
.expect("got configure for dead window.")
self.window_compositor_updates[index].resized |= window
.lock()
.unwrap()
.configure_window(configure, &self.shm, &self.subcompositor_state);
.configure_xdg_toplevel(configure, &self.shm, &self.subcompositor_state);

// NOTE: configure demands wl_surface::commit, however winit doesn't commit on behalf of the
// users, since it can break a lot of things, thus it'll ask users to redraw instead.
// NOTE: configure demands wl_surface::commit, however winit doesn't commit on behalf of
// the users, since it can break a lot of things, thus it'll ask users to redraw instead.
self.window_requests
.get_mut()
.get(&window_id)
Expand All @@ -357,6 +336,35 @@ impl WindowHandler for WinitState {
}
}

impl ShmHandler for WinitState {
fn shm_state(&mut self) -> &mut Shm {
&mut self.shm
}
}

impl WindowHandler for WinitState {
fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, window: &Window) {
let window_id = super::make_wid(window.wl_surface());
if !self.windows.get_mut().contains_key(&window_id) {
tracing::debug!("got close request for dead window {window_id:?}, ignoring it");
return;
}
Self::queue_close(&mut self.window_compositor_updates, window_id);
}

fn configure(
&mut self,
_: &Connection,
_: &QueueHandle<Self>,
window: &Window,
configure: WindowConfigure,
_serial: u32,
) {
let window_id = super::make_wid(window.wl_surface());
self.configure_xdg_toplevel(window_id, configure);
}
}

impl PopupHandler for WinitState {
fn configure(
&mut self,
Expand All @@ -366,6 +374,10 @@ impl PopupHandler for WinitState {
configure: PopupConfigure,
) {
let window_id = super::make_wid(popup.wl_surface());
let Some(window) = self.windows.get_mut().get_mut(&window_id) else {
tracing::debug!("got configure for dead window {window_id:?}, ignoring it");
return;
};

let index = if let Some(index) =
self.window_compositor_updates.iter().position(|update| update.window_id == window_id)
Expand All @@ -376,14 +388,8 @@ impl PopupHandler for WinitState {
self.window_compositor_updates.len() - 1
};

self.window_compositor_updates[index].resized |= self
.windows
.get_mut()
.get_mut(&window_id)
.expect("got configure for dead window.")
.lock()
.unwrap()
.configure_popup(configure);
self.window_compositor_updates[index].resized |=
window.lock().unwrap().configure_popup(configure);

// NOTE: configure demands wl_surface::commit, however winit doesn't commit on behalf of the
// users, since it can break a lot of things, thus it'll ask users to redraw instead
Expand All @@ -400,9 +406,12 @@ impl PopupHandler for WinitState {

fn done(&mut self, _: &Connection, _: &QueueHandle<Self>, popup: &XdgPopup) {
let window_id = super::make_wid(popup.wl_surface());
let window_requests = self.window_requests.get_mut().iter().find(|r| *r.0 == window_id);
if let Some(window_requests) = window_requests {
window_requests.1.closed.store(true, Ordering::Relaxed);
if !self.windows.get_mut().contains_key(&window_id) {
tracing::debug!("got popup_done for dead popup {window_id:?}, ignoring it");
return;
}
if let Some(window_requests) = self.window_requests.get_mut().get(&window_id) {
window_requests.closed.store(true, Ordering::Relaxed);
}
Self::queue_close(&mut self.window_compositor_updates, window_id);
}
Expand Down
Loading
Loading