Groundwork for tiling layout

This commit is contained in:
Victoria Brekenfeld 2022-03-24 20:32:31 +01:00
parent 5657a77c5b
commit 4796832521
19 changed files with 1685 additions and 837 deletions

View file

@ -0,0 +1,126 @@
use super::Layout;
use smithay::{
desktop::{Space, Window},
reexports::wayland_protocols::xdg_shell::server::xdg_toplevel::ResizeEdge,
wayland::{
compositor::with_states,
seat::{PointerGrabStartData, Seat},
shell::xdg::XdgToplevelSurfaceRoleAttributes,
Serial,
},
};
use std::sync::Mutex;
struct Filtered;
pub struct Combined<A: Layout, B: Layout> {
first: A,
second: B,
windows_a: Vec<Window>,
windows_b: Vec<Window>,
filter: Box<dyn Fn(Option<&str>, Option<&str>) -> bool>,
}
impl<A: Layout, B: Layout> Combined<A, B> {
pub fn new(
first: A,
second: B,
filter: impl Fn(Option<&str>, Option<&str>) -> bool + 'static,
) -> Combined<A, B> {
Combined {
first,
second,
windows_a: Vec::new(),
windows_b: Vec::new(),
filter: Box::new(filter),
}
}
}
impl<A: Layout, B: Layout> Layout for Combined<A, B> {
fn map_window<'a>(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
focus_stack: Box<dyn Iterator<Item = &'a Window> + 'a>,
) {
if let Some(surface) = window.toplevel().get_surface() {
let filtered = with_states(surface, |states| {
let attrs = states
.data_map
.get::<Mutex<XdgToplevelSurfaceRoleAttributes>>()
.unwrap()
.lock()
.unwrap();
if (self.filter)(attrs.app_id.as_deref(), attrs.title.as_deref()) {
window.user_data().insert_if_missing(|| Filtered);
true
} else {
false
}
})
.unwrap_or(false);
if filtered {
self.windows_b.push(window.clone());
return self.second.map_window(
space,
window,
seat,
Box::new(focus_stack.filter(|w| w.user_data().get::<Filtered>().is_some())),
);
}
}
self.windows_a.push(window.clone());
return self.first.map_window(
space,
window,
seat,
Box::new(focus_stack.filter(|w| w.user_data().get::<Filtered>().is_none())),
);
}
fn refresh(&mut self, space: &mut Space) {
self.first.refresh(space);
self.second.refresh(space);
self.windows_a.retain(|w| w.toplevel().alive());
self.windows_b.retain(|w| w.toplevel().alive());
}
//fn unmap_window(&mut self, space: &mut Space, window: &Window);
fn move_request(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
) {
if self.windows_a.contains(window) {
self.first
.move_request(space, window, seat, serial, start_data)
} else if self.windows_b.contains(window) {
self.second
.move_request(space, window, seat, serial, start_data)
}
}
fn resize_request(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
edges: ResizeEdge,
) {
if self.windows_a.contains(window) {
self.first
.resize_request(space, window, seat, serial, start_data, edges)
} else if self.windows_b.contains(window) {
self.second
.resize_request(space, window, seat, serial, start_data, edges)
}
}
}

View file

@ -0,0 +1,439 @@
// SPDX-License-Identifier: GPL-3.0-only
use smithay::{
desktop::{Kind, Window},
reexports::{
wayland_protocols::xdg_shell::server::xdg_toplevel,
wayland_server::protocol::{wl_pointer::ButtonState, wl_surface},
},
utils::{Logical, Point, Size},
wayland::{
compositor::with_states,
seat::{AxisFrame, PointerGrab, PointerGrabStartData, PointerInnerHandle},
shell::xdg::{SurfaceCachedState, ToplevelConfigure, XdgToplevelSurfaceRoleAttributes},
Serial,
},
};
use std::{cell::RefCell, sync::Mutex};
#[derive(Debug, Default)]
struct MoveData {
new_location: Point<i32, Logical>,
}
pub struct MoveSurfaceGrab {
start_data: PointerGrabStartData,
window: Window,
initial_window_location: Point<i32, Logical>,
}
impl PointerGrab for MoveSurfaceGrab {
fn motion(
&mut self,
handle: &mut PointerInnerHandle<'_>,
location: Point<f64, Logical>,
_focus: Option<(wl_surface::WlSurface, Point<i32, Logical>)>,
serial: Serial,
time: u32,
) {
// While the grab is active, no client has pointer focus
handle.motion(location, None, serial, time);
let delta = location - self.start_data.location;
let new_location = self.initial_window_location.to_f64() + delta;
self.window
.user_data()
.insert_if_missing(|| RefCell::<Option<MoveData>>::new(None));
let data = self
.window
.user_data()
.get::<RefCell<Option<MoveData>>>()
.unwrap();
*data.borrow_mut() = Some(MoveData {
new_location: new_location.to_i32_round(),
});
}
fn button(
&mut self,
handle: &mut PointerInnerHandle<'_>,
button: u32,
state: ButtonState,
serial: Serial,
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);
}
}
fn axis(&mut self, handle: &mut PointerInnerHandle<'_>, details: AxisFrame) {
handle.axis(details)
}
fn start_data(&self) -> &PointerGrabStartData {
&self.start_data
}
}
impl MoveSurfaceGrab {
pub fn new(
start_data: PointerGrabStartData,
window: Window,
initial_window_location: Point<i32, Logical>,
) -> MoveSurfaceGrab {
MoveSurfaceGrab {
start_data,
window,
initial_window_location,
}
}
pub fn apply_move_state(window: &Window) -> Option<Point<i32, Logical>> {
window
.user_data()
.get::<RefCell<Option<MoveData>>>()
.and_then(|opt| {
opt.borrow_mut()
.take()
.map(|move_data| move_data.new_location)
})
}
}
bitflags::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<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()
}
}
/// Information about the resize operation.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
struct ResizeData {
/// The edges the surface is being resized with.
edges: ResizeEdge,
/// The initial window location.
initial_window_location: Point<i32, Logical>,
/// The initial window size (geometry width and height).
initial_window_size: Size<i32, Logical>,
}
/// State of the resize operation.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
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, Serial),
/// The resize has finished, and the surface needs to commit its final state.
WaitingForCommit(ResizeData),
}
impl Default for ResizeState {
fn default() -> Self {
ResizeState::NotResizing
}
}
pub struct ResizeSurfaceGrab {
start_data: PointerGrabStartData,
window: Window,
edges: ResizeEdge,
initial_window_size: Size<i32, Logical>,
last_window_size: Size<i32, Logical>,
}
impl PointerGrab for ResizeSurfaceGrab {
fn motion(
&mut self,
handle: &mut PointerInnerHandle<'_>,
location: Point<f64, Logical>,
_focus: Option<(wl_surface::WlSurface, Point<i32, Logical>)>,
serial: Serial,
time: u32,
) {
// While the grab is active, no client has pointer focus
handle.motion(location, None, serial, time);
// It is impossible to get `min_size` and `max_size` of dead toplevel, so we return early.
if !self.window.toplevel().alive() | self.window.toplevel().get_surface().is_none() {
handle.unset_grab(serial, time);
return;
}
let (mut dx, mut dy) = (location - self.start_data.location).into();
let mut new_window_width = self.initial_window_size.w;
let mut new_window_height = self.initial_window_size.h;
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.w 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.h as f64 + dy) as i32;
}
let (min_size, max_size) =
with_states(self.window.toplevel().get_surface().unwrap(), |states| {
let data = states.cached_state.current::<SurfaceCachedState>();
(data.min_size, data.max_size)
})
.unwrap();
let min_width = min_size.w.max(1);
let min_height = min_size.h.max(1);
let max_width = if max_size.w == 0 {
i32::max_value()
} else {
max_size.w
};
let max_height = if max_size.h == 0 {
i32::max_value()
} else {
max_size.h
};
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).into();
match &self.window.toplevel() {
Kind::Xdg(xdg) => {
let ret = xdg.with_pending_state(|state| {
state.states.set(xdg_toplevel::State::Resizing);
state.size = Some(self.last_window_size);
});
if ret.is_ok() {
xdg.send_configure();
}
}
}
}
fn button(
&mut self,
handle: &mut PointerInnerHandle<'_>,
button: u32,
state: ButtonState,
serial: Serial,
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 toplevel is dead, we can't resize it, so we return early.
if !self.window.toplevel().alive() | self.window.toplevel().get_surface().is_none() {
return;
}
#[allow(irrefutable_let_patterns)]
if let Kind::Xdg(xdg) = &self.window.toplevel() {
let ret = xdg.with_pending_state(|state| {
state.states.unset(xdg_toplevel::State::Resizing);
state.size = Some(self.last_window_size);
});
if ret.is_ok() {
xdg.send_configure();
}
}
let mut resize_state = self
.window
.user_data()
.get::<RefCell<ResizeState>>()
.unwrap()
.borrow_mut();
if let ResizeState::Resizing(resize_data) = *resize_state {
*resize_state = ResizeState::WaitingForFinalAck(resize_data, serial);
} else {
panic!("invalid resize state: {:?}", resize_state);
}
}
}
fn axis(&mut self, handle: &mut PointerInnerHandle<'_>, details: AxisFrame) {
handle.axis(details)
}
fn start_data(&self) -> &PointerGrabStartData {
&self.start_data
}
}
impl ResizeSurfaceGrab {
pub fn new(
start_data: PointerGrabStartData,
window: Window,
edges: xdg_toplevel::ResizeEdge,
initial_window_location: Point<i32, Logical>,
initial_window_size: Size<i32, Logical>,
) -> ResizeSurfaceGrab {
let resize_state = ResizeState::Resizing(ResizeData {
edges: edges.into(),
initial_window_location,
initial_window_size,
});
window
.user_data()
.insert_if_missing(|| RefCell::new(ResizeState::default()));
*window
.user_data()
.get::<RefCell<ResizeState>>()
.unwrap()
.borrow_mut() = resize_state;
ResizeSurfaceGrab {
start_data,
window,
edges: edges.into(),
initial_window_size,
last_window_size: initial_window_size,
}
}
pub fn ack_configure(window: &Window, configure: ToplevelConfigure) {
let surface = if let Some(surface) = window.toplevel().get_surface() {
surface
} else {
return;
};
let waiting_for_serial =
if let Some(data) = window.user_data().get::<RefCell<ResizeState>>() {
if let ResizeState::WaitingForFinalAck(_, serial) = *data.borrow() {
Some(serial)
} else {
None
}
} else {
None
};
if let Some(serial) = waiting_for_serial {
// When the resize grab is released the surface
// resize state will be set to WaitingForFinalAck
// and the client will receive a configure request
// without the resize state to inform the client
// resizing has finished. Here we will wait for
// the client to acknowledge the end of the
// resizing. To check if the surface was resizing
// before sending the configure we need to use
// the current state as the received acknowledge
// will no longer have the resize state set
let is_resizing = with_states(&surface, |states| {
states
.data_map
.get::<Mutex<XdgToplevelSurfaceRoleAttributes>>()
.unwrap()
.lock()
.unwrap()
.current
.states
.contains(xdg_toplevel::State::Resizing)
})
.unwrap();
if configure.serial >= serial && is_resizing {
let mut resize_state = window
.user_data()
.get::<RefCell<ResizeState>>()
.unwrap()
.borrow_mut();
if let ResizeState::WaitingForFinalAck(resize_data, _) = *resize_state {
*resize_state = ResizeState::WaitingForCommit(resize_data);
} else {
unreachable!()
}
}
}
}
pub fn apply_resize_state(
window: &Window,
mut location: Point<i32, Logical>,
size: Size<i32, Logical>,
) -> Option<Point<i32, Logical>> {
let mut new_location = None;
if let Some(resize_state) = window.user_data().get::<RefCell<ResizeState>>() {
let mut resize_state = resize_state.borrow_mut();
// If the window is being resized by top or left, its location must be adjusted
// accordingly.
match *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;
if edges.intersects(ResizeEdge::TOP_LEFT) {
if edges.intersects(ResizeEdge::LEFT) {
location.x =
initial_window_location.x + (initial_window_size.w - size.w);
}
if edges.intersects(ResizeEdge::TOP) {
location.y =
initial_window_location.y + (initial_window_size.h - size.h);
}
new_location = Some(location);
}
}
ResizeState::NotResizing => (),
}
// Finish resizing.
if let ResizeState::WaitingForCommit(_) = *resize_state {
*resize_state = ResizeState::NotResizing;
}
}
new_location
}
}

View file

@ -0,0 +1,142 @@
// SPDX-License-Identifier: GPL-3.0-only
use crate::shell::layout::Layout;
use smithay::{
desktop::{layer_map_for_output, Kind, Space, Window},
reexports::wayland_protocols::xdg_shell::server::xdg_toplevel::{
ResizeEdge, State as XdgState,
},
wayland::{
output::Output,
seat::{PointerGrabStartData, Seat},
Serial,
},
};
mod grabs;
pub use self::grabs::*;
pub struct FloatingLayout;
impl Layout for FloatingLayout {
fn map_window<'a>(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
_focus_stack: Box<dyn Iterator<Item = &'a Window> + 'a>,
) {
let output = super::output_from_seat(seat, space);
let win_geo = window.bbox();
let layers = layer_map_for_output(&output);
let geometry = layers.non_exclusive_zone();
let position = (
-geometry.loc.x + (geometry.size.w / 2) - (win_geo.size.w / 2),
-geometry.loc.y + (geometry.size.h / 2) - (win_geo.size.h / 2),
);
#[allow(irrefutable_let_patterns)]
if let Kind::Xdg(xdg) = &window.toplevel() {
let ret = xdg.with_pending_state(|state| {
state.states.unset(XdgState::TiledLeft);
state.states.unset(XdgState::TiledRight);
state.states.unset(XdgState::TiledTop);
state.states.unset(XdgState::TiledBottom);
});
if ret.is_ok() {
xdg.send_configure();
}
}
space.map_window(&window, position, false);
}
fn refresh(&mut self, _space: &mut Space) {
// TODO make sure all windows are still visible on any output or move them
}
fn maximize_request(&mut self, space: &mut Space, window: &Window, output: &Output) {
let layers = layer_map_for_output(&output);
let geometry = layers.non_exclusive_zone();
space.map_window(&window, (-geometry.loc.x, -geometry.loc.y), true);
#[allow(irrefutable_let_patterns)]
if let Kind::Xdg(surface) = &window.toplevel() {
let ret = surface.with_pending_state(|state| {
state.states.set(XdgState::Maximized);
state.size = Some(geometry.size);
});
if ret.is_ok() {
window.configure();
}
}
}
fn move_request(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
) {
if let Some(pointer) = seat.get_pointer() {
let mut initial_window_location = space.window_location(&window).unwrap();
#[allow(irrefutable_let_patterns)]
if let Kind::Xdg(surface) = &window.toplevel() {
// If surface is maximized then unmaximize it
if let Some(current_state) = surface.current_state() {
if current_state.states.contains(XdgState::Maximized) {
let fs_changed = surface.with_pending_state(|state| {
state.states.unset(XdgState::Maximized);
state.size = None;
});
if fs_changed.is_ok() {
surface.send_configure();
// NOTE: In real compositor mouse location should be mapped to a new window size
// For example, you could:
// 1) transform mouse pointer position from compositor space to window space (location relative)
// 2) divide the x coordinate by width of the window to get the percentage
// - 0.0 would be on the far left of the window
// - 0.5 would be in middle of the window
// - 1.0 would be on the far right of the window
// 3) multiply the percentage by new window width
// 4) by doing that, drag will look a lot more natural
//
// but for anvil needs setting location to pointer location is fine
let pos = pointer.current_location();
initial_window_location = (pos.x as i32, pos.y as i32).into();
}
}
}
}
let grab = MoveSurfaceGrab::new(start_data, window.clone(), initial_window_location);
pointer.set_grab(grab, serial, 0);
}
}
fn resize_request(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
edges: ResizeEdge,
) {
if let Some(pointer) = seat.get_pointer() {
let location = space.window_location(&window).unwrap();
let size = window.geometry().size;
let grab =
grabs::ResizeSurfaceGrab::new(start_data, window.clone(), edges, location, size);
pointer.set_grab(grab, serial, 0);
}
}
}

82
src/shell/layout/mod.rs Normal file
View file

@ -0,0 +1,82 @@
// SPDX-License-Identifier: GPL-3.0-only
use crate::input::ActiveOutput;
use smithay::{
desktop::{Space, Window},
reexports::wayland_protocols::xdg_shell::server::xdg_toplevel::ResizeEdge,
wayland::{
output::Output,
seat::{PointerGrabStartData, Seat},
Serial,
},
};
pub mod combined;
pub mod floating;
pub mod tiling;
pub trait Layout {
fn map_window<'a>(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
focus_stack: Box<dyn Iterator<Item = &'a Window> + 'a>,
); //working around object safety..
fn refresh(&mut self, space: &mut Space);
//fn unmap_window(&mut self, space: &mut Space, window: &Window);
fn maximize_request(&mut self, space: &mut Space, window: &Window, output: &Output) {
let _ = (space, window, output);
}
fn move_request(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
) {
let _ = (space, window, seat, serial, start_data);
}
fn resize_request(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
edges: ResizeEdge,
) {
let _ = (space, window, seat, serial, start_data, edges);
}
}
pub fn new_default_layout() -> Box<dyn Layout> {
Box::new(combined::Combined::new(
tiling::TilingLayout::new(),
floating::FloatingLayout,
|app_id, title| {
slog_scope::debug!(
"New filter input: ({}:{})",
app_id.unwrap_or("<unknown>"),
title.unwrap_or("<no title>")
);
match (app_id.unwrap_or(""), title.unwrap_or("")) {
("gcr-prompter", _) => true,
_ => false,
}
},
))
}
fn output_from_seat(seat: &Seat, space: &Space) -> Output {
seat.user_data()
.get::<ActiveOutput>()
.map(|active| active.0.borrow().clone())
.or_else(|| {
seat.get_pointer()
.map(|ptr| space.output_under(ptr.current_location()).next().unwrap())
.cloned()
})
.unwrap_or_else(|| space.outputs().next().cloned().unwrap())
}

371
src/shell/layout/tiling.rs Normal file
View file

@ -0,0 +1,371 @@
// SPDX-License-Identifier: GPL-3.0-only
use crate::shell::layout::Layout;
use id_tree::{InsertBehavior, MoveBehavior, Node, NodeId, NodeIdError, RemoveBehavior, Tree};
use smithay::{
desktop::{layer_map_for_output, Kind, Space, Window},
reexports::wayland_protocols::xdg_shell::server::xdg_toplevel::State as XdgState,
utils::Rectangle,
wayland::{output::Output, seat::Seat},
};
use std::cell::RefCell;
#[derive(Debug)]
pub struct TilingLayout {
gaps: (i32, i32),
}
#[derive(Debug)]
pub enum Orientation {
Horizontal,
Vertical,
}
#[derive(Debug)]
pub enum Data {
Fork {
orientation: Orientation,
ratio: f64,
},
Stack {
active: usize,
len: usize,
},
Window(Window),
}
#[derive(Debug, Clone)]
pub struct WindowInfo {
node: NodeId,
output: Output,
}
pub struct OutputInfo {
tree: Tree<Data>,
}
impl std::fmt::Debug for OutputInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.tree.write_formatted(f)
}
}
impl Default for OutputInfo {
fn default() -> OutputInfo {
OutputInfo { tree: Tree::new() }
}
}
impl Data {
fn fork() -> Data {
Data::Fork {
orientation: Orientation::Vertical,
ratio: 0.5,
}
}
}
impl TilingLayout {
pub fn new() -> TilingLayout {
TilingLayout { gaps: (0, 4) }
}
}
impl Layout for TilingLayout {
fn map_window<'a>(
&mut self,
space: &mut Space,
window: &Window,
seat: &Seat,
mut focus_stack: Box<dyn Iterator<Item = &'a Window> + 'a>,
) {
{
let output = super::output_from_seat(seat, space);
output
.user_data()
.insert_if_missing(|| RefCell::new(OutputInfo::default()));
let output_info = output.user_data().get::<RefCell<OutputInfo>>().unwrap();
let tree = &mut output_info.borrow_mut().tree;
let new_window = Node::new(Data::Window(window.clone()));
let last_active = focus_stack
.find_map(|window| tree.root_node_id()
.and_then(|root| tree.traverse_pre_order_ids(root).unwrap()
.find(|id| matches!(tree.get(id).map(|n| n.data()), Ok(Data::Window(w)) if w == window))
)
);
let window_id = if let Some(ref node_id) = last_active {
let parent_id = tree.get(node_id).unwrap().parent().cloned();
if let Some(stack_id) = parent_id
.filter(|id| matches!(tree.get(id).unwrap().data(), Data::Stack { .. }))
{
// we add to the stack
let window_id = tree
.insert(new_window, InsertBehavior::UnderNode(&stack_id))
.unwrap();
if let Data::Stack {
ref mut len,
ref mut active,
} = tree.get_mut(&stack_id).unwrap().data_mut()
{
*active = *len;
*len += 1;
}
Ok(window_id)
} else {
// we create a new fork
new_fork(tree, node_id, new_window)
}
} else {
// nothing? then we add to the root
if let Some(root_id) = tree.root_node_id().cloned() {
new_fork(tree, &root_id, new_window)
} else {
tree.insert(new_window, InsertBehavior::AsRoot)
}
}
.unwrap();
{
let user_data = window.user_data();
let window_info = WindowInfo {
node: window_id.clone(),
output: output.clone(),
};
// insert or update
if !user_data.insert_if_missing(|| RefCell::new(window_info.clone())) {
*user_data.get::<RefCell<WindowInfo>>().unwrap().borrow_mut() = window_info;
}
}
}
self.refresh(space);
}
fn refresh(&mut self, space: &mut Space) {
while let Some(dead_windows) =
Some(update_space_positions(space, self.gaps)).filter(|v| !v.is_empty())
{
for window in dead_windows {
self.unmap_window(&window);
}
}
}
}
impl TilingLayout {
fn unmap_window(&mut self, window: &Window) {
if let Some(info) = window.user_data().get::<RefCell<WindowInfo>>() {
let output = &info.borrow().output;
let output_info = output.user_data().get::<RefCell<OutputInfo>>().unwrap();
let tree = &mut output_info.borrow_mut().tree;
let node_id = info.borrow().node.clone();
let parent_id = tree
.get(&node_id)
.ok()
.and_then(|node| node.parent())
.cloned();
let parent_parent_id = parent_id.as_ref().and_then(|parent_id| {
tree.get(parent_id)
.ok()
.and_then(|node| node.parent())
.cloned()
});
// remove self
slog_scope::debug!("Remove window {:?}", window);
let _ = tree.remove_node(node_id.clone(), RemoveBehavior::DropChildren);
// fixup parent node
match parent_id {
Some(id) if matches!(tree.get(&id).unwrap().data(), Data::Fork { .. }) => {
slog_scope::debug!("Removing Fork");
let other_child = tree.children_ids(&id).unwrap().cloned().next().unwrap();
let fork_pos = parent_parent_id.as_ref().and_then(|parent_id| {
tree.children_ids(parent_id).unwrap().position(|i| i == &id)
});
let _ = tree.remove_node(id.clone(), RemoveBehavior::OrphanChildren);
tree.move_node(
&other_child,
parent_parent_id
.as_ref()
.map(|parent_id| MoveBehavior::ToParent(parent_id))
.unwrap_or(MoveBehavior::ToRoot),
)
.unwrap();
if let Some(old_pos) = fork_pos {
tree.make_nth_sibling(&other_child, old_pos).unwrap();
}
}
Some(id) if matches!(tree.get(&id).unwrap().data(), Data::Stack { .. }) => {
if tree.children_ids(&id).unwrap().count() == 0 {
slog_scope::debug!("Removing Stack");
// remove stack
let _ = tree.remove_node(id.clone(), RemoveBehavior::DropChildren);
// TODO now we need to untangle the parent_parent
// So we should REFACTOR this unmap function to not only work with windows
} else {
// fixup stack values
if let Data::Stack {
ref mut active,
ref mut len,
} = tree.get_mut(&id).unwrap().data_mut()
{
*len -= 1;
*active = std::cmp::max(*active, *len - 1);
}
}
}
None => {} // root
_ => unreachable!(),
}
// update_space_positions(space, self.gaps);
}
}
}
fn new_fork(
tree: &mut Tree<Data>,
old_id: &NodeId,
new: Node<Data>,
) -> Result<NodeId, NodeIdError> {
let new_fork = Node::new(Data::fork());
let old = tree.get(old_id)?;
let parent_id = old.parent().cloned();
let pos = parent_id.as_ref().and_then(|parent_id| {
tree.children_ids(parent_id)
.unwrap()
.position(|id| id == old_id)
});
let fork_id = tree
.insert(
new_fork,
if let Some(parent) = parent_id.as_ref() {
InsertBehavior::UnderNode(parent)
} else {
InsertBehavior::AsRoot
},
)
.unwrap();
tree.move_node(old_id, MoveBehavior::ToParent(&fork_id))
.unwrap();
// keep position
if let Some(old_pos) = pos {
tree.make_nth_sibling(&fork_id, old_pos).unwrap();
}
tree.insert(new, InsertBehavior::UnderNode(&fork_id))
}
fn update_space_positions(space: &mut Space, gaps: (i32, i32)) -> Vec<Window> {
let mut dead_windows = Vec::new();
let (outer, inner) = gaps;
for output in space.outputs().cloned().collect::<Vec<_>>().into_iter() {
if let Some(mut info) = output
.user_data()
.get::<RefCell<OutputInfo>>()
.map(|x| x.borrow_mut())
{
slog_scope::trace!("Tree:\n{:?}", info);
let tree = &mut info.tree;
if let Some(root) = tree.root_node_id() {
let mut stack = Vec::new();
let mut geo = Some(layer_map_for_output(&output).non_exclusive_zone());
// TODO saturate? minimum?
if let Some(mut geo) = geo.as_mut() {
geo.loc.x += outer;
geo.loc.y += outer;
geo.size.w -= outer * 2;
geo.size.h -= outer * 2;
}
for node in tree.traverse_pre_order(root).unwrap() {
let geo = stack.pop().unwrap_or(geo);
match node.data() {
Data::Fork { orientation, ratio } => {
if let Some(geo) = geo {
match orientation {
Orientation::Horizontal => {
let top_size = (
geo.size.w,
((geo.size.h as f64) * ratio).ceil() as i32,
);
stack.push(Some(Rectangle::from_loc_and_size(
(geo.loc.x, geo.loc.y + top_size.1),
(geo.size.w, geo.size.h - top_size.1),
)));
stack.push(Some(Rectangle::from_loc_and_size(
geo.loc, top_size,
)));
}
Orientation::Vertical => {
let left_size = (
((geo.size.w as f64) * ratio).ceil() as i32,
geo.size.h,
);
stack.push(Some(Rectangle::from_loc_and_size(
(geo.loc.x + left_size.0, geo.loc.y),
(geo.size.w - left_size.0, geo.size.h),
)));
stack.push(Some(Rectangle::from_loc_and_size(
geo.loc, left_size,
)));
}
}
} else {
stack.push(None);
stack.push(None);
}
}
Data::Stack { active, len } => {
for i in 0..*len {
if i == *active {
stack.push(geo);
} else {
stack.push(None);
}
}
}
Data::Window(window) => {
if window.toplevel().alive() {
if let Some(geo) = geo {
#[allow(irrefutable_let_patterns)]
if let Kind::Xdg(xdg) = &window.toplevel() {
let ret = xdg.with_pending_state(|state| {
state.size = Some(
(geo.size.w - inner * 2, geo.size.h - inner * 2)
.into(),
);
state.states.set(XdgState::TiledLeft);
state.states.set(XdgState::TiledRight);
state.states.set(XdgState::TiledTop);
state.states.set(XdgState::TiledBottom);
});
if ret.is_ok() {
xdg.send_configure();
}
}
let window_geo = window.geometry();
space.map_window(
&window,
(
geo.loc.x + inner - window_geo.loc.x,
geo.loc.y + inner - window_geo.loc.y,
),
false,
);
}
} else {
dead_windows.push(window.clone());
}
}
}
}
}
}
}
dead_windows
}