forge
Explore
Log in

Don't you dare go Hollow

Implement resize transactions

Browse files at this commit

7bfdf87bf0138d602888fc3167921bc1d029b0abIvan MolodetskikhParent: cf357d7
niri-config/src/lib.rsmodified+2 -0
@@ -1370,6 +1370,8 @@ pub struct DebugConfig {
1370 pub emulate_zero_presentation_time: bool,1370 pub emulate_zero_presentation_time: bool,
1371 #[knuffel(child)]1371 #[knuffel(child)]
1372 pub disable_resize_throttling: bool,1372 pub disable_resize_throttling: bool,
1373+ #[knuffel(child)]
1374+ pub disable_transactions: bool,
1373 }1375 }
1374 1376
1375 #[derive(knuffel::DecodeScalar, Debug, Clone, Copy, PartialEq, Eq)]1377 #[derive(knuffel::DecodeScalar, Debug, Clone, Copy, PartialEq, Eq)]
niri-visual-tests/src/cases/layout.rsmodified+2 -2
@@ -147,7 +147,7 @@ impl Layout {
147 147
148 fn add_window(&mut self, mut window: TestWindow, width: Option<ColumnWidth>) {148 fn add_window(&mut self, mut window: TestWindow, width: Option<ColumnWidth>) {
149 let ws = self.layout.active_workspace().unwrap();149 let ws = self.layout.active_workspace().unwrap();
150- window.request_size(ws.new_window_size(width, window.rules()), false);150+ window.request_size(ws.new_window_size(width, window.rules()), false, None);
151 window.communicate();151 window.communicate();
152 152
153 self.layout.add_window(window.clone(), width, false);153 self.layout.add_window(window.clone(), width, false);
@@ -161,7 +161,7 @@ impl Layout {
161 width: Option<ColumnWidth>,161 width: Option<ColumnWidth>,
162 ) {162 ) {
163 let ws = self.layout.active_workspace().unwrap();163 let ws = self.layout.active_workspace().unwrap();
164- window.request_size(ws.new_window_size(width, window.rules()), false);164+ window.request_size(ws.new_window_size(width, window.rules()), false, None);
165 window.communicate();165 window.communicate();
166 166
167 self.layout167 self.layout
niri-visual-tests/src/cases/tile.rsmodified+4 -4
@@ -20,7 +20,7 @@ impl Tile {
20 pub fn freeform(size: Size<i32, Logical>) -> Self {20 pub fn freeform(size: Size<i32, Logical>) -> Self {
21 let window = TestWindow::freeform(0);21 let window = TestWindow::freeform(0);
22 let mut rv = Self::with_window(window);22 let mut rv = Self::with_window(window);
23- rv.tile.request_tile_size(size.to_f64(), false);23+ rv.tile.request_tile_size(size.to_f64(), false, None);
24 rv.window.communicate();24 rv.window.communicate();
25 rv25 rv
26 }26 }
@@ -28,7 +28,7 @@ impl Tile {
28 pub fn fixed_size(size: Size<i32, Logical>) -> Self {28 pub fn fixed_size(size: Size<i32, Logical>) -> Self {
29 let window = TestWindow::fixed_size(0);29 let window = TestWindow::fixed_size(0);
30 let mut rv = Self::with_window(window);30 let mut rv = Self::with_window(window);
31- rv.tile.request_tile_size(size.to_f64(), false);31+ rv.tile.request_tile_size(size.to_f64(), false, None);
32 rv.window.communicate();32 rv.window.communicate();
33 rv33 rv
34 }34 }
@@ -37,7 +37,7 @@ impl Tile {
37 let window = TestWindow::fixed_size(0);37 let window = TestWindow::fixed_size(0);
38 window.set_csd_shadow_width(64);38 window.set_csd_shadow_width(64);
39 let mut rv = Self::with_window(window);39 let mut rv = Self::with_window(window);
40- rv.tile.request_tile_size(size.to_f64(), false);40+ rv.tile.request_tile_size(size.to_f64(), false, None);
41 rv.window.communicate();41 rv.window.communicate();
42 rv42 rv
43 }43 }
@@ -85,7 +85,7 @@ impl Tile {
85 impl TestCase for Tile {85 impl TestCase for Tile {
86 fn resize(&mut self, width: i32, height: i32) {86 fn resize(&mut self, width: i32, height: i32) {
87 self.tile87 self.tile
88- .request_tile_size(Size::from((width, height)).to_f64(), false);88+ .request_tile_size(Size::from((width, height)).to_f64(), false, None);
89 self.window.communicate();89 self.window.communicate();
90 }90 }
91 91
niri-visual-tests/src/cases/window.rsmodified+5 -4
@@ -14,14 +14,14 @@ pub struct Window {
14 impl Window {14 impl Window {
15 pub fn freeform(size: Size<i32, Logical>) -> Self {15 pub fn freeform(size: Size<i32, Logical>) -> Self {
16 let mut window = TestWindow::freeform(0);16 let mut window = TestWindow::freeform(0);
17- window.request_size(size, false);17+ window.request_size(size, false, None);
18 window.communicate();18 window.communicate();
19 Self { window }19 Self { window }
20 }20 }
21 21
22 pub fn fixed_size(size: Size<i32, Logical>) -> Self {22 pub fn fixed_size(size: Size<i32, Logical>) -> Self {
23 let mut window = TestWindow::fixed_size(0);23 let mut window = TestWindow::fixed_size(0);
24- window.request_size(size, false);24+ window.request_size(size, false, None);
25 window.communicate();25 window.communicate();
26 Self { window }26 Self { window }
27 }27 }
@@ -29,7 +29,7 @@ impl Window {
29 pub fn fixed_size_with_csd_shadow(size: Size<i32, Logical>) -> Self {29 pub fn fixed_size_with_csd_shadow(size: Size<i32, Logical>) -> Self {
30 let mut window = TestWindow::fixed_size(0);30 let mut window = TestWindow::fixed_size(0);
31 window.set_csd_shadow_width(64);31 window.set_csd_shadow_width(64);
32- window.request_size(size, false);32+ window.request_size(size, false, None);
33 window.communicate();33 window.communicate();
34 Self { window }34 Self { window }
35 }35 }
@@ -37,7 +37,8 @@ impl Window {
37 37
38 impl TestCase for Window {38 impl TestCase for Window {
39 fn resize(&mut self, width: i32, height: i32) {39 fn resize(&mut self, width: i32, height: i32) {
40- self.window.request_size(Size::from((width, height)), false);40+ self.window
41+ .request_size(Size::from((width, height)), false, None);
41 self.window.communicate();42 self.window.communicate();
42 }43 }
43 44
niri-visual-tests/src/test_window.rsmodified+7 -1
@@ -9,6 +9,7 @@ use niri::layout::{
9 use niri::render_helpers::renderer::NiriRenderer;9 use niri::render_helpers::renderer::NiriRenderer;
10 use niri::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};10 use niri::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
11 use niri::render_helpers::{RenderTarget, SplitElements};11 use niri::render_helpers::{RenderTarget, SplitElements};
12+use niri::utils::transaction::Transaction;
12 use niri::window::ResolvedWindowRules;13 use niri::window::ResolvedWindowRules;
13 use smithay::backend::renderer::element::{Id, Kind};14 use smithay::backend::renderer::element::{Id, Kind};
14 use smithay::output::{self, Output};15 use smithay::output::{self, Output};
@@ -177,7 +178,12 @@ impl LayoutElement for TestWindow {
177 }178 }
178 }179 }
179 180
180- fn request_size(&mut self, size: Size<i32, Logical>, _animate: bool) {181+ fn request_size(
182+ &mut self,
183+ size: Size<i32, Logical>,
184+ _animate: bool,
185+ _transaction: Option<Transaction>,
186+ ) {
181 self.inner.borrow_mut().requested_size = Some(size);187 self.inner.borrow_mut().requested_size = Some(size);
182 self.inner.borrow_mut().pending_fullscreen = false;188 self.inner.borrow_mut().pending_fullscreen = false;
183 }189 }
src/handlers/compositor.rsmodified+1 -0
@@ -52,6 +52,7 @@ impl CompositorHandler for State {
52 52
53 fn commit(&mut self, surface: &WlSurface) {53 fn commit(&mut self, surface: &WlSurface) {
54 let _span = tracy_client::span!("CompositorHandler::commit");54 let _span = tracy_client::span!("CompositorHandler::commit");
55+ trace!(surface = ?surface.id(), "commit");
55 56
56 on_commit_buffer_handler::<Self>(surface);57 on_commit_buffer_handler::<Self>(surface);
57 self.backend.early_import(surface);58 self.backend.early_import(surface);
src/handlers/xdg_shell.rsmodified+52 -7
@@ -34,6 +34,7 @@ use smithay::wayland::xdg_foreign::{XdgForeignHandler, XdgForeignState};
34 use smithay::{34 use smithay::{
35 delegate_kde_decoration, delegate_xdg_decoration, delegate_xdg_foreign, delegate_xdg_shell,35 delegate_kde_decoration, delegate_xdg_decoration, delegate_xdg_foreign, delegate_xdg_shell,
36 };36 };
37+use tracing::field::Empty;
37 38
38 use crate::input::resize_grab::ResizeGrab;39 use crate::input::resize_grab::ResizeGrab;
39 use crate::input::DOUBLE_CLICK_TIME;40 use crate::input::DOUBLE_CLICK_TIME;
@@ -1003,6 +1004,8 @@ fn unconstrain_with_padding(
1003 pub fn add_mapped_toplevel_pre_commit_hook(toplevel: &ToplevelSurface) -> HookId {1004 pub fn add_mapped_toplevel_pre_commit_hook(toplevel: &ToplevelSurface) -> HookId {
1004 add_pre_commit_hook::<State, _>(toplevel.wl_surface(), move |state, _dh, surface| {1005 add_pre_commit_hook::<State, _>(toplevel.wl_surface(), move |state, _dh, surface| {
1005 let _span = tracy_client::span!("mapped toplevel pre-commit");1006 let _span = tracy_client::span!("mapped toplevel pre-commit");
1007+ let span =
1008+ trace_span!("toplevel pre-commit", surface = %surface.id(), serial = Empty).entered();
1006 1009
1007 let Some((mapped, _)) = state.niri.layout.find_window_and_output_mut(surface) else {1010 let Some((mapped, _)) = state.niri.layout.find_window_and_output_mut(surface) else {
1008 error!("pre-commit hook for mapped surfaces must be removed upon unmapping");1011 error!("pre-commit hook for mapped surfaces must be removed upon unmapping");
@@ -1032,31 +1035,73 @@ pub fn add_mapped_toplevel_pre_commit_hook(toplevel: &ToplevelSurface) -> HookId
1032 (got_unmapped, dmabuf, role.configure_serial)1035 (got_unmapped, dmabuf, role.configure_serial)
1033 });1036 });
1034 1037
1035- let mut dmabuf_blocker =1038+ let mut transaction_for_dmabuf = None;
1036- dmabuf.and_then(|dmabuf| dmabuf.generate_blocker(Interest::READ).ok());1039+ let mut animate = false;
1040+ if let Some(serial) = commit_serial {
1041+ if !span.is_disabled() {
1042+ span.record("serial", format!("{serial:?}"));
1043+ }
1044+
1045+ trace!("taking pending transaction");
1046+ if let Some(transaction) = mapped.take_pending_transaction(serial) {
1047+ // Transaction can be already completed if it ran past the deadline.
1048+ let disable = state.niri.config.borrow().debug.disable_transactions;
1049+ if !transaction.is_completed() && !disable {
1050+ // Register the deadline even if this is the last pending, since dmabuf
1051+ // rendering can still run over the deadline.
1052+ transaction.register_deadline_timer(&state.niri.event_loop);
1053+
1054+ let is_last = transaction.is_last();
1055+
1056+ // If this is the last transaction, we don't need to add a separate
1057+ // notification, because the transaction will complete in our dmabuf blocker
1058+ // callback, which already calls blocker_cleared(), or by the end of this
1059+ // function, in which case there would be no blocker in the first place.
1060+ if !is_last {
1061+ // Waiting for some other surface; register a notification and add a
1062+ // transaction blocker.
1063+ if let Some(client) = surface.client() {
1064+ transaction.add_notification(
1065+ state.niri.blocker_cleared_tx.clone(),
1066+ client.clone(),
1067+ );
1068+ add_blocker(surface, transaction.blocker());
1069+ }
1070+ }
1071+
1072+ // Delay dropping (and completing) the transaction until the dmabuf is ready.
1073+ // If there's no dmabuf, this will be dropped by the end of this pre-commit
1074+ // hook.
1075+ transaction_for_dmabuf = Some(transaction);
1076+ }
1077+ }
1037 1078
1038- let animate = if let Some(serial) = commit_serial {1079+ animate = mapped.should_animate_commit(serial);
1039- mapped.should_animate_commit(serial)
1040 } else {1080 } else {
1041 error!("commit on a mapped surface without a configured serial");1081 error!("commit on a mapped surface without a configured serial");
1042- false
1043 };1082 };
1044 1083
1045- if let Some((blocker, source)) = dmabuf_blocker.take() {1084+ if let Some((blocker, source)) =
1085+ dmabuf.and_then(|dmabuf| dmabuf.generate_blocker(Interest::READ).ok())
1086+ {
1046 if let Some(client) = surface.client() {1087 if let Some(client) = surface.client() {
1047 let res = state1088 let res = state
1048 .niri1089 .niri
1049 .event_loop1090 .event_loop
1050 .insert_source(source, move |_, _, state| {1091 .insert_source(source, move |_, _, state| {
1092+ // This surface is now ready for the transaction.
1093+ drop(transaction_for_dmabuf.take());
1094+
1051 let display_handle = state.niri.display_handle.clone();1095 let display_handle = state.niri.display_handle.clone();
1052 state1096 state
1053 .client_compositor_state(&client)1097 .client_compositor_state(&client)
1054 .blocker_cleared(state, &display_handle);1098 .blocker_cleared(state, &display_handle);
1099+
1055 Ok(())1100 Ok(())
1056 });1101 });
1057 if res.is_ok() {1102 if res.is_ok() {
1058 add_blocker(surface, blocker);1103 add_blocker(surface, blocker);
1059- trace!("added toplevel dmabuf blocker");1104+ trace!("added dmabuf blocker");
1060 }1105 }
1061 }1106 }
1062 }1107 }
src/layout/mod.rsmodified+16 -2
@@ -52,6 +52,7 @@ use crate::render_helpers::snapshot::RenderSnapshot;
52 use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};52 use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
53 use crate::render_helpers::texture::TextureBuffer;53 use crate::render_helpers::texture::TextureBuffer;
54 use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};54 use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};
55+use crate::utils::transaction::Transaction;
55 use crate::utils::{output_size, round_logical_in_physical_max1, ResizeEdge};56 use crate::utils::{output_size, round_logical_in_physical_max1, ResizeEdge};
56 use crate::window::ResolvedWindowRules;57 use crate::window::ResolvedWindowRules;
57 58
@@ -153,7 +154,12 @@ pub trait LayoutElement {
153 self.render(renderer, location, scale, alpha, target).popups154 self.render(renderer, location, scale, alpha, target).popups
154 }155 }
155 156
156- fn request_size(&mut self, size: Size<i32, Logical>, animate: bool);157+ fn request_size(
158+ &mut self,
159+ size: Size<i32, Logical>,
160+ animate: bool,
161+ transaction: Option<Transaction>,
162+ );
157 fn request_fullscreen(&self, size: Size<i32, Logical>);163 fn request_fullscreen(&self, size: Size<i32, Logical>);
158 fn min_size(&self) -> Size<i32, Logical>;164 fn min_size(&self) -> Size<i32, Logical>;
159 fn max_size(&self) -> Size<i32, Logical>;165 fn max_size(&self) -> Size<i32, Logical>;
@@ -237,6 +243,7 @@ pub struct Options {
237 243
238 // Debug flags.244 // Debug flags.
239 pub disable_resize_throttling: bool,245 pub disable_resize_throttling: bool,
246+ pub disable_transactions: bool,
240 }247 }
241 248
242 impl Default for Options {249 impl Default for Options {
@@ -255,6 +262,7 @@ impl Default for Options {
255 default_width: None,262 default_width: None,
256 animations: Default::default(),263 animations: Default::default(),
257 disable_resize_throttling: false,264 disable_resize_throttling: false,
265+ disable_transactions: false,
258 }266 }
259 }267 }
260 }268 }
@@ -292,6 +300,7 @@ impl Options {
292 default_width,300 default_width,
293 animations: config.animations.clone(),301 animations: config.animations.clone(),
294 disable_resize_throttling: config.debug.disable_resize_throttling,302 disable_resize_throttling: config.debug.disable_resize_throttling,
303+ disable_transactions: config.debug.disable_transactions,
295 }304 }
296 }305 }
297 306
@@ -2636,7 +2645,12 @@ mod tests {
2636 SplitElements::default()2645 SplitElements::default()
2637 }2646 }
2638 2647
2639- fn request_size(&mut self, size: Size<i32, Logical>, _animate: bool) {2648+ fn request_size(
2649+ &mut self,
2650+ size: Size<i32, Logical>,
2651+ _animate: bool,
2652+ _transaction: Option<Transaction>,
2653+ ) {
2640 self.0.requested_size.set(Some(size));2654 self.0.requested_size.set(Some(size));
2641 self.0.pending_fullscreen.set(false);2655 self.0.pending_fullscreen.set(false);
2642 }2656 }
src/layout/tile.rsmodified+9 -2
@@ -23,6 +23,7 @@ use crate::render_helpers::resize::ResizeRenderElement;
23 use crate::render_helpers::snapshot::RenderSnapshot;23 use crate::render_helpers::snapshot::RenderSnapshot;
24 use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};24 use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
25 use crate::render_helpers::{render_to_encompassing_texture, RenderTarget};25 use crate::render_helpers::{render_to_encompassing_texture, RenderTarget};
26+use crate::utils::transaction::Transaction;
26 27
27 /// Toplevel window with decorations.28 /// Toplevel window with decorations.
28 #[derive(Debug)]29 #[derive(Debug)]
@@ -503,7 +504,12 @@ impl<W: LayoutElement> Tile<W> {
503 activation_region.contains(point)504 activation_region.contains(point)
504 }505 }
505 506
506- pub fn request_tile_size(&mut self, mut size: Size<f64, Logical>, animate: bool) {507+ pub fn request_tile_size(
508+ &mut self,
509+ mut size: Size<f64, Logical>,
510+ animate: bool,
511+ transaction: Option<Transaction>,
512+ ) {
507 // Can't go through effective_border_width() because we might be fullscreen.513 // Can't go through effective_border_width() because we might be fullscreen.
508 if !self.border.is_off() {514 if !self.border.is_off() {
509 let width = self.border.width();515 let width = self.border.width();
@@ -514,7 +520,8 @@ impl<W: LayoutElement> Tile<W> {
514 // The size request has to be i32 unfortunately, due to Wayland. We floor here instead of520 // The size request has to be i32 unfortunately, due to Wayland. We floor here instead of
515 // round to avoid situations where proportionally-sized columns don't fit on the screen521 // round to avoid situations where proportionally-sized columns don't fit on the screen
516 // exactly.522 // exactly.
517- self.window.request_size(size.to_i32_floor(), animate);523+ self.window
524+ .request_size(size.to_i32_floor(), animate, transaction);
518 }525 }
519 526
520 pub fn tile_width_for_window_width(&self, size: f64) -> f64 {527 pub fn tile_width_for_window_width(&self, size: f64) -> f64 {
src/layout/workspace.rsmodified+31 -2
@@ -22,6 +22,7 @@ use crate::niri_render_elements;
22 use crate::render_helpers::renderer::NiriRenderer;22 use crate::render_helpers::renderer::NiriRenderer;
23 use crate::render_helpers::RenderTarget;23 use crate::render_helpers::RenderTarget;
24 use crate::utils::id::IdCounter;24 use crate::utils::id::IdCounter;
25+use crate::utils::transaction::Transaction;
25 use crate::utils::{output_size, send_scale_transform, ResizeEdge};26 use crate::utils::{output_size, send_scale_transform, ResizeEdge};
26 use crate::window::ResolvedWindowRules;27 use crate::window::ResolvedWindowRules;
27 28
@@ -2740,6 +2741,27 @@ impl<W: LayoutElement> Workspace<W> {
2740 }2741 }
2741 }2742 }
2742 2743
2744+ let intent = if self.options.disable_resize_throttling {
2745+ ConfigureIntent::CanSend
2746+ } else if self.options.disable_transactions {
2747+ // When transactions are disabled, we don't use combined throttling, but rather
2748+ // compute throttling individually below.
2749+ ConfigureIntent::CanSend
2750+ } else {
2751+ col.tiles
2752+ .iter()
2753+ .fold(ConfigureIntent::NotNeeded, |intent, tile| {
2754+ match (intent, tile.window().configure_intent()) {
2755+ (_, ConfigureIntent::ShouldSend) => ConfigureIntent::ShouldSend,
2756+ (ConfigureIntent::NotNeeded, tile_intent) => tile_intent,
2757+ (ConfigureIntent::CanSend, ConfigureIntent::Throttled) => {
2758+ ConfigureIntent::Throttled
2759+ }
2760+ (intent, _) => intent,
2761+ }
2762+ })
2763+ };
2764+
2743 for (tile_idx, tile) in col.tiles.iter_mut().enumerate() {2765 for (tile_idx, tile) in col.tiles.iter_mut().enumerate() {
2744 let win = tile.window_mut();2766 let win = tile.window_mut();
2745 2767
@@ -2759,7 +2781,13 @@ impl<W: LayoutElement> Workspace<W> {
2759 );2781 );
2760 win.set_bounds(bounds);2782 win.set_bounds(bounds);
2761 2783
2762- let intent = win.configure_intent();2784+ // If transactions are disabled, also disable combined throttling, for more
2785+ // intuitive behavior.
2786+ let intent = if self.options.disable_transactions {
2787+ win.configure_intent()
2788+ } else {
2789+ intent
2790+ };
2763 2791
2764 if matches!(2792 if matches!(
2765 intent,2793 intent,
@@ -3167,13 +3195,14 @@ impl<W: LayoutElement> Column<W> {
3167 assert_eq!(auto_tiles_left, 0);3195 assert_eq!(auto_tiles_left, 0);
3168 }3196 }
3169 3197
3198+ let transaction = Transaction::new();
3170 for (tile, h) in zip(&mut self.tiles, heights) {3199 for (tile, h) in zip(&mut self.tiles, heights) {
3171 let WindowHeight::Fixed(height) = h else {3200 let WindowHeight::Fixed(height) = h else {
3172 unreachable!()3201 unreachable!()
3173 };3202 };
3174 3203
3175 let size = Size::from((width, height));3204 let size = Size::from((width, height));
3176- tile.request_tile_size(size, animate);3205+ tile.request_tile_size(size, animate, Some(transaction.clone()));
3177 }3206 }
3178 }3207 }
3179 3208
src/niri.rsmodified+26 -3
@@ -4,6 +4,7 @@ use std::ffi::OsString;
4 use std::path::PathBuf;4 use std::path::PathBuf;
5 use std::rc::Rc;5 use std::rc::Rc;
6 use std::sync::atomic::{AtomicBool, Ordering};6 use std::sync::atomic::{AtomicBool, Ordering};
7+use std::sync::mpsc::{self, Receiver, Sender};
7 use std::sync::{Arc, Mutex};8 use std::sync::{Arc, Mutex};
8 use std::time::{Duration, Instant};9 use std::time::{Duration, Instant};
9 use std::{env, mem, thread};10 use std::{env, mem, thread};
@@ -61,14 +62,14 @@ use smithay::reexports::wayland_server::backend::{
61 };62 };
62 use smithay::reexports::wayland_server::protocol::wl_shm;63 use smithay::reexports::wayland_server::protocol::wl_shm;
63 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;64 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
64-use smithay::reexports::wayland_server::{Display, DisplayHandle, Resource};65+use smithay::reexports::wayland_server::{Client, Display, DisplayHandle, Resource};
65 use smithay::utils::{66 use smithay::utils::{
66 ClockSource, IsAlive as _, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size,67 ClockSource, IsAlive as _, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size,
67 Transform, SERIAL_COUNTER,68 Transform, SERIAL_COUNTER,
68 };69 };
69 use smithay::wayland::compositor::{70 use smithay::wayland::compositor::{
70- with_states, with_surface_tree_downward, CompositorClientState, CompositorState, HookId,71+ with_states, with_surface_tree_downward, CompositorClientState, CompositorHandler,
71- SurfaceData, TraversalAction,72+ CompositorState, HookId, SurfaceData, TraversalAction,
72 };73 };
73 use smithay::wayland::cursor_shape::CursorShapeManagerState;74 use smithay::wayland::cursor_shape::CursorShapeManagerState;
74 use smithay::wayland::dmabuf::DmabufState;75 use smithay::wayland::dmabuf::DmabufState;
@@ -192,6 +193,10 @@ pub struct Niri {
192 // Dmabuf readiness pre-commit hook for a surface.193 // Dmabuf readiness pre-commit hook for a surface.
193 pub dmabuf_pre_commit_hook: HashMap<WlSurface, HookId>,194 pub dmabuf_pre_commit_hook: HashMap<WlSurface, HookId>,
194 195
196+ /// Clients to notify about their blockers being cleared.
197+ pub blocker_cleared_tx: Sender<Client>,
198+ pub blocker_cleared_rx: Receiver<Client>,
199+
195 pub output_state: HashMap<Output, OutputState>,200 pub output_state: HashMap<Output, OutputState>,
196 pub output_by_name: HashMap<String, Output>,201 pub output_by_name: HashMap<String, Output>,
197 202
@@ -517,6 +522,10 @@ impl State {
517 fn refresh(&mut self) {522 fn refresh(&mut self) {
518 let _span = tracy_client::span!("State::refresh");523 let _span = tracy_client::span!("State::refresh");
519 524
525+ // Handle commits for surfaces whose blockers cleared this cycle. This should happen before
526+ // layout.refresh() since this is where these surfaces handle commits.
527+ self.notify_blocker_cleared();
528+
520 // These should be called periodically, before flushing the clients.529 // These should be called periodically, before flushing the clients.
521 self.niri.layout.refresh();530 self.niri.layout.refresh();
522 self.niri.cursor_manager.check_cursor_image_surface_alive();531 self.niri.cursor_manager.check_cursor_image_surface_alive();
@@ -535,6 +544,15 @@ impl State {
535 self.niri.refresh_mapped_cast_outputs();544 self.niri.refresh_mapped_cast_outputs();
536 }545 }
537 546
547+ fn notify_blocker_cleared(&mut self) {
548+ let dh = self.niri.display_handle.clone();
549+ while let Ok(client) = self.niri.blocker_cleared_rx.try_recv() {
550+ trace!("calling blocker_cleared");
551+ self.client_compositor_state(&client)
552+ .blocker_cleared(self, &dh);
553+ }
554+ }
555+
538 pub fn move_cursor(&mut self, location: Point<f64, Logical>) {556 pub fn move_cursor(&mut self, location: Point<f64, Logical>) {
539 let under = self.niri.surface_under_and_global_space(location);557 let under = self.niri.surface_under_and_global_space(location);
540 self.niri558 self.niri
@@ -1523,6 +1541,8 @@ impl Niri {
1523 1541
1524 let layout = Layout::new(&config_);1542 let layout = Layout::new(&config_);
1525 1543
1544+ let (blocker_cleared_tx, blocker_cleared_rx) = mpsc::channel();
1545+
1526 let compositor_state = CompositorState::new_v6::<State>(&display_handle);1546 let compositor_state = CompositorState::new_v6::<State>(&display_handle);
1527 let xdg_shell_state = XdgShellState::new_with_capabilities::<State>(1547 let xdg_shell_state = XdgShellState::new_with_capabilities::<State>(
1528 &display_handle,1548 &display_handle,
@@ -1737,6 +1757,8 @@ impl Niri {
1737 unmapped_windows: HashMap::new(),1757 unmapped_windows: HashMap::new(),
1738 root_surface: HashMap::new(),1758 root_surface: HashMap::new(),
1739 dmabuf_pre_commit_hook: HashMap::new(),1759 dmabuf_pre_commit_hook: HashMap::new(),
1760+ blocker_cleared_tx,
1761+ blocker_cleared_rx,
1740 monitors_active: true,1762 monitors_active: true,
1741 1763
1742 devices: HashSet::new(),1764 devices: HashSet::new(),
@@ -2497,6 +2519,7 @@ impl Niri {
2497 RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)2519 RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)
2498 )2520 )
2499 }) {2521 }) {
2522+ trace!("redrawing output");
2500 let output = output.clone();2523 let output = output.clone();
2501 self.redraw(backend, &output);2524 self.redraw(backend, &output);
2502 }2525 }
src/utils/mod.rsmodified+1 -0
@@ -23,6 +23,7 @@ use smithay::wayland::fractional_scale::with_fractional_scale;
23 pub mod id;23 pub mod id;
24 pub mod scale;24 pub mod scale;
25 pub mod spawning;25 pub mod spawning;
26+pub mod transaction;
26 pub mod watcher;27 pub mod watcher;
27 28
28 pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);29 pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
src/utils/transaction.rsadded+185 -0
@@ -0,0 +1,185 @@
1+use std::cell::RefCell;
2+use std::rc::Rc;
3+use std::sync::atomic::AtomicBool;
4+use std::sync::mpsc::Sender;
5+use std::sync::{Arc, Mutex, Weak};
6+use std::time::{Duration, Instant};
7+
8+use atomic::Ordering;
9+use calloop::ping::{make_ping, Ping};
10+use calloop::timer::{TimeoutAction, Timer};
11+use calloop::LoopHandle;
12+use smithay::reexports::wayland_server::Client;
13+use smithay::wayland::compositor::{Blocker, BlockerState};
14+
15+/// Default time limit, after which the transaction completes.
16+///
17+/// Serves to avoid hanging when a client fails to respond to a configure promptly.
18+const TIME_LIMIT: Duration = Duration::from_millis(300);
19+
20+/// Transaction between Wayland clients.
21+///
22+/// How to use it:
23+/// 1. Create a transaction with [`Transaction::new()`].
24+/// 2. Clone it as many times as you need.
25+/// 3. Before adding the transaction as a commit blocker, remember to call
26+/// [`Transaction::add_notification()`] to receive a notification when the transaction completes.
27+/// 4. Before adding the transaction as a commit blocker, remember to call
28+/// [`Transaction::register_deadline_timer()`] to make sure the transaction completes when
29+/// reaching the deadline.
30+/// 5. In your surface pre-commit handler, if the transaction corresponding to that commit isn't
31+/// ready, get a blocker with [`Transaction::blocker()`] and add it to the surface.
32+#[derive(Debug, Clone)]
33+pub struct Transaction {
34+ inner: Arc<Inner>,
35+ deadline: Rc<RefCell<Deadline>>,
36+}
37+
38+/// Blocker for a [`Transaction`].
39+#[derive(Debug)]
40+pub struct TransactionBlocker(Weak<Inner>);
41+
42+#[derive(Debug)]
43+enum Deadline {
44+ NotRegistered(Instant),
45+ Registered { remove: Ping },
46+}
47+
48+#[derive(Debug)]
49+struct Inner {
50+ /// Whether the transaction is completed.
51+ completed: AtomicBool,
52+ /// Notifications to send out upon completing the transaction.
53+ notifications: Mutex<Option<(Sender<Client>, Vec<Client>)>>,
54+}
55+
56+impl Transaction {
57+ /// Creates a new transaction.
58+ #[allow(clippy::new_without_default)]
59+ pub fn new() -> Self {
60+ Self {
61+ inner: Arc::new(Inner::new()),
62+ deadline: Rc::new(RefCell::new(Deadline::NotRegistered(
63+ Instant::now() + TIME_LIMIT,
64+ ))),
65+ }
66+ }
67+
68+ /// Gets a blocker for this transaction.
69+ pub fn blocker(&self) -> TransactionBlocker {
70+ trace!(transaction = ?Arc::as_ptr(&self.inner), "generating blocker");
71+ TransactionBlocker(Arc::downgrade(&self.inner))
72+ }
73+
74+ /// Adds a notification for when this transaction completes.
75+ pub fn add_notification(&self, sender: Sender<Client>, client: Client) {
76+ if self.is_completed() {
77+ error!("tried to add notification to a completed transaction");
78+ return;
79+ }
80+
81+ let mut guard = self.inner.notifications.lock().unwrap();
82+ guard.get_or_insert((sender, Vec::new())).1.push(client);
83+ }
84+
85+ /// Registers this transaction's deadline timer on an event loop.
86+ pub fn register_deadline_timer<T: 'static>(&self, event_loop: &LoopHandle<'static, T>) {
87+ let mut cell = self.deadline.borrow_mut();
88+ if let Deadline::NotRegistered(deadline) = *cell {
89+ let timer = Timer::from_deadline(deadline);
90+ let inner = Arc::downgrade(&self.inner);
91+ let token = event_loop
92+ .insert_source(timer, move |_, _, _| {
93+ let _span = trace_span!("deadline timer", transaction = ?Weak::as_ptr(&inner))
94+ .entered();
95+
96+ if let Some(inner) = inner.upgrade() {
97+ trace!("deadline reached, completing transaction");
98+ inner.complete();
99+ } else {
100+ // We should remove the timer automatically. But this callback can still
101+ // just happen to run while the ping callback is scheduled, leading to this
102+ // branch being legitimately taken.
103+ trace!("transaction completed without removing the timer");
104+ }
105+
106+ TimeoutAction::Drop
107+ })
108+ .unwrap();
109+
110+ // Add a ping source that will be used to remove the timer automatically.
111+ let (ping, source) = make_ping().unwrap();
112+ let loop_handle = event_loop.clone();
113+ event_loop
114+ .insert_source(source, move |_, _, _| {
115+ loop_handle.remove(token);
116+ })
117+ .unwrap();
118+
119+ *cell = Deadline::Registered { remove: ping };
120+ }
121+ }
122+
123+ /// Returns whether this transaction has already completed.
124+ pub fn is_completed(&self) -> bool {
125+ self.inner.is_completed()
126+ }
127+
128+ /// Returns whether this is the last instance of this transaction.
129+ pub fn is_last(&self) -> bool {
130+ Arc::strong_count(&self.inner) == 1
131+ }
132+}
133+
134+impl Drop for Transaction {
135+ fn drop(&mut self) {
136+ let _span = trace_span!("drop", transaction = ?Arc::as_ptr(&self.inner)).entered();
137+
138+ if self.is_last() {
139+ // If this was the last transaction, complete it.
140+ trace!("last transaction dropped, completing");
141+ self.inner.complete();
142+
143+ // Also remove the timer.
144+ if let Deadline::Registered { remove } = &*self.deadline.borrow() {
145+ remove.ping();
146+ };
147+ }
148+ }
149+}
150+
151+impl Blocker for TransactionBlocker {
152+ fn state(&self) -> BlockerState {
153+ if self.0.upgrade().map_or(true, |x| x.is_completed()) {
154+ BlockerState::Released
155+ } else {
156+ BlockerState::Pending
157+ }
158+ }
159+}
160+
161+impl Inner {
162+ fn new() -> Self {
163+ Self {
164+ completed: AtomicBool::new(false),
165+ notifications: Mutex::new(None),
166+ }
167+ }
168+
169+ fn is_completed(&self) -> bool {
170+ self.completed.load(Ordering::Relaxed)
171+ }
172+
173+ fn complete(&self) {
174+ self.completed.store(true, Ordering::Relaxed);
175+
176+ let mut guard = self.notifications.lock().unwrap();
177+ if let Some((sender, clients)) = guard.take() {
178+ for client in clients {
179+ if let Err(err) = sender.send(client) {
180+ warn!("error sending blocker notification: {err:?}");
181+ };
182+ }
183+ }
184+ }
185+}
src/window/mapped.rsmodified+69 -1
@@ -32,6 +32,7 @@ use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderEleme
32 use crate::render_helpers::surface::render_snapshot_from_surface_tree;32 use crate::render_helpers::surface::render_snapshot_from_surface_tree;
33 use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};33 use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};
34 use crate::utils::id::IdCounter;34 use crate::utils::id::IdCounter;
35+use crate::utils::transaction::Transaction;
35 use crate::utils::{send_scale_transform, ResizeEdge};36 use crate::utils::{send_scale_transform, ResizeEdge};
36 37
37 #[derive(Debug)]38 #[derive(Debug)]
@@ -71,6 +72,12 @@ pub struct Mapped {
71 /// Snapshot right before an animated commit.72 /// Snapshot right before an animated commit.
72 animation_snapshot: Option<LayoutElementRenderSnapshot>,73 animation_snapshot: Option<LayoutElementRenderSnapshot>,
73 74
75+ /// Transaction that the next configure should take part in, if any.
76+ transaction_for_next_configure: Option<Transaction>,
77+
78+ /// Pending transactions that have not been added as blockers for this window yet.
79+ pending_transactions: Vec<(Serial, Transaction)>,
80+
74 /// State of an ongoing interactive resize.81 /// State of an ongoing interactive resize.
75 interactive_resize: Option<InteractiveResize>,82 interactive_resize: Option<InteractiveResize>,
76 83
@@ -141,6 +148,8 @@ impl Mapped {
141 animate_next_configure: false,148 animate_next_configure: false,
142 animate_serials: Vec::new(),149 animate_serials: Vec::new(),
143 animation_snapshot: None,150 animation_snapshot: None,
151+ transaction_for_next_configure: None,
152+ pending_transactions: Vec::new(),
144 interactive_resize: None,153 interactive_resize: None,
145 last_interactive_resize_start: Cell::new(None),154 last_interactive_resize_start: Cell::new(None),
146 }155 }
@@ -255,6 +264,40 @@ impl Mapped {
255 self.animation_snapshot = Some(self.render_snapshot(renderer));264 self.animation_snapshot = Some(self.render_snapshot(renderer));
256 }265 }
257 266
267+ pub fn take_pending_transaction(&mut self, commit_serial: Serial) -> Option<Transaction> {
268+ let mut rv = None;
269+
270+ // Pending transactions are appended in order by serial, so we can loop from the start
271+ // until we hit a serial that is too new.
272+ while let Some((serial, _)) = self.pending_transactions.first() {
273+ // In this loop, we will complete the transaction corresponding to the commit, as well
274+ // as all transactions corresponding to previous serials. This can happen when we
275+ // request resizes too quickly, and the surface only responds to the last one.
276+ //
277+ // Note that in this case, completing the previous transactions can result in an
278+ // inconsistent visual state, if another window is waiting for this window to assume a
279+ // specific size (in a previous transaction), which is now different (in this commit).
280+ //
281+ // However, there isn't really a good way to deal with that. We cannot cancel any
282+ // transactions because we need to keep sending frame callbacks, and cancelling a
283+ // transaction will make the corresponding frame callbacks get lost, and the window
284+ // will hang.
285+ //
286+ // This is why resize throttling (implemented separately) is important: it prevents
287+ // visually inconsistent states by way of never having more than one transaction in
288+ // flight.
289+ if commit_serial.is_no_older_than(serial) {
290+ let (_, transaction) = self.pending_transactions.remove(0);
291+ // Previous transaction is dropped here, signaling completion.
292+ rv = Some(transaction);
293+ } else {
294+ break;
295+ }
296+ }
297+
298+ rv
299+ }
300+
258 pub fn last_interactive_resize_start(&self) -> &Cell<Option<(Duration, ResizeEdge)>> {301 pub fn last_interactive_resize_start(&self) -> &Cell<Option<(Duration, ResizeEdge)>> {
259 &self.last_interactive_resize_start302 &self.last_interactive_resize_start
260 }303 }
@@ -442,7 +485,12 @@ impl LayoutElement for Mapped {
442 }485 }
443 }486 }
444 487
445- fn request_size(&mut self, size: Size<i32, Logical>, animate: bool) {488+ fn request_size(
489+ &mut self,
490+ size: Size<i32, Logical>,
491+ animate: bool,
492+ transaction: Option<Transaction>,
493+ ) {
446 let changed = self.toplevel().with_pending_state(|state| {494 let changed = self.toplevel().with_pending_state(|state| {
447 let changed = state.size != Some(size);495 let changed = state.size != Some(size);
448 state.size = Some(size);496 state.size = Some(size);
@@ -453,6 +501,15 @@ impl LayoutElement for Mapped {
453 if changed && animate {501 if changed && animate {
454 self.animate_next_configure = true;502 self.animate_next_configure = true;
455 }503 }
504+
505+ // Store the transaction regardless of whether the size changed. This is because with 3+
506+ // windows in a column, the size may change among windows 1 and 2 and then right away among
507+ // windows 2 and 3, and we want all windows 1, 2 and 3 to use the last transaction, rather
508+ // than window 1 getting stuck with the previous transaction that is immediately released
509+ // by 2.
510+ if let Some(transaction) = transaction {
511+ self.transaction_for_next_configure = Some(transaction);
512+ }
456 }513 }
457 514
458 fn request_fullscreen(&self, size: Size<i32, Logical>) {515 fn request_fullscreen(&self, size: Size<i32, Logical>) {
@@ -627,11 +684,21 @@ impl LayoutElement for Mapped {
627 }684 }
628 685
629 fn send_pending_configure(&mut self) {686 fn send_pending_configure(&mut self) {
687+ let _span =
688+ trace_span!("send_pending_configure", surface = ?self.toplevel().wl_surface().id())
689+ .entered();
690+
630 if let Some(serial) = self.toplevel().send_pending_configure() {691 if let Some(serial) = self.toplevel().send_pending_configure() {
692+ trace!(?serial, "sending configure");
693+
631 if self.animate_next_configure {694 if self.animate_next_configure {
632 self.animate_serials.push(serial);695 self.animate_serials.push(serial);
633 }696 }
634 697
698+ if let Some(transaction) = self.transaction_for_next_configure.take() {
699+ self.pending_transactions.push((serial, transaction));
700+ }
701+
635 self.interactive_resize = match self.interactive_resize.take() {702 self.interactive_resize = match self.interactive_resize.take() {
636 Some(InteractiveResize::WaitingForLastConfigure(data)) => {703 Some(InteractiveResize::WaitingForLastConfigure(data)) => {
637 Some(InteractiveResize::WaitingForLastCommit { data, serial })704 Some(InteractiveResize::WaitingForLastCommit { data, serial })
@@ -648,6 +715,7 @@ impl LayoutElement for Mapped {
648 }715 }
649 716
650 self.animate_next_configure = false;717 self.animate_next_configure = false;
718+ self.transaction_for_next_configure = None;
651 }719 }
652 720
653 fn is_fullscreen(&self) -> bool {721 fn is_fullscreen(&self) -> bool {
wiki/Configuration:-Debug-Options.mdmodified+19 -0
@@ -21,6 +21,7 @@ debug {
21 wait-for-frame-completion-before-queueing21 wait-for-frame-completion-before-queueing
22 emulate-zero-presentation-time22 emulate-zero-presentation-time
23 disable-resize-throttling23 disable-resize-throttling
24+ disable-transactions
24 }25 }
25 26
26 binds {27 binds {
@@ -146,6 +147,24 @@ debug {
146 }147 }
147 ```148 ```
148 149
150+### `disable-transactions`
151+
152+<sup>Since: 0.1.9</sup>
153+
154+Disable transactions (as of niri 0.1.9, only resize transactions are implemented).
155+
156+By default, windows which must resize together, do resize together.
157+For example, all windows in a column must resize at the same time to maintain the combined column height equal to the screen height, and to maintain the same window width.
158+
159+Transactions make niri wait until all windows finish resizing before showing them all on screen in one, synchronized frame.
160+For them to work properly, resize throttling shouldn't be disabled (with the previous debug flag).
161+
162+```kdl
163+debug {
164+ disable-transactions
165+}
166+```
167+
149 ### Key Bindings168 ### Key Bindings
150 169
151 These are not debug options, but rather key bindings.170 These are not debug options, but rather key bindings.