Merge pull request #156 from YaLTeR/resize

anvil: implement the Resize request
This commit is contained in:
Victor Berger 2020-02-12 22:57:32 +01:00 committed by GitHub
commit a60e1cd7fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 612 additions and 103 deletions

View File

@ -14,6 +14,7 @@ rand = "0.6"
glium = { version = "0.23.0", default-features = false } glium = { version = "0.23.0", default-features = false }
wayland-server = "0.23" wayland-server = "0.23"
xkbcommon = "0.4.0" xkbcommon = "0.4.0"
bitflags = "1.2.1"
[dependencies.smithay] [dependencies.smithay]
path = ".." path = ".."

View File

@ -4,12 +4,16 @@ use std::{
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
use bitflags::bitflags;
use rand; use rand;
use smithay::{ use smithay::{
reexports::wayland_server::{ reexports::{
protocol::{wl_buffer, wl_pointer::ButtonState, wl_shell_surface, wl_surface}, wayland_protocols::xdg_shell::server::xdg_toplevel,
Display, wayland_server::{
protocol::{wl_buffer, wl_pointer::ButtonState, wl_shell_surface, wl_surface},
Display,
},
}, },
utils::Rectangle, utils::Rectangle,
wayland::{ wayland::{
@ -22,7 +26,7 @@ use smithay::{
}, },
xdg::{ xdg::{
xdg_shell_init, PopupConfigure, ShellState as XdgShellState, ToplevelConfigure, XdgRequest, xdg_shell_init, PopupConfigure, ShellState as XdgShellState, ToplevelConfigure, XdgRequest,
XdgSurfaceRole, XdgSurfacePendingState, XdgSurfaceRole,
}, },
}, },
SERIAL_COUNTER as SCOUNTER, SERIAL_COUNTER as SCOUNTER,
@ -41,11 +45,7 @@ define_roles!(Roles =>
[ CursorImage, CursorImageRole ] [ CursorImage, CursorImageRole ]
); );
pub type MyWindowMap = WindowMap< pub type MyWindowMap = WindowMap<Roles>;
Roles,
fn(&SurfaceAttributes) -> Option<(i32, i32)>,
fn(&SurfaceAttributes, (f64, f64)) -> bool,
>;
pub type MyCompositorToken = CompositorToken<Roles>; pub type MyCompositorToken = CompositorToken<Roles>;
@ -99,6 +99,182 @@ impl PointerGrab for MoveSurfaceGrab {
} }
} }
bitflags! {
struct ResizeEdge: u32 {
const NONE = 0;
const TOP = 1;
const BOTTOM = 2;
const LEFT = 4;
const TOP_LEFT = 5;
const BOTTOM_LEFT = 6;
const RIGHT = 8;
const TOP_RIGHT = 9;
const BOTTOM_RIGHT = 10;
}
}
impl From<wl_shell_surface::Resize> for ResizeEdge {
#[inline]
fn from(x: wl_shell_surface::Resize) -> Self {
Self::from_bits(x.bits()).unwrap()
}
}
impl From<ResizeEdge> for wl_shell_surface::Resize {
#[inline]
fn from(x: ResizeEdge) -> Self {
Self::from_bits(x.bits()).unwrap()
}
}
impl From<xdg_toplevel::ResizeEdge> for ResizeEdge {
#[inline]
fn from(x: xdg_toplevel::ResizeEdge) -> Self {
Self::from_bits(x.to_raw()).unwrap()
}
}
impl From<ResizeEdge> for xdg_toplevel::ResizeEdge {
#[inline]
fn from(x: ResizeEdge) -> Self {
Self::from_raw(x.bits()).unwrap()
}
}
struct ResizeSurfaceGrab {
start_data: GrabStartData,
ctoken: MyCompositorToken,
toplevel: SurfaceKind<Roles>,
edges: ResizeEdge,
initial_window_size: (i32, i32),
last_window_size: (i32, i32),
}
impl PointerGrab for ResizeSurfaceGrab {
fn motion(
&mut self,
_handle: &mut PointerInnerHandle<'_>,
location: (f64, f64),
_focus: Option<(wl_surface::WlSurface, (f64, f64))>,
serial: u32,
_time: u32,
) {
let mut dx = location.0 - self.start_data.location.0;
let mut dy = location.1 - self.start_data.location.1;
let mut new_window_width = self.initial_window_size.0;
let mut new_window_height = self.initial_window_size.1;
let left_right = ResizeEdge::LEFT | ResizeEdge::RIGHT;
let top_bottom = ResizeEdge::TOP | ResizeEdge::BOTTOM;
if self.edges.intersects(left_right) {
if self.edges.intersects(ResizeEdge::LEFT) {
dx = -dx;
}
new_window_width = (self.initial_window_size.0 as f64 + dx) as i32;
}
if self.edges.intersects(top_bottom) {
if self.edges.intersects(ResizeEdge::TOP) {
dy = -dy;
}
new_window_height = (self.initial_window_size.1 as f64 + dy) as i32;
}
let (min_size, max_size) =
self.ctoken
.with_surface_data(self.toplevel.get_surface().unwrap(), |attrs| {
let data = attrs.user_data.get::<SurfaceData>().unwrap();
(data.min_size, data.max_size)
});
let min_width = min_size.0.max(1);
let min_height = min_size.1.max(1);
let max_width = if max_size.0 == 0 {
i32::max_value()
} else {
max_size.0
};
let max_height = if max_size.1 == 0 {
i32::max_value()
} else {
max_size.1
};
new_window_width = new_window_width.max(min_width).min(max_width);
new_window_height = new_window_height.max(min_height).min(max_height);
self.last_window_size = (new_window_width, new_window_height);
match &self.toplevel {
SurfaceKind::Xdg(xdg) => xdg.send_configure(ToplevelConfigure {
size: Some(self.last_window_size),
states: vec![xdg_toplevel::State::Resizing],
serial,
}),
SurfaceKind::Wl(wl) => wl.send_configure(
(self.last_window_size.0 as u32, self.last_window_size.1 as u32),
self.edges.into(),
),
}
}
fn button(
&mut self,
handle: &mut PointerInnerHandle<'_>,
button: u32,
state: ButtonState,
serial: u32,
time: u32,
) {
handle.button(button, state, serial, time);
if handle.current_pressed().is_empty() {
// No more buttons are pressed, release the grab.
handle.unset_grab(serial, time);
if let SurfaceKind::Xdg(xdg) = &self.toplevel {
// Send the final configure without the resizing state.
xdg.send_configure(ToplevelConfigure {
size: Some(self.last_window_size),
states: vec![],
serial,
});
self.ctoken
.with_surface_data(self.toplevel.get_surface().unwrap(), |attrs| {
let data = attrs.user_data.get_mut::<SurfaceData>().unwrap();
if let ResizeState::Resizing(resize_data) = data.resize_state {
data.resize_state = ResizeState::WaitingForFinalAck(resize_data, serial);
} else {
panic!("invalid resize state: {:?}", data.resize_state);
}
});
} else {
self.ctoken
.with_surface_data(self.toplevel.get_surface().unwrap(), |attrs| {
let data = attrs.user_data.get_mut::<SurfaceData>().unwrap();
if let ResizeState::Resizing(resize_data) = data.resize_state {
data.resize_state = ResizeState::WaitingForCommit(resize_data);
} else {
panic!("invalid resize state: {:?}", data.resize_state);
}
});
}
}
}
fn axis(&mut self, handle: &mut PointerInnerHandle<'_>, details: AxisFrame) {
handle.axis(details)
}
fn start_data(&self) -> &GrabStartData {
&self.start_data
}
}
pub fn init_shell( pub fn init_shell(
display: &mut Display, display: &mut Display,
buffer_utils: BufferUtils, buffer_utils: BufferUtils,
@ -109,11 +285,19 @@ pub fn init_shell(
Arc<Mutex<WlShellState<Roles>>>, Arc<Mutex<WlShellState<Roles>>>,
Rc<RefCell<MyWindowMap>>, Rc<RefCell<MyWindowMap>>,
) { ) {
// TODO: this is awkward...
let almost_window_map = Rc::new(RefCell::new(None::<Rc<RefCell<MyWindowMap>>>));
let almost_window_map_compositor = almost_window_map.clone();
// Create the compositor // Create the compositor
let (compositor_token, _, _) = compositor_init( let (compositor_token, _, _) = compositor_init(
display, display,
move |request, surface, ctoken| match request { move |request, surface, ctoken| match request {
SurfaceEvent::Commit => surface_commit(&surface, ctoken, &buffer_utils), SurfaceEvent::Commit => {
let window_map = almost_window_map_compositor.borrow();
let window_map = window_map.as_ref().unwrap();
surface_commit(&surface, ctoken, &buffer_utils, &*window_map)
}
SurfaceEvent::Frame { callback } => callback SurfaceEvent::Frame { callback } => callback
.implement_closure(|_, _| unreachable!(), None::<fn(_)>, ()) .implement_closure(|_, _| unreachable!(), None::<fn(_)>, ())
.done(0), .done(0),
@ -122,11 +306,8 @@ pub fn init_shell(
); );
// Init a window map, to track the location of our windows // Init a window map, to track the location of our windows
let window_map = Rc::new(RefCell::new(WindowMap::new( let window_map = Rc::new(RefCell::new(WindowMap::new(compositor_token)));
compositor_token, *almost_window_map.borrow_mut() = Some(window_map.clone());
get_size as _,
contains_point as _,
)));
// init the xdg_shell // init the xdg_shell
let xdg_window_map = window_map.clone(); let xdg_window_map = window_map.clone();
@ -196,6 +377,91 @@ pub fn init_shell(
pointer.set_grab(grab, serial); pointer.set_grab(grab, serial);
} }
XdgRequest::Resize {
surface,
seat,
serial,
edges,
} => {
let seat = Seat::from_resource(&seat).unwrap();
// TODO: touch resize.
let pointer = seat.get_pointer().unwrap();
// Check that this surface has a click grab.
if !pointer.has_grab(serial) {
return;
}
let start_data = pointer.grab_start_data().unwrap();
// If the focus was for a different surface, ignore the request.
if start_data.focus.is_none()
|| !start_data
.focus
.as_ref()
.unwrap()
.0
.as_ref()
.same_client_as(surface.get_surface().unwrap().as_ref())
{
return;
}
let toplevel = SurfaceKind::Xdg(surface.clone());
let initial_window_location = xdg_window_map.borrow().location(&toplevel).unwrap();
let geometry = xdg_window_map.borrow().geometry(&toplevel).unwrap();
let initial_window_size = (geometry.width, geometry.height);
compositor_token.with_surface_data(surface.get_surface().unwrap(), move |attrs| {
attrs.user_data.get_mut::<SurfaceData>().unwrap().resize_state =
ResizeState::Resizing(ResizeData {
edges: edges.into(),
initial_window_location,
initial_window_size,
});
});
let grab = ResizeSurfaceGrab {
start_data,
ctoken: compositor_token,
toplevel,
edges: edges.into(),
initial_window_size,
last_window_size: initial_window_size,
};
pointer.set_grab(grab, serial);
}
XdgRequest::AckConfigure { surface, .. } => {
let waiting_for_serial = compositor_token.with_surface_data(&surface, |attrs| {
if let Some(data) = attrs.user_data.get_mut::<SurfaceData>() {
if let ResizeState::WaitingForFinalAck(_, serial) = data.resize_state {
return Some(serial);
}
}
None
});
if let Some(serial) = waiting_for_serial {
let acked = compositor_token
.with_role_data(&surface, |role: &mut XdgSurfaceRole| {
!role.pending_configures.contains(&serial)
})
.unwrap();
if acked {
compositor_token.with_surface_data(&surface, |attrs| {
let data = attrs.user_data.get_mut::<SurfaceData>().unwrap();
if let ResizeState::WaitingForFinalAck(resize_data, _) = data.resize_state {
data.resize_state = ResizeState::WaitingForCommit(resize_data);
} else {
unreachable!()
}
})
}
}
}
_ => (), _ => (),
}, },
log.clone(), log.clone(),
@ -263,6 +529,61 @@ pub fn init_shell(
pointer.set_grab(grab, serial); pointer.set_grab(grab, serial);
} }
ShellRequest::Resize {
surface,
seat,
serial,
edges,
} => {
let seat = Seat::from_resource(&seat).unwrap();
// TODO: touch resize.
let pointer = seat.get_pointer().unwrap();
// Check that this surface has a click grab.
if !pointer.has_grab(serial) {
return;
}
let start_data = pointer.grab_start_data().unwrap();
// If the focus was for a different surface, ignore the request.
if start_data.focus.is_none()
|| !start_data
.focus
.as_ref()
.unwrap()
.0
.as_ref()
.same_client_as(surface.get_surface().unwrap().as_ref())
{
return;
}
let toplevel = SurfaceKind::Wl(surface.clone());
let initial_window_location = shell_window_map.borrow().location(&toplevel).unwrap();
let geometry = shell_window_map.borrow().geometry(&toplevel).unwrap();
let initial_window_size = (geometry.width, geometry.height);
compositor_token.with_surface_data(surface.get_surface().unwrap(), move |attrs| {
attrs.user_data.get_mut::<SurfaceData>().unwrap().resize_state =
ResizeState::Resizing(ResizeData {
edges: edges.into(),
initial_window_location,
initial_window_size,
});
});
let grab = ResizeSurfaceGrab {
start_data,
ctoken: compositor_token,
toplevel,
edges: edges.into(),
initial_window_size,
last_window_size: initial_window_size,
};
pointer.set_grab(grab, serial);
}
_ => (), _ => (),
} }
}, },
@ -272,24 +593,117 @@ pub fn init_shell(
(compositor_token, xdg_shell_state, wl_shell_state, window_map) (compositor_token, xdg_shell_state, wl_shell_state, window_map)
} }
/// Information about the resize operation.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct ResizeData {
/// The edges the surface is being resized with.
edges: ResizeEdge,
/// The initial window location.
initial_window_location: (i32, i32),
/// The initial window size (geometry width and height).
initial_window_size: (i32, i32),
}
/// State of the resize operation.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ResizeState {
/// The surface is not being resized.
NotResizing,
/// The surface is currently being resized.
Resizing(ResizeData),
/// The resize has finished, and the surface needs to ack the final configure.
WaitingForFinalAck(ResizeData, u32),
/// The resize has finished, and the surface needs to commit its final state.
WaitingForCommit(ResizeData),
}
impl Default for ResizeState {
fn default() -> Self {
ResizeState::NotResizing
}
}
#[derive(Default)] #[derive(Default)]
pub struct SurfaceData { pub struct SurfaceData {
pub buffer: Option<wl_buffer::WlBuffer>, pub buffer: Option<wl_buffer::WlBuffer>,
pub texture: Option<crate::glium_drawer::TextureMetadata>, pub texture: Option<crate::glium_drawer::TextureMetadata>,
pub dimensions: Option<(i32, i32)>, pub dimensions: Option<(i32, i32)>,
pub geometry: Option<Rectangle>,
pub input_region: Option<RegionAttributes>, pub input_region: Option<RegionAttributes>,
pub resize_state: ResizeState,
/// Minimum width and height, as requested by the surface.
///
/// `0` means unlimited.
pub min_size: (i32, i32),
/// Maximum width and height, as requested by the surface.
///
/// `0` means unlimited.
pub max_size: (i32, i32),
}
impl SurfaceData {
/// Returns the size of the surface.
pub fn size(&self) -> Option<(i32, i32)> {
self.dimensions
}
/// Checks if the surface's input region contains the point.
pub fn contains_point(&self, point: (f64, f64)) -> bool {
let (w, h) = match self.size() {
None => return false, // If the surface has no size, it can't have an input region.
Some(wh) => wh,
};
let rect = Rectangle {
x: 0,
y: 0,
width: w,
height: h,
};
let point = (point.0 as i32, point.1 as i32);
// The input region is always within the surface itself, so if the surface itself doesn't contain the
// point we can return false.
if !rect.contains(point) {
return false;
}
// If there's no input region, we're done.
if self.input_region.is_none() {
return true;
}
self.input_region.as_ref().unwrap().contains(point)
}
} }
fn surface_commit( fn surface_commit(
surface: &wl_surface::WlSurface, surface: &wl_surface::WlSurface,
token: CompositorToken<Roles>, token: CompositorToken<Roles>,
buffer_utils: &BufferUtils, buffer_utils: &BufferUtils,
window_map: &RefCell<MyWindowMap>,
) { ) {
token.with_surface_data(surface, |attributes| { let mut geometry = None;
let mut min_size = (0, 0);
let mut max_size = (0, 0);
let _ = token.with_role_data(surface, |role: &mut XdgSurfaceRole| {
if let XdgSurfacePendingState::Toplevel(ref state) = role.pending_state {
min_size = state.min_size;
max_size = state.max_size;
}
geometry = role.window_geometry;
});
let refresh = token.with_surface_data(surface, |attributes| {
attributes.user_data.insert_if_missing(SurfaceData::default); attributes.user_data.insert_if_missing(SurfaceData::default);
let data = attributes.user_data.get_mut::<SurfaceData>().unwrap(); let data = attributes.user_data.get_mut::<SurfaceData>().unwrap();
data.geometry = geometry;
data.input_region = attributes.input_region.clone(); data.input_region = attributes.input_region.clone();
data.min_size = min_size;
data.max_size = max_size;
// we retrieve the contents of the associated buffer and copy it // we retrieve the contents of the associated buffer and copy it
match attributes.buffer.take() { match attributes.buffer.take() {
@ -313,43 +727,59 @@ fn surface_commit(
} }
None => {} None => {}
} }
window_map.borrow().find(surface)
}); });
}
fn get_size(attrs: &SurfaceAttributes) -> Option<(i32, i32)> { if let Some(toplevel) = refresh {
attrs let mut window_map = window_map.borrow_mut();
.user_data window_map.refresh_toplevel(&toplevel);
.get::<SurfaceData>() // Get the geometry outside since it uses the token, and so would block inside.
.and_then(|data| data.dimensions) let Rectangle { width, height, .. } = window_map.geometry(&toplevel).unwrap();
}
fn contains_point(attrs: &SurfaceAttributes, point: (f64, f64)) -> bool { let new_location = token.with_surface_data(surface, |attributes| {
let (w, h) = match get_size(attrs) { let data = attributes.user_data.get_mut::<SurfaceData>().unwrap();
None => return false, // If the surface has no size, it can't have an input region.
Some(wh) => wh,
};
let rect = Rectangle { let mut new_location = None;
x: 0,
y: 0,
width: w,
height: h,
};
let point = (point.0 as i32, point.1 as i32); // If the window is being resized by top or left, its location must be adjusted
// accordingly.
match data.resize_state {
ResizeState::Resizing(resize_data)
| ResizeState::WaitingForFinalAck(resize_data, _)
| ResizeState::WaitingForCommit(resize_data) => {
let ResizeData {
edges,
initial_window_location,
initial_window_size,
} = resize_data;
// The input region is always within the surface itself, so if the surface itself doesn't contain the if edges.intersects(ResizeEdge::TOP_LEFT) {
// point we can return false. let mut location = window_map.location(&toplevel).unwrap();
if !rect.contains(point) {
return false; if edges.intersects(ResizeEdge::LEFT) {
location.0 = initial_window_location.0 + (initial_window_size.0 - width);
}
if edges.intersects(ResizeEdge::TOP) {
location.1 = initial_window_location.1 + (initial_window_size.1 - height);
}
new_location = Some(location);
}
}
ResizeState::NotResizing => (),
}
// Finish resizing.
if let ResizeState::WaitingForCommit(_) = data.resize_state {
data.resize_state = ResizeState::NotResizing;
}
new_location
});
if let Some(location) = new_location {
window_map.set_location(&toplevel, location);
}
} }
let input_region = &attrs.user_data.get::<SurfaceData>().unwrap().input_region;
// If there's no input region, we're done.
if input_region.is_none() {
return true;
}
input_region.as_ref().unwrap().contains(point)
} }

View File

@ -4,7 +4,7 @@ use smithay::{
reexports::wayland_server::protocol::wl_surface, reexports::wayland_server::protocol::wl_surface,
utils::Rectangle, utils::Rectangle,
wayland::{ wayland::{
compositor::{roles::Role, CompositorToken, SubsurfaceRole, SurfaceAttributes, TraversalAction}, compositor::{roles::Role, CompositorToken, SubsurfaceRole, TraversalAction},
shell::{ shell::{
legacy::{ShellSurface, ShellSurfaceRole}, legacy::{ShellSurface, ShellSurfaceRole},
xdg::{ToplevelSurface, XdgSurfaceRole}, xdg::{ToplevelSurface, XdgSurfaceRole},
@ -12,11 +12,23 @@ use smithay::{
}, },
}; };
use crate::shell::SurfaceData;
pub enum Kind<R> { pub enum Kind<R> {
Xdg(ToplevelSurface<R>), Xdg(ToplevelSurface<R>),
Wl(ShellSurface<R>), Wl(ShellSurface<R>),
} }
// We implement Clone manually because #[derive(..)] would require R: Clone.
impl<R> Clone for Kind<R> {
fn clone(&self) -> Self {
match self {
Kind::Xdg(xdg) => Kind::Xdg(xdg.clone()),
Kind::Wl(wl) => Kind::Wl(wl.clone()),
}
}
}
impl<R> Kind<R> impl<R> Kind<R>
where where
R: Role<SubsurfaceRole> + Role<XdgSurfaceRole> + Role<ShellSurfaceRole> + 'static, R: Role<SubsurfaceRole> + Role<XdgSurfaceRole> + Role<ShellSurfaceRole> + 'static,
@ -46,10 +58,11 @@ where
struct Window<R> { struct Window<R> {
location: (i32, i32), location: (i32, i32),
/// A bounding box over the input areas of this window and its children. /// A bounding box over this window and its children.
/// ///
/// Used for the fast path of the check in `matching`. /// Used for the fast path of the check in `matching`, and as the fall-back for the window
input_bbox: Rectangle, /// geometry if that's not set explicitly.
bbox: Rectangle,
toplevel: Kind<R>, toplevel: Kind<R>,
} }
@ -59,19 +72,12 @@ where
{ {
/// Finds the topmost surface under this point if any and returns it together with the location of this /// Finds the topmost surface under this point if any and returns it together with the location of this
/// surface. /// surface.
/// fn matching(
/// You need to provide a `contains_point` function which checks if the point (in surface-local
/// coordinates) is within the input region of the given `SurfaceAttributes`.
fn matching<F>(
&self, &self,
point: (f64, f64), point: (f64, f64),
ctoken: CompositorToken<R>, ctoken: CompositorToken<R>,
contains_point: F, ) -> Option<(wl_surface::WlSurface, (f64, f64))> {
) -> Option<(wl_surface::WlSurface, (f64, f64))> if !self.bbox.contains((point.0 as i32, point.1 as i32)) {
where
F: Fn(&SurfaceAttributes, (f64, f64)) -> bool,
{
if !self.input_bbox.contains((point.0 as i32, point.1 as i32)) {
return None; return None;
} }
// need to check more carefully // need to check more carefully
@ -81,13 +87,18 @@ where
wl_surface, wl_surface,
self.location, self.location,
|wl_surface, attributes, role, &(mut x, mut y)| { |wl_surface, attributes, role, &(mut x, mut y)| {
let data = attributes.user_data.get::<SurfaceData>();
if let Ok(subdata) = Role::<SubsurfaceRole>::data(role) { if let Ok(subdata) = Role::<SubsurfaceRole>::data(role) {
x += subdata.location.0; x += subdata.location.0;
y += subdata.location.1; y += subdata.location.1;
} }
let surface_local_point = (point.0 - x as f64, point.1 - y as f64); let surface_local_point = (point.0 - x as f64, point.1 - y as f64);
if contains_point(attributes, surface_local_point) { if data
.map(|data| data.contains_point(surface_local_point))
.unwrap_or(false)
{
*found.borrow_mut() = Some((wl_surface.clone(), (x as f64, y as f64))); *found.borrow_mut() = Some((wl_surface.clone(), (x as f64, y as f64)));
} }
@ -103,10 +114,7 @@ where
found.into_inner() found.into_inner()
} }
fn self_update<F>(&mut self, ctoken: CompositorToken<R>, get_size: F) fn self_update(&mut self, ctoken: CompositorToken<R>) {
where
F: Fn(&SurfaceAttributes) -> Option<(i32, i32)>,
{
let (base_x, base_y) = self.location; let (base_x, base_y) = self.location;
let (mut min_x, mut min_y, mut max_x, mut max_y) = (base_x, base_y, base_x, base_y); let (mut min_x, mut min_y, mut max_x, mut max_y) = (base_x, base_y, base_x, base_y);
if let Some(wl_surface) = self.toplevel.get_surface() { if let Some(wl_surface) = self.toplevel.get_surface() {
@ -114,28 +122,24 @@ where
wl_surface, wl_surface,
(base_x, base_y), (base_x, base_y),
|_, attributes, role, &(mut x, mut y)| { |_, attributes, role, &(mut x, mut y)| {
// The input region is intersected with the surface size, so the surface size let data = attributes.user_data.get::<SurfaceData>();
// can serve as an approximation for the input bounding box.
if let Some((w, h)) = get_size(attributes) { if let Some((w, h)) = data.and_then(SurfaceData::size) {
if let Ok(subdata) = Role::<SubsurfaceRole>::data(role) { if let Ok(subdata) = Role::<SubsurfaceRole>::data(role) {
x += subdata.location.0; x += subdata.location.0;
y += subdata.location.1; y += subdata.location.1;
} }
// update the bounding box
if x < min_x { // Update the bounding box.
min_x = x; min_x = min_x.min(x);
} min_y = min_y.min(y);
if y < min_y { max_x = max_x.max(x + w);
min_y = y; max_y = max_y.max(y + h);
}
if x + w > max_x {
max_x = x + w;
}
if y + h > max_y {
max_y = y + w;
}
TraversalAction::DoChildren((x, y)) TraversalAction::DoChildren((x, y))
} else { } else {
// If the parent surface is unmapped, then the child surfaces are hidden as
// well, no need to consider them here.
TraversalAction::SkipChildren TraversalAction::SkipChildren
} }
}, },
@ -143,52 +147,54 @@ where
|_, _, _, _| true, |_, _, _, _| true,
); );
} }
self.input_bbox = Rectangle { self.bbox = Rectangle {
x: min_x, x: min_x,
y: min_y, y: min_y,
width: max_x - min_x, width: max_x - min_x,
height: max_y - min_y, height: max_y - min_y,
}; };
} }
/// Returns the geometry of this window.
pub fn geometry(&self, ctoken: CompositorToken<R>) -> Rectangle {
// It's the set geometry with the full bounding box as the fallback.
ctoken
.with_surface_data(self.toplevel.get_surface().unwrap(), |attributes| {
attributes.user_data.get::<SurfaceData>().unwrap().geometry
})
.unwrap_or(self.bbox)
}
} }
pub struct WindowMap<R, F, G> { pub struct WindowMap<R> {
ctoken: CompositorToken<R>, ctoken: CompositorToken<R>,
windows: Vec<Window<R>>, windows: Vec<Window<R>>,
/// A function returning the surface size.
get_size: F,
/// A function that checks if the point is in the surface's input region.
contains_point: G,
} }
impl<R, F, G> WindowMap<R, F, G> impl<R> WindowMap<R>
where where
F: Fn(&SurfaceAttributes) -> Option<(i32, i32)>,
G: Fn(&SurfaceAttributes, (f64, f64)) -> bool,
R: Role<SubsurfaceRole> + Role<XdgSurfaceRole> + Role<ShellSurfaceRole> + 'static, R: Role<SubsurfaceRole> + Role<XdgSurfaceRole> + Role<ShellSurfaceRole> + 'static,
{ {
pub fn new(ctoken: CompositorToken<R>, get_size: F, contains_point: G) -> Self { pub fn new(ctoken: CompositorToken<R>) -> Self {
WindowMap { WindowMap {
ctoken, ctoken,
windows: Vec::new(), windows: Vec::new(),
get_size,
contains_point,
} }
} }
pub fn insert(&mut self, toplevel: Kind<R>, location: (i32, i32)) { pub fn insert(&mut self, toplevel: Kind<R>, location: (i32, i32)) {
let mut window = Window { let mut window = Window {
location, location,
input_bbox: Rectangle::default(), bbox: Rectangle::default(),
toplevel, toplevel,
}; };
window.self_update(self.ctoken, &self.get_size); window.self_update(self.ctoken);
self.windows.insert(0, window); self.windows.insert(0, window);
} }
pub fn get_surface_under(&self, point: (f64, f64)) -> Option<(wl_surface::WlSurface, (f64, f64))> { pub fn get_surface_under(&self, point: (f64, f64)) -> Option<(wl_surface::WlSurface, (f64, f64))> {
for w in &self.windows { for w in &self.windows {
if let Some(surface) = w.matching(point, self.ctoken, &self.contains_point) { if let Some(surface) = w.matching(point, self.ctoken) {
return Some(surface); return Some(surface);
} }
} }
@ -201,7 +207,7 @@ where
) -> Option<(wl_surface::WlSurface, (f64, f64))> { ) -> Option<(wl_surface::WlSurface, (f64, f64))> {
let mut found = None; let mut found = None;
for (i, w) in self.windows.iter().enumerate() { for (i, w) in self.windows.iter().enumerate() {
if let Some(surface) = w.matching(point, self.ctoken, &self.contains_point) { if let Some(surface) = w.matching(point, self.ctoken) {
found = Some((i, surface)); found = Some((i, surface));
break; break;
} }
@ -227,7 +233,14 @@ where
pub fn refresh(&mut self) { pub fn refresh(&mut self) {
self.windows.retain(|w| w.toplevel.alive()); self.windows.retain(|w| w.toplevel.alive());
for w in &mut self.windows { for w in &mut self.windows {
w.self_update(self.ctoken, &self.get_size); w.self_update(self.ctoken);
}
}
/// Refreshes the state of the toplevel, if it exists.
pub fn refresh_toplevel(&mut self, toplevel: &Kind<R>) {
if let Some(w) = self.windows.iter_mut().find(|w| w.toplevel.equals(toplevel)) {
w.self_update(self.ctoken);
} }
} }
@ -235,6 +248,21 @@ where
self.windows.clear(); self.windows.clear();
} }
/// Finds the toplevel corresponding to the given `WlSurface`.
pub fn find(&self, surface: &wl_surface::WlSurface) -> Option<Kind<R>> {
self.windows.iter().find_map(|w| {
if w.toplevel
.get_surface()
.map(|s| s.as_ref().equals(surface.as_ref()))
.unwrap_or(false)
{
Some(w.toplevel.clone())
} else {
None
}
})
}
/// Returns the location of the toplevel, if it exists. /// Returns the location of the toplevel, if it exists.
pub fn location(&self, toplevel: &Kind<R>) -> Option<(i32, i32)> { pub fn location(&self, toplevel: &Kind<R>) -> Option<(i32, i32)> {
self.windows self.windows
@ -247,7 +275,15 @@ where
pub fn set_location(&mut self, toplevel: &Kind<R>, location: (i32, i32)) { pub fn set_location(&mut self, toplevel: &Kind<R>, location: (i32, i32)) {
if let Some(w) = self.windows.iter_mut().find(|w| w.toplevel.equals(toplevel)) { if let Some(w) = self.windows.iter_mut().find(|w| w.toplevel.equals(toplevel)) {
w.location = location; w.location = location;
w.self_update(self.ctoken, &self.get_size); w.self_update(self.ctoken);
} }
} }
/// Returns the geometry of the toplevel, if it exists.
pub fn geometry(&self, toplevel: &Kind<R>) -> Option<Rectangle> {
self.windows
.iter()
.find(|w| w.toplevel.equals(toplevel))
.map(|w| w.geometry(self.ctoken))
}
} }

View File

@ -92,6 +92,17 @@ pub struct ShellSurface<R> {
token: CompositorToken<R>, token: CompositorToken<R>,
} }
// We implement Clone manually because #[derive(..)] would require R: Clone.
impl<R> Clone for ShellSurface<R> {
fn clone(&self) -> Self {
Self {
wl_surface: self.wl_surface.clone(),
shell_surface: self.shell_surface.clone(),
token: self.token.clone(),
}
}
}
impl<R> ShellSurface<R> impl<R> ShellSurface<R>
where where
R: Role<ShellSurfaceRole> + 'static, R: Role<ShellSurfaceRole> + 'static,

View File

@ -472,6 +472,7 @@ where
} }
} }
#[derive(Clone)]
pub(crate) enum ToplevelKind { pub(crate) enum ToplevelKind {
Xdg(xdg_toplevel::XdgToplevel), Xdg(xdg_toplevel::XdgToplevel),
ZxdgV6(zxdg_toplevel_v6::ZxdgToplevelV6), ZxdgV6(zxdg_toplevel_v6::ZxdgToplevelV6),
@ -484,6 +485,17 @@ pub struct ToplevelSurface<R> {
token: CompositorToken<R>, token: CompositorToken<R>,
} }
// We implement Clone manually because #[derive(..)] would require R: Clone.
impl<R> Clone for ToplevelSurface<R> {
fn clone(&self) -> Self {
Self {
wl_surface: self.wl_surface.clone(),
shell_surface: self.shell_surface.clone(),
token: self.token.clone(),
}
}
}
impl<R> ToplevelSurface<R> impl<R> ToplevelSurface<R>
where where
R: Role<XdgSurfaceRole> + 'static, R: Role<XdgSurfaceRole> + 'static,
@ -929,4 +941,11 @@ pub enum XdgRequest<R> {
/// location of the menu request /// location of the menu request
location: (i32, i32), location: (i32, i32),
}, },
/// A surface has acknowledged a configure serial.
AckConfigure {
/// The surface.
surface: wl_surface::WlSurface,
/// The configure serial.
serial: u32,
},
} }

View File

@ -333,6 +333,12 @@ where
role_data.configured = true; role_data.configured = true;
}) })
.expect("xdg_surface exists but surface has not shell_surface role?!"); .expect("xdg_surface exists but surface has not shell_surface role?!");
let mut user_impl = data.shell_data.user_impl.borrow_mut();
(&mut *user_impl)(XdgRequest::AckConfigure {
surface: data.wl_surface.clone(),
serial,
});
} }
_ => unreachable!(), _ => unreachable!(),
} }
@ -467,7 +473,7 @@ where
} }
xdg_toplevel::Request::SetMinSize { width, height } => { xdg_toplevel::Request::SetMinSize { width, height } => {
with_surface_toplevel_data(&data.shell_data, &toplevel, |toplevel_data| { with_surface_toplevel_data(&data.shell_data, &toplevel, |toplevel_data| {
toplevel_data.max_size = (width, height); toplevel_data.min_size = (width, height);
}); });
} }
xdg_toplevel::Request::SetMaximized => { xdg_toplevel::Request::SetMaximized => {

View File

@ -349,6 +349,12 @@ fn xdg_surface_implementation<R>(
role_data.configured = true; role_data.configured = true;
}) })
.expect("xdg_surface exists but surface has not shell_surface role?!"); .expect("xdg_surface exists but surface has not shell_surface role?!");
let mut user_impl = data.shell_data.user_impl.borrow_mut();
(&mut *user_impl)(XdgRequest::AckConfigure {
surface: data.wl_surface.clone(),
serial,
});
} }
_ => unreachable!(), _ => unreachable!(),
} }
@ -485,7 +491,7 @@ where
} }
zxdg_toplevel_v6::Request::SetMinSize { width, height } => { zxdg_toplevel_v6::Request::SetMinSize { width, height } => {
with_surface_toplevel_data::<R, _>(&toplevel, |toplevel_data| { with_surface_toplevel_data::<R, _>(&toplevel, |toplevel_data| {
toplevel_data.max_size = (width, height); toplevel_data.min_size = (width, height);
}); });
} }
zxdg_toplevel_v6::Request::SetMaximized => { zxdg_toplevel_v6::Request::SetMaximized => {