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 {
13701370 pub emulate_zero_presentation_time: bool,
13711371 #[knuffel(child)]
13721372 pub disable_resize_throttling: bool,
1373+ #[knuffel(child)]
1374+ pub disable_transactions: bool,
13731375 }
13741376
13751377 #[derive(knuffel::DecodeScalar, Debug, Clone, Copy, PartialEq, Eq)]
niri-visual-tests/src/cases/layout.rsmodified+2 -2
@@ -147,7 +147,7 @@ impl Layout {
147147
148148 fn add_window(&mut self, mut window: TestWindow, width: Option<ColumnWidth>) {
149149 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);
151151 window.communicate();
152152
153153 self.layout.add_window(window.clone(), width, false);
@@ -161,7 +161,7 @@ impl Layout {
161161 width: Option<ColumnWidth>,
162162 ) {
163163 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);
165165 window.communicate();
166166
167167 self.layout
niri-visual-tests/src/cases/tile.rsmodified+4 -4
@@ -20,7 +20,7 @@ impl Tile {
2020 pub fn freeform(size: Size<i32, Logical>) -> Self {
2121 let window = TestWindow::freeform(0);
2222 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);
2424 rv.window.communicate();
2525 rv
2626 }
@@ -28,7 +28,7 @@ impl Tile {
2828 pub fn fixed_size(size: Size<i32, Logical>) -> Self {
2929 let window = TestWindow::fixed_size(0);
3030 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);
3232 rv.window.communicate();
3333 rv
3434 }
@@ -37,7 +37,7 @@ impl Tile {
3737 let window = TestWindow::fixed_size(0);
3838 window.set_csd_shadow_width(64);
3939 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);
4141 rv.window.communicate();
4242 rv
4343 }
@@ -85,7 +85,7 @@ impl Tile {
8585 impl TestCase for Tile {
8686 fn resize(&mut self, width: i32, height: i32) {
8787 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);
8989 self.window.communicate();
9090 }
9191
niri-visual-tests/src/cases/window.rsmodified+5 -4
@@ -14,14 +14,14 @@ pub struct Window {
1414 impl Window {
1515 pub fn freeform(size: Size<i32, Logical>) -> Self {
1616 let mut window = TestWindow::freeform(0);
17- window.request_size(size, false);
17+ window.request_size(size, false, None);
1818 window.communicate();
1919 Self { window }
2020 }
2121
2222 pub fn fixed_size(size: Size<i32, Logical>) -> Self {
2323 let mut window = TestWindow::fixed_size(0);
24- window.request_size(size, false);
24+ window.request_size(size, false, None);
2525 window.communicate();
2626 Self { window }
2727 }
@@ -29,7 +29,7 @@ impl Window {
2929 pub fn fixed_size_with_csd_shadow(size: Size<i32, Logical>) -> Self {
3030 let mut window = TestWindow::fixed_size(0);
3131 window.set_csd_shadow_width(64);
32- window.request_size(size, false);
32+ window.request_size(size, false, None);
3333 window.communicate();
3434 Self { window }
3535 }
@@ -37,7 +37,8 @@ impl Window {
3737
3838 impl TestCase for Window {
3939 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);
4142 self.window.communicate();
4243 }
4344
niri-visual-tests/src/test_window.rsmodified+7 -1
@@ -9,6 +9,7 @@ use niri::layout::{
99 use niri::render_helpers::renderer::NiriRenderer;
1010 use niri::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
1111 use niri::render_helpers::{RenderTarget, SplitElements};
12+use niri::utils::transaction::Transaction;
1213 use niri::window::ResolvedWindowRules;
1314 use smithay::backend::renderer::element::{Id, Kind};
1415 use smithay::output::{self, Output};
@@ -177,7 +178,12 @@ impl LayoutElement for TestWindow {
177178 }
178179 }
179180
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+ ) {
181187 self.inner.borrow_mut().requested_size = Some(size);
182188 self.inner.borrow_mut().pending_fullscreen = false;
183189 }
src/handlers/compositor.rsmodified+1 -0
@@ -52,6 +52,7 @@ impl CompositorHandler for State {
5252
5353 fn commit(&mut self, surface: &WlSurface) {
5454 let _span = tracy_client::span!("CompositorHandler::commit");
55+ trace!(surface = ?surface.id(), "commit");
5556
5657 on_commit_buffer_handler::<Self>(surface);
5758 self.backend.early_import(surface);
src/handlers/xdg_shell.rsmodified+52 -7
@@ -34,6 +34,7 @@ use smithay::wayland::xdg_foreign::{XdgForeignHandler, XdgForeignState};
3434 use smithay::{
3535 delegate_kde_decoration, delegate_xdg_decoration, delegate_xdg_foreign, delegate_xdg_shell,
3636 };
37+use tracing::field::Empty;
3738
3839 use crate::input::resize_grab::ResizeGrab;
3940 use crate::input::DOUBLE_CLICK_TIME;
@@ -1003,6 +1004,8 @@ fn unconstrain_with_padding(
10031004 pub fn add_mapped_toplevel_pre_commit_hook(toplevel: &ToplevelSurface) -> HookId {
10041005 add_pre_commit_hook::<State, _>(toplevel.wl_surface(), move |state, _dh, surface| {
10051006 let _span = tracy_client::span!("mapped toplevel pre-commit");
1007+ let span =
1008+ trace_span!("toplevel pre-commit", surface = %surface.id(), serial = Empty).entered();
10061009
10071010 let Some((mapped, _)) = state.niri.layout.find_window_and_output_mut(surface) else {
10081011 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
10321035 (got_unmapped, dmabuf, role.configure_serial)
10331036 });
10341037
1035- let mut dmabuf_blocker =
1036- dmabuf.and_then(|dmabuf| dmabuf.generate_blocker(Interest::READ).ok());
1038+ let mut transaction_for_dmabuf = None;
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+ }
10371078
1038- let animate = if let Some(serial) = commit_serial {
1039- mapped.should_animate_commit(serial)
1079+ animate = mapped.should_animate_commit(serial);
10401080 } else {
10411081 error!("commit on a mapped surface without a configured serial");
1042- false
10431082 };
10441083
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+ {
10461087 if let Some(client) = surface.client() {
10471088 let res = state
10481089 .niri
10491090 .event_loop
10501091 .insert_source(source, move |_, _, state| {
1092+ // This surface is now ready for the transaction.
1093+ drop(transaction_for_dmabuf.take());
1094+
10511095 let display_handle = state.niri.display_handle.clone();
10521096 state
10531097 .client_compositor_state(&client)
10541098 .blocker_cleared(state, &display_handle);
1099+
10551100 Ok(())
10561101 });
10571102 if res.is_ok() {
10581103 add_blocker(surface, blocker);
1059- trace!("added toplevel dmabuf blocker");
1104+ trace!("added dmabuf blocker");
10601105 }
10611106 }
10621107 }
src/layout/mod.rsmodified+16 -2
@@ -52,6 +52,7 @@ use crate::render_helpers::snapshot::RenderSnapshot;
5252 use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
5353 use crate::render_helpers::texture::TextureBuffer;
5454 use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};
55+use crate::utils::transaction::Transaction;
5556 use crate::utils::{output_size, round_logical_in_physical_max1, ResizeEdge};
5657 use crate::window::ResolvedWindowRules;
5758
@@ -153,7 +154,12 @@ pub trait LayoutElement {
153154 self.render(renderer, location, scale, alpha, target).popups
154155 }
155156
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+ );
157163 fn request_fullscreen(&self, size: Size<i32, Logical>);
158164 fn min_size(&self) -> Size<i32, Logical>;
159165 fn max_size(&self) -> Size<i32, Logical>;
@@ -237,6 +243,7 @@ pub struct Options {
237243
238244 // Debug flags.
239245 pub disable_resize_throttling: bool,
246+ pub disable_transactions: bool,
240247 }
241248
242249 impl Default for Options {
@@ -255,6 +262,7 @@ impl Default for Options {
255262 default_width: None,
256263 animations: Default::default(),
257264 disable_resize_throttling: false,
265+ disable_transactions: false,
258266 }
259267 }
260268 }
@@ -292,6 +300,7 @@ impl Options {
292300 default_width,
293301 animations: config.animations.clone(),
294302 disable_resize_throttling: config.debug.disable_resize_throttling,
303+ disable_transactions: config.debug.disable_transactions,
295304 }
296305 }
297306
@@ -2636,7 +2645,12 @@ mod tests {
26362645 SplitElements::default()
26372646 }
26382647
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+ ) {
26402654 self.0.requested_size.set(Some(size));
26412655 self.0.pending_fullscreen.set(false);
26422656 }
src/layout/tile.rsmodified+9 -2
@@ -23,6 +23,7 @@ use crate::render_helpers::resize::ResizeRenderElement;
2323 use crate::render_helpers::snapshot::RenderSnapshot;
2424 use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
2525 use crate::render_helpers::{render_to_encompassing_texture, RenderTarget};
26+use crate::utils::transaction::Transaction;
2627
2728 /// Toplevel window with decorations.
2829 #[derive(Debug)]
@@ -503,7 +504,12 @@ impl<W: LayoutElement> Tile<W> {
503504 activation_region.contains(point)
504505 }
505506
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+ ) {
507513 // Can't go through effective_border_width() because we might be fullscreen.
508514 if !self.border.is_off() {
509515 let width = self.border.width();
@@ -514,7 +520,8 @@ impl<W: LayoutElement> Tile<W> {
514520 // The size request has to be i32 unfortunately, due to Wayland. We floor here instead of
515521 // round to avoid situations where proportionally-sized columns don't fit on the screen
516522 // exactly.
517- self.window.request_size(size.to_i32_floor(), animate);
523+ self.window
524+ .request_size(size.to_i32_floor(), animate, transaction);
518525 }
519526
520527 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;
2222 use crate::render_helpers::renderer::NiriRenderer;
2323 use crate::render_helpers::RenderTarget;
2424 use crate::utils::id::IdCounter;
25+use crate::utils::transaction::Transaction;
2526 use crate::utils::{output_size, send_scale_transform, ResizeEdge};
2627 use crate::window::ResolvedWindowRules;
2728
@@ -2740,6 +2741,27 @@ impl<W: LayoutElement> Workspace<W> {
27402741 }
27412742 }
27422743
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+
27432765 for (tile_idx, tile) in col.tiles.iter_mut().enumerate() {
27442766 let win = tile.window_mut();
27452767
@@ -2759,7 +2781,13 @@ impl<W: LayoutElement> Workspace<W> {
27592781 );
27602782 win.set_bounds(bounds);
27612783
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+ };
27632791
27642792 if matches!(
27652793 intent,
@@ -3167,13 +3195,14 @@ impl<W: LayoutElement> Column<W> {
31673195 assert_eq!(auto_tiles_left, 0);
31683196 }
31693197
3198+ let transaction = Transaction::new();
31703199 for (tile, h) in zip(&mut self.tiles, heights) {
31713200 let WindowHeight::Fixed(height) = h else {
31723201 unreachable!()
31733202 };
31743203
31753204 let size = Size::from((width, height));
3176- tile.request_tile_size(size, animate);
3205+ tile.request_tile_size(size, animate, Some(transaction.clone()));
31773206 }
31783207 }
31793208
src/niri.rsmodified+26 -3
@@ -4,6 +4,7 @@ use std::ffi::OsString;
44 use std::path::PathBuf;
55 use std::rc::Rc;
66 use std::sync::atomic::{AtomicBool, Ordering};
7+use std::sync::mpsc::{self, Receiver, Sender};
78 use std::sync::{Arc, Mutex};
89 use std::time::{Duration, Instant};
910 use std::{env, mem, thread};
@@ -61,14 +62,14 @@ use smithay::reexports::wayland_server::backend::{
6162 };
6263 use smithay::reexports::wayland_server::protocol::wl_shm;
6364 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};
6566 use smithay::utils::{
6667 ClockSource, IsAlive as _, Logical, Monotonic, Physical, Point, Rectangle, Scale, Size,
6768 Transform, SERIAL_COUNTER,
6869 };
6970 use smithay::wayland::compositor::{
70- with_states, with_surface_tree_downward, CompositorClientState, CompositorState, HookId,
71- SurfaceData, TraversalAction,
71+ with_states, with_surface_tree_downward, CompositorClientState, CompositorHandler,
72+ CompositorState, HookId, SurfaceData, TraversalAction,
7273 };
7374 use smithay::wayland::cursor_shape::CursorShapeManagerState;
7475 use smithay::wayland::dmabuf::DmabufState;
@@ -192,6 +193,10 @@ pub struct Niri {
192193 // Dmabuf readiness pre-commit hook for a surface.
193194 pub dmabuf_pre_commit_hook: HashMap<WlSurface, HookId>,
194195
196+ /// Clients to notify about their blockers being cleared.
197+ pub blocker_cleared_tx: Sender<Client>,
198+ pub blocker_cleared_rx: Receiver<Client>,
199+
195200 pub output_state: HashMap<Output, OutputState>,
196201 pub output_by_name: HashMap<String, Output>,
197202
@@ -517,6 +522,10 @@ impl State {
517522 fn refresh(&mut self) {
518523 let _span = tracy_client::span!("State::refresh");
519524
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+
520529 // These should be called periodically, before flushing the clients.
521530 self.niri.layout.refresh();
522531 self.niri.cursor_manager.check_cursor_image_surface_alive();
@@ -535,6 +544,15 @@ impl State {
535544 self.niri.refresh_mapped_cast_outputs();
536545 }
537546
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+
538556 pub fn move_cursor(&mut self, location: Point<f64, Logical>) {
539557 let under = self.niri.surface_under_and_global_space(location);
540558 self.niri
@@ -1523,6 +1541,8 @@ impl Niri {
15231541
15241542 let layout = Layout::new(&config_);
15251543
1544+ let (blocker_cleared_tx, blocker_cleared_rx) = mpsc::channel();
1545+
15261546 let compositor_state = CompositorState::new_v6::<State>(&display_handle);
15271547 let xdg_shell_state = XdgShellState::new_with_capabilities::<State>(
15281548 &display_handle,
@@ -1737,6 +1757,8 @@ impl Niri {
17371757 unmapped_windows: HashMap::new(),
17381758 root_surface: HashMap::new(),
17391759 dmabuf_pre_commit_hook: HashMap::new(),
1760+ blocker_cleared_tx,
1761+ blocker_cleared_rx,
17401762 monitors_active: true,
17411763
17421764 devices: HashSet::new(),
@@ -2497,6 +2519,7 @@ impl Niri {
24972519 RedrawState::Queued | RedrawState::WaitingForEstimatedVBlankAndQueued(_)
24982520 )
24992521 }) {
2522+ trace!("redrawing output");
25002523 let output = output.clone();
25012524 self.redraw(backend, &output);
25022525 }
src/utils/mod.rsmodified+1 -0
@@ -23,6 +23,7 @@ use smithay::wayland::fractional_scale::with_fractional_scale;
2323 pub mod id;
2424 pub mod scale;
2525 pub mod spawning;
26+pub mod transaction;
2627 pub mod watcher;
2728
2829 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
3232 use crate::render_helpers::surface::render_snapshot_from_surface_tree;
3333 use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};
3434 use crate::utils::id::IdCounter;
35+use crate::utils::transaction::Transaction;
3536 use crate::utils::{send_scale_transform, ResizeEdge};
3637
3738 #[derive(Debug)]
@@ -71,6 +72,12 @@ pub struct Mapped {
7172 /// Snapshot right before an animated commit.
7273 animation_snapshot: Option<LayoutElementRenderSnapshot>,
7374
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+
7481 /// State of an ongoing interactive resize.
7582 interactive_resize: Option<InteractiveResize>,
7683
@@ -141,6 +148,8 @@ impl Mapped {
141148 animate_next_configure: false,
142149 animate_serials: Vec::new(),
143150 animation_snapshot: None,
151+ transaction_for_next_configure: None,
152+ pending_transactions: Vec::new(),
144153 interactive_resize: None,
145154 last_interactive_resize_start: Cell::new(None),
146155 }
@@ -255,6 +264,40 @@ impl Mapped {
255264 self.animation_snapshot = Some(self.render_snapshot(renderer));
256265 }
257266
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+
258301 pub fn last_interactive_resize_start(&self) -> &Cell<Option<(Duration, ResizeEdge)>> {
259302 &self.last_interactive_resize_start
260303 }
@@ -442,7 +485,12 @@ impl LayoutElement for Mapped {
442485 }
443486 }
444487
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+ ) {
446494 let changed = self.toplevel().with_pending_state(|state| {
447495 let changed = state.size != Some(size);
448496 state.size = Some(size);
@@ -453,6 +501,15 @@ impl LayoutElement for Mapped {
453501 if changed && animate {
454502 self.animate_next_configure = true;
455503 }
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+ }
456513 }
457514
458515 fn request_fullscreen(&self, size: Size<i32, Logical>) {
@@ -627,11 +684,21 @@ impl LayoutElement for Mapped {
627684 }
628685
629686 fn send_pending_configure(&mut self) {
687+ let _span =
688+ trace_span!("send_pending_configure", surface = ?self.toplevel().wl_surface().id())
689+ .entered();
690+
630691 if let Some(serial) = self.toplevel().send_pending_configure() {
692+ trace!(?serial, "sending configure");
693+
631694 if self.animate_next_configure {
632695 self.animate_serials.push(serial);
633696 }
634697
698+ if let Some(transaction) = self.transaction_for_next_configure.take() {
699+ self.pending_transactions.push((serial, transaction));
700+ }
701+
635702 self.interactive_resize = match self.interactive_resize.take() {
636703 Some(InteractiveResize::WaitingForLastConfigure(data)) => {
637704 Some(InteractiveResize::WaitingForLastCommit { data, serial })
@@ -648,6 +715,7 @@ impl LayoutElement for Mapped {
648715 }
649716
650717 self.animate_next_configure = false;
718+ self.transaction_for_next_configure = None;
651719 }
652720
653721 fn is_fullscreen(&self) -> bool {
wiki/Configuration:-Debug-Options.mdmodified+19 -0
@@ -21,6 +21,7 @@ debug {
2121 wait-for-frame-completion-before-queueing
2222 emulate-zero-presentation-time
2323 disable-resize-throttling
24+ disable-transactions
2425 }
2526
2627 binds {
@@ -146,6 +147,24 @@ debug {
146147 }
147148 ```
148149
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+
149168 ### Key Bindings
150169
151170 These are not debug options, but rather key bindings.