forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

compositor.rs584 lines, 24.3 KiBHistoryRawDownload
1use std::collections::hash_map::Entry;
2
3use niri_ipc::PositionChange;
4use smithay::backend::renderer::utils::on_commit_buffer_handler;
5use smithay::input::pointer::{CursorImageStatus, CursorImageSurfaceData};
6use smithay::reexports::calloop::Interest;
7use smithay::reexports::wayland_server::protocol::wl_buffer;
8use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
9use smithay::reexports::wayland_server::{Client, Resource};
10use smithay::wayland::buffer::BufferHandler;
11use smithay::wayland::compositor::{
12 add_blocker, add_pre_commit_hook, get_parent, is_sync_subsurface, remove_pre_commit_hook,
13 with_states, BufferAssignment, CompositorClientState, CompositorHandler, CompositorState,
14 SurfaceAttributes,
15};
16use smithay::wayland::dmabuf::get_dmabuf;
17use smithay::wayland::shell::xdg::ToplevelCachedState;
18use smithay::wayland::shm::{ShmHandler, ShmState};
19
20use super::xdg_shell::add_mapped_toplevel_pre_commit_hook;
21use crate::handlers::XDG_ACTIVATION_TOKEN_TIMEOUT;
22use crate::layout::{ActivateWindow, AddWindowTarget, LayoutElement as _};
23use crate::niri::{CastTarget, ClientState, LockState, State};
24use crate::utils::transaction::Transaction;
25use crate::utils::{is_mapped, send_scale_transform};
26use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped};
27
28impl CompositorHandler for State {
29 fn compositor_state(&mut self) -> &mut CompositorState {
30 &mut self.niri.compositor_state
31 }
32
33 fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
34 &client.get_data::<ClientState>().unwrap().compositor_state
35 }
36
37 fn new_subsurface(&mut self, surface: &WlSurface, parent: &WlSurface) {
38 let mut root = parent.clone();
39 while let Some(parent) = get_parent(&root) {
40 root = parent;
41 }
42
43 if let Some(output) = self.niri.output_for_root(&root) {
44 let scale = output.current_scale();
45 let transform = output.current_transform();
46 with_states(surface, |data| {
47 send_scale_transform(surface, data, scale, transform);
48 });
49 }
50 }
51
52 fn new_surface(&mut self, surface: &WlSurface) {
53 self.add_default_dmabuf_pre_commit_hook(surface);
54 }
55
56 fn commit(&mut self, surface: &WlSurface) {
57 let _span = tracy_client::span!("CompositorHandler::commit");
58 let _span = trace_span!("commit", surface = %surface.id()).entered();
59 trace!("commit");
60
61 on_commit_buffer_handler::<Self>(surface);
62 self.backend.early_import(surface);
63
64 let mut root_surface = surface.clone();
65 while let Some(parent) = get_parent(&root_surface) {
66 root_surface = parent;
67 }
68
69 // Update the cached root surface.
70 self.niri
71 .root_surface
72 .insert(surface.clone(), root_surface.clone());
73
74 if is_sync_subsurface(surface) {
75 return;
76 }
77
78 if surface == &root_surface {
79 // This is a root surface commit. It might have mapped a previously-unmapped toplevel.
80 if let Entry::Occupied(entry) = self.niri.unmapped_windows.entry(surface.clone()) {
81 if is_mapped(surface) {
82 // The toplevel got mapped.
83 let Unmapped {
84 window,
85 state,
86 activation_token_data,
87 } = entry.remove();
88
89 window.on_commit();
90
91 let toplevel = window.toplevel().expect("no X11 support");
92
93 let (
94 rules,
95 width,
96 height,
97 is_full_width,
98 output,
99 workspace_id,
100 is_pending_maximized,
101 ) = if let InitialConfigureState::Configured {
102 rules,
103 width,
104 height,
105 floating_width: _,
106 floating_height: _,
107 is_full_width,
108 output,
109 workspace_name,
110 is_pending_maximized,
111 } = state
112 {
113 // Check that the output is still connected.
114 let output =
115 output.filter(|o| self.niri.layout.monitor_for_output(o).is_some());
116
117 // Check that the workspace still exists.
118 let workspace_id = workspace_name
119 .as_deref()
120 .and_then(|n| self.niri.layout.find_workspace_by_name(n))
121 .map(|(_, ws)| ws.id());
122
123 (
124 rules,
125 width,
126 height,
127 is_full_width,
128 output,
129 workspace_id,
130 is_pending_maximized,
131 )
132 } else {
133 // Can happen when a surface unmaps by attaching a null buffer while
134 // there are in-flight pending configures.
135 debug!("window mapped without proper initial configure");
136 (
137 ResolvedWindowRules::default(),
138 None,
139 None,
140 false,
141 None,
142 None,
143 false,
144 )
145 };
146
147 // The GTK about dialog sets min/max size after the initial configure but
148 // before mapping, so we need to compute open_floating at the last possible
149 // moment, that is here.
150 let is_floating = rules.compute_open_floating(toplevel);
151
152 // Figure out if we should activate the window.
153 let activate = rules.open_focused.map(|focus| {
154 if focus {
155 ActivateWindow::Yes
156 } else {
157 ActivateWindow::No
158 }
159 });
160 let activate = activate.unwrap_or_else(|| {
161 // Check the token timestamp again in case the window took a while between
162 // requesting activation and mapping.
163 let token = activation_token_data.filter(|token| {
164 token.timestamp.elapsed() < XDG_ACTIVATION_TOKEN_TIMEOUT
165 });
166 if token.is_some() {
167 ActivateWindow::Yes
168 } else {
169 let config = self.niri.config.borrow();
170 if config.debug.strict_new_window_focus_policy {
171 ActivateWindow::No
172 } else {
173 ActivateWindow::Smart
174 }
175 }
176 });
177
178 let parent = toplevel
179 .parent()
180 .and_then(|parent| self.niri.layout.find_window_and_output(&parent))
181 // Only consider the parent if we configured the window for the same
182 // output.
183 //
184 // Normally when we're following the parent, the configured output will be
185 // None. If the configured output is set, that means it was set explicitly
186 // by a window rule or a fullscreen request.
187 .filter(|(_, parent_output)| {
188 parent_output.is_none()
189 || output.is_none()
190 || output.as_ref() == *parent_output
191 })
192 .map(|(mapped, _)| mapped.window.clone());
193
194 // The mapped pre-commit hook deals with dma-bufs on its own.
195 self.remove_default_dmabuf_pre_commit_hook(surface);
196 let hook = add_mapped_toplevel_pre_commit_hook(toplevel);
197 let mapped = {
198 let config = self.niri.config.borrow();
199 Mapped::new(window, rules, hook, &config)
200 };
201 let window = mapped.window.clone();
202
203 let target = if let Some(p) = &parent {
204 // Open dialogs next to their parent window.
205 AddWindowTarget::NextTo(p)
206 } else if let Some(id) = workspace_id {
207 AddWindowTarget::Workspace(id)
208 } else if let Some(output) = &output {
209 AddWindowTarget::Output(output)
210 } else {
211 AddWindowTarget::Auto
212 };
213 let output = self.niri.layout.add_window(
214 mapped,
215 target,
216 width,
217 height,
218 is_full_width,
219 is_floating,
220 activate,
221 );
222 let output = output.cloned();
223
224 // The window state cannot contain Fullscreen and Maximized at once. Therefore,
225 // if the window ended up fullscreen, then we only know that it is also
226 // maximized from the is_pending_maximized variable. Tell the layout about it
227 // here so that unfullscreening the window makes it maximized.
228 if let Some((mapped, _)) = self.niri.layout.find_window_and_output(surface) {
229 if mapped.pending_sizing_mode().is_fullscreen() && is_pending_maximized {
230 self.niri.layout.set_maximized(&window, true);
231 }
232 } else {
233 error!("layout is missing the window that we just added");
234 }
235
236 if let Some(output) = output {
237 self.niri.layout.start_open_animation_for_window(&window);
238
239 let new_focus = self.niri.layout.focus().map(|m| &m.window);
240 if new_focus == Some(&window) {
241 // We activated the newly opened window.
242 self.maybe_warp_cursor_to_focus();
243 self.niri.layer_shell_on_demand_focus = None;
244 }
245
246 self.niri.queue_redraw(&output);
247 }
248 return;
249 }
250
251 // The toplevel remains unmapped.
252 trace!("toplevel remains unmapped");
253 let unmapped = entry.get();
254 if unmapped.needs_initial_configure() {
255 let toplevel = unmapped.window.toplevel().expect("no x11 support").clone();
256 self.queue_initial_configure(toplevel);
257 }
258 return;
259 }
260
261 // This is a commit of a previously-mapped root or a non-toplevel root.
262 if let Some((mapped, output)) = self.niri.layout.find_window_and_output(surface) {
263 let window = mapped.window.clone();
264 let output = output.cloned();
265
266 let id = mapped.id();
267
268 // This is a commit of a previously-mapped toplevel.
269 let is_mapped = is_mapped(surface);
270
271 // Must start the close animation before window.on_commit().
272 let transaction = Transaction::new();
273 if !is_mapped {
274 let blocker = transaction.blocker();
275 self.backend.with_primary_renderer(|renderer| {
276 self.niri
277 .layout
278 .start_close_animation_for_window(renderer, &window, blocker);
279 });
280 }
281
282 window.on_commit();
283
284 if !is_mapped {
285 // The toplevel got unmapped.
286 //
287 // Test client: wleird-unmap.
288 trace!("toplevel got unmapped");
289
290 let active_window = self.niri.layout.focus().map(|m| &m.window);
291 let was_active = active_window == Some(&window);
292
293 self.niri
294 .stop_casts_for_target(CastTarget::Window { id: id.get() });
295
296 self.niri.window_mru_ui.remove_window(id);
297 self.niri.layout.remove_window(&window, transaction.clone());
298 self.add_default_dmabuf_pre_commit_hook(surface);
299
300 // If this is the only instance, then this transaction will complete
301 // immediately, so no need to set the timer.
302 if !transaction.is_last() {
303 transaction.register_deadline_timer(&self.niri.event_loop);
304 }
305
306 if was_active {
307 self.maybe_warp_cursor_to_focus();
308 }
309
310 // Newly-unmapped toplevels must perform the initial commit-configure sequence
311 // afresh.
312 let unmapped = Unmapped::new(window);
313 self.niri.unmapped_windows.insert(surface.clone(), unmapped);
314
315 if let Some(output) = output {
316 self.niri.queue_redraw(&output);
317 self.niri.queue_redraw_mru_output();
318 }
319 return;
320 }
321
322 let (serial, buffer_delta) = with_states(surface, |states| {
323 let buffer_delta = states
324 .cached_state
325 .get::<SurfaceAttributes>()
326 .current()
327 .buffer_delta
328 .take();
329
330 let serial = states
331 .cached_state
332 .get::<ToplevelCachedState>()
333 .current()
334 .last_acked
335 .as_ref()
336 .map(|c| c.serial);
337 (serial, buffer_delta)
338 });
339 if serial.is_none() {
340 error!("commit on a mapped surface without a configured serial");
341 }
342
343 // The toplevel remains mapped.
344 self.niri.window_mru_ui.update_window(&self.niri.layout, id);
345 self.niri.layout.update_window(&window, serial);
346
347 // Move the toplevel according to the attach offset.
348 if let Some(delta) = buffer_delta {
349 if delta.x != 0 || delta.y != 0 {
350 let (x, y) = delta.to_f64().into();
351 self.niri.layout.move_floating_window(
352 Some(&window),
353 PositionChange::AdjustFixed(x),
354 PositionChange::AdjustFixed(y),
355 false,
356 );
357 }
358 }
359
360 // Popup placement depends on window size which might have changed.
361 self.update_reactive_popups(&window);
362
363 if let Some(output) = output {
364 self.niri.queue_redraw(&output);
365 self.niri.queue_redraw_mru_output();
366 }
367 return;
368 }
369
370 // This is a commit of a non-toplevel root.
371
372 // This might be a popup.
373 self.popups_handle_commit(surface);
374 }
375
376 // This is a commit of a non-root or a non-toplevel root.
377 let root_window_output = self.niri.layout.find_window_and_output(&root_surface);
378 if let Some((mapped, output)) = root_window_output {
379 let window = mapped.window.clone();
380 let output = output.cloned();
381 window.on_commit();
382 self.niri
383 .window_mru_ui
384 .update_window(&self.niri.layout, mapped.id());
385 self.niri.layout.update_window(&window, None);
386 if let Some(output) = output {
387 self.niri.queue_redraw(&output);
388 self.niri.queue_redraw_mru_output();
389 }
390 return;
391 }
392
393 // This might be a popup unsync subsurface.
394 if let Some(popup) = self.niri.popups.find_popup(&root_surface) {
395 if let Some(output) = self.output_for_popup(&popup) {
396 self.niri.queue_redraw(&output.clone());
397 }
398 return;
399 }
400
401 // This might be a layer-shell surface.
402 if self.layer_shell_handle_commit(surface) {
403 return;
404 }
405
406 // This might be a cursor surface.
407 if matches!(
408 &self.niri.cursor_manager.cursor_image(),
409 CursorImageStatus::Surface(s) if s == &root_surface
410 ) {
411 // In case the cursor surface has been committed handle the role specific
412 // buffer offset by applying the offset on the cursor image hotspot
413 if surface == &root_surface {
414 with_states(surface, |states| {
415 let cursor_image_attributes = states.data_map.get::<CursorImageSurfaceData>();
416
417 if let Some(mut cursor_image_attributes) =
418 cursor_image_attributes.map(|attrs| attrs.lock().unwrap())
419 {
420 let buffer_delta = states
421 .cached_state
422 .get::<SurfaceAttributes>()
423 .current()
424 .buffer_delta
425 .take();
426 if let Some(buffer_delta) = buffer_delta {
427 cursor_image_attributes.hotspot -= buffer_delta;
428 }
429 }
430 });
431 }
432
433 // FIXME: granular redraws for cursors.
434 self.niri.queue_redraw_all();
435 return;
436 }
437
438 // This might be a DnD icon surface.
439 if matches!(&self.niri.dnd_icon, Some(icon) if icon.surface == root_surface) {
440 let dnd_icon = self.niri.dnd_icon.as_mut().unwrap();
441
442 // In case the dnd surface has been committed handle the role specific
443 // buffer offset by applying the offset on the dnd icon offset
444 if surface == &dnd_icon.surface {
445 with_states(&dnd_icon.surface, |states| {
446 let buffer_delta = states
447 .cached_state
448 .get::<SurfaceAttributes>()
449 .current()
450 .buffer_delta
451 .take()
452 .unwrap_or_default();
453 dnd_icon.offset += buffer_delta;
454 });
455 }
456
457 // FIXME: granular redraws for cursors.
458 self.niri.queue_redraw_all();
459 return;
460 }
461
462 // This might be a lock surface.
463 for (output, state) in &self.niri.output_state {
464 if let Some(lock_surface) = &state.lock_surface {
465 if lock_surface.wl_surface() == &root_surface {
466 if matches!(self.niri.lock_state, LockState::WaitingForSurfaces { .. }) {
467 self.niri.maybe_continue_to_locking();
468 } else {
469 self.niri.queue_redraw(&output.clone());
470 }
471
472 return;
473 }
474 }
475 }
476
477 // This message can trigger for lock surfaces that had a commit right after we unlocked
478 // the session, but that's ok, we don't need to handle them.
479 trace!("commit on an unrecognized surface: {surface:?}, root: {root_surface:?}");
480 }
481
482 fn destroyed(&mut self, surface: &WlSurface) {
483 // Clients may destroy their subsurfaces before the main surface. Ensure we have a snapshot
484 // when that happens, so that the closing animation includes all these subsurfaces.
485 //
486 // Test client: alacritty with CSD <= 0.13 (it was fixed in winit afterwards:
487 // https://github.com/rust-windowing/winit/pull/3625).
488 //
489 // This is still not perfect, as this function is called already after the (first)
490 // subsurface is destroyed; in the case of alacritty, this is the top CSD shadow. But, it
491 // gets most of the job done.
492 if let Some(root) = self.niri.root_surface.get(surface) {
493 if let Some((mapped, output)) = self.niri.layout.find_window_and_output(root) {
494 let window = mapped.window.clone();
495 let output = output.cloned();
496 self.store_unmap_snapshot(&window, output.as_ref());
497 }
498 }
499
500 self.niri
501 .root_surface
502 .retain(|k, v| k != surface && v != surface);
503
504 // The object destruction order is not guaranteed to follow the logical role order. So for
505 // example when a client disconnects unexpectedly, WlSurface::destroyed() may be called
506 // before XdgShellHandler::toplevel_destroyed(). In this case, the surface will *not* have
507 // the default dmabuf pre-commit hook: it will still have the toplevel pre-commit hook.
508 //
509 // So, this may come out empty, and then the toplevel pre-commit hook will be removed in the
510 // subsequent toplevel_destroyed() call.
511 if let Some(hook) = self.niri.dmabuf_pre_commit_hook.remove(surface) {
512 remove_pre_commit_hook(surface, &hook);
513 }
514 }
515}
516
517impl BufferHandler for State {
518 fn buffer_destroyed(&mut self, _buffer: &wl_buffer::WlBuffer) {}
519}
520
521impl ShmHandler for State {
522 fn shm_state(&self) -> &ShmState {
523 &self.niri.shm_state
524 }
525}
526
527impl State {
528 pub fn add_default_dmabuf_pre_commit_hook(&mut self, surface: &WlSurface) {
529 if !surface.is_alive() {
530 error!("tried to add dmabuf pre-commit hook for a dead surface");
531 return;
532 }
533
534 let hook = add_pre_commit_hook::<Self, _>(surface, move |state, _dh, surface| {
535 let maybe_dmabuf = with_states(surface, |surface_data| {
536 surface_data
537 .cached_state
538 .get::<SurfaceAttributes>()
539 .pending()
540 .buffer
541 .as_ref()
542 .and_then(|assignment| match assignment {
543 BufferAssignment::NewBuffer(buffer) => get_dmabuf(buffer).cloned().ok(),
544 _ => None,
545 })
546 });
547 if let Some(dmabuf) = maybe_dmabuf {
548 if let Ok((blocker, source)) = dmabuf.generate_blocker(Interest::READ) {
549 if let Some(client) = surface.client() {
550 let res =
551 state
552 .niri
553 .event_loop
554 .insert_source(source, move |_, _, state| {
555 let display_handle = state.niri.display_handle.clone();
556 state
557 .client_compositor_state(&client)
558 .blocker_cleared(state, &display_handle);
559 Ok(())
560 });
561 if res.is_ok() {
562 add_blocker(surface, blocker);
563 trace!("added default dmabuf blocker");
564 }
565 }
566 }
567 }
568 });
569
570 let s = surface.clone();
571 if let Some(prev) = self.niri.dmabuf_pre_commit_hook.insert(s, hook) {
572 error!("tried to add dmabuf pre-commit hook when there was already one");
573 remove_pre_commit_hook(surface, &prev);
574 }
575 }
576
577 pub fn remove_default_dmabuf_pre_commit_hook(&mut self, surface: &WlSurface) {
578 if let Some(hook) = self.niri.dmabuf_pre_commit_hook.remove(surface) {
579 remove_pre_commit_hook(surface, &hook);
580 } else {
581 error!("tried to remove dmabuf pre-commit hook but there was none");
582 }
583 }
584}