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

389
src/shell/handler.rs Normal file
View file

@ -0,0 +1,389 @@
// SPDX-License-Identifier: GPL-3.0-only
use crate::{input::active_output, state::State, utils::SurfaceDropNotifier};
use smithay::{
backend::renderer::utils::on_commit_buffer_handler,
desktop::{
layer_map_for_output, Kind, LayerSurface, PopupKeyboardGrab, PopupKind, PopupPointerGrab,
PopupUngrabStrategy, Window,
},
reexports::{
wayland_protocols::xdg_shell::server::xdg_toplevel,
wayland_server::{protocol::wl_surface::WlSurface, Display},
},
wayland::{
compositor::{compositor_init, with_states},
output::Output,
seat::{PointerGrabStartData, Seat},
shell::{
wlr_layer::{wlr_layer_shell_init, LayerShellRequest, LayerSurfaceAttributes},
xdg::{
xdg_shell_init, Configure, XdgPopupSurfaceRoleAttributes, XdgRequest,
XdgToplevelSurfaceRoleAttributes,
},
},
Serial,
},
};
use std::{cell::Cell, rc::Rc, sync::Mutex};
pub fn init_shell(display: &mut Display) -> super::Shell {
compositor_init(
display,
move |surface, mut ddata| {
on_commit_buffer_handler(&surface);
let state = ddata.get::<State>().unwrap();
state.common.shell.commit(&surface);
commit(&surface, state)
},
None,
);
let popup_grab = Rc::new(Cell::new(None));
let popup_grab_clone = popup_grab.clone();
let (_xdg_shell_state, _xdg_global) = xdg_shell_init(
display,
move |event, mut ddata| {
let state = &mut ddata.get::<State>().unwrap().common;
match event {
XdgRequest::NewToplevel { surface } => {
state.pending_toplevels.push(surface.clone());
let seat = &state.last_active_seat;
let output = active_output(seat, &*state);
let space = state.shell.active_space_mut(&output);
let window = Window::new(Kind::Xdg(surface));
space.pending_window(window, seat);
// We will position the window after the first commit, when we know its size
}
XdgRequest::NewPopup { surface, .. } => {
state
.shell
.popups
.track_popup(PopupKind::from(surface))
.unwrap();
}
XdgRequest::RePosition {
surface,
positioner,
token,
} => {
let result = surface.with_pending_state(|state| {
// TODO: This is a simplification, a proper compositor would
// calculate the geometry of the popup here.
// For now we just use the default implementation here that does not take the
// window position and output constraints into account.
let geometry = positioner.get_geometry();
state.geometry = geometry;
state.positioner = positioner;
});
if result.is_ok() {
surface.send_repositioned(token);
}
}
XdgRequest::Move {
surface,
seat,
serial,
} => {
let seat = Seat::from_resource(&seat).unwrap();
if let Some(start_data) =
check_grab_preconditions(&seat, surface.get_surface(), serial)
{
let workspace = state
.shell
.space_for_surface_mut(surface.get_surface().unwrap())
.unwrap();
let window = workspace
.space
.window_for_surface(surface.get_surface().unwrap())
.unwrap()
.clone();
workspace.move_request(&window, &seat, serial, start_data);
}
}
XdgRequest::Resize {
surface,
seat,
serial,
edges,
} => {
let seat = Seat::from_resource(&seat).unwrap();
if let Some(start_data) =
check_grab_preconditions(&seat, surface.get_surface(), serial)
{
let workspace = state
.shell
.space_for_surface_mut(surface.get_surface().unwrap())
.unwrap();
let window = workspace
.space
.window_for_surface(surface.get_surface().unwrap())
.unwrap()
.clone();
workspace.resize_request(&window, &seat, serial, start_data, edges);
}
}
XdgRequest::AckConfigure {
surface,
configure: Configure::Toplevel(configure),
} => {
// TODO: This is way to hardcoded and hacky, but wayland-rs 0.30 will make this unnecessary so don't bother.
if let Some(window) = state
.shell
.space_for_surface(&surface)
.and_then(|workspace| workspace.space.window_for_surface(&surface))
{
crate::shell::layout::floating::ResizeSurfaceGrab::ack_configure(
window, configure,
)
}
}
XdgRequest::Maximize { surface } => {
if let Some(surface) = surface.get_surface() {
let seat = &state.last_active_seat;
let output = active_output(seat, &*state);
if let Some(workspace) = state.shell.space_for_surface_mut(surface) {
let window =
workspace.space.window_for_surface(surface).unwrap().clone();
workspace.maximize_request(&window, &output)
}
}
}
XdgRequest::UnMaximize { surface } => {
let ret = surface.with_pending_state(|state| {
state.states.unset(xdg_toplevel::State::Maximized);
state.size = None;
});
if ret.is_ok() {
surface.send_configure();
}
}
XdgRequest::Grab {
serial,
surface,
seat,
} => {
let seat = Seat::from_resource(&seat).unwrap();
let ret = state.shell.popups.grab_popup(surface.into(), &seat, serial);
if let Ok(mut grab) = ret {
if let Some(keyboard) = seat.get_keyboard() {
if keyboard.is_grabbed()
&& !(keyboard.has_grab(serial)
|| keyboard.has_grab(grab.previous_serial().unwrap_or(serial)))
{
grab.ungrab(PopupUngrabStrategy::All);
return;
}
keyboard.set_focus(grab.current_grab().as_ref(), serial);
keyboard.set_grab(PopupKeyboardGrab::new(&grab), serial);
}
if let Some(pointer) = seat.get_pointer() {
if pointer.is_grabbed()
&& !(pointer.has_grab(serial)
|| pointer.has_grab(
grab.previous_serial().unwrap_or_else(|| grab.serial()),
))
{
grab.ungrab(PopupUngrabStrategy::All);
return;
}
pointer.set_grab(PopupPointerGrab::new(&grab), serial, 0);
}
popup_grab_clone.set(Some(grab));
}
}
_ => { /*TODO*/ }
}
},
None,
);
let (_layer_shell_state, _layer_global) = wlr_layer_shell_init(
display,
|event, mut ddata| match event {
LayerShellRequest::NewLayerSurface {
surface,
output: wl_output,
namespace,
..
} => {
let state = &mut ddata.get::<State>().unwrap().common;
let seat = &state.last_active_seat;
let output = wl_output
.as_ref()
.and_then(Output::from_resource)
.unwrap_or_else(|| active_output(seat, &*state));
let mut map = layer_map_for_output(&output);
map.map_layer(&LayerSurface::new(surface, namespace))
.unwrap();
}
_ => {}
},
None,
);
super::Shell::new(popup_grab)
}
fn check_grab_preconditions(
seat: &Seat,
surface: Option<&WlSurface>,
serial: Serial,
) -> Option<PointerGrabStartData> {
let surface = if let Some(surface) = surface {
surface
} else {
return None;
};
// TODO: touch resize.
let pointer = seat.get_pointer().unwrap();
// Check that this surface has a click grab.
if !pointer.has_grab(serial) {
return None;
}
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.as_ref())
{
return None;
}
Some(start_data)
}
fn commit(surface: &WlSurface, state: &mut State) {
// TODO figure out which output the surface is on.
for output in state.common.shell.outputs() {
//.cloned().collect::<Vec<_>>().into_iter() {
state.backend.schedule_render(output);
// let space = state.common.spaces.active_space(output);
// get output for surface
}
let state = &mut state.common;
let _ = with_states(surface, |states| {
states
.data_map
.insert_if_missing(|| SurfaceDropNotifier::from(&*state));
});
if let Some(toplevel) = state.pending_toplevels.iter().find(|toplevel| {
toplevel
.get_surface()
.map(|s| s == surface)
.unwrap_or(false)
}) {
// send the initial configure if relevant
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<Mutex<XdgToplevelSurfaceRoleAttributes>>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
})
.unwrap();
if !initial_configure_sent {
toplevel.send_configure();
}
return;
}
// TODO: This is way to hardcoded and hacky, but wayland-rs 0.30 will make this unnecessary so don't bother.
if let Some((space, window)) =
state
.shell
.space_for_surface_mut(surface)
.and_then(|workspace| {
workspace
.space
.window_for_surface(surface)
.cloned()
.map(|window| (&mut workspace.space, window))
})
{
let new_location = crate::shell::layout::floating::ResizeSurfaceGrab::apply_resize_state(
&window,
space.window_location(&window).unwrap(),
window.geometry().size,
);
if let Some(location) = new_location {
space.map_window(&window, location, true);
}
return;
}
if let Some(popup) = state.shell.popups.find_popup(surface) {
let PopupKind::Xdg(ref popup) = popup;
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<Mutex<XdgPopupSurfaceRoleAttributes>>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
})
.unwrap();
if !initial_configure_sent {
// NOTE: This should never fail as the initial configure is always
// allowed.
popup.send_configure().expect("initial configure failed");
}
return;
}
if let Some(output) = state.shell.outputs().find(|o| {
let map = layer_map_for_output(o);
map.layer_for_surface(surface).is_some()
}) {
let mut map = layer_map_for_output(output);
let layer = map.layer_for_surface(surface).unwrap();
// send the initial configure if relevant
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<Mutex<LayerSurfaceAttributes>>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
})
.unwrap();
if !initial_configure_sent {
layer.layer_surface().send_configure();
}
map.arrange();
return;
};
}

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,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
}

View file

@ -1,476 +1,392 @@
// SPDX-License-Identifier: GPL-3.0-only
use crate::{input::active_output, state::State, utils::SurfaceDropNotifier};
use smithay::{
backend::renderer::utils::on_commit_buffer_handler,
desktop::{
layer_map_for_output, Kind, LayerSurface, PopupKeyboardGrab, PopupKind, PopupManager,
PopupPointerGrab, PopupUngrabStrategy, Window,
},
reexports::{
wayland_protocols::xdg_shell::server::xdg_toplevel,
wayland_server::{protocol::wl_surface::WlSurface, Display},
},
wayland::{
compositor::{compositor_init, with_states},
output::Output,
seat::{PointerGrabStartData, PointerHandle, Seat},
shell::{
wlr_layer::{
wlr_layer_shell_init, LayerShellRequest, LayerShellState, LayerSurfaceAttributes,
},
xdg::{
xdg_shell_init, Configure, ShellState as XdgShellState,
XdgPopupSurfaceRoleAttributes, XdgRequest, XdgToplevelSurfaceRoleAttributes,
},
},
Serial,
},
pub use smithay::{
desktop::{PopupGrab, PopupManager, PopupUngrabStrategy, Space, Window},
reexports::wayland_server::protocol::wl_surface::WlSurface,
utils::{Logical, Point, Rectangle, Size},
wayland::{output::Output, seat::Seat, SERIAL_COUNTER},
};
use std::sync::{Arc, Mutex};
use std::{cell::Cell, mem::MaybeUninit, rc::Rc};
pub mod grabs;
pub mod workspaces;
pub const MAX_WORKSPACES: usize = 10; // TODO?
pub struct ShellStates {
popups: PopupManager,
xdg: Arc<Mutex<XdgShellState>>,
layer: Arc<Mutex<LayerShellState>>,
mod handler;
pub mod layout;
mod workspace;
pub use self::handler::init_shell;
pub use self::layout::Layout;
pub use self::workspace::*;
pub struct ActiveWorkspace(Cell<Option<usize>>);
impl ActiveWorkspace {
fn new() -> Self {
ActiveWorkspace(Cell::new(None))
}
pub fn get(&self) -> Option<usize> {
self.0.get()
}
fn set(&self, active: usize) -> Option<usize> {
self.0.replace(Some(active))
}
fn clear(&self) -> Option<usize> {
self.0.replace(None)
}
}
pub fn init_shell(display: &mut Display) -> ShellStates {
compositor_init(
display,
move |surface, mut ddata| {
on_commit_buffer_handler(&surface);
let state = ddata.get::<State>().unwrap();
state.common.spaces.commit(&surface);
state.common.shell.popups.commit(&surface);
commit(&surface, state)
},
None,
);
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Mode {
OutputBound,
Global { active: usize },
}
let (xdg_shell_state, _xdg_global) = xdg_shell_init(
display,
|event, mut ddata| {
let state = &mut ddata.get::<State>().unwrap().common;
impl Mode {
pub fn output_bound() -> Mode {
Mode::OutputBound
}
match event {
XdgRequest::NewToplevel { surface } => {
state.pending_toplevels.push(surface.clone());
pub fn global() -> Mode {
Mode::Global { active: 0 }
}
}
let seat = &state.last_active_seat;
let output = active_output(seat, &*state);
let space = state.spaces.active_space_mut(&output);
let window = Window::new(Kind::Xdg(surface));
space.map_window(&window, (0, 0), true);
// We will position the window after the first commit, when we know its size
pub struct Shell {
popups: PopupManager,
popup_grab: Rc<Cell<Option<PopupGrab>>>,
mode: Mode,
outputs: Vec<Output>,
pub spaces: [Workspace; MAX_WORKSPACES],
}
const UNINIT_SPACE: MaybeUninit<Workspace> = MaybeUninit::uninit();
impl Shell {
fn new(popup_grab: Rc<Cell<Option<PopupGrab>>>) -> Self {
Shell {
popups: PopupManager::new(None),
popup_grab,
mode: Mode::global(),
outputs: Vec::new(),
spaces: unsafe {
let mut spaces = [UNINIT_SPACE; MAX_WORKSPACES];
for space in &mut spaces {
*space = MaybeUninit::new(Workspace::new());
}
XdgRequest::NewPopup { surface, .. } => {
state
.shell
.popups
.track_popup(PopupKind::from(surface))
.unwrap();
}
XdgRequest::RePosition {
surface,
positioner,
token,
} => {
let result = surface.with_pending_state(|state| {
// TODO: This is a simplification, a proper compositor would
// calculate the geometry of the popup here.
// For now we just use the default implementation here that does not take the
// window position and output constraints into account.
let geometry = positioner.get_geometry();
state.geometry = geometry;
state.positioner = positioner;
});
std::mem::transmute(spaces)
},
}
}
if result.is_ok() {
surface.send_repositioned(token);
}
}
XdgRequest::Move {
surface,
seat,
serial,
} => {
let seat = Seat::from_resource(&seat).unwrap();
if let Some((pointer, start_data)) =
check_grab_preconditions(&seat, surface.get_surface(), serial)
{
let space = state
.spaces
.space_for_surface(surface.get_surface().unwrap())
.unwrap();
let window = space
.window_for_surface(surface.get_surface().unwrap())
.unwrap()
.clone();
let mut initial_window_location = space.window_location(&window).unwrap();
pub fn map_output(&mut self, output: &Output) {
match self.mode {
Mode::OutputBound => {
output
.user_data()
.insert_if_missing(|| ActiveWorkspace::new());
// If surface is maximized then unmaximize it
if let Some(current_state) = surface.current_state() {
if current_state
.states
.contains(xdg_toplevel::State::Maximized)
{
let fs_changed = surface.with_pending_state(|state| {
state.states.unset(xdg_toplevel::State::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 = grabs::MoveSurfaceGrab::new(
start_data,
window,
initial_window_location,
);
pointer.set_grab(grab, serial, 0);
}
}
XdgRequest::Resize {
surface,
seat,
serial,
edges,
} => {
let seat = Seat::from_resource(&seat).unwrap();
if let Some((pointer, start_data)) =
check_grab_preconditions(&seat, surface.get_surface(), serial)
{
let space = state
.spaces
.space_for_surface(surface.get_surface().unwrap())
.unwrap();
let window = space
.window_for_surface(surface.get_surface().unwrap())
.unwrap()
.clone();
let location = space.window_location(&window).unwrap();
let size = window.geometry().size;
let grab = grabs::ResizeSurfaceGrab::new(
start_data, window, edges, location, size,
);
pointer.set_grab(grab, serial, 0);
}
}
XdgRequest::AckConfigure {
surface,
configure: Configure::Toplevel(configure),
} => {
if let Some(window) = state
.spaces
.space_for_surface(&surface)
.and_then(|space| space.window_for_surface(&surface))
{
grabs::ResizeSurfaceGrab::ack_configure(window, configure)
}
}
XdgRequest::Maximize { surface } => {
let seat = &state.last_active_seat;
let output = active_output(seat, &*state);
let space = state.spaces.active_space_mut(&output);
let window = space
.window_for_surface(surface.get_surface().unwrap())
.unwrap()
.clone();
let layers = layer_map_for_output(&output);
let geometry = layers.non_exclusive_zone();
space.map_window(&window, geometry.loc, true);
let ret = surface.with_pending_state(|state| {
state.states.set(xdg_toplevel::State::Maximized);
state.size = Some(geometry.size);
});
if ret.is_ok() {
window.configure();
}
}
XdgRequest::UnMaximize { surface } => {
let ret = surface.with_pending_state(|state| {
state.states.unset(xdg_toplevel::State::Maximized);
state.size = None;
});
if ret.is_ok() {
surface.send_configure();
}
}
XdgRequest::Grab {
serial,
surface,
seat,
} => {
let seat = Seat::from_resource(&seat).unwrap();
let ret = state.shell.popups.grab_popup(surface.into(), &seat, serial);
if let Ok(mut grab) = ret {
if let Some(keyboard) = seat.get_keyboard() {
if keyboard.is_grabbed()
&& !(keyboard.has_grab(serial)
|| keyboard.has_grab(grab.previous_serial().unwrap_or(serial)))
{
grab.ungrab(PopupUngrabStrategy::All);
return;
}
keyboard.set_focus(grab.current_grab().as_ref(), serial);
keyboard.set_grab(PopupKeyboardGrab::new(&grab), serial);
}
if let Some(pointer) = seat.get_pointer() {
if pointer.is_grabbed()
&& !(pointer.has_grab(serial)
|| pointer.has_grab(
grab.previous_serial().unwrap_or_else(|| grab.serial()),
))
{
grab.ungrab(PopupUngrabStrategy::All);
return;
}
pointer.set_grab(PopupPointerGrab::new(&grab), serial, 0);
}
}
}
_ => { /*TODO*/ }
let (idx, workspace) = self
.spaces
.iter_mut()
.enumerate()
.find(|(_, x)| x.space.outputs().next().is_none())
.expect("More then 10 outputs?");
output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.set(idx);
workspace.space.map_output(output, 1.0, (0, 0));
self.outputs.push(output.clone());
}
},
None,
);
Mode::Global { active } => {
// just put new outputs on the right of the previous ones.
// in the future we will only need that as a fallback and need to read saved configurations here
let workspace = &mut self.spaces[active];
let x = workspace
.space
.outputs()
.map(|output| workspace.space.output_geometry(&output).unwrap())
.fold(0, |acc, geo| std::cmp::max(acc, geo.loc.x + geo.size.w));
workspace.space.map_output(output, 1.0, (x, 0));
self.outputs.push(output.clone());
}
}
}
let (layer_shell_state, _layer_global) = wlr_layer_shell_init(
display,
|event, mut ddata| match event {
LayerShellRequest::NewLayerSurface {
surface,
output: wl_output,
namespace,
..
} => {
let state = &mut ddata.get::<State>().unwrap().common;
let seat = &state.last_active_seat;
let output = wl_output
.as_ref()
.and_then(Output::from_resource)
.unwrap_or_else(|| active_output(seat, &*state));
pub fn unmap_output(&mut self, output: &Output) {
match self.mode {
Mode::OutputBound => {
if let Some(idx) = output
.user_data()
.get::<ActiveWorkspace>()
.and_then(|a| a.get())
{
self.spaces[idx].space.unmap_output(output);
self.outputs.retain(|o| o != output);
}
}
Mode::Global { active } => {
self.spaces[active].space.unmap_output(output);
self.outputs.retain(|o| o != output);
// TODO move windows and outputs farther on the right / or load save config for remaining monitors
}
}
}
let mut map = layer_map_for_output(&output);
map.map_layer(&LayerSurface::new(surface, namespace))
.unwrap();
pub fn output_size(&self, output: &Output) -> Size<i32, Logical> {
let workspace = self.active_space(output);
workspace
.space
.output_geometry(&output)
.unwrap_or(Rectangle::from_loc_and_size((0, 0), (0, 0)))
.size
}
pub fn global_space(&self) -> Rectangle<i32, Logical> {
let size = self.outputs.iter().fold((0, 0), |(w, h), output| {
let size = self.output_size(output);
(w + size.w, std::cmp::max(h, size.h))
});
Rectangle::from_loc_and_size((0, 0), size)
}
pub fn space_relative_output_geometry(
&self,
global_loc: impl Into<Point<i32, Logical>>,
output: &Output,
) -> Point<i32, Logical> {
match self.mode {
Mode::Global { .. } => global_loc.into(),
Mode::OutputBound => global_loc.into() - self.output_geometry(output).loc,
}
}
pub fn output_geometry(&self, output: &Output) -> Rectangle<i32, Logical> {
// due to our different modes, we cannot just ask the space for the global output coordinates,
// because for `Mode::OutputBound` the origin will always be (0, 0)
// TODO: Add a proper grid like structure, for now the outputs just extend to the right
let pos =
self.outputs
.iter()
.take_while(|o| o != &output)
.fold((0, 0), |(x, y), output| {
let size = self.output_size(output);
(x + size.w, y)
});
Rectangle::from_loc_and_size(pos, self.output_size(output))
}
pub fn activate(&mut self, output: &Output, idx: usize) {
match self.mode {
Mode::OutputBound => {
// TODO check for other outputs already occupying that space
if let Some(active) = output.user_data().get::<ActiveWorkspace>() {
if let Some(old_idx) = active.set(idx) {
self.spaces[old_idx].space.unmap_output(output);
}
self.spaces[idx].space.map_output(output, 1.0, (0, 0));
}
// TODO translate windows from previous space size into new size
}
Mode::Global { ref mut active } => {
let old = *active;
*active = idx;
for output in &self.outputs {
let loc = self.spaces[old].space.output_geometry(output).unwrap().loc;
self.spaces[old].space.unmap_output(output);
self.spaces[*active].space.map_output(output, 1.0, loc);
}
}
};
}
#[cfg(feature = "debug")]
pub fn mode(&self) -> &Mode {
&self.mode
}
pub fn set_mode(&mut self, mode: Mode) {
match (&mut self.mode, mode) {
(Mode::OutputBound, Mode::Global { .. }) => {
let active = self
.outputs
.iter()
.next()
.map(|o| {
o.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.get()
.unwrap()
})
.unwrap_or(0);
let mut x = 0;
for output in &self.outputs {
let old_active = output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.clear()
.unwrap();
let width = self.spaces[old_active]
.space
.output_geometry(output)
.unwrap()
.size
.w;
self.spaces[old_active].space.unmap_output(output);
self.spaces[active].space.map_output(output, 1.0, (x, 0));
x += width;
}
self.mode = Mode::Global { active };
// TODO move windows into new bounds
}
(Mode::Global { active }, new @ Mode::OutputBound) => {
for output in &self.outputs {
self.spaces[*active].space.unmap_output(output);
}
self.mode = new;
let outputs = self.outputs.drain(..).collect::<Vec<_>>();
for output in &outputs {
self.map_output(output);
}
// TODO move windows into new bounds
// TODO active should probably be mapped somewhere
}
_ => {}
},
None,
);
ShellStates {
popups: PopupManager::new(None),
xdg: xdg_shell_state,
layer: layer_shell_state,
}
}
fn check_grab_preconditions(
seat: &Seat,
surface: Option<&WlSurface>,
serial: Serial,
) -> Option<(PointerHandle, PointerGrabStartData)> {
let surface = if let Some(surface) = surface {
surface
} else {
return None;
};
// TODO: touch resize.
let pointer = seat.get_pointer().unwrap();
// Check that this surface has a click grab.
if !pointer.has_grab(serial) {
return None;
};
}
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.as_ref())
{
return None;
pub fn outputs(&self) -> impl Iterator<Item = &Output> {
self.outputs.iter()
}
Some((pointer, start_data))
}
fn commit(surface: &WlSurface, state: &mut State) {
// TODO figure out which output the surface is on.
for output in state.common.spaces.outputs() {
//.cloned().collect::<Vec<_>>().into_iter() {
state.backend.schedule_render(output);
// let space = state.common.spaces.active_space(output);
// get output for surface
}
let state = &mut state.common;
let _ = with_states(surface, |states| {
states
.data_map
.insert_if_missing(|| SurfaceDropNotifier::from(&*state));
});
if let Some(toplevel) = state.pending_toplevels.iter().find(|toplevel| {
toplevel
.get_surface()
.map(|s| s == surface)
.unwrap_or(false)
}) {
// send the initial configure if relevant
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<Mutex<XdgToplevelSurfaceRoleAttributes>>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
})
.unwrap();
if !initial_configure_sent {
toplevel.send_configure();
pub fn active_space(&self, output: &Output) -> &Workspace {
match &self.mode {
Mode::OutputBound => {
let active = output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.get()
.unwrap();
&self.spaces[active]
}
Mode::Global { active } => &self.spaces[*active],
}
}
// position our new window
if let Some(space) = toplevel
.get_surface()
.and_then(|surface| state.spaces.space_for_surface_mut(surface))
{
let window = space
.window_for_surface(toplevel.get_surface().unwrap())
.unwrap()
.clone();
if let Some(output) = space.outputs_for_window(&window).iter().next() {
let win_geo = window.bbox();
if win_geo.size.w > 0 && win_geo.size.h > 0 {
let layers = layer_map_for_output(&output);
let geometry = layers.non_exclusive_zone();
pub fn active_space_mut(&mut self, output: &Output) -> &mut Workspace {
match &self.mode {
Mode::OutputBound => {
let active = output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.get()
.unwrap();
&mut self.spaces[active]
}
Mode::Global { active } => &mut self.spaces[*active],
}
}
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),
);
space.map_window(&window, position, true);
state.pending_toplevels.retain(|toplevel| {
toplevel
.get_surface()
.map(|s| s != surface)
.unwrap_or(false)
});
pub fn space_for_surface(&self, surface: &WlSurface) -> Option<&Workspace> {
self.spaces.iter().find(|workspace| {
workspace
.pending_windows
.iter()
.any(|(w, _)| w.toplevel().get_surface() == Some(surface))
|| workspace.space.window_for_surface(surface).is_some()
})
}
pub fn space_for_surface_mut(&mut self, surface: &WlSurface) -> Option<&mut Workspace> {
self.spaces
.iter_mut()
.find(|workspace| workspace.space.window_for_surface(surface).is_some())
}
pub fn refresh(&mut self) {
for workspace in &mut self.spaces {
workspace.refresh();
}
}
pub fn commit(&mut self, surface: &WlSurface) {
let mut new_focus = None;
for (idx, workspace) in self.spaces.iter_mut().enumerate() {
if let Some((window, seat)) = workspace
.pending_windows
.iter()
.find(|(w, _)| w.toplevel().get_surface() == Some(surface))
.cloned()
{
workspace.map_window(&window, &seat);
if match self.mode {
Mode::OutputBound => self.outputs.iter().any(|o| {
o.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.get()
.unwrap()
== idx
}),
Mode::Global { active } => active == idx,
} {
new_focus = Some(seat);
}
workspace.pending_windows.retain(|(w, _)| w != &window);
}
workspace.space.commit(surface)
}
if let Some(seat) = new_focus {
self.set_focus(Some(surface), &seat)
}
self.popups.commit(&surface);
}
pub fn set_focus(&mut self, surface: Option<&WlSurface>, active_seat: &Seat) {
// update FocusStack and notify layouts about new focus (if any window)
if let Some(surface) = surface {
if let Some(workspace) = self.space_for_surface_mut(surface) {
if let Some(window) = workspace.space.window_for_surface(surface) {
if Some(window) != workspace.focus_stack.last().as_ref() {
slog_scope::debug!("Focusing window: {:?}", window);
workspace.focus_stack.append(window);
// also remove popup grabs, if we are switching focus
if let Some(mut popup_grab) = self.popup_grab.take() {
if !popup_grab.has_ended() {
popup_grab.ungrab(PopupUngrabStrategy::All);
}
}
}
}
}
}
return;
}
if let Some((space, window)) = state
.spaces
.space_for_surface_mut(surface)
.and_then(|space| {
space
.window_for_surface(surface)
.cloned()
.map(|window| (space, window))
})
{
let new_location = grabs::ResizeSurfaceGrab::apply_resize_state(
&window,
space.window_location(&window).unwrap(),
window.geometry().size,
);
if let Some(location) = new_location {
space.map_window(&window, location, true);
// update keyboard focus
if let Some(keyboard) = active_seat.get_keyboard() {
keyboard.set_focus(surface, SERIAL_COUNTER.next_serial());
}
return;
}
// update activate status
let focused_windows = self
.outputs
.iter()
.flat_map(|o| self.active_space(o).focus_stack.last())
.collect::<Vec<_>>();
if let Some(popup) = state.shell.popups.find_popup(surface) {
let PopupKind::Xdg(ref popup) = popup;
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<Mutex<XdgPopupSurfaceRoleAttributes>>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
})
.unwrap();
if !initial_configure_sent {
// NOTE: This should never fail as the initial configure is always
// allowed.
popup.send_configure().expect("initial configure failed");
for workspace in &self.spaces {
for window in workspace.space.windows() {
window.set_activated(focused_windows.contains(window));
window.configure();
}
}
return;
}
if let Some(output) = state.spaces.outputs().find(|o| {
let map = layer_map_for_output(o);
map.layer_for_surface(surface).is_some()
}) {
let mut map = layer_map_for_output(output);
let layer = map.layer_for_surface(surface).unwrap();
// send the initial configure if relevant
let initial_configure_sent = with_states(surface, |states| {
states
.data_map
.get::<Mutex<LayerSurfaceAttributes>>()
.unwrap()
.lock()
.unwrap()
.initial_configure_sent
})
.unwrap();
if !initial_configure_sent {
layer.layer_surface().send_configure();
}
map.arrange();
return;
};
}

93
src/shell/workspace.rs Normal file
View file

@ -0,0 +1,93 @@
use super::{layout, Layout};
use indexmap::IndexSet;
use smithay::{
desktop::{Space, Window},
reexports::wayland_protocols::xdg_shell::server::xdg_toplevel::ResizeEdge,
wayland::{
output::Output,
seat::{PointerGrabStartData, Seat},
Serial,
},
};
pub struct FocusStack(IndexSet<Window>);
impl FocusStack {
pub fn new() -> FocusStack {
FocusStack(IndexSet::new())
}
pub fn append(&mut self, window: &Window) {
self.0.retain(|w| w.toplevel().alive());
self.0.shift_remove(window);
self.0.insert(window.clone());
}
pub fn last(&self) -> Option<Window> {
self.0.iter().rev().find(|w| w.toplevel().alive()).cloned()
}
pub fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Window> + 'a> {
//working around object-safety constraints for trait Layout
Box::new(self.0.iter().rev().filter(|w| w.toplevel().alive()))
}
}
pub struct Workspace {
pub space: Space,
pub(super) layout: Box<dyn Layout>,
pub focus_stack: FocusStack,
pub(super) pending_windows: Vec<(Window, Seat)>,
}
impl Workspace {
pub fn new() -> Workspace {
Workspace {
space: Space::new(None),
layout: layout::new_default_layout(),
focus_stack: FocusStack::new(),
pending_windows: Vec::new(),
}
}
pub fn pending_window(&mut self, window: Window, seat: &Seat) {
self.pending_windows.push((window, seat.clone()));
}
pub(super) fn map_window<'a>(&mut self, window: &Window, seat: &Seat) {
self.layout
.map_window(&mut self.space, window, seat, self.focus_stack.iter())
}
pub fn refresh(&mut self) {
self.layout.refresh(&mut self.space);
self.space.refresh();
}
pub fn maximize_request(&mut self, window: &Window, output: &Output) {
self.layout
.maximize_request(&mut self.space, window, output)
}
pub fn move_request(
&mut self,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
) {
self.layout
.move_request(&mut self.space, window, seat, serial, start_data)
}
pub fn resize_request(
&mut self,
window: &Window,
seat: &Seat,
serial: Serial,
start_data: PointerGrabStartData,
edges: ResizeEdge,
) {
self.layout
.resize_request(&mut self.space, window, seat, serial, start_data, edges)
}
}

View file

@ -1,306 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
pub use smithay::{
desktop::Space,
reexports::wayland_server::protocol::wl_surface::WlSurface,
utils::{Logical, Point, Rectangle, Size},
wayland::output::Output,
};
use std::{cell::Cell, mem::MaybeUninit};
pub const MAX_WORKSPACES: usize = 10; // TODO?
pub struct ActiveWorkspace(Cell<Option<usize>>);
impl ActiveWorkspace {
fn new() -> Self {
ActiveWorkspace(Cell::new(None))
}
pub fn get(&self) -> Option<usize> {
self.0.get()
}
fn set(&self, active: usize) -> Option<usize> {
self.0.replace(Some(active))
}
fn clear(&self) -> Option<usize> {
self.0.replace(None)
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Mode {
OutputBound,
Global { active: usize },
}
impl Mode {
pub fn output_bound() -> Mode {
Mode::OutputBound
}
pub fn global() -> Mode {
Mode::Global { active: 0 }
}
}
pub struct Workspaces {
mode: Mode,
outputs: Vec<Output>,
pub spaces: [Space; MAX_WORKSPACES],
}
const UNINIT_SPACE: MaybeUninit<Space> = MaybeUninit::uninit();
impl Workspaces {
pub fn new() -> Self {
Workspaces {
mode: Mode::global(),
outputs: Vec::new(),
spaces: unsafe {
let mut spaces = [UNINIT_SPACE; MAX_WORKSPACES];
spaces.fill_with(|| MaybeUninit::new(Space::new(None)));
std::mem::transmute(spaces)
},
}
}
pub fn map_output(&mut self, output: &Output) {
match self.mode {
Mode::OutputBound => {
output
.user_data()
.insert_if_missing(|| ActiveWorkspace::new());
let (idx, space) = self
.spaces
.iter_mut()
.enumerate()
.find(|(_, x)| x.outputs().next().is_none())
.expect("More then 10 outputs?");
output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.set(idx);
space.map_output(output, 1.0, (0, 0));
self.outputs.push(output.clone());
}
Mode::Global { active } => {
// just put new outputs on the right of the previous ones.
// in the future we will only need that as a fallback and need to read saved configurations here
let space = &mut self.spaces[active];
let x = space
.outputs()
.map(|output| space.output_geometry(&output).unwrap())
.fold(0, |acc, geo| std::cmp::max(acc, geo.loc.x + geo.size.w));
space.map_output(output, 1.0, (x, 0));
self.outputs.push(output.clone());
}
}
}
pub fn unmap_output(&mut self, output: &Output) {
match self.mode {
Mode::OutputBound => {
if let Some(idx) = output
.user_data()
.get::<ActiveWorkspace>()
.and_then(|a| a.get())
{
self.spaces[idx].unmap_output(output);
self.outputs.retain(|o| o != output);
}
}
Mode::Global { active } => {
self.spaces[active].unmap_output(output);
self.outputs.retain(|o| o != output);
// TODO move windows and outputs farther on the right / or load save config for remaining monitors
}
}
}
pub fn output_size(&self, output: &Output) -> Size<i32, Logical> {
let space = self.active_space(output);
space
.output_geometry(&output)
.unwrap_or(Rectangle::from_loc_and_size((0, 0), (0, 0)))
.size
}
pub fn global_space(&self) -> Rectangle<i32, Logical> {
let size = self.outputs.iter().fold((0, 0), |(w, h), output| {
let size = self.output_size(output);
(w + size.w, std::cmp::max(h, size.h))
});
Rectangle::from_loc_and_size((0, 0), size)
}
pub fn space_relative_output_geometry(
&self,
global_loc: impl Into<Point<i32, Logical>>,
output: &Output,
) -> Point<i32, Logical> {
match self.mode {
Mode::Global { .. } => global_loc.into(),
Mode::OutputBound => global_loc.into() - self.output_geometry(output).loc,
}
}
pub fn output_geometry(&self, output: &Output) -> Rectangle<i32, Logical> {
// due to our different modes, we cannot just ask the space for the global output coordinates,
// because for `Mode::OutputBound` the origin will always be (0, 0)
// TODO: Add a proper grid like structure, for now the outputs just extend to the right
let pos =
self.outputs
.iter()
.take_while(|o| o != &output)
.fold((0, 0), |(x, y), output| {
let size = self.output_size(output);
(x + size.w, y)
});
Rectangle::from_loc_and_size(pos, self.output_size(output))
}
pub fn activate(&mut self, output: &Output, idx: usize) {
match self.mode {
Mode::OutputBound => {
// TODO check for other outputs already occupying that space
if let Some(active) = output.user_data().get::<ActiveWorkspace>() {
if let Some(old_idx) = active.set(idx) {
self.spaces[old_idx].unmap_output(output);
}
self.spaces[idx].map_output(output, 1.0, (0, 0));
}
// TODO translate windows from previous space size into new size
}
Mode::Global { ref mut active } => {
let old = *active;
*active = idx;
for output in &self.outputs {
let loc = self.spaces[old].output_geometry(output).unwrap().loc;
self.spaces[old].unmap_output(output);
self.spaces[*active].map_output(output, 1.0, loc);
}
}
};
}
#[cfg(feature = "debug")]
pub fn mode(&self) -> &Mode {
&self.mode
}
pub fn set_mode(&mut self, mode: Mode) {
match (&mut self.mode, mode) {
(Mode::OutputBound, Mode::Global { .. }) => {
let active = self
.outputs
.iter()
.next()
.map(|o| {
o.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.get()
.unwrap()
})
.unwrap_or(0);
let mut x = 0;
for output in &self.outputs {
let old_active = output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.clear()
.unwrap();
let width = self.spaces[old_active]
.output_geometry(output)
.unwrap()
.size
.w;
self.spaces[old_active].unmap_output(output);
self.spaces[active].map_output(output, 1.0, (x, 0));
x += width;
}
self.mode = Mode::Global { active };
// TODO move windows into new bounds
}
(Mode::Global { active }, new @ Mode::OutputBound) => {
for output in &self.outputs {
self.spaces[*active].unmap_output(output);
}
self.mode = new;
let outputs = self.outputs.drain(..).collect::<Vec<_>>();
for output in &outputs {
self.map_output(output);
}
// TODO move windows into new bounds
// TODO active should probably be mapped somewhere
}
_ => {}
};
}
pub fn outputs(&self) -> impl Iterator<Item = &Output> {
self.outputs.iter()
}
pub fn active_space(&self, output: &Output) -> &Space {
match &self.mode {
Mode::OutputBound => {
let active = output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.get()
.unwrap();
&self.spaces[active]
}
Mode::Global { active } => &self.spaces[*active],
}
}
pub fn active_space_mut(&mut self, output: &Output) -> &mut Space {
match &self.mode {
Mode::OutputBound => {
let active = output
.user_data()
.get::<ActiveWorkspace>()
.unwrap()
.get()
.unwrap();
&mut self.spaces[active]
}
Mode::Global { active } => &mut self.spaces[*active],
}
}
pub fn space_for_surface(&self, surface: &WlSurface) -> Option<&Space> {
self.spaces
.iter()
.find(|space| space.window_for_surface(surface).is_some())
}
pub fn space_for_surface_mut(&mut self, surface: &WlSurface) -> Option<&mut Space> {
self.spaces
.iter_mut()
.find(|space| space.window_for_surface(surface).is_some())
}
pub fn refresh(&mut self) {
for space in &mut self.spaces {
space.refresh()
}
}
pub fn commit(&mut self, surface: &WlSurface) {
for space in &mut self.spaces {
space.commit(surface)
}
}
}