forge
Explore
Log in

Don't you dare go Hollow

Refactor everything, add initial tiling code

Browse files at this commit

95c810c855a27a28f4dfa7dc6b949fef0901c7b2Ivan MolodetskikhParent: e02e35f

13 changed files +1974 -438

Cargo.tomlmodified+1 -1
@@ -1,7 +1,7 @@
1 [package]1 [package]
2 name = "niri"2 name = "niri"
3 version = "0.1.0"3 version = "0.1.0"
4-description = "A Wayland compositor"4+description = "A scrollable-tiling Wayland compositor"
5 authors = ["Ivan Molodetskikh <yalterz@gmail.com>"]5 authors = ["Ivan Molodetskikh <yalterz@gmail.com>"]
6 license = "GPL-3.0-or-later"6 license = "GPL-3.0-or-later"
7 edition = "2021"7 edition = "2021"
README.mdmodified+62 -3
@@ -1,12 +1,71 @@
1 # niri1 # niri
2 2
3-The beginnings of a Wayland compositor.3+The beginnings of a scrollable-tiling Wayland compositor.
4+
5+## Status
6+
7+Heavily work in progress.
8+The occasional thing works, but likely is in a half-broken state.
9+
10+## Idea
11+
12+This section describes the goals I'm working towards.
13+Many things don't work as written yet.
14+
15+Niri implements scrollable tiling, heavily inspired by [PaperWM].
16+Windows are arranged in columns on an infinite strip going to the right.
17+Every column takes up as much height as possible, spread between its windows.
18+
19+![](https://github.com/YaLTeR/niri/assets/1794388/b734da07-301a-452b-b201-d4789a3eca60)
20+
21+With multiple monitors, every monitor has its own separate window strip.
22+Windows can never "overflow" to an adjacent monitor.
23+
24+This is one of the reasons that prompted me to try writing my own compositor.
25+PaperWM is a solid implementation that I use every day, but, being a GNOME Shell extension, it has to work around Shell's global window coordinate space to prevent windows from overflowing.
26+
27+Niri also has dynamic workspaces which work similar to GNOME Shell.
28+Since windows go left-to-right horizontally, workspaces are arranged vertically.
29+Every monitor has an independent set of workspaces, and there's always one empty workspace present all the way down.
30+
31+Niri tries to preserve the workspace arrangement as much as possible upon disconnecting and connecting monitors.
32+When a monitor disconnects, its workspaces will move to another monitor, but upon reconnection they will move back to the original monitor where it makes sense.
4 33
5 ## Running34 ## Running
6 35
7 `cargo run -- -- alacritty`36 `cargo run -- -- alacritty`
8 37
9-Inside a desktop session, it will run in a window. On a TTY, it will run natively.38+Inside a desktop session, it will run in a window.
39+On a TTY, it will run natively.
40+
41+To exit when running on a TTY, press <kbd>Super</kbd><kbd>Shift</kbd><kbd>E</kbd>.
42+
43+## Hotkeys
44+
45+When running on a TTY, the Mod key is <kbd>Super</kbd>.
46+When running in a window, the Mod key is <kbd>Alt</kbd>.
47+
48+The general system is: if a hotkey switches somewhere, then adding <kbd>Ctrl</kbd> will move the focused window or column there.
49+
50+| Hotkey | Description |
51+| ------ | ----------- |
52+| <kbd>Mod</kbd><kbd>T</kbd> | Spawn `alacritty` |
53+| <kbd>Mod</kbd><kbd>Q</kbd> | Close the focused window |
54+| <kbd>Mod</kbd><kbd>H</kbd> or <kbd>Mod</kbd><kbd>←</kbd> | Focus the window to the left |
55+| <kbd>Mod</kbd><kbd>L</kbd> or <kbd>Mod</kbd><kbd>→</kbd> | Focus the window to the right |
56+| <kbd>Mod</kbd><kbd>J</kbd> or <kbd>Mod</kbd><kbd>↓</kbd> | Focus the window below in a column |
57+| <kbd>Mod</kbd><kbd>K</kbd> or <kbd>Mod</kbd><kbd>↑</kbd> | Focus the window above in a column |
58+| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>H</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>←</kbd> | Move the focused column to the left |
59+| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>L</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>→</kbd> | Move the focused column to the right |
60+| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>J</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>↓</kbd> | Move the focused window below in a column |
61+| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>K</kbd> or <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>↑</kbd> | Move the focused window above in a column |
62+| <kbd>Mod</kbd><kbd>U</kbd> | Switch to the workspace below |
63+| <kbd>Mod</kbd><kbd>I</kbd> | Switch to the workspace above |
64+| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>U</kbd> | Move the focused window to the workspace below |
65+| <kbd>Mod</kbd><kbd>Ctrl</kbd><kbd>I</kbd> | Move the focused window to the workspace above |
66+| <kbd>Mod</kbd><kbd>,</kbd> | Consume the window to the right into the focused column |
67+| <kbd>Mod</kbd><kbd>.</kbd> | Expel the focused window into its own column |
68+| <kbd>Mod</kbd><kbd>Shift</kbd><kbd>E</kbd> | Exit niri |
10 69
11-To exit when running on a TTY, press <kbd>Super</kbd>+<kbd>Shift</kbd>+<kbd>e</kbd>.70+[PaperWM]: https://github.com/paperwm/PaperWM
12 71
src/backend.rsmodified+2 -0
@@ -1,5 +1,6 @@
1 use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;1 use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
2 use smithay::backend::renderer::gles::GlesRenderer;2 use smithay::backend::renderer::gles::GlesRenderer;
3+use smithay::output::Output;
3 4
4 use crate::niri::OutputRenderElements;5 use crate::niri::OutputRenderElements;
5 use crate::Niri;6 use crate::Niri;
@@ -10,6 +11,7 @@ pub trait Backend {
10 fn render(11 fn render(
11 &mut self,12 &mut self,
12 niri: &mut Niri,13 niri: &mut Niri,
14+ output: &Output,
13 elements: &[OutputRenderElements<15 elements: &[OutputRenderElements<
14 GlesRenderer,16 GlesRenderer,
15 WaylandSurfaceRenderElement<GlesRenderer>,17 WaylandSurfaceRenderElement<GlesRenderer>,
src/grabs/move_grab.rsmodified+8 -4
@@ -5,6 +5,7 @@ use smithay::input::pointer::{
5 };5 };
6 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;6 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
7 use smithay::utils::{Logical, Point};7 use smithay::utils::{Logical, Point};
8+use smithay::wayland::seat::WaylandFocus;
8 9
9 use crate::Niri;10 use crate::Niri;
10 11
@@ -25,10 +26,13 @@ impl PointerGrab<Niri> for MoveSurfaceGrab {
25 // While the grab is active, no client has pointer focus26 // While the grab is active, no client has pointer focus
26 handle.motion(data, None, event);27 handle.motion(data, None, event);
27 28
28- let delta = event.location - self.start_data.location;29+ // let delta = event.location - self.start_data.location;
29- let new_location = self.initial_window_location.to_f64() + delta;30+ // let new_location = self.initial_window_location.to_f64() + delta;
30- data.space31+ // let (window, space) = data
31- .map_element(self.window.clone(), new_location.to_i32_round(), true);32+ // .monitor_set
33+ // .find_window_and_space(self.window.wl_surface().as_ref().unwrap())
34+ // .unwrap();
35+ // space.map_element(window.clone(), new_location.to_i32_round(), true);
32 }36 }
33 37
34 fn relative_motion(38 fn relative_motion(
src/grabs/resize_grab.rsmodified+41 -41
@@ -1,6 +1,6 @@
1 use std::cell::RefCell;1 use std::cell::RefCell;
2 2
3-use smithay::desktop::{Space, Window};3+use smithay::desktop::Window;
4 use smithay::input::pointer::{4 use smithay::input::pointer::{
5 AxisFrame, ButtonEvent, GrabStartData as PointerGrabStartData, MotionEvent, PointerGrab,5 AxisFrame, ButtonEvent, GrabStartData as PointerGrabStartData, MotionEvent, PointerGrab,
6 PointerInnerHandle, RelativeMotionEvent,6 PointerInnerHandle, RelativeMotionEvent,
@@ -241,48 +241,48 @@ impl ResizeSurfaceState {
241 }241 }
242 }242 }
243 243
244-/// Should be called on `WlSurface::commit`244+pub fn handle_commit(window: &Window) -> Option<()> {
245-pub fn handle_commit(space: &mut Space<Window>, surface: &WlSurface) -> Option<()> {245+ // FIXME
246- let window = space246+ let surface = window.toplevel().wl_surface();
247- .elements()247+ ResizeSurfaceState::with(surface, |state| {
248- .find(|w| w.toplevel().wl_surface() == surface)248+ state.commit();
249- .cloned()?;
250-
251- let mut window_loc = space.element_location(&window)?;
252- let geometry = window.geometry();
253-
254- let new_loc: Point<Option<i32>, Logical> = ResizeSurfaceState::with(surface, |state| {
255- state
256- .commit()
257- .and_then(|(edges, initial_rect)| {
258- // If the window is being resized by top or left, its location must be adjusted
259- // accordingly.
260- edges.intersects(ResizeEdge::TOP_LEFT).then(|| {
261- let new_x = edges
262- .intersects(ResizeEdge::LEFT)
263- .then_some(initial_rect.loc.x + (initial_rect.size.w - geometry.size.w));
264-
265- let new_y = edges
266- .intersects(ResizeEdge::TOP)
267- .then_some(initial_rect.loc.y + (initial_rect.size.h - geometry.size.h));
268-
269- (new_x, new_y).into()
270- })
271- })
272- .unwrap_or_default()
273 });249 });
274 250
275- if let Some(new_x) = new_loc.x {251+ // let mut window_loc = space.element_location(&window)?;
276- window_loc.x = new_x;252+ // let geometry = window.geometry();
277- }253+
278- if let Some(new_y) = new_loc.y {254+ // let new_loc: Point<Option<i32>, Logical> = ResizeSurfaceState::with(surface, |state| {
279- window_loc.y = new_y;255+ // state
280- }256+ // .commit()
281-257+ // .and_then(|(edges, initial_rect)| {
282- if new_loc.x.is_some() || new_loc.y.is_some() {258+ // // If the window is being resized by top or left, its location must be adjusted
283- // If TOP or LEFT side of the window got resized, we have to move it259+ // // accordingly.
284- space.map_element(window, window_loc, false);260+ // edges.intersects(ResizeEdge::TOP_LEFT).then(|| {
285- }261+ // let new_x = edges
262+ // .intersects(ResizeEdge::LEFT)
263+ // .then_some(initial_rect.loc.x + (initial_rect.size.w - geometry.size.w));
264+
265+ // let new_y = edges
266+ // .intersects(ResizeEdge::TOP)
267+ // .then_some(initial_rect.loc.y + (initial_rect.size.h - geometry.size.h));
268+
269+ // (new_x, new_y).into()
270+ // })
271+ // })
272+ // .unwrap_or_default()
273+ // });
274+
275+ // if let Some(new_x) = new_loc.x {
276+ // window_loc.x = new_x;
277+ // }
278+ // if let Some(new_y) = new_loc.y {
279+ // window_loc.y = new_y;
280+ // }
281+
282+ // if new_loc.x.is_some() || new_loc.y.is_some() {
283+ // // If TOP or LEFT side of the window got resized, we have to move it
284+ // space.map_element(window, window_loc, false);
285+ // }
286 286
287 Some(())287 Some(())
288 }288 }
src/handlers/compositor.rsmodified+89 -14
@@ -1,4 +1,7 @@
1-use smithay::backend::renderer::utils::on_commit_buffer_handler;1+use std::collections::hash_map::Entry;
2+
3+use smithay::backend::renderer::utils::{on_commit_buffer_handler, with_renderer_surface_state};
4+use smithay::desktop::find_popup_root_surface;
2 use smithay::reexports::wayland_server::protocol::wl_buffer;5 use smithay::reexports::wayland_server::protocol::wl_buffer;
3 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;6 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
4 use smithay::reexports::wayland_server::Client;7 use smithay::reexports::wayland_server::Client;
@@ -9,6 +12,7 @@ use smithay::wayland::compositor::{
9 use smithay::wayland::shm::{ShmHandler, ShmState};12 use smithay::wayland::shm::{ShmHandler, ShmState};
10 use smithay::{delegate_compositor, delegate_shm};13 use smithay::{delegate_compositor, delegate_shm};
11 14
15+use super::xdg_shell;
12 use crate::grabs::resize_grab;16 use crate::grabs::resize_grab;
13 use crate::niri::ClientState;17 use crate::niri::ClientState;
14 use crate::Niri;18 use crate::Niri;
@@ -28,24 +32,95 @@ impl CompositorHandler for Niri {
28 .message("client commit", 0);32 .message("client commit", 0);
29 33
30 on_commit_buffer_handler::<Self>(surface);34 on_commit_buffer_handler::<Self>(surface);
31- if !is_sync_subsurface(surface) {35+
32- let mut root = surface.clone();36+ if is_sync_subsurface(surface) {
33- while let Some(parent) = get_parent(&root) {37+ return;
34- root = parent;38+ }
39+
40+ let mut root_surface = surface.clone();
41+ while let Some(parent) = get_parent(&root_surface) {
42+ root_surface = parent;
43+ }
44+
45+ if surface == &root_surface {
46+ // This is a root surface commit. It might have mapped a previously-unmapped toplevel.
47+ if let Entry::Occupied(entry) = self.unmapped_windows.entry(surface.clone()) {
48+ let is_mapped =
49+ with_renderer_surface_state(surface, |state| state.buffer().is_some());
50+
51+ if is_mapped {
52+ // The toplevel got mapped.
53+ let window = entry.remove();
54+ window.on_commit();
55+
56+ let output = self.monitor_set.active_output().unwrap().clone();
57+ self.monitor_set.add_window_to_output(&output, window, true);
58+ self.update_focus();
59+
60+ self.queue_redraw(output);
61+ return;
62+ }
63+
64+ // The toplevel remains unmapped.
65+ let window = entry.get();
66+ xdg_shell::send_initial_configure_if_needed(window);
67+ return;
35 }68 }
36- if let Some(window) = self69+
37- .space70+ // This is a commit of a previously-mapped root or a non-toplevel root.
38- .elements()71+ if let Some((window, space)) = self.monitor_set.find_window_and_space(surface) {
39- .find(|w| w.toplevel().wl_surface() == &root)72+ // This is a commit of a previously-mapped toplevel.
40- {73+ let output = space.outputs().next().unwrap().clone();
74+
41 window.on_commit();75 window.on_commit();
76+
77+ // This is a commit of a previously-mapped toplevel.
78+ let is_mapped =
79+ with_renderer_surface_state(surface, |state| state.buffer().is_some());
80+
81+ if !is_mapped {
82+ // The toplevel got unmapped.
83+ let window = window.clone();
84+ self.monitor_set.remove_window(&window);
85+ self.unmapped_windows.insert(surface.clone(), window);
86+ self.update_focus();
87+
88+ self.queue_redraw(output);
89+ return;
90+ }
91+
92+ // The toplevel remains mapped.
93+ resize_grab::handle_commit(&window);
94+ self.monitor_set.update_window(&window);
95+
96+ self.queue_redraw(output);
97+ return;
42 }98 }
43- };
44 99
45- self.xdg_handle_commit(surface);100+ // This is a commit of a non-toplevel root.
46- resize_grab::handle_commit(&mut self.space, surface);101+ }
47 102
48- self.queue_redraw();103+ // This is a commit of a non-root or a non-toplevel root.
104+ let root_window_space = self.monitor_set.find_window_and_space(&root_surface);
105+ if let Some((window, space)) = root_window_space {
106+ let output = space.outputs().next().unwrap().clone();
107+ window.on_commit();
108+ self.monitor_set.update_window(&window);
109+ self.queue_redraw(output);
110+ return;
111+ }
112+
113+ // This might be a popup.
114+ self.popups_handle_commit(surface);
115+ if let Some(popup) = self.popups.find_popup(surface) {
116+ if let Ok(root) = find_popup_root_surface(&popup) {
117+ let root_window_space = self.monitor_set.find_window_and_space(&root);
118+ if let Some((_window, space)) = root_window_space {
119+ let output = space.outputs().next().unwrap().clone();
120+ self.queue_redraw(output);
121+ }
122+ }
123+ }
49 }124 }
50 }125 }
51 126
src/handlers/xdg_shell.rsmodified+87 -100
@@ -2,20 +2,19 @@ use smithay::delegate_xdg_shell;
2 use smithay::desktop::{PopupKind, Window};2 use smithay::desktop::{PopupKind, Window};
3 use smithay::input::pointer::{Focus, GrabStartData as PointerGrabStartData};3 use smithay::input::pointer::{Focus, GrabStartData as PointerGrabStartData};
4 use smithay::input::Seat;4 use smithay::input::Seat;
5-use smithay::output::Output;
6 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;5 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
7 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;6 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
8 use smithay::reexports::wayland_server::protocol::{wl_output, wl_seat};7 use smithay::reexports::wayland_server::protocol::{wl_output, wl_seat};
9 use smithay::reexports::wayland_server::Resource;8 use smithay::reexports::wayland_server::Resource;
10 use smithay::utils::{Rectangle, Serial};9 use smithay::utils::{Rectangle, Serial};
11 use smithay::wayland::compositor::with_states;10 use smithay::wayland::compositor::with_states;
12-use smithay::wayland::seat::WaylandFocus;
13 use smithay::wayland::shell::xdg::{11 use smithay::wayland::shell::xdg::{
14 PopupSurface, PositionerState, ToplevelSurface, XdgPopupSurfaceData, XdgShellHandler,12 PopupSurface, PositionerState, ToplevelSurface, XdgPopupSurfaceData, XdgShellHandler,
15 XdgShellState, XdgToplevelSurfaceData,13 XdgShellState, XdgToplevelSurfaceData,
16 };14 };
17 15
18 use crate::grabs::{MoveSurfaceGrab, ResizeSurfaceGrab};16 use crate::grabs::{MoveSurfaceGrab, ResizeSurfaceGrab};
17+use crate::layout::MonitorSet;
19 use crate::Niri;18 use crate::Niri;
20 19
21 impl XdgShellHandler for Niri {20 impl XdgShellHandler for Niri {
@@ -24,8 +23,16 @@ impl XdgShellHandler for Niri {
24 }23 }
25 24
26 fn new_toplevel(&mut self, surface: ToplevelSurface) {25 fn new_toplevel(&mut self, surface: ToplevelSurface) {
26+ let wl_surface = surface.wl_surface().clone();
27 let window = Window::new(surface);27 let window = Window::new(surface);
28- self.space.map_element(window, (0, 0), false);28+
29+ // Tell the surface the preferred size and bounds for its likely output.
30+ let output = self.monitor_set.active_output().unwrap();
31+ MonitorSet::configure_new_window(output, &window);
32+
33+ // At the moment of creation, xdg toplevels must have no buffer.
34+ let existing = self.unmapped_windows.insert(wl_surface, window);
35+ assert!(existing.is_none());
29 }36 }
30 37
31 fn new_popup(&mut self, surface: PopupSurface, positioner: PositionerState) {38 fn new_popup(&mut self, surface: PopupSurface, positioner: PositionerState) {
@@ -49,17 +56,12 @@ impl XdgShellHandler for Niri {
49 if let Some(start_data) = check_grab(&seat, wl_surface, serial) {56 if let Some(start_data) = check_grab(&seat, wl_surface, serial) {
50 let pointer = seat.get_pointer().unwrap();57 let pointer = seat.get_pointer().unwrap();
51 58
52- let window = self59+ let (window, space) = self.monitor_set.find_window_and_space(wl_surface).unwrap();
53- .space60+ let initial_window_location = space.element_location(&window).unwrap();
54- .elements()
55- .find(|w| w.toplevel().wl_surface() == wl_surface)
56- .unwrap()
57- .clone();
58- let initial_window_location = self.space.element_location(&window).unwrap();
59 61
60 let grab = MoveSurfaceGrab {62 let grab = MoveSurfaceGrab {
61 start_data,63 start_data,
62- window,64+ window: window.clone(),
63 initial_window_location,65 initial_window_location,
64 };66 };
65 67
@@ -81,13 +83,8 @@ impl XdgShellHandler for Niri {
81 if let Some(start_data) = check_grab(&seat, wl_surface, serial) {83 if let Some(start_data) = check_grab(&seat, wl_surface, serial) {
82 let pointer = seat.get_pointer().unwrap();84 let pointer = seat.get_pointer().unwrap();
83 85
84- let window = self86+ let (window, space) = self.monitor_set.find_window_and_space(wl_surface).unwrap();
85- .space87+ let initial_window_location = space.element_location(&window).unwrap();
86- .elements()
87- .find(|w| w.toplevel().wl_surface() == wl_surface)
88- .unwrap()
89- .clone();
90- let initial_window_location = self.space.element_location(&window).unwrap();
91 let initial_window_size = window.geometry().size;88 let initial_window_size = window.geometry().size;
92 89
93 surface.with_pending_state(|state| {90 surface.with_pending_state(|state| {
@@ -98,7 +95,7 @@ impl XdgShellHandler for Niri {
98 95
99 let grab = ResizeSurfaceGrab::start(96 let grab = ResizeSurfaceGrab::start(
100 start_data,97 start_data,
101- window,98+ window.clone(),
102 edges.into(),99 edges.into(),
103 Rectangle::from_loc_and_size(initial_window_location, initial_window_size),100 Rectangle::from_loc_and_size(initial_window_location, initial_window_size),
104 );101 );
@@ -126,7 +123,7 @@ impl XdgShellHandler for Niri {
126 }123 }
127 124
128 fn grab(&mut self, _surface: PopupSurface, _seat: wl_seat::WlSeat, _serial: Serial) {125 fn grab(&mut self, _surface: PopupSurface, _seat: wl_seat::WlSeat, _serial: Serial) {
129- // TODO popup grabs126+ // FIXME popup grabs
130 }127 }
131 128
132 fn maximize_request(&mut self, surface: ToplevelSurface) {129 fn maximize_request(&mut self, surface: ToplevelSurface) {
@@ -135,23 +132,17 @@ impl XdgShellHandler for Niri {
135 .capabilities132 .capabilities
136 .contains(xdg_toplevel::WmCapabilities::Maximize)133 .contains(xdg_toplevel::WmCapabilities::Maximize)
137 {134 {
138- let wl_surface = surface.wl_surface();135+ // let wl_surface = surface.wl_surface();
139- let window = self136+ // let (window, space) = self.monitor_set.find_window_and_space(wl_surface).unwrap();
140- .space137+ // let geometry = space
141- .elements()138+ // .output_geometry(space.outputs().next().unwrap())
142- .find(|w| w.toplevel().wl_surface() == wl_surface)139+ // .unwrap();
143- .unwrap()140+
144- .clone();141+ // surface.with_pending_state(|state| {
145- let geometry = self142+ // state.states.set(xdg_toplevel::State::Maximized);
146- .space143+ // state.size = Some(geometry.size);
147- .output_geometry(self.output.as_ref().unwrap())144+ // });
148- .unwrap();145+ // space.map_element(window.clone(), geometry.loc, true);
149-
150- surface.with_pending_state(|state| {
151- state.states.set(xdg_toplevel::State::Maximized);
152- state.size = Some(geometry.size);
153- });
154- self.space.map_element(window, geometry.loc, true);
155 }146 }
156 147
157 // The protocol demands us to always reply with a configure,148 // The protocol demands us to always reply with a configure,
@@ -185,44 +176,32 @@ impl XdgShellHandler for Niri {
185 .capabilities176 .capabilities
186 .contains(xdg_toplevel::WmCapabilities::Fullscreen)177 .contains(xdg_toplevel::WmCapabilities::Fullscreen)
187 {178 {
188- // NOTE: This is only one part of the solution. We can set the179+ // // NOTE: This is only one part of the solution. We can set the
189- // location and configure size here, but the surface should be rendered fullscreen180+ // // location and configure size here, but the surface should be rendered fullscreen
190- // independently from its buffer size181+ // // independently from its buffer size
191- let wl_surface = surface.wl_surface();182+ // let wl_surface = surface.wl_surface();
192-183+
193- let output = wl_output184+ // let output = wl_output
194- .as_ref()185+ // .as_ref()
195- .and_then(Output::from_resource)186+ // .and_then(Output::from_resource)
196- .or_else(|| {187+ // .or_else(|| {
197- let w = self188+ // self.monitor_set
198- .space189+ // .find_window_and_space(wl_surface)
199- .elements()190+ // .and_then(|(_window, space)| space.outputs().next().cloned())
200- .find(|window| {191+ // });
201- window192+
202- .wl_surface()193+ // if let Some(output) = output {
203- .map(|s| s == *wl_surface)194+ // let (window, space) =
204- .unwrap_or(false)195+ // self.monitor_set.find_window_and_space(wl_surface).unwrap();
205- })196+ // let geometry = space.output_geometry(&output).unwrap();
206- .cloned();197+
207- w.and_then(|w| self.space.outputs_for_element(&w).get(0).cloned())198+ // surface.with_pending_state(|state| {
208- });199+ // state.states.set(xdg_toplevel::State::Fullscreen);
209-200+ // state.size = Some(geometry.size);
210- if let Some(output) = output {201+ // });
211- let geometry = self.space.output_geometry(&output).unwrap();202+
212-203+ // space.map_element(window.clone(), geometry.loc, true);
213- surface.with_pending_state(|state| {204+ // }
214- state.states.set(xdg_toplevel::State::Fullscreen);
215- state.size = Some(geometry.size);
216- });
217-
218- let window = self
219- .space
220- .elements()
221- .find(|w| w.toplevel().wl_surface() == wl_surface)
222- .unwrap()
223- .clone();
224- self.space.map_element(window, geometry.loc, true);
225- }
226 }205 }
227 206
228 // The protocol demands us to always reply with a configure,207 // The protocol demands us to always reply with a configure,
@@ -247,12 +226,25 @@ impl XdgShellHandler for Niri {
247 surface.send_pending_configure();226 surface.send_pending_configure();
248 }227 }
249 228
250- fn toplevel_destroyed(&mut self, _surface: ToplevelSurface) {229+ fn toplevel_destroyed(&mut self, surface: ToplevelSurface) {
251- self.queue_redraw();230+ if self.unmapped_windows.remove(surface.wl_surface()).is_some() {
231+ // An unmapped toplevel got destroyed.
232+ return;
233+ }
234+
235+ let (window, space) = self
236+ .monitor_set
237+ .find_window_and_space(surface.wl_surface())
238+ .unwrap();
239+ let output = space.outputs().next().unwrap().clone();
240+ self.monitor_set.remove_window(&window);
241+ self.update_focus();
242+ self.queue_redraw(output);
252 }243 }
253 244
254 fn popup_destroyed(&mut self, _surface: PopupSurface) {245 fn popup_destroyed(&mut self, _surface: PopupSurface) {
255- self.queue_redraw();246+ // FIXME granular
247+ self.queue_redraw_all();
256 }248 }
257 }249 }
258 250
@@ -282,32 +274,27 @@ fn check_grab(
282 Some(start_data)274 Some(start_data)
283 }275 }
284 276
277+pub fn send_initial_configure_if_needed(window: &Window) {
278+ let initial_configure_sent = with_states(window.toplevel().wl_surface(), |states| {
279+ states
280+ .data_map
281+ .get::<XdgToplevelSurfaceData>()
282+ .unwrap()
283+ .lock()
284+ .unwrap()
285+ .initial_configure_sent
286+ });
287+
288+ if !initial_configure_sent {
289+ window.toplevel().send_configure();
290+ }
291+}
292+
285 impl Niri {293 impl Niri {
286 /// Should be called on `WlSurface::commit`294 /// Should be called on `WlSurface::commit`
287- pub fn xdg_handle_commit(&mut self, surface: &WlSurface) {295+ pub fn popups_handle_commit(&mut self, surface: &WlSurface) {
288 self.popups.commit(surface);296 self.popups.commit(surface);
289 297
290- if let Some(window) = self
291- .space
292- .elements()
293- .find(|w| w.toplevel().wl_surface() == surface)
294- .cloned()
295- {
296- let initial_configure_sent = with_states(surface, |states| {
297- states
298- .data_map
299- .get::<XdgToplevelSurfaceData>()
300- .unwrap()
301- .lock()
302- .unwrap()
303- .initial_configure_sent
304- });
305-
306- if !initial_configure_sent {
307- window.toplevel().send_configure();
308- }
309- }
310-
311 if let Some(popup) = self.popups.find_popup(surface) {298 if let Some(popup) = self.popups.find_popup(surface) {
312 let PopupKind::Xdg(ref popup) = popup;299 let PopupKind::Xdg(ref popup) = popup;
313 let initial_configure_sent = with_states(surface, |states| {300 let initial_configure_sent = with_states(surface, |states| {
src/input.rsmodified+201 -77
@@ -5,21 +5,35 @@ use smithay::backend::input::{
5 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Event, InputBackend, InputEvent,5 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Event, InputBackend, InputEvent,
6 KeyState, KeyboardKeyEvent, PointerAxisEvent, PointerButtonEvent, PointerMotionEvent,6 KeyState, KeyboardKeyEvent, PointerAxisEvent, PointerButtonEvent, PointerMotionEvent,
7 };7 };
8-use smithay::input::keyboard::{keysyms, FilterResult};8+use smithay::input::keyboard::{keysyms, FilterResult, KeysymHandle, ModifiersState};
9 use smithay::input::pointer::{AxisFrame, ButtonEvent, MotionEvent, RelativeMotionEvent};9 use smithay::input::pointer::{AxisFrame, ButtonEvent, MotionEvent, RelativeMotionEvent};
10 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;10 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
11-use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
12 use smithay::utils::SERIAL_COUNTER;11 use smithay::utils::SERIAL_COUNTER;
13 use smithay::wayland::shell::xdg::XdgShellHandler;12 use smithay::wayland::shell::xdg::XdgShellHandler;
14 13
15 use crate::niri::Niri;14 use crate::niri::Niri;
16 15
17-enum InputAction {16+enum Action {
17+ None,
18 Quit,18 Quit,
19 ChangeVt(i32),19 ChangeVt(i32),
20 SpawnTerminal,20 SpawnTerminal,
21 CloseWindow,21 CloseWindow,
22 ToggleFullscreen,22 ToggleFullscreen,
23+ FocusLeft,
24+ FocusRight,
25+ FocusDown,
26+ FocusUp,
27+ MoveLeft,
28+ MoveRight,
29+ MoveDown,
30+ MoveUp,
31+ ConsumeIntoColumn,
32+ ExpelFromColumn,
33+ SwitchWorkspaceDown,
34+ SwitchWorkspaceUp,
35+ MoveToWorkspaceDown,
36+ MoveToWorkspaceUp,
23 }37 }
24 38
25 pub enum CompositorMod {39 pub enum CompositorMod {
@@ -27,11 +41,64 @@ pub enum CompositorMod {
27 Alt,41 Alt,
28 }42 }
29 43
44+impl From<Action> for FilterResult<Action> {
45+ fn from(value: Action) -> Self {
46+ match value {
47+ Action::None => FilterResult::Forward,
48+ action => FilterResult::Intercept(action),
49+ }
50+ }
51+}
52+
53+fn action(comp_mod: CompositorMod, keysym: KeysymHandle, mods: ModifiersState) -> Action {
54+ use keysyms::*;
55+
56+ let modified = keysym.modified_sym();
57+ if matches!(modified, KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12) {
58+ let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
59+ return Action::ChangeVt(vt);
60+ }
61+
62+ let mod_down = match comp_mod {
63+ CompositorMod::Super => mods.logo,
64+ CompositorMod::Alt => mods.alt,
65+ };
66+
67+ if !mod_down {
68+ return Action::None;
69+ }
70+
71+ // FIXME: these don't work in the Russian layout. I guess I'll need to
72+ // find a US keymap, then map keys somehow.
73+ #[allow(non_upper_case_globals)] // wat
74+ match modified {
75+ KEY_E => Action::Quit,
76+ KEY_t => Action::SpawnTerminal,
77+ KEY_q => Action::CloseWindow,
78+ KEY_f => Action::ToggleFullscreen,
79+ KEY_h | KEY_Left if mods.ctrl => Action::MoveLeft,
80+ KEY_l | KEY_Right if mods.ctrl => Action::MoveRight,
81+ KEY_j | KEY_Down if mods.ctrl => Action::MoveDown,
82+ KEY_k | KEY_Up if mods.ctrl => Action::MoveUp,
83+ KEY_h | KEY_Left => Action::FocusLeft,
84+ KEY_l | KEY_Right => Action::FocusRight,
85+ KEY_j | KEY_Down => Action::FocusDown,
86+ KEY_k | KEY_Up => Action::FocusUp,
87+ KEY_u if mods.ctrl => Action::MoveToWorkspaceDown,
88+ KEY_i if mods.ctrl => Action::MoveToWorkspaceUp,
89+ KEY_u => Action::SwitchWorkspaceDown,
90+ KEY_i => Action::SwitchWorkspaceUp,
91+ KEY_comma => Action::ConsumeIntoColumn,
92+ KEY_period => Action::ExpelFromColumn,
93+ _ => Action::None,
94+ }
95+}
96+
30 impl Niri {97 impl Niri {
31 pub fn process_input_event<I: InputBackend>(98 pub fn process_input_event<I: InputBackend>(
32 &mut self,99 &mut self,
33 change_vt: &mut dyn FnMut(i32),100 change_vt: &mut dyn FnMut(i32),
34- compositor_mod: CompositorMod,101+ comp_mod: CompositorMod,
35 event: InputEvent<I>,102 event: InputEvent<I>,
36 ) {103 ) {
37 let _span = tracy_client::span!("process_input_event");104 let _span = tracy_client::span!("process_input_event");
@@ -50,33 +117,7 @@ impl Niri {
50 time,117 time,
51 |_, mods, keysym| {118 |_, mods, keysym| {
52 if event.state() == KeyState::Pressed {119 if event.state() == KeyState::Pressed {
53- let mod_down = match compositor_mod {120+ action(comp_mod, keysym, *mods).into()
54- CompositorMod::Super => mods.logo,
55- CompositorMod::Alt => mods.alt,
56- };
57-
58- // FIXME: these don't work in the Russian layout. I guess I'll need to
59- // find a US keymap, then map keys somehow.
60- match keysym.modified_sym() {
61- keysyms::KEY_E if mod_down => {
62- FilterResult::Intercept(InputAction::Quit)
63- }
64- keysym @ keysyms::KEY_XF86Switch_VT_1
65- ..=keysyms::KEY_XF86Switch_VT_12 => {
66- let vt = (keysym - keysyms::KEY_XF86Switch_VT_1 + 1) as i32;
67- FilterResult::Intercept(InputAction::ChangeVt(vt))
68- }
69- keysyms::KEY_t if mod_down => {
70- FilterResult::Intercept(InputAction::SpawnTerminal)
71- }
72- keysyms::KEY_q if mod_down => {
73- FilterResult::Intercept(InputAction::CloseWindow)
74- }
75- keysyms::KEY_f if mod_down => {
76- FilterResult::Intercept(InputAction::ToggleFullscreen)
77- }
78- _ => FilterResult::Forward,
79- }
80 } else {121 } else {
81 FilterResult::Forward122 FilterResult::Forward
82 }123 }
@@ -85,22 +126,27 @@ impl Niri {
85 126
86 if let Some(action) = action {127 if let Some(action) = action {
87 match action {128 match action {
88- InputAction::Quit => {129+ Action::None => unreachable!(),
130+ Action::Quit => {
89 info!("quitting because quit bind was pressed");131 info!("quitting because quit bind was pressed");
90 self.stop_signal.stop()132 self.stop_signal.stop()
91 }133 }
92- InputAction::ChangeVt(vt) => {134+ Action::ChangeVt(vt) => {
93 (*change_vt)(vt);135 (*change_vt)(vt);
94 }136 }
95- InputAction::SpawnTerminal => {137+ Action::SpawnTerminal => {
96 if let Err(err) = Command::new("alacritty").spawn() {138 if let Err(err) = Command::new("alacritty").spawn() {
97 warn!("error spawning alacritty: {err}");139 warn!("error spawning alacritty: {err}");
98 }140 }
99 }141 }
100- InputAction::CloseWindow => {142+ Action::CloseWindow => {
101 if let Some(focus) = self.seat.get_keyboard().unwrap().current_focus() {143 if let Some(focus) = self.seat.get_keyboard().unwrap().current_focus() {
102 // FIXME: is there a better way of doing this?144 // FIXME: is there a better way of doing this?
103- for window in self.space.elements() {145+ for window in self
146+ .monitor_set
147+ .workspaces()
148+ .flat_map(|workspace| workspace.space.elements())
149+ {
104 let found = Cell::new(false);150 let found = Cell::new(false);
105 window.with_surfaces(|surface, _| {151 window.with_surfaces(|surface, _| {
106 if surface == &focus {152 if surface == &focus {
@@ -114,18 +160,22 @@ impl Niri {
114 }160 }
115 }161 }
116 }162 }
117- InputAction::ToggleFullscreen => {163+ Action::ToggleFullscreen => {
118 if let Some(focus) = self.seat.get_keyboard().unwrap().current_focus() {164 if let Some(focus) = self.seat.get_keyboard().unwrap().current_focus() {
119 // FIXME: is there a better way of doing this?165 // FIXME: is there a better way of doing this?
120- let window = self.space.elements().find(|window| {166+ let window = self
121- let found = Cell::new(false);167+ .monitor_set
122- window.with_surfaces(|surface, _| {168+ .workspaces()
123- if surface == &focus {169+ .flat_map(|workspace| workspace.space.elements())
124- found.set(true);170+ .find(|window| {
125- }171+ let found = Cell::new(false);
172+ window.with_surfaces(|surface, _| {
173+ if surface == &focus {
174+ found.set(true);
175+ }
176+ });
177+ found.get()
126 });178 });
127- found.get()
128- });
129 if let Some(window) = window {179 if let Some(window) = window {
130 let toplevel = window.toplevel().clone();180 let toplevel = window.toplevel().clone();
131 if toplevel181 if toplevel
@@ -140,6 +190,78 @@ impl Niri {
140 }190 }
141 }191 }
142 }192 }
193+ Action::MoveLeft => {
194+ self.monitor_set.move_left();
195+ // FIXME: granular
196+ self.queue_redraw_all();
197+ }
198+ Action::MoveRight => {
199+ self.monitor_set.move_right();
200+ // FIXME: granular
201+ self.queue_redraw_all();
202+ }
203+ Action::MoveDown => {
204+ self.monitor_set.move_down();
205+ // FIXME: granular
206+ self.queue_redraw_all();
207+ }
208+ Action::MoveUp => {
209+ self.monitor_set.move_up();
210+ // FIXME: granular
211+ self.queue_redraw_all();
212+ }
213+ Action::FocusLeft => {
214+ self.monitor_set.focus_left();
215+ self.update_focus();
216+ }
217+ Action::FocusRight => {
218+ self.monitor_set.focus_right();
219+ self.update_focus();
220+ }
221+ Action::FocusDown => {
222+ self.monitor_set.focus_down();
223+ self.update_focus();
224+ }
225+ Action::FocusUp => {
226+ self.monitor_set.focus_up();
227+ self.update_focus();
228+ }
229+ Action::MoveToWorkspaceDown => {
230+ self.monitor_set.move_to_workspace_down();
231+ self.update_focus();
232+ // FIXME: granular
233+ self.queue_redraw_all();
234+ }
235+ Action::MoveToWorkspaceUp => {
236+ self.monitor_set.move_to_workspace_up();
237+ self.update_focus();
238+ // FIXME: granular
239+ self.queue_redraw_all();
240+ }
241+ Action::SwitchWorkspaceDown => {
242+ self.monitor_set.switch_workspace_down();
243+ self.update_focus();
244+ // FIXME: granular
245+ self.queue_redraw_all();
246+ }
247+ Action::SwitchWorkspaceUp => {
248+ self.monitor_set.switch_workspace_up();
249+ self.update_focus();
250+ // FIXME: granular
251+ self.queue_redraw_all();
252+ }
253+ Action::ConsumeIntoColumn => {
254+ self.monitor_set.consume_into_column();
255+ self.update_focus();
256+ // FIXME: granular
257+ self.queue_redraw_all();
258+ }
259+ Action::ExpelFromColumn => {
260+ self.monitor_set.expel_from_column();
261+ self.update_focus();
262+ // FIXME: granular
263+ self.queue_redraw_all();
264+ }
143 }265 }
144 }266 }
145 }267 }
@@ -147,22 +269,33 @@ impl Niri {
147 let serial = SERIAL_COUNTER.next_serial();269 let serial = SERIAL_COUNTER.next_serial();
148 270
149 let pointer = self.seat.get_pointer().unwrap();271 let pointer = self.seat.get_pointer().unwrap();
150- let mut pointer_location = pointer.current_location();272+ let mut pos = pointer.current_location();
273+
274+ pos += event.delta();
151 275
152- pointer_location += event.delta();276+ let mut min_x = i32::MAX;
277+ let mut min_y = i32::MAX;
278+ let mut max_x = 0;
279+ let mut max_y = 0;
280+ for output in self.global_space.outputs() {
281+ // FIXME: smarter clamping.
282+ let geom = self.global_space.output_geometry(output).unwrap();
283+ min_x = min_x.min(geom.loc.x);
284+ min_y = min_y.min(geom.loc.y);
285+ max_x = max_x.max(geom.loc.x + geom.size.w);
286+ max_y = max_y.max(geom.loc.y + geom.size.h);
287+ }
153 288
154- let output = self.space.outputs().next().unwrap();289+ pos.x = pos.x.clamp(min_x as f64, max_x as f64);
155- let output_geo = self.space.output_geometry(output).unwrap();290+ pos.y = pos.y.clamp(min_y as f64, max_y as f64);
156 291
157- pointer_location.x = pointer_location.x.clamp(0., output_geo.size.w as f64);292+ let under = self.surface_under_and_global_space(pos);
158- pointer_location.y = pointer_location.y.clamp(0., output_geo.size.h as f64);
159 293
160- let under = self.surface_under(pointer_location);
161 pointer.motion(294 pointer.motion(
162 self,295 self,
163 under.clone(),296 under.clone(),
164 &MotionEvent {297 &MotionEvent {
165- location: pointer_location,298+ location: pos,
166 serial,299 serial,
167 time: event.time_msec(),300 time: event.time_msec(),
168 },301 },
@@ -179,12 +312,14 @@ impl Niri {
179 );312 );
180 313
181 // Redraw to update the cursor position.314 // Redraw to update the cursor position.
182- self.queue_redraw();315+ // FIXME: redraw only outputs overlapping the cursor.
316+ self.queue_redraw_all();
183 }317 }
184 InputEvent::PointerMotionAbsolute { event, .. } => {318 InputEvent::PointerMotionAbsolute { event, .. } => {
185- let output = self.space.outputs().next().unwrap();319+ // FIXME: allow mapping tablet to different outputs.
320+ let output = self.global_space.outputs().next().unwrap();
186 321
187- let output_geo = self.space.output_geometry(output).unwrap();322+ let output_geo = self.global_space.output_geometry(output).unwrap();
188 323
189 let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();324 let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();
190 325
@@ -192,7 +327,7 @@ impl Niri {
192 327
193 let pointer = self.seat.get_pointer().unwrap();328 let pointer = self.seat.get_pointer().unwrap();
194 329
195- let under = self.surface_under(pos);330+ let under = self.surface_under_and_global_space(pos);
196 331
197 pointer.motion(332 pointer.motion(
198 self,333 self,
@@ -205,11 +340,11 @@ impl Niri {
205 );340 );
206 341
207 // Redraw to update the cursor position.342 // Redraw to update the cursor position.
208- self.queue_redraw();343+ // FIXME: redraw only outputs overlapping the cursor.
344+ self.queue_redraw_all();
209 }345 }
210 InputEvent::PointerButton { event, .. } => {346 InputEvent::PointerButton { event, .. } => {
211 let pointer = self.seat.get_pointer().unwrap();347 let pointer = self.seat.get_pointer().unwrap();
212- let keyboard = self.seat.get_keyboard().unwrap();
213 348
214 let serial = SERIAL_COUNTER.next_serial();349 let serial = SERIAL_COUNTER.next_serial();
215 350
@@ -218,27 +353,16 @@ impl Niri {
218 let button_state = event.state();353 let button_state = event.state();
219 354
220 if ButtonState::Pressed == button_state && !pointer.is_grabbed() {355 if ButtonState::Pressed == button_state && !pointer.is_grabbed() {
221- if let Some((window, _loc)) = self356+ if let Some((_space, window, _loc)) =
222- .space357+ self.window_under(pointer.current_location())
223- .element_under(pointer.current_location())
224- .map(|(w, l)| (w.clone(), l))
225 {358 {
226- self.space.raise_element(&window, true);359+ self.monitor_set.activate_window(&window);
227- keyboard.set_focus(
228- self,
229- Some(window.toplevel().wl_surface().clone()),
230- serial,
231- );
232- self.space.elements().for_each(|window| {
233- window.toplevel().send_pending_configure();
234- });
235 } else {360 } else {
236- self.space.elements().for_each(|window| {361+ let output = self.output_under_cursor().unwrap();
237- window.set_activated(false);362+ self.monitor_set.activate_output(&output);
238- window.toplevel().send_pending_configure();
239- });
240- keyboard.set_focus(self, Option::<WlSurface>::None, serial);
241 }363 }
364+
365+ self.update_focus();
242 };366 };
243 367
244 pointer.button(368 pointer.button(
src/layout.rsadded+1099 -0
@@ -0,0 +1,1099 @@
1+//! Window layout logic.
2+//!
3+//! Niri implements scrollable tiling with workspaces. There's one primary output, and potentially
4+//! multiple other outputs.
5+//!
6+//! Our layout has the following invariants:
7+//!
8+//! 1. Disconnecting and reconnecting the same output must not change the layout.
9+//! * This includes both secondary outputs and the primary output.
10+//! 2. Connecting an output must not change the layout for any workspaces that were never on that
11+//! output.
12+//!
13+//! Therefore, we implement the following logic: every workspace keeps track of which output it
14+//! originated on. When an output disconnects, its workspace (or workspaces, in case of the primary
15+//! output disconnecting) are appended to the (potentially new) primary output, but remember their
16+//! original output. Then, if the original output connects again, all workspaces originally from
17+//! there move back to that output.
18+//!
19+//! In order to avoid surprising behavior, if the user creates or moves any new windows onto a
20+//! workspace, it forgets its original output, and its current output becomes its original output.
21+//! Imagine a scenario: the user works with a laptop and a monitor at home, then takes their laptop
22+//! with them, disconnecting the monitor, and keeps working as normal, using the second monitor's
23+//! workspace just like any other. Then they come back, reconnect the second monitor, and now we
24+//! don't want an unassuming workspace to end up on it.
25+//!
26+//! ## Workspaces-only-on-primary considerations
27+//!
28+//! If this logic results in more than one workspace present on a secondary output, then as a
29+//! compromise we only keep the first workspace there, and move the rest to the primary output,
30+//! making the primary output their original output.
31+
32+use std::cmp::{max, min};
33+use std::mem;
34+
35+use smithay::desktop::{Space, Window};
36+use smithay::output::Output;
37+use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
38+use smithay::utils::{Logical, Size};
39+
40+const PADDING: i32 = 16;
41+
42+#[derive(Debug, Clone, PartialEq, Eq)]
43+pub struct OutputId(String);
44+
45+#[derive(Debug)]
46+pub enum MonitorSet {
47+ /// At least one output is connected.
48+ Normal {
49+ monitors: Vec<Monitor>,
50+ /// Index of the primary monitor.
51+ primary_idx: usize,
52+ /// Index of the active monitor.
53+ active_monitor_idx: usize,
54+ },
55+ /// No outputs are connected, and these are the workspaces.
56+ // FIXME: preserve active output id?
57+ NoOutputs(Vec<Workspace>),
58+}
59+
60+#[derive(Debug)]
61+pub struct Monitor {
62+ output: Output,
63+ // Must always contain at least one.
64+ workspaces: Vec<Workspace>,
65+ /// Index of the currently active workspace.
66+ active_workspace_idx: usize,
67+}
68+
69+#[derive(Debug)]
70+pub struct Workspace {
71+ /// The original output of this workspace.
72+ ///
73+ /// Most of the time this will be the workspace's current output, however, after an output
74+ /// disconnection, it may remain pointing to the disconnected output.
75+ original_output: OutputId,
76+
77+ layout: Layout,
78+
79+ // The actual Space with windows in this workspace. Should be synchronized to the layout except
80+ // for a brief period during surface commit handling.
81+ pub space: Space<Window>,
82+}
83+
84+#[derive(Debug)]
85+pub struct Layout {
86+ columns: Vec<Column>,
87+ /// Index of the currently active column, if any.
88+ active_column_idx: usize,
89+}
90+
91+#[derive(Debug)]
92+pub struct Column {
93+ // Must be non-empty.
94+ windows: Vec<Window>,
95+ /// Index of the currently active window.
96+ active_window_idx: usize,
97+}
98+
99+impl OutputId {
100+ pub fn new(output: &Output) -> Self {
101+ Self(output.name())
102+ }
103+}
104+
105+impl MonitorSet {
106+ pub fn new() -> Self {
107+ Self::NoOutputs(vec![])
108+ }
109+
110+ pub fn add_output(&mut self, output: Output) {
111+ let id = OutputId::new(&output);
112+
113+ *self = match mem::take(self) {
114+ MonitorSet::Normal {
115+ mut monitors,
116+ primary_idx,
117+ active_monitor_idx,
118+ } => {
119+ let primary = &mut monitors[primary_idx];
120+
121+ let mut workspaces = vec![];
122+ for i in (0..primary.workspaces.len()).rev() {
123+ if primary.workspaces[i].original_output == id {
124+ let mut ws = primary.workspaces.remove(i);
125+ ws.space.unmap_output(&primary.output);
126+ workspaces.push(ws);
127+ }
128+ }
129+ workspaces.reverse();
130+ if workspaces
131+ .iter()
132+ .all(|ws| ws.space.elements().next().is_some())
133+ {
134+ // Make sure there's always an empty workspace.
135+ workspaces.push(Workspace {
136+ original_output: id,
137+ layout: Layout::new(),
138+ space: Space::default(),
139+ });
140+ }
141+
142+ for ws in &mut workspaces {
143+ ws.space.map_output(&output, (0, 0));
144+ }
145+
146+ monitors.push(Monitor {
147+ output,
148+ workspaces,
149+ active_workspace_idx: 0,
150+ });
151+ MonitorSet::Normal {
152+ monitors,
153+ primary_idx,
154+ active_monitor_idx,
155+ }
156+ }
157+ MonitorSet::NoOutputs(mut workspaces) => {
158+ if workspaces.iter().all(|ws| ws.original_output != id) {
159+ workspaces.insert(
160+ 0,
161+ Workspace {
162+ original_output: id.clone(),
163+ layout: Layout::new(),
164+ space: Space::default(),
165+ },
166+ );
167+ }
168+
169+ for workspace in &mut workspaces {
170+ workspace.space.map_output(&output, (0, 0));
171+ }
172+
173+ let monitor = Monitor {
174+ output,
175+ workspaces,
176+ active_workspace_idx: 0,
177+ };
178+ MonitorSet::Normal {
179+ monitors: vec![monitor],
180+ primary_idx: 0,
181+ active_monitor_idx: 0,
182+ }
183+ }
184+ }
185+ }
186+
187+ pub fn remove_output(&mut self, output: &Output) {
188+ *self = match mem::take(self) {
189+ MonitorSet::Normal {
190+ mut monitors,
191+ mut primary_idx,
192+ mut active_monitor_idx,
193+ } => {
194+ let idx = monitors
195+ .iter()
196+ .position(|mon| &mon.output == output)
197+ .expect("trying to remove non-existing output");
198+ let monitor = monitors.remove(idx);
199+ let mut workspaces = monitor.workspaces;
200+
201+ for ws in &mut workspaces {
202+ ws.space.unmap_output(output);
203+ }
204+
205+ // Get rid of empty workspaces.
206+ workspaces.retain(|ws| ws.space.elements().next().is_some());
207+
208+ if monitors.is_empty() {
209+ // Removed the last monitor.
210+ MonitorSet::NoOutputs(workspaces)
211+ } else {
212+ if primary_idx >= idx {
213+ // Update primary_idx to either still point at the same monitor, or at some
214+ // other monitor if the primary has been removed.
215+ primary_idx = primary_idx.saturating_sub(1);
216+ }
217+ if active_monitor_idx >= idx {
218+ // Update active_monitor_idx to either still point at the same monitor, or
219+ // at some other monitor if the active monitor has
220+ // been removed.
221+ active_monitor_idx = active_monitor_idx.saturating_sub(1);
222+ }
223+
224+ let primary = &mut monitors[primary_idx];
225+ for ws in &mut workspaces {
226+ ws.space.map_output(&primary.output, (0, 0));
227+ }
228+ primary.workspaces.extend(workspaces);
229+
230+ MonitorSet::Normal {
231+ monitors,
232+ primary_idx,
233+ active_monitor_idx,
234+ }
235+ }
236+ }
237+ MonitorSet::NoOutputs(_) => {
238+ panic!("tried to remove output when there were already none")
239+ }
240+ }
241+ }
242+
243+ pub fn configure_new_window(output: &Output, window: &Window) {
244+ let output_size = output_size(output);
245+ let size = Size::from((
246+ (output_size.w - PADDING * 3) / 2,
247+ output_size.h - PADDING * 2,
248+ ));
249+ let bounds = Size::from((output_size.w - PADDING * 2, output_size.h - PADDING * 2));
250+
251+ window.toplevel().with_pending_state(|state| {
252+ state.size = Some(size);
253+ state.bounds = Some(bounds);
254+ });
255+ }
256+
257+ pub fn add_window(
258+ &mut self,
259+ monitor_idx: usize,
260+ workspace_idx: usize,
261+ window: Window,
262+ activate: bool,
263+ ) {
264+ let MonitorSet::Normal {
265+ monitors,
266+ active_monitor_idx,
267+ ..
268+ } = self
269+ else {
270+ panic!()
271+ };
272+
273+ let monitor = &mut monitors[monitor_idx];
274+ let workspace = &mut monitor.workspaces[workspace_idx];
275+ workspace.layout.add_window(window.clone(), activate);
276+ workspace.space.map_element(window.clone(), (0, 0), false);
277+ workspace.layout.sync_space(&mut workspace.space);
278+
279+ MonitorSet::configure_new_window(&monitor.output, &window);
280+ window.toplevel().send_pending_configure();
281+
282+ if activate {
283+ *active_monitor_idx = monitor_idx;
284+ monitor.active_workspace_idx = workspace_idx;
285+ }
286+
287+ if workspace_idx == monitor.workspaces.len() - 1 {
288+ // Insert a new empty workspace.
289+ let mut ws = Workspace {
290+ original_output: OutputId::new(&monitor.output),
291+ layout: Layout::new(),
292+ space: Space::default(),
293+ };
294+ ws.space.map_output(&monitor.output, (0, 0));
295+ monitor.workspaces.push(ws);
296+ }
297+ }
298+
299+ pub fn add_window_to_output(&mut self, output: &Output, window: Window, activate: bool) {
300+ let MonitorSet::Normal { monitors, .. } = self else {
301+ panic!()
302+ };
303+
304+ let (monitor_idx, monitor) = monitors
305+ .iter()
306+ .enumerate()
307+ .find(|(_, mon)| &mon.output == output)
308+ .unwrap();
309+ let workspace_idx = monitor.active_workspace_idx;
310+
311+ self.add_window(monitor_idx, workspace_idx, window, activate)
312+ }
313+
314+ pub fn remove_window(&mut self, window: &Window) {
315+ let MonitorSet::Normal { monitors, .. } = self else {
316+ panic!()
317+ };
318+
319+ let (output, workspace) = monitors
320+ .iter_mut()
321+ .flat_map(|mon| mon.workspaces.iter_mut().map(|ws| (&mon.output, ws)))
322+ .find(|(_, ws)| ws.space.elements().any(|win| win == window))
323+ .unwrap();
324+
325+ workspace
326+ .layout
327+ .remove_window(window, output_size(output).h);
328+ workspace.space.unmap_elem(window);
329+ workspace.layout.sync_space(&mut workspace.space);
330+
331+ // FIXME: remove empty unfocused workspaces.
332+ }
333+
334+ pub fn update_window(&mut self, window: &Window) {
335+ let workspace = self
336+ .workspaces()
337+ .find(|ws| ws.space.elements().any(|w| w == window))
338+ .unwrap();
339+ workspace.layout.sync_space(&mut workspace.space);
340+ }
341+
342+ pub fn activate_window(&mut self, window: &Window) {
343+ let MonitorSet::Normal {
344+ monitors,
345+ active_monitor_idx,
346+ ..
347+ } = self
348+ else {
349+ todo!()
350+ };
351+
352+ for (monitor_idx, mon) in monitors.iter_mut().enumerate() {
353+ for (workspace_idx, ws) in mon.workspaces.iter_mut().enumerate() {
354+ if ws.space.elements().any(|win| win == window) {
355+ *active_monitor_idx = monitor_idx;
356+ mon.active_workspace_idx = workspace_idx;
357+
358+ let changed = ws.layout.activate_window(window);
359+ if changed {
360+ ws.layout.sync_space(&mut ws.space);
361+ }
362+
363+ break;
364+ }
365+ }
366+ }
367+ }
368+
369+ pub fn activate_output(&mut self, output: &Output) {
370+ let MonitorSet::Normal {
371+ monitors,
372+ active_monitor_idx,
373+ ..
374+ } = self
375+ else {
376+ return;
377+ };
378+
379+ let idx = monitors
380+ .iter()
381+ .position(|mon| &mon.output == output)
382+ .unwrap();
383+ *active_monitor_idx = idx;
384+ }
385+
386+ pub fn active_output(&self) -> Option<&Output> {
387+ let MonitorSet::Normal {
388+ monitors,
389+ active_monitor_idx,
390+ ..
391+ } = self
392+ else {
393+ return None;
394+ };
395+
396+ Some(&monitors[*active_monitor_idx].output)
397+ }
398+
399+ fn active_workspace(&mut self) -> Option<&mut Workspace> {
400+ let monitor = self.active_monitor()?;
401+ Some(&mut monitor.workspaces[monitor.active_workspace_idx])
402+ }
403+
404+ fn active_monitor(&mut self) -> Option<&mut Monitor> {
405+ let MonitorSet::Normal {
406+ monitors,
407+ active_monitor_idx,
408+ ..
409+ } = self
410+ else {
411+ return None;
412+ };
413+
414+ Some(&mut monitors[*active_monitor_idx])
415+ }
416+
417+ pub fn move_left(&mut self) {
418+ let Some(workspace) = self.active_workspace() else {
419+ return;
420+ };
421+ let changed = workspace.layout.move_left();
422+ if changed {
423+ workspace.layout.sync_space(&mut workspace.space);
424+ }
425+ }
426+
427+ pub fn move_right(&mut self) {
428+ let Some(workspace) = self.active_workspace() else {
429+ return;
430+ };
431+ let changed = workspace.layout.move_right();
432+ if changed {
433+ workspace.layout.sync_space(&mut workspace.space);
434+ }
435+ }
436+
437+ pub fn move_down(&mut self) {
438+ let Some(workspace) = self.active_workspace() else {
439+ return;
440+ };
441+ let changed = workspace.layout.move_down();
442+ if changed {
443+ workspace.layout.sync_space(&mut workspace.space);
444+ }
445+ }
446+
447+ pub fn move_up(&mut self) {
448+ let Some(workspace) = self.active_workspace() else {
449+ return;
450+ };
451+ let changed = workspace.layout.move_up();
452+ if changed {
453+ workspace.layout.sync_space(&mut workspace.space);
454+ }
455+ }
456+
457+ pub fn focus_left(&mut self) {
458+ let Some(workspace) = self.active_workspace() else {
459+ return;
460+ };
461+ workspace.layout.focus_left();
462+ }
463+
464+ pub fn focus_right(&mut self) {
465+ let Some(workspace) = self.active_workspace() else {
466+ return;
467+ };
468+ workspace.layout.focus_right();
469+ }
470+
471+ pub fn focus_down(&mut self) {
472+ let Some(workspace) = self.active_workspace() else {
473+ return;
474+ };
475+ workspace.layout.focus_down();
476+ }
477+
478+ pub fn focus_up(&mut self) {
479+ let Some(workspace) = self.active_workspace() else {
480+ return;
481+ };
482+ workspace.layout.focus_up();
483+ }
484+
485+ pub fn move_to_workspace_up(&mut self) {
486+ let MonitorSet::Normal {
487+ monitors,
488+ ref active_monitor_idx,
489+ ..
490+ } = self
491+ else {
492+ return;
493+ };
494+
495+ let monitor = &mut monitors[*active_monitor_idx];
496+
497+ let new_idx = monitor.active_workspace_idx.saturating_sub(1);
498+ if new_idx == monitor.active_workspace_idx {
499+ return;
500+ }
501+
502+ let workspace = &mut monitor.workspaces[monitor.active_workspace_idx];
503+ if workspace.layout.columns.is_empty() {
504+ return;
505+ }
506+
507+ let column = &mut workspace.layout.columns[workspace.layout.active_column_idx];
508+ let window = column.windows[column.active_window_idx].clone();
509+ workspace
510+ .layout
511+ .remove_window(&window, output_size(&monitor.output).h);
512+ workspace.space.unmap_elem(&window);
513+ workspace.layout.sync_space(&mut workspace.space);
514+
515+ self.add_window(*active_monitor_idx, new_idx, window, true);
516+
517+ // FIXME: remove empty unfocused workspaces.
518+ }
519+
520+ pub fn move_to_workspace_down(&mut self) {
521+ let MonitorSet::Normal {
522+ monitors,
523+ ref active_monitor_idx,
524+ ..
525+ } = self
526+ else {
527+ return;
528+ };
529+
530+ let monitor = &mut monitors[*active_monitor_idx];
531+
532+ let new_idx = min(
533+ monitor.active_workspace_idx + 1,
534+ monitor.workspaces.len() - 1,
535+ );
536+
537+ if new_idx == monitor.active_workspace_idx {
538+ return;
539+ }
540+
541+ let workspace = &mut monitor.workspaces[monitor.active_workspace_idx];
542+ if workspace.layout.columns.is_empty() {
543+ return;
544+ }
545+
546+ let column = &mut workspace.layout.columns[workspace.layout.active_column_idx];
547+ let window = column.windows[column.active_window_idx].clone();
548+ workspace
549+ .layout
550+ .remove_window(&window, output_size(&monitor.output).h);
551+ workspace.space.unmap_elem(&window);
552+ workspace.layout.sync_space(&mut workspace.space);
553+
554+ self.add_window(*active_monitor_idx, new_idx, window, true);
555+
556+ // FIXME: remove empty unfocused workspaces.
557+ }
558+
559+ pub fn switch_workspace_up(&mut self) {
560+ let Some(monitor) = self.active_monitor() else {
561+ return;
562+ };
563+
564+ monitor.active_workspace_idx = monitor.active_workspace_idx.saturating_sub(1);
565+
566+ // FIXME: remove empty unfocused workspaces.
567+ }
568+
569+ pub fn switch_workspace_down(&mut self) {
570+ let Some(monitor) = self.active_monitor() else {
571+ return;
572+ };
573+ monitor.active_workspace_idx = min(
574+ monitor.active_workspace_idx + 1,
575+ monitor.workspaces.len() - 1,
576+ );
577+
578+ // FIXME: remove empty unfocused workspaces.
579+ }
580+
581+ pub fn consume_into_column(&mut self) {
582+ let MonitorSet::Normal {
583+ monitors,
584+ active_monitor_idx,
585+ ..
586+ } = self
587+ else {
588+ return;
589+ };
590+
591+ let monitor = &mut monitors[*active_monitor_idx];
592+
593+ let workspace = &mut monitor.workspaces[monitor.active_workspace_idx];
594+ let changed = workspace
595+ .layout
596+ .consume_into_column(output_size(&monitor.output).h);
597+ if changed {
598+ workspace.layout.sync_space(&mut workspace.space);
599+ }
600+ }
601+
602+ pub fn expel_from_column(&mut self) {
603+ let MonitorSet::Normal {
604+ monitors,
605+ active_monitor_idx,
606+ ..
607+ } = self
608+ else {
609+ return;
610+ };
611+
612+ let monitor = &mut monitors[*active_monitor_idx];
613+
614+ let output_scale = monitor.output.current_scale().integer_scale();
615+ let output_transform = monitor.output.current_transform();
616+ let output_mode = monitor.output.current_mode().unwrap();
617+ let output_size = output_transform
618+ .transform_size(output_mode.size)
619+ .to_logical(output_scale);
620+
621+ let workspace = &mut monitor.workspaces[monitor.active_workspace_idx];
622+ let changed = workspace.layout.expel_from_column(output_size.h);
623+ if changed {
624+ workspace.layout.sync_space(&mut workspace.space);
625+ }
626+ }
627+
628+ pub fn focus(&self) -> Option<&Window> {
629+ let MonitorSet::Normal {
630+ monitors,
631+ active_monitor_idx,
632+ ..
633+ } = self
634+ else {
635+ return None;
636+ };
637+
638+ let monitor = &monitors[*active_monitor_idx];
639+ let workspace = &monitor.workspaces[monitor.active_workspace_idx];
640+ if workspace.layout.columns.is_empty() {
641+ return None;
642+ }
643+
644+ let column = &workspace.layout.columns[workspace.layout.active_column_idx];
645+ Some(&column.windows[column.active_window_idx])
646+ }
647+
648+ pub fn workspace_for_output(&mut self, output: &Output) -> Option<&mut Workspace> {
649+ let MonitorSet::Normal { monitors, .. } = self else {
650+ return None;
651+ };
652+
653+ monitors.iter_mut().find_map(|monitor| {
654+ if &monitor.output == output {
655+ Some(&mut monitor.workspaces[monitor.active_workspace_idx])
656+ } else {
657+ None
658+ }
659+ })
660+ }
661+
662+ pub fn workspaces(&mut self) -> impl Iterator<Item = &mut Workspace> + '_ {
663+ match self {
664+ MonitorSet::Normal { monitors, .. } => {
665+ monitors.iter_mut().flat_map(|mon| &mut mon.workspaces)
666+ }
667+ MonitorSet::NoOutputs(_workspaces) => todo!(),
668+ }
669+ }
670+
671+ pub fn spaces(&mut self) -> impl Iterator<Item = &Space<Window>> + '_ {
672+ self.workspaces().map(|workspace| &workspace.space)
673+ }
674+
675+ pub fn find_window(&mut self, wl_surface: &WlSurface) -> Option<&Window> {
676+ self.workspaces()
677+ .flat_map(|workspace| workspace.space.elements())
678+ .find(|window| window.toplevel().wl_surface() == wl_surface)
679+ }
680+
681+ pub fn find_window_and_space(
682+ &mut self,
683+ wl_surface: &WlSurface,
684+ ) -> Option<(Window, &Space<Window>)> {
685+ self.spaces().find_map(|space| {
686+ let window = space
687+ .elements()
688+ .find(|window| window.toplevel().wl_surface() == wl_surface)
689+ .cloned();
690+ window.map(|window| (window, space))
691+ })
692+ }
693+
694+ /// Refreshes the `Space`s.
695+ pub fn refresh(&mut self) {
696+ for workspace in self.workspaces() {
697+ workspace.space.refresh();
698+ }
699+ }
700+
701+ fn verify_invariants(&self) {
702+ let (monitors, &primary_idx, &active_monitor_idx) = match &self {
703+ MonitorSet::Normal {
704+ monitors,
705+ primary_idx,
706+ active_monitor_idx,
707+ } => (monitors, primary_idx, active_monitor_idx),
708+ MonitorSet::NoOutputs(workspaces) => {
709+ for workspace in workspaces {
710+ assert!(
711+ !workspace.layout.has_windows(),
712+ "with no outputs there cannot be empty workspaces"
713+ );
714+
715+ workspace.layout.verify_invariants();
716+ }
717+
718+ return;
719+ }
720+ };
721+
722+ assert!(primary_idx <= monitors.len());
723+ assert!(active_monitor_idx <= monitors.len());
724+
725+ for (idx, monitor) in monitors.iter().enumerate() {
726+ assert!(
727+ !monitor.workspaces.is_empty(),
728+ "monitor monitor must have at least one workspace"
729+ );
730+
731+ let monitor_id = OutputId::new(&monitor.output);
732+
733+ if idx == primary_idx {
734+ assert!(
735+ monitor
736+ .workspaces
737+ .iter()
738+ .any(|workspace| workspace.original_output == monitor_id),
739+ "primary monitor must have at least one own workspace"
740+ );
741+ } else {
742+ assert!(
743+ monitor
744+ .workspaces
745+ .iter()
746+ .any(|workspace| workspace.original_output == monitor_id),
747+ "secondary monitor must have all own workspaces"
748+ );
749+ }
750+
751+ // FIXME: verify that primary doesn't have any workspaces for which their own monitor
752+ // exists.
753+
754+ for workspace in &monitor.workspaces {
755+ workspace.layout.verify_invariants();
756+ }
757+ }
758+ }
759+}
760+
761+fn output_size(output: &Output) -> Size<i32, Logical> {
762+ let output_scale = output.current_scale().integer_scale();
763+ let output_transform = output.current_transform();
764+ let output_mode = output.current_mode().unwrap();
765+ let output_size = output_transform
766+ .transform_size(output_mode.size)
767+ .to_logical(output_scale);
768+ output_size
769+}
770+
771+impl Default for MonitorSet {
772+ fn default() -> Self {
773+ Self::new()
774+ }
775+}
776+
777+impl Layout {
778+ fn new() -> Self {
779+ Self {
780+ columns: vec![],
781+ active_column_idx: 0,
782+ }
783+ }
784+
785+ fn sync_space(&self, space: &mut Space<Window>) {
786+ // FIXME: this is really inefficient
787+ let mut active_window = None;
788+
789+ let mut x = PADDING;
790+ for (column_idx, column) in self.columns.iter().enumerate() {
791+ let mut y = PADDING;
792+ for (window_idx, window) in column.windows.iter().enumerate() {
793+ let active =
794+ column_idx == self.active_column_idx && window_idx == column.active_window_idx;
795+ if active {
796+ active_window = Some(window.clone());
797+ }
798+
799+ window.set_activated(active);
800+ space.map_element(window.clone(), (x, y), false);
801+ window.toplevel().send_pending_configure();
802+ y += window.geometry().size.h + PADDING;
803+ }
804+ x += column.size().w + PADDING;
805+ }
806+
807+ if let Some(window) = active_window {
808+ space.raise_element(&window, false);
809+ }
810+ }
811+
812+ fn has_windows(&self) -> bool {
813+ self.columns.is_empty()
814+ }
815+
816+ /// Computes the width of the layout including left and right padding, in Logical coordinates.
817+ fn width(&self) -> i32 {
818+ let mut total = PADDING;
819+
820+ for column in &self.columns {
821+ total += column.size().w + PADDING;
822+ }
823+
824+ total
825+ }
826+
827+ /// Computes the X position of the windows in the given column, in logical coordinates.
828+ fn column_x(&self, column_idx: usize) -> i32 {
829+ let mut x = PADDING;
830+
831+ for column in self.columns.iter().take(column_idx) {
832+ x += column.size().w + PADDING;
833+ }
834+
835+ x
836+ }
837+
838+ fn add_window(&mut self, window: Window, activate: bool) {
839+ let idx = if self.columns.is_empty() {
840+ 0
841+ } else {
842+ self.active_column_idx + 1
843+ };
844+
845+ let column = Column {
846+ windows: vec![window],
847+ active_window_idx: 0,
848+ };
849+ self.columns.insert(idx, column);
850+
851+ if activate {
852+ self.active_column_idx = idx;
853+ }
854+ }
855+
856+ fn remove_window(&mut self, window: &Window, total_height: i32) {
857+ let column_idx = self
858+ .columns
859+ .iter()
860+ .position(|col| col.windows.contains(window))
861+ .unwrap();
862+ let column = &mut self.columns[column_idx];
863+
864+ let window_idx = column.windows.iter().position(|win| win == window).unwrap();
865+ column.windows.remove(window_idx);
866+ if column.windows.is_empty() {
867+ self.columns.remove(column_idx);
868+ if self.columns.is_empty() {
869+ return;
870+ }
871+
872+ self.active_column_idx = min(self.active_column_idx, self.columns.len() - 1);
873+ return;
874+ }
875+
876+ column.active_window_idx = min(column.active_window_idx, column.windows.len() - 1);
877+
878+ // Update window sizes.
879+ let window_count = column.windows.len() as i32;
880+ let height = (total_height - PADDING * (window_count + 1)) / window_count;
881+ let width = column.size().w;
882+
883+ for window in &mut column.windows {
884+ window
885+ .toplevel()
886+ .with_pending_state(|state| state.size = Some(Size::from((width, height))));
887+ window.toplevel().send_pending_configure();
888+ }
889+ }
890+
891+ fn activate_window(&mut self, window: &Window) -> bool {
892+ let column_idx = self
893+ .columns
894+ .iter()
895+ .position(|col| col.windows.contains(window))
896+ .unwrap();
897+ let column = &mut self.columns[column_idx];
898+
899+ let window_idx = column.windows.iter().position(|win| win == window).unwrap();
900+
901+ if column.active_window_idx != window_idx || self.active_column_idx != column_idx {
902+ column.active_window_idx = window_idx;
903+ self.active_column_idx = column_idx;
904+ true
905+ } else {
906+ false
907+ }
908+ }
909+
910+ fn verify_invariants(&self) {
911+ for column in &self.columns {
912+ column.verify_invariants();
913+ }
914+ }
915+
916+ fn focus_left(&mut self) {
917+ self.active_column_idx = self.active_column_idx.saturating_sub(1);
918+ }
919+
920+ fn focus_right(&mut self) {
921+ if self.columns.is_empty() {
922+ return;
923+ }
924+
925+ self.active_column_idx = min(self.active_column_idx + 1, self.columns.len() - 1);
926+ }
927+
928+ fn focus_down(&mut self) {
929+ if self.columns.is_empty() {
930+ return;
931+ }
932+
933+ self.columns[self.active_column_idx].focus_down();
934+ }
935+
936+ fn focus_up(&mut self) {
937+ if self.columns.is_empty() {
938+ return;
939+ }
940+
941+ self.columns[self.active_column_idx].focus_up();
942+ }
943+
944+ fn move_left(&mut self) -> bool {
945+ let new_idx = self.active_column_idx.saturating_sub(1);
946+ if self.active_column_idx == new_idx {
947+ return false;
948+ }
949+
950+ self.columns.swap(self.active_column_idx, new_idx);
951+ self.active_column_idx = new_idx;
952+ true
953+ }
954+
955+ fn move_right(&mut self) -> bool {
956+ if self.columns.is_empty() {
957+ return false;
958+ }
959+
960+ let new_idx = min(self.active_column_idx + 1, self.columns.len() - 1);
961+ if self.active_column_idx == new_idx {
962+ return false;
963+ }
964+
965+ self.columns.swap(self.active_column_idx, new_idx);
966+ self.active_column_idx = new_idx;
967+ true
968+ }
969+
970+ fn move_down(&mut self) -> bool {
971+ if self.columns.is_empty() {
972+ return false;
973+ }
974+
975+ self.columns[self.active_column_idx].move_down()
976+ }
977+
978+ fn move_up(&mut self) -> bool {
979+ if self.columns.is_empty() {
980+ return false;
981+ }
982+
983+ self.columns[self.active_column_idx].move_up()
984+ }
985+
986+ fn consume_into_column(&mut self, total_height: i32) -> bool {
987+ if self.columns.len() < 2 {
988+ return false;
989+ }
990+
991+ if self.active_column_idx == self.columns.len() - 1 {
992+ return false;
993+ }
994+
995+ let source_column_idx = self.active_column_idx + 1;
996+
997+ let source_column = &mut self.columns[source_column_idx];
998+ let window = source_column.windows[0].clone();
999+ self.remove_window(&window, total_height);
1000+
1001+ let target_column = &mut self.columns[self.active_column_idx];
1002+
1003+ let window_count = target_column.windows.len() as i32 + 1;
1004+ let height = (total_height - PADDING * (window_count + 1)) / window_count;
1005+ let width = target_column.size().w;
1006+
1007+ target_column.windows.push(window);
1008+
1009+ for window in &mut target_column.windows {
1010+ window
1011+ .toplevel()
1012+ .with_pending_state(|state| state.size = Some(Size::from((width, height))));
1013+ window.toplevel().send_pending_configure();
1014+ }
1015+ true
1016+ }
1017+
1018+ fn expel_from_column(&mut self, total_height: i32) -> bool {
1019+ if self.columns.is_empty() {
1020+ return false;
1021+ }
1022+
1023+ let source_column = &mut self.columns[self.active_column_idx];
1024+ if source_column.windows.len() == 1 {
1025+ return false;
1026+ }
1027+
1028+ let window = source_column.windows[source_column.active_window_idx].clone();
1029+ self.remove_window(&window, total_height);
1030+
1031+ window.toplevel().with_pending_state(|state| {
1032+ state.size = Some(Size::from((state.size.unwrap().w, total_height)))
1033+ });
1034+ window.toplevel().send_pending_configure();
1035+ self.add_window(window, true);
1036+
1037+ true
1038+ }
1039+}
1040+
1041+impl Column {
1042+ /// Computes the size of the column including top and bottom padding.
1043+ fn size(&self) -> Size<i32, Logical> {
1044+ let mut total = Size::from((0, PADDING));
1045+
1046+ for window in &self.windows {
1047+ let size = window.geometry().size;
1048+ total.w = max(total.w, size.w);
1049+ total.h += size.h + PADDING;
1050+ }
1051+
1052+ total
1053+ }
1054+
1055+ fn window_y(&self, window_idx: usize) -> i32 {
1056+ let mut y = PADDING;
1057+
1058+ for window in self.windows.iter().take(window_idx) {
1059+ let size = window.geometry().size;
1060+ y += size.h + PADDING;
1061+ }
1062+
1063+ y
1064+ }
1065+
1066+ fn focus_up(&mut self) {
1067+ self.active_window_idx = self.active_window_idx.saturating_sub(1);
1068+ }
1069+
1070+ fn focus_down(&mut self) {
1071+ self.active_window_idx = min(self.active_window_idx + 1, self.windows.len() - 1);
1072+ }
1073+
1074+ fn move_up(&mut self) -> bool {
1075+ let new_idx = self.active_window_idx.saturating_sub(1);
1076+ if self.active_window_idx == new_idx {
1077+ return false;
1078+ }
1079+
1080+ self.windows.swap(self.active_window_idx, new_idx);
1081+ self.active_window_idx = new_idx;
1082+ true
1083+ }
1084+
1085+ fn move_down(&mut self) -> bool {
1086+ let new_idx = min(self.active_window_idx + 1, self.windows.len() - 1);
1087+ if self.active_window_idx == new_idx {
1088+ return false;
1089+ }
1090+
1091+ self.windows.swap(self.active_window_idx, new_idx);
1092+ self.active_window_idx = new_idx;
1093+ true
1094+ }
1095+
1096+ fn verify_invariants(&self) {
1097+ assert!(!self.windows.is_empty(), "columns can't be empty");
1098+ }
1099+}
src/main.rsmodified+2 -1
@@ -6,6 +6,7 @@ mod handlers;
6 mod backend;6 mod backend;
7 mod grabs;7 mod grabs;
8 mod input;8 mod input;
9+mod layout;
9 mod niri;10 mod niri;
10 mod tty;11 mod tty;
11 mod winit;12 mod winit;
@@ -108,7 +109,7 @@ fn main() {
108 let _span = tracy_client::span!("loop callback");109 let _span = tracy_client::span!("loop callback");
109 110
110 // These should be called periodically, before flushing the clients.111 // These should be called periodically, before flushing the clients.
111- data.niri.space.refresh();112+ data.niri.monitor_set.refresh();
112 data.niri.popups.cleanup();113 data.niri.popups.cleanup();
113 114
114 {115 {
src/niri.rsmodified+204 -43
@@ -1,9 +1,10 @@
1+use std::collections::HashMap;
1 use std::os::unix::io::AsRawFd;2 use std::os::unix::io::AsRawFd;
2 use std::sync::Arc;3 use std::sync::Arc;
3 use std::time::Duration;4 use std::time::Duration;
4 5
5-use smithay::backend::renderer::element::render_elements;
6 use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};6 use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
7+use smithay::backend::renderer::element::{render_elements, RenderElement};
7 use smithay::backend::renderer::ImportAll;8 use smithay::backend::renderer::ImportAll;
8 use smithay::desktop::space::{space_render_elements, SpaceRenderElements};9 use smithay::desktop::space::{space_render_elements, SpaceRenderElements};
9 use smithay::desktop::{PopupManager, Space, Window, WindowSurfaceType};10 use smithay::desktop::{PopupManager, Space, Window, WindowSurfaceType};
@@ -11,12 +12,14 @@ use smithay::input::keyboard::XkbConfig;
11 use smithay::input::{Seat, SeatState};12 use smithay::input::{Seat, SeatState};
12 use smithay::output::Output;13 use smithay::output::Output;
13 use smithay::reexports::calloop::generic::Generic;14 use smithay::reexports::calloop::generic::Generic;
14-use smithay::reexports::calloop::{Interest, LoopHandle, LoopSignal, Mode, PostAction};15+use smithay::reexports::calloop::{Idle, Interest, LoopHandle, LoopSignal, Mode, PostAction};
15 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;16 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;
16-use smithay::reexports::wayland_server::backend::{ClientData, ClientId, DisconnectReason};17+use smithay::reexports::wayland_server::backend::{
18+ ClientData, ClientId, DisconnectReason, GlobalId,
19+};
17 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;20 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
18 use smithay::reexports::wayland_server::{Display, DisplayHandle};21 use smithay::reexports::wayland_server::{Display, DisplayHandle};
19-use smithay::utils::{Logical, Point};22+use smithay::utils::{Logical, Point, SERIAL_COUNTER};
20 use smithay::wayland::compositor::{CompositorClientState, CompositorState};23 use smithay::wayland::compositor::{CompositorClientState, CompositorState};
21 use smithay::wayland::data_device::DataDeviceState;24 use smithay::wayland::data_device::DataDeviceState;
22 use smithay::wayland::output::OutputManagerState;25 use smithay::wayland::output::OutputManagerState;
@@ -25,6 +28,7 @@ use smithay::wayland::shm::ShmState;
25 use smithay::wayland::socket::ListeningSocketSource;28 use smithay::wayland::socket::ListeningSocketSource;
26 29
27 use crate::backend::Backend;30 use crate::backend::Backend;
31+use crate::layout::MonitorSet;
28 use crate::LoopData;32 use crate::LoopData;
29 33
30 pub struct Niri {34 pub struct Niri {
@@ -33,7 +37,18 @@ pub struct Niri {
33 pub stop_signal: LoopSignal,37 pub stop_signal: LoopSignal,
34 pub display_handle: DisplayHandle,38 pub display_handle: DisplayHandle,
35 39
36- pub space: Space<Window>,40+ // Each workspace corresponds to a Space. Each workspace generally has one Output mapped to it,
41+ // however it may have none (when there are no outputs connected) or mutiple (when mirroring).
42+ pub monitor_set: MonitorSet,
43+
44+ // This space does not actually contain any windows, but all outputs are mapped into it
45+ // according to their global position.
46+ pub global_space: Space<Window>,
47+
48+ // Windows which don't have a buffer attached yet.
49+ pub unmapped_windows: HashMap<WlSurface, Window>,
50+
51+ pub output_state: HashMap<Output, OutputState>,
37 52
38 // Smithay state.53 // Smithay state.
39 pub compositor_state: CompositorState,54 pub compositor_state: CompositorState,
@@ -45,13 +60,17 @@ pub struct Niri {
45 pub popups: PopupManager,60 pub popups: PopupManager,
46 61
47 pub seat: Seat<Self>,62 pub seat: Seat<Self>,
48- pub output: Option<Output>,
49 63
50 pub pointer_buffer: SolidColorBuffer,64 pub pointer_buffer: SolidColorBuffer,
65+}
51 66
52- // Set to `true` if there's a redraw queued on the event loop. Reset to `false` in redraw()67+pub struct OutputState {
53- // which means that you cannot queue more than one redraw at once.68+ pub global: GlobalId,
54- pub redraw_queued: bool,69+ // Set if there's a redraw queued on the event loop. Reset in redraw() which means that you
70+ // cannot queue more than one redraw at once.
71+ pub queued_redraw: Option<Idle<'static>>,
72+ // Set to `true` when the output was redrawn and is waiting for a VBlank. Upon VBlank a redraw
73+ // will always be queued, so you cannot queue a redraw while waiting for a VBlank.
55 pub waiting_for_vblank: bool,74 pub waiting_for_vblank: bool,
56 }75 }
57 76
@@ -90,8 +109,6 @@ impl Niri {
90 seat.add_keyboard(xkb, 400, 30).unwrap();109 seat.add_keyboard(xkb, 400, 30).unwrap();
91 seat.add_pointer();110 seat.add_pointer();
92 111
93- let space = Space::default();
94-
95 let socket_source = ListeningSocketSource::new_auto().unwrap();112 let socket_source = ListeningSocketSource::new_auto().unwrap();
96 let socket_name = socket_source.socket_name().to_os_string();113 let socket_name = socket_source.socket_name().to_os_string();
97 event_loop114 event_loop
@@ -130,7 +147,10 @@ impl Niri {
130 stop_signal,147 stop_signal,
131 display_handle,148 display_handle,
132 149
133- space,150+ monitor_set: MonitorSet::new(),
151+ global_space: Space::default(),
152+ output_state: HashMap::new(),
153+ unmapped_windows: HashMap::new(),
134 154
135 compositor_state,155 compositor_state,
136 xdg_shell_state,156 xdg_shell_state,
@@ -141,60 +161,188 @@ impl Niri {
141 popups: PopupManager::default(),161 popups: PopupManager::default(),
142 162
143 seat,163 seat,
144- output: None,
145 pointer_buffer,164 pointer_buffer,
146- redraw_queued: false,165+ }
166+ }
167+
168+ pub fn add_output(&mut self, output: Output) {
169+ let x = self
170+ .global_space
171+ .outputs()
172+ .map(|output| self.global_space.output_geometry(output).unwrap())
173+ .map(|geom| geom.loc.x + geom.size.w)
174+ .max()
175+ .unwrap_or(0);
176+
177+ self.global_space.map_output(&output, (x, 0));
178+ self.monitor_set.add_output(output.clone());
179+
180+ let state = OutputState {
181+ global: output.create_global::<Niri>(&self.display_handle),
182+ queued_redraw: None,
147 waiting_for_vblank: false,183 waiting_for_vblank: false,
184+ };
185+ let rv = self.output_state.insert(output, state);
186+ assert!(rv.is_none(), "output was already tracked");
187+ }
188+
189+ pub fn remove_output(&mut self, output: &Output) {
190+ let mut state = self.output_state.remove(output).unwrap();
191+ self.display_handle.remove_global::<Niri>(state.global);
192+
193+ if let Some(idle) = state.queued_redraw.take() {
194+ idle.cancel();
148 }195 }
196+
197+ self.monitor_set.remove_output(output);
198+ self.global_space.unmap_output(output);
199+ // FIXME: reposition outputs so they are adjacent.
200+ }
201+
202+ pub fn output_resized(&mut self, output: Output) {
203+ // FIXME resize windows etc
204+ self.queue_redraw(output);
205+ }
206+
207+ pub fn output_under(&self, pos: Point<f64, Logical>) -> Option<(&Output, Point<f64, Logical>)> {
208+ let output = self.global_space.output_under(pos).next()?;
209+ let pos_within_output = pos
210+ - self
211+ .global_space
212+ .output_geometry(output)
213+ .unwrap()
214+ .loc
215+ .to_f64();
216+
217+ Some((output, pos_within_output))
218+ }
219+
220+ pub fn window_under(
221+ &mut self,
222+ pos: Point<f64, Logical>,
223+ ) -> Option<(&mut Space<Window>, Window, Point<i32, Logical>)> {
224+ let (output, pos_within_output) = self.output_under(pos)?;
225+ let output = output.clone();
226+
227+ let space = &mut self.monitor_set.workspace_for_output(&output)?.space;
228+ let output_pos = space.output_geometry(&output).unwrap().loc.to_f64();
229+
230+ let pos_within_space = pos_within_output + output_pos;
231+ let (window, loc) = space.element_under(pos_within_space)?;
232+ let window = window.clone();
233+ Some((space, window, loc))
149 }234 }
150 235
151 pub fn surface_under(236 pub fn surface_under(
152- &self,237+ &mut self,
153 pos: Point<f64, Logical>,238 pos: Point<f64, Logical>,
154 ) -> Option<(WlSurface, Point<i32, Logical>)> {239 ) -> Option<(WlSurface, Point<i32, Logical>)> {
155- self.space240+ let (output, pos_within_output) = self.output_under(pos)?;
156- .element_under(pos)241+ let output = output.clone();
242+
243+ let space = &self.monitor_set.workspace_for_output(&output)?.space;
244+ let output_pos = space.output_geometry(&output).unwrap().loc.to_f64();
245+
246+ let pos_within_space = pos_within_output + output_pos;
247+ space
248+ .element_under(pos_within_space)
157 .and_then(|(window, location)| {249 .and_then(|(window, location)| {
158 window250 window
159- .surface_under(pos - location.to_f64(), WindowSurfaceType::ALL)251+ .surface_under(pos_within_space - location.to_f64(), WindowSurfaceType::ALL)
160 .map(|(s, p)| (s, p + location))252 .map(|(s, p)| (s, p + location))
161 })253 })
162 }254 }
163 255
256+ /// Returns the surface under cursor and its position in the global space.
257+ ///
258+ /// Pointer needs location in global space, and focused window location compatible with that
259+ /// global space. We don't have a global space for all windows, but this function converts the
260+ /// window location temporarily to the current global space.
261+ pub fn surface_under_and_global_space(
262+ &mut self,
263+ pos: Point<f64, Logical>,
264+ ) -> Option<(WlSurface, Point<i32, Logical>)> {
265+ let (output, pos_within_output) = self.output_under(pos)?;
266+ let output = output.clone();
267+
268+ let workspace = &self.monitor_set.workspace_for_output(&output)?;
269+ let space = &workspace.space;
270+ let output_pos_in_local_space = space.output_geometry(&output).unwrap().loc;
271+ let pos_within_space = pos_within_output + output_pos_in_local_space.to_f64();
272+
273+ let (surface, surface_loc_in_local_space) = space
274+ .element_under(pos_within_space)
275+ .and_then(|(window, location)| {
276+ window
277+ .surface_under(pos_within_space - location.to_f64(), WindowSurfaceType::ALL)
278+ .map(|(s, p)| (s, p + location))
279+ })?;
280+ let output_pos_in_global_space = self.global_space.output_geometry(&output).unwrap().loc;
281+ let surface_loc_in_global_space =
282+ surface_loc_in_local_space - output_pos_in_local_space + output_pos_in_global_space;
283+
284+ Some((surface, surface_loc_in_global_space))
285+ }
286+
287+ pub fn output_under_cursor(&self) -> Option<Output> {
288+ let pos = self.seat.get_pointer().unwrap().current_location();
289+ self.global_space.output_under(pos).next().cloned()
290+ }
291+
292+ pub fn update_focus(&mut self) {
293+ let focus = self
294+ .monitor_set
295+ .focus()
296+ .map(|win| win.toplevel().wl_surface().clone());
297+ let keyboard = self.seat.get_keyboard().unwrap();
298+ if keyboard.current_focus() != focus {
299+ keyboard.set_focus(self, focus, SERIAL_COUNTER.next_serial());
300+ // FIXME: can be more granular.
301+ self.queue_redraw_all();
302+ }
303+ }
304+
305+ /// Schedules an immediate redraw on all outputs if one is not already scheduled.
306+ pub fn queue_redraw_all(&mut self) {
307+ let outputs: Vec<_> = self.output_state.keys().cloned().collect();
308+ for output in outputs {
309+ self.queue_redraw(output);
310+ }
311+ }
312+
164 /// Schedules an immediate redraw if one is not already scheduled.313 /// Schedules an immediate redraw if one is not already scheduled.
165- pub fn queue_redraw(&mut self) {314+ pub fn queue_redraw(&mut self, output: Output) {
166- if self.redraw_queued || self.waiting_for_vblank {315+ let state = self.output_state.get_mut(&output).unwrap();
316+
317+ if state.queued_redraw.is_some() || state.waiting_for_vblank {
167 return;318 return;
168 }319 }
169 320
170- self.redraw_queued = true;
171-
172 // Timer::immediate() adds a millisecond of delay for some reason.321 // Timer::immediate() adds a millisecond of delay for some reason.
173 // This should be fixed in calloop v0.11: https://github.com/Smithay/calloop/issues/142322 // This should be fixed in calloop v0.11: https://github.com/Smithay/calloop/issues/142
174- self.event_loop.insert_idle(|data| {323+ let idle = self.event_loop.insert_idle(move |data| {
175 let backend: &mut dyn Backend = if let Some(tty) = &mut data.tty {324 let backend: &mut dyn Backend = if let Some(tty) = &mut data.tty {
176 tty325 tty
177 } else {326 } else {
178 data.winit.as_mut().unwrap()327 data.winit.as_mut().unwrap()
179 };328 };
180- data.niri.redraw(backend);329+ data.niri.redraw(backend, &output);
181 });330 });
331+ state.queued_redraw = Some(idle);
182 }332 }
183 333
184- fn redraw(&mut self, backend: &mut dyn Backend) {334+ fn redraw(&mut self, backend: &mut dyn Backend, output: &Output) {
185 let _span = tracy_client::span!("redraw");335 let _span = tracy_client::span!("redraw");
336+ let state = self.output_state.get_mut(output).unwrap();
186 337
187- assert!(self.redraw_queued);338+ assert!(state.queued_redraw.take().is_some());
188- assert!(!self.waiting_for_vblank);339+ assert!(!state.waiting_for_vblank);
189- self.redraw_queued = false;
190 340
191- let elements = space_render_elements(341+ let space = &self.monitor_set.workspace_for_output(output).unwrap().space;
192- backend.renderer(),342+ let elements = space_render_elements(backend.renderer(), [space], output, 1.).unwrap();
193- [&self.space],343+
194- self.output.as_ref().unwrap(),344+ let output_pos = self.global_space.output_geometry(output).unwrap().loc;
195- 1.,345+ let pointer_pos = self.seat.get_pointer().unwrap().current_location() - output_pos.to_f64();
196- )
197- .unwrap();
198 346
199 let mut elements: Vec<_> = elements347 let mut elements: Vec<_> = elements
200 .into_iter()348 .into_iter()
@@ -204,20 +352,16 @@ impl Niri {
204 0,352 0,
205 OutputRenderElements::Pointer(SolidColorRenderElement::from_buffer(353 OutputRenderElements::Pointer(SolidColorRenderElement::from_buffer(
206 &self.pointer_buffer,354 &self.pointer_buffer,
207- self.seat355+ pointer_pos.to_physical_precise_round(1.),
208- .get_pointer()
209- .unwrap()
210- .current_location()
211- .to_physical_precise_round(1.),
212 1.,356 1.,
213 1.,357 1.,
214 )),358 )),
215 );359 );
216 360
217- backend.render(self, &elements);361+ backend.render(self, output, &elements);
218 362
219- let output = self.output.as_ref().unwrap();363+ let space = &self.monitor_set.workspace_for_output(output).unwrap().space;
220- self.space.elements().for_each(|window| {364+ space.elements().for_each(|window| {
221 window.send_frame(365 window.send_frame(
222 output,366 output,
223 self.start_time.elapsed(),367 self.start_time.elapsed(),
@@ -234,6 +378,23 @@ render_elements! {
234 Pointer = SolidColorRenderElement,378 Pointer = SolidColorRenderElement,
235 }379 }
236 380
381+impl<R: ImportAll, E: RenderElement<R>> std::fmt::Debug for OutputRenderElements<R, E> {
382+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
383+ match self {
384+ OutputRenderElements::Space(_) => {
385+ f.debug_tuple("OutputRenderElements::Space").finish()?
386+ }
387+ OutputRenderElements::Pointer(element) => f
388+ .debug_tuple("OutputRenderElements::Pointer")
389+ .field(element)
390+ .finish()?,
391+ _ => (),
392+ }
393+
394+ Ok(())
395+ }
396+}
397+
237 #[derive(Default)]398 #[derive(Default)]
238 pub struct ClientState {399 pub struct ClientState {
239 pub compositor_state: CompositorClientState,400 pub compositor_state: CompositorClientState,
src/tty.rsmodified+165 -148
@@ -1,10 +1,11 @@
1+use std::collections::{HashMap, HashSet};
1 use std::os::fd::FromRawFd;2 use std::os::fd::FromRawFd;
2-use std::path::PathBuf;3+use std::path::{Path, PathBuf};
3 4
4 use anyhow::anyhow;5 use anyhow::anyhow;
5 use smithay::backend::allocator::dmabuf::Dmabuf;6 use smithay::backend::allocator::dmabuf::Dmabuf;
6 use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};7 use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};
7-use smithay::backend::allocator::Fourcc;8+use smithay::backend::allocator::{Format as DrmFormat, Fourcc};
8 use smithay::backend::drm::compositor::DrmCompositor;9 use smithay::backend::drm::compositor::DrmCompositor;
9 use smithay::backend::drm::{DrmDevice, DrmDeviceFd, DrmEvent};10 use smithay::backend::drm::{DrmDevice, DrmDeviceFd, DrmEvent};
10 use smithay::backend::egl::{EGLContext, EGLDisplay};11 use smithay::backend::egl::{EGLContext, EGLDisplay};
@@ -17,14 +18,12 @@ use smithay::backend::session::{Event as SessionEvent, Session};
17 use smithay::backend::udev::{self, UdevBackend, UdevEvent};18 use smithay::backend::udev::{self, UdevBackend, UdevEvent};
18 use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties, Subpixel};19 use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties, Subpixel};
19 use smithay::reexports::calloop::{LoopHandle, RegistrationToken};20 use smithay::reexports::calloop::{LoopHandle, RegistrationToken};
20-use smithay::reexports::drm::control::connector::{21+use smithay::reexports::drm::control::{connector, crtc, ModeTypeFlags};
21- Interface as ConnectorInterface, State as ConnectorState,
22-};
23-use smithay::reexports::drm::control::{Device, ModeTypeFlags};
24 use smithay::reexports::input::Libinput;22 use smithay::reexports::input::Libinput;
25 use smithay::reexports::nix::fcntl::OFlag;23 use smithay::reexports::nix::fcntl::OFlag;
26 use smithay::reexports::nix::libc::dev_t;24 use smithay::reexports::nix::libc::dev_t;
27 use smithay::utils::DeviceFd;25 use smithay::utils::DeviceFd;
26+use smithay_drm_extras::drm_scanner::{DrmScanEvent, DrmScanner};
28 use smithay_drm_extras::edid::EdidInfo;27 use smithay_drm_extras::edid::EdidInfo;
29 28
30 use crate::backend::Backend;29 use crate::backend::Backend;
@@ -46,11 +45,19 @@ type GbmDrmCompositor =
46 45
47 struct OutputDevice {46 struct OutputDevice {
48 id: dev_t,47 id: dev_t,
49- path: PathBuf,
50 token: RegistrationToken,48 token: RegistrationToken,
51 drm: DrmDevice,49 drm: DrmDevice,
50+ gbm: GbmDevice<DrmDeviceFd>,
52 gles: GlesRenderer,51 gles: GlesRenderer,
53- drm_compositor: GbmDrmCompositor,52+ formats: HashSet<DrmFormat>,
53+ drm_scanner: DrmScanner,
54+ surfaces: HashMap<crtc::Handle, GbmDrmCompositor>,
55+}
56+
57+#[derive(Debug, Clone, Copy)]
58+struct TtyOutputState {
59+ device_id: dev_t,
60+ crtc: crtc::Handle,
54 }61 }
55 62
56 impl Backend for Tty {63 impl Backend for Tty {
@@ -65,6 +72,7 @@ impl Backend for Tty {
65 fn render(72 fn render(
66 &mut self,73 &mut self,
67 niri: &mut Niri,74 niri: &mut Niri,
75+ output: &Output,
68 elements: &[OutputRenderElements<76 elements: &[OutputRenderElements<
69 GlesRenderer,77 GlesRenderer,
70 WaylandSurfaceRenderElement<GlesRenderer>,78 WaylandSurfaceRenderElement<GlesRenderer>,
@@ -72,19 +80,26 @@ impl Backend for Tty {
72 ) {80 ) {
73 let _span = tracy_client::span!("Tty::render");81 let _span = tracy_client::span!("Tty::render");
74 82
75- let output_device = self.output_device.as_mut().unwrap();83+ let device = self.output_device.as_mut().unwrap();
76- let drm_compositor = &mut output_device.drm_compositor;84+ let tty_state: &TtyOutputState = output.user_data().get().unwrap();
85+ let drm_compositor = device.surfaces.get_mut(&tty_state.crtc).unwrap();
77 86
78 match drm_compositor.render_frame::<_, _, GlesTexture>(87 match drm_compositor.render_frame::<_, _, GlesTexture>(
79- &mut output_device.gles,88+ &mut device.gles,
80 elements,89 elements,
81 BACKGROUND_COLOR,90 BACKGROUND_COLOR,
82 ) {91 ) {
83 Ok(res) => {92 Ok(res) => {
84 assert!(!res.needs_sync());93 assert!(!res.needs_sync());
94+ // debug!("{:?}", res);
85 if res.damage.is_some() {95 if res.damage.is_some() {
86- match output_device.drm_compositor.queue_frame(()) {96+ match drm_compositor.queue_frame(()) {
87- Ok(()) => niri.waiting_for_vblank = true,97+ Ok(()) => {
98+ niri.output_state
99+ .get_mut(output)
100+ .unwrap()
101+ .waiting_for_vblank = true
102+ }
88 Err(err) => {103 Err(err) => {
89 error!("error queueing frame: {err}");104 error!("error queueing frame: {err}");
90 }105 }
@@ -142,13 +157,15 @@ impl Tty {
142 if let Some(output_device) = &mut tty.output_device {157 if let Some(output_device) = &mut tty.output_device {
143 output_device.drm.activate();158 output_device.drm.activate();
144 159
145- if let Err(err) = output_device.drm_compositor.surface().reset_state() {160+ for drm_compositor in output_device.surfaces.values_mut() {
146- warn!("error resetting DRM surface state: {err}");161+ if let Err(err) = drm_compositor.surface().reset_state() {
162+ warn!("error resetting DRM surface state: {err}");
163+ }
164+ drm_compositor.reset_buffers();
147 }165 }
148- output_device.drm_compositor.reset_buffers();
149 }166 }
150 167
151- niri.queue_redraw();168+ niri.queue_redraw_all();
152 }169 }
153 }170 }
154 })171 })
@@ -166,7 +183,7 @@ impl Tty {
166 pub fn init(&mut self, niri: &mut Niri) {183 pub fn init(&mut self, niri: &mut Niri) {
167 let backend = UdevBackend::new(&self.session.seat()).unwrap();184 let backend = UdevBackend::new(&self.session.seat()).unwrap();
168 for (device_id, path) in backend.device_list() {185 for (device_id, path) in backend.device_list() {
169- if let Err(err) = self.device_added(device_id, path.to_owned(), niri) {186+ if let Err(err) = self.device_added(device_id, path, niri) {
170 warn!("error adding device: {err:?}");187 warn!("error adding device: {err:?}");
171 }188 }
172 }189 }
@@ -178,24 +195,21 @@ impl Tty {
178 195
179 match event {196 match event {
180 UdevEvent::Added { device_id, path } => {197 UdevEvent::Added { device_id, path } => {
181- if let Err(err) = tty.device_added(device_id, path, niri) {198+ if let Err(err) = tty.device_added(device_id, &path, niri) {
182 warn!("error adding device: {err:?}");199 warn!("error adding device: {err:?}");
183 }200 }
184- niri.queue_redraw();
185 }201 }
186 UdevEvent::Changed { device_id } => tty.device_changed(device_id, niri),202 UdevEvent::Changed { device_id } => tty.device_changed(device_id, niri),
187 UdevEvent::Removed { device_id } => tty.device_removed(device_id, niri),203 UdevEvent::Removed { device_id } => tty.device_removed(device_id, niri),
188 }204 }
189 })205 })
190 .unwrap();206 .unwrap();
191-
192- niri.queue_redraw();
193 }207 }
194 208
195 fn device_added(209 fn device_added(
196 &mut self,210 &mut self,
197 device_id: dev_t,211 device_id: dev_t,
198- path: PathBuf,212+ path: &Path,
199 niri: &mut Niri,213 niri: &mut Niri,
200 ) -> anyhow::Result<()> {214 ) -> anyhow::Result<()> {
201 if path != self.primary_gpu_path {215 if path != self.primary_gpu_path {
@@ -207,7 +221,7 @@ impl Tty {
207 assert!(self.output_device.is_none());221 assert!(self.output_device.is_none());
208 222
209 let open_flags = OFlag::O_RDWR | OFlag::O_CLOEXEC | OFlag::O_NOCTTY | OFlag::O_NONBLOCK;223 let open_flags = OFlag::O_RDWR | OFlag::O_CLOEXEC | OFlag::O_NOCTTY | OFlag::O_NONBLOCK;
210- let fd = self.session.open(&path, open_flags)?;224+ let fd = self.session.open(path, open_flags)?;
211 let device_fd = unsafe { DrmDeviceFd::new(DeviceFd::from_raw_fd(fd)) };225 let device_fd = unsafe { DrmDeviceFd::new(DeviceFd::from_raw_fd(fd)) };
212 226
213 let (drm, drm_notifier) = DrmDevice::new(device_fd.clone(), true)?;227 let (drm, drm_notifier) = DrmDevice::new(device_fd.clone(), true)?;
@@ -219,23 +233,22 @@ impl Tty {
219 let mut gles = unsafe { GlesRenderer::new(egl_context)? };233 let mut gles = unsafe { GlesRenderer::new(egl_context)? };
220 gles.bind_wl_display(&niri.display_handle)?;234 gles.bind_wl_display(&niri.display_handle)?;
221 235
222- let drm_compositor = self.create_drm_compositor(&drm, &gbm, &gles, niri)?;
223-
224 let token = niri236 let token = niri
225 .event_loop237 .event_loop
226 .insert_source(drm_notifier, move |event, metadata, data| {238 .insert_source(drm_notifier, move |event, metadata, data| {
227 let tty = data.tty.as_mut().unwrap();239 let tty = data.tty.as_mut().unwrap();
228 match event {240 match event {
229- DrmEvent::VBlank(_crtc) => {241+ DrmEvent::VBlank(crtc) => {
230 tracy_client::Client::running()242 tracy_client::Client::running()
231 .unwrap()243 .unwrap()
232 .message("vblank", 0);244 .message("vblank", 0);
233 trace!("vblank {metadata:?}");245 trace!("vblank {metadata:?}");
234 246
235- let output_device = tty.output_device.as_mut().unwrap();247+ let device = tty.output_device.as_mut().unwrap();
248+ let drm_compositor = device.surfaces.get_mut(&crtc).unwrap();
236 249
237 // Mark the last frame as submitted.250 // Mark the last frame as submitted.
238- if let Err(err) = output_device.drm_compositor.frame_submitted() {251+ if let Err(err) = drm_compositor.frame_submitted() {
239 error!("error marking frame as submitted: {err}");252 error!("error marking frame as submitted: {err}");
240 }253 }
241 254
@@ -244,103 +257,111 @@ impl Tty {
244 // .windows257 // .windows
245 // .mark_presented(&output_device.last_render_states, metadata);258 // .mark_presented(&output_device.last_render_states, metadata);
246 259
247- data.niri.waiting_for_vblank = false;260+ let output = data
248- data.niri.queue_redraw();261+ .niri
262+ .global_space
263+ .outputs()
264+ .find(|output| {
265+ let tty_state: &TtyOutputState = output.user_data().get().unwrap();
266+ tty_state.device_id == device.id && tty_state.crtc == crtc
267+ })
268+ .unwrap()
269+ .clone();
270+ data.niri
271+ .output_state
272+ .get_mut(&output)
273+ .unwrap()
274+ .waiting_for_vblank = false;
275+ data.niri.queue_redraw(output);
249 }276 }
250 DrmEvent::Error(error) => error!("DRM error: {error}"),277 DrmEvent::Error(error) => error!("DRM error: {error}"),
251 };278 };
252 })279 })
253 .unwrap();280 .unwrap();
254 281
282+ let formats = Bind::<Dmabuf>::supported_formats(&gles).unwrap_or_default();
283+
255 self.output_device = Some(OutputDevice {284 self.output_device = Some(OutputDevice {
256 id: device_id,285 id: device_id,
257- path,
258 token,286 token,
259 drm,287 drm,
288+ gbm,
260 gles,289 gles,
261- drm_compositor,290+ formats,
291+ drm_scanner: DrmScanner::new(),
292+ surfaces: HashMap::new(),
262 });293 });
263 294
295+ self.device_changed(device_id, niri);
296+
264 Ok(())297 Ok(())
265 }298 }
266 299
267 fn device_changed(&mut self, device_id: dev_t, niri: &mut Niri) {300 fn device_changed(&mut self, device_id: dev_t, niri: &mut Niri) {
268- if let Some(output_device) = &self.output_device {301+ let Some(device) = &mut self.output_device else {
269- if output_device.id == device_id {302+ return;
270- debug!("output device changed");303+ };
271-304+ if device.id != device_id {
272- let path = output_device.path.clone();305+ return;
273- self.device_removed(device_id, niri);306+ }
274- if let Err(err) = self.device_added(device_id, path, niri) {307+ debug!("output device changed");
275- warn!("error adding device: {err:?}");308+
309+ for event in device.drm_scanner.scan_connectors(&device.drm) {
310+ match event {
311+ DrmScanEvent::Connected {
312+ connector,
313+ crtc: Some(crtc),
314+ } => {
315+ if let Err(err) = self.connector_connected(niri, connector, crtc) {
316+ warn!("error connecting connector: {err:?}");
317+ }
276 }318 }
319+ DrmScanEvent::Disconnected {
320+ connector,
321+ crtc: Some(crtc),
322+ } => self.connector_disconnected(niri, connector, crtc),
323+ _ => (),
277 }324 }
278 }325 }
279 }326 }
280 327
281 fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) {328 fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) {
282- if let Some(mut output_device) = self.output_device.take() {329+ let Some(device) = self.output_device.take() else {
283- if output_device.id != device_id {330+ return;
284- self.output_device = Some(output_device);331+ };
285- return;332+ if device.id != device_id {
286- }333+ // It wasn't the output device, put it back in.
334+ self.output_device = Some(device);
335+ return;
336+ }
337+
338+ let crtcs: Vec<_> = device
339+ .drm_scanner
340+ .crtcs()
341+ .map(|(info, crtc)| (info.clone(), crtc))
342+ .collect();
287 343
288- // FIXME: remove wl_output.344+ for (connector, crtc) in crtcs {
289- niri.event_loop.remove(output_device.token);345+ self.connector_disconnected(niri, connector, crtc);
290- niri.output = None;
291- output_device.gles.unbind_wl_display();
292 }346 }
347+
348+ niri.event_loop.remove(device.token);
293 }349 }
294 350
295- fn create_drm_compositor(351+ fn connector_connected(
296 &mut self,352 &mut self,
297- drm: &DrmDevice,
298- gbm: &GbmDevice<DrmDeviceFd>,
299- gles: &GlesRenderer,
300 niri: &mut Niri,353 niri: &mut Niri,
301- ) -> anyhow::Result<GbmDrmCompositor> {354+ connector: connector::Info,
302- let formats = Bind::<Dmabuf>::supported_formats(gles)355+ crtc: crtc::Handle,
303- .ok_or_else(|| anyhow!("no supported formats"))?;356+ ) -> anyhow::Result<()> {
304- let resources = drm.resource_handles()?;357+ let output_name = format!(
305-358+ "{}-{}",
306- let mut connector = None;
307- let mut edp_connector = None;
308- resources
309- .connectors()
310- .iter()
311- .filter_map(|conn| match drm.get_connector(*conn, true) {
312- Ok(info) => Some(info),
313- Err(err) => {
314- warn!("error probing connector: {err}");
315- None
316- }
317- })
318- .inspect(|conn| {
319- debug!(
320- "connector: {}-{}, {:?}, {} modes",
321- conn.interface().as_str(),
322- conn.interface_id(),
323- conn.state(),
324- conn.modes().len(),
325- );
326- })
327- .filter(|conn| conn.state() == ConnectorState::Connected)
328- .for_each(|conn| {
329- connector = Some(conn.clone());
330-
331- if conn.interface() == ConnectorInterface::EmbeddedDisplayPort {
332- edp_connector = Some(conn);
333- }
334- });
335- // Since we're only using one output at the moment, prefer eDP.
336- let connector = edp_connector
337- .or(connector)
338- .ok_or_else(|| anyhow!("no compatible connector"))?;
339- info!(
340- "picking connector: {}-{}",
341 connector.interface().as_str(),359 connector.interface().as_str(),
342 connector.interface_id(),360 connector.interface_id(),
343 );361 );
362+ debug!("connecting connector: {output_name}");
363+
364+ let device = self.output_device.as_mut().unwrap();
344 365
345 let mut mode = connector.modes().get(0);366 let mut mode = connector.modes().get(0);
346 connector.modes().iter().for_each(|m| {367 connector.modes().iter().for_each(|m| {
@@ -357,57 +378,20 @@ impl Tty {
357 }378 }
358 });379 });
359 let mode = mode.ok_or_else(|| anyhow!("no mode"))?;380 let mode = mode.ok_or_else(|| anyhow!("no mode"))?;
360- info!("picking mode: {mode:?}");381+ debug!("picking mode: {mode:?}");
361-
362- let surface = connector
363- .encoders()
364- .iter()
365- .filter_map(|enc| match drm.get_encoder(*enc) {
366- Ok(info) => Some(info),
367- Err(err) => {
368- warn!("error probing encoder: {err}");
369- None
370- }
371- })
372- .flat_map(|enc| {
373- // Get all CRTCs compatible with the encoder.
374- let mut crtcs = resources.filter_crtcs(enc.possible_crtcs());
375-
376- // Sort by maximum number of overlay planes.
377- crtcs.sort_by_cached_key(|crtc| match drm.planes(crtc) {
378- Ok(planes) => -(planes.overlay.len() as isize),
379- Err(err) => {
380- warn!("error probing planes for CRTC: {err}");
381- 0
382- }
383- });
384 382
385- crtcs383+ let surface = device
386- })384+ .drm
387- .find_map(385+ .create_surface(crtc, *mode, &[connector.handle()])?;
388- |crtc| match drm.create_surface(crtc, *mode, &[connector.handle()]) {
389- Ok(surface) => Some(surface),
390- Err(err) => {
391- warn!("error creating DRM surface: {err}");
392- None
393- }
394- },
395- );
396- let surface = surface.ok_or_else(|| anyhow!("no surface"))?;
397 386
398 // Create GBM allocator.387 // Create GBM allocator.
399 let gbm_flags = GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT;388 let gbm_flags = GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT;
400- let allocator = GbmAllocator::new(gbm.clone(), gbm_flags);389+ let allocator = GbmAllocator::new(device.gbm.clone(), gbm_flags);
401 390
402 // Update the output mode.391 // Update the output mode.
403 let (physical_width, physical_height) = connector.size().unwrap_or((0, 0));392 let (physical_width, physical_height) = connector.size().unwrap_or((0, 0));
404- let output_name = format!(
405- "{}-{}",
406- connector.interface().as_str(),
407- connector.interface_id(),
408- );
409 393
410- let (make, model) = EdidInfo::for_connector(drm, connector.handle())394+ let (make, model) = EdidInfo::for_connector(&device.drm, connector.handle())
411 .map(|info| (info.manufacturer, info.model))395 .map(|info| (info.manufacturer, info.model))
412 .unwrap_or_else(|| ("Unknown".into(), "Unknown".into()));396 .unwrap_or_else(|| ("Unknown".into(), "Unknown".into()));
413 397
@@ -424,25 +408,58 @@ impl Tty {
424 output.change_current_state(Some(wl_mode), None, None, Some((0, 0).into()));408 output.change_current_state(Some(wl_mode), None, None, Some((0, 0).into()));
425 output.set_preferred(wl_mode);409 output.set_preferred(wl_mode);
426 410
427- // FIXME: store this somewhere to remove on disconnect, etc.411+ output.user_data().insert_if_missing(|| TtyOutputState {
428- let _global = output.create_global::<Niri>(&niri.display_handle);412+ device_id: device.id,
429- niri.space.map_output(&output, (0, 0));413+ crtc,
430- niri.output = Some(output.clone());414+ });
431- // windows.set_output();
432 415
433 // Create the compositor.416 // Create the compositor.
434 let compositor = DrmCompositor::new(417 let compositor = DrmCompositor::new(
435- OutputModeSource::Auto(output),418+ OutputModeSource::Auto(output.clone()),
436 surface,419 surface,
437 None,420 None,
438 allocator,421 allocator,
439- gbm.clone(),422+ device.gbm.clone(),
440 SUPPORTED_COLOR_FORMATS,423 SUPPORTED_COLOR_FORMATS,
441- formats,424+ device.formats.clone(),
442- drm.cursor_size(),425+ device.drm.cursor_size(),
443- Some(gbm.clone()),426+ Some(device.gbm.clone()),
444 )?;427 )?;
445- Ok(compositor)428+
429+ let res = device.surfaces.insert(crtc, compositor);
430+ assert!(res.is_none(), "crtc must not have already existed");
431+
432+ niri.add_output(output.clone());
433+ niri.queue_redraw(output);
434+
435+ Ok(())
436+ }
437+
438+ fn connector_disconnected(
439+ &mut self,
440+ niri: &mut Niri,
441+ connector: connector::Info,
442+ crtc: crtc::Handle,
443+ ) {
444+ debug!("disconnecting connector: {connector:?}");
445+ let device = self.output_device.as_mut().unwrap();
446+
447+ if device.surfaces.remove(&crtc).is_none() {
448+ debug!("crts wasn't enabled");
449+ return;
450+ }
451+
452+ let output = niri
453+ .global_space
454+ .outputs()
455+ .find(|output| {
456+ let tty_state: &TtyOutputState = output.user_data().get().unwrap();
457+ tty_state.device_id == device.id && tty_state.crtc == crtc
458+ })
459+ .unwrap()
460+ .clone();
461+
462+ niri.remove_output(&output);
446 }463 }
447 464
448 fn change_vt(&mut self, vt: i32) {465 fn change_vt(&mut self, vt: i32) {
src/winit.rsmodified+13 -6
@@ -8,6 +8,8 @@ use smithay::backend::winit::{self, WinitError, WinitEvent, WinitEventLoop, Wini
8 use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};8 use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};
9 use smithay::reexports::calloop::timer::{TimeoutAction, Timer};9 use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
10 use smithay::reexports::calloop::LoopHandle;10 use smithay::reexports::calloop::LoopHandle;
11+use smithay::reexports::winit::dpi::LogicalSize;
12+use smithay::reexports::winit::window::WindowBuilder;
11 use smithay::utils::{Rectangle, Transform};13 use smithay::utils::{Rectangle, Transform};
12 14
13 use crate::backend::Backend;15 use crate::backend::Backend;
@@ -34,6 +36,7 @@ impl Backend for Winit {
34 fn render(36 fn render(
35 &mut self,37 &mut self,
36 _niri: &mut Niri,38 _niri: &mut Niri,
39+ _output: &Output,
37 elements: &[OutputRenderElements<40 elements: &[OutputRenderElements<
38 GlesRenderer,41 GlesRenderer,
39 WaylandSurfaceRenderElement<GlesRenderer>,42 WaylandSurfaceRenderElement<GlesRenderer>,
@@ -54,7 +57,11 @@ impl Backend for Winit {
54 57
55 impl Winit {58 impl Winit {
56 pub fn new(event_loop: LoopHandle<LoopData>) -> Self {59 pub fn new(event_loop: LoopHandle<LoopData>) -> Self {
57- let (backend, winit_event_loop) = winit::init().unwrap();60+ let builder = WindowBuilder::new()
61+ .with_inner_size(LogicalSize::new(1280.0, 800.0))
62+ // .with_resizable(false)
63+ .with_title("niri");
64+ let (backend, winit_event_loop) = winit::init_from_builder(builder).unwrap();
58 65
59 let mode = Mode {66 let mode = Mode {
60 size: backend.window_size().physical_size,67 size: backend.window_size().physical_size,
@@ -98,9 +105,6 @@ impl Winit {
98 }105 }
99 106
100 pub fn init(&mut self, niri: &mut Niri) {107 pub fn init(&mut self, niri: &mut Niri) {
101- let _global = self.output.create_global::<Niri>(&niri.display_handle);
102- niri.space.map_output(&self.output, (0, 0));
103- niri.output = Some(self.output.clone());
104 if let Err(err) = self108 if let Err(err) = self
105 .backend109 .backend
106 .renderer()110 .renderer()
@@ -108,6 +112,7 @@ impl Winit {
108 {112 {
109 warn!("error binding renderer wl_display: {err}");113 warn!("error binding renderer wl_display: {err}");
110 }114 }
115+ niri.add_output(self.output.clone());
111 }116 }
112 117
113 fn dispatch(&mut self, niri: &mut Niri) {118 fn dispatch(&mut self, niri: &mut Niri) {
@@ -115,7 +120,7 @@ impl Winit {
115 .winit_event_loop120 .winit_event_loop
116 .dispatch_new_events(|event| match event {121 .dispatch_new_events(|event| match event {
117 WinitEvent::Resized { size, .. } => {122 WinitEvent::Resized { size, .. } => {
118- niri.output.as_ref().unwrap().change_current_state(123+ self.output.change_current_state(
119 Some(Mode {124 Some(Mode {
120 size,125 size,
121 refresh: 60_000,126 refresh: 60_000,
@@ -124,12 +129,13 @@ impl Winit {
124 None,129 None,
125 None,130 None,
126 );131 );
132+ niri.output_resized(self.output.clone());
127 }133 }
128 WinitEvent::Input(event) => {134 WinitEvent::Input(event) => {
129 niri.process_input_event(&mut |_| (), CompositorMod::Alt, event)135 niri.process_input_event(&mut |_| (), CompositorMod::Alt, event)
130 }136 }
131 WinitEvent::Focus(_) => (),137 WinitEvent::Focus(_) => (),
132- WinitEvent::Refresh => niri.queue_redraw(),138+ WinitEvent::Refresh => niri.queue_redraw(self.output.clone()),
133 });139 });
134 140
135 // I want this to stop compiling if more errors are added.141 // I want this to stop compiling if more errors are added.
@@ -137,6 +143,7 @@ impl Winit {
137 match res {143 match res {
138 Err(WinitError::WindowClosed) => {144 Err(WinitError::WindowClosed) => {
139 niri.stop_signal.stop();145 niri.stop_signal.stop();
146+ niri.remove_output(&self.output);
140 }147 }
141 Ok(()) => (),148 Ok(()) => (),
142 }149 }