forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

xdg_shell.rs1627 lines, 65.1 KiBHistoryRawDownload
1use std::cell::Cell;
2
3use calloop::Interest;
4use niri_config::PresetSize;
5use smithay::backend::input::InputTime;
6use smithay::desktop::{
7 find_popup_root_surface, get_popup_toplevel_coords, layer_map_for_output, utils, LayerSurface,
8 PopupKeyboardGrab, PopupKind, PopupManager, PopupPointerGrab, PopupUngrabStrategy, Window,
9 WindowSurfaceType,
10};
11use smithay::input::pointer::Focus;
12use smithay::input::tablet::TabletSeatTrait;
13use smithay::output::Output;
14use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1;
15use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_positioner::ConstraintAdjustment;
16use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::{self};
17use smithay::reexports::wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration;
18use smithay::reexports::wayland_server::protocol::wl_output;
19use smithay::reexports::wayland_server::protocol::wl_seat::WlSeat;
20use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
21use smithay::reexports::wayland_server::{self, Resource, WEnum};
22use smithay::utils::{Logical, Point, Rectangle, Serial};
23use smithay::wayland::compositor::{
24 add_blocker, add_pre_commit_hook, with_states, BufferAssignment, CompositorHandler as _,
25 HookId, SurfaceAttributes,
26};
27use smithay::wayland::dmabuf::get_dmabuf;
28use smithay::wayland::input_method::InputMethodSeat;
29use smithay::wayland::shell::kde::decoration::{KdeDecorationHandler, KdeDecorationState};
30use smithay::wayland::shell::wlr_layer::{self, Layer};
31use smithay::wayland::shell::xdg::decoration::XdgDecorationHandler;
32use smithay::wayland::shell::xdg::{
33 PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler, XdgShellState,
34 XdgToplevelSurfaceData,
35};
36use smithay::wayland::xdg_foreign::{XdgForeignHandler, XdgForeignState};
37use tracing::field::Empty;
38
39use crate::input::move_grab::MoveGrab;
40use crate::input::resize_grab::ResizeGrab;
41use crate::input::{AnyStartData, DOUBLE_CLICK_TIME};
42use crate::layout::ActivateWindow;
43use crate::niri::{CastTarget, PopupGrabState, State};
44use crate::utils::transaction::Transaction;
45use crate::utils::{
46 get_monotonic_time, output_matches_name, send_scale_transform, update_tiled_state, ResizeEdge,
47};
48use crate::window::{InitialConfigureState, ResolvedWindowRules, Unmapped, WindowRef};
49
50impl XdgShellHandler for State {
51 fn xdg_shell_state(&mut self) -> &mut XdgShellState {
52 &mut self.niri.xdg_shell_state
53 }
54
55 fn new_toplevel(&mut self, surface: ToplevelSurface) {
56 let wl_surface = surface.wl_surface().clone();
57 let unmapped = Unmapped::new(Window::new_wayland_window(surface));
58 let existing = self.niri.unmapped_windows.insert(wl_surface, unmapped);
59 assert!(existing.is_none());
60 }
61
62 fn new_popup(&mut self, surface: PopupSurface, _positioner: PositionerState) {
63 let popup = PopupKind::Xdg(surface);
64 self.unconstrain_popup(&popup);
65
66 if let Err(err) = self.niri.popups.track_popup(popup) {
67 warn!("error tracking popup: {err:?}");
68 }
69 }
70
71 fn move_request(&mut self, surface: ToplevelSurface, _seat: WlSeat, serial: Serial) {
72 let wl_surface = surface.wl_surface();
73
74 let mut grab_start_data = None;
75
76 // See if this comes from a pointer grab.
77 let pointer = self.niri.seat.get_pointer().unwrap();
78 pointer.with_grab(|grab_serial, grab| {
79 if grab_serial == serial {
80 let start_data = grab.start_data();
81 if let Some((focus, _)) = &start_data.focus {
82 if focus.id().same_client_as(&wl_surface.id()) {
83 // Deny move requests from DnD grabs to work around
84 // https://gitlab.gnome.org/GNOME/gtk/-/issues/7113
85 let is_dnd_grab = Self::is_dnd_grab(grab.as_any());
86
87 if !is_dnd_grab {
88 grab_start_data = Some(AnyStartData::Pointer(start_data.clone()));
89 }
90 }
91 }
92 }
93 });
94
95 // See if this comes from a touch grab.
96 if let Some(touch) = self.niri.seat.get_touch() {
97 touch.with_grab(|grab_serial, grab| {
98 if grab_serial == serial {
99 let start_data = grab.start_data();
100 if let Some((focus, _)) = &start_data.focus {
101 if focus.id().same_client_as(&wl_surface.id()) {
102 // Deny move requests from DnD grabs to work around
103 // https://gitlab.gnome.org/GNOME/gtk/-/issues/7113
104 let is_dnd_grab = Self::is_dnd_grab(grab.as_any());
105
106 if !is_dnd_grab {
107 grab_start_data = Some(AnyStartData::Touch(start_data.clone()));
108 }
109 }
110 }
111 }
112 });
113 }
114
115 // See if this comes from a tablet tool grab.
116 let mut tablet_tool = None;
117 let tools = self.niri.seat.tablet_seat().get_tools();
118 for tool in tools.values() {
119 let found = tool.with_grab(|grab_serial, grab| {
120 if grab_serial == serial {
121 let start_data = grab.start_data();
122 if let Some((focus, _)) = &start_data.focus {
123 if focus.id().same_client_as(&wl_surface.id()) {
124 // Deny move requests from DnD grabs to work around
125 // https://gitlab.gnome.org/GNOME/gtk/-/issues/7113
126 let is_dnd_grab = Self::is_dnd_grab(grab.as_any());
127
128 if !is_dnd_grab {
129 grab_start_data =
130 Some(AnyStartData::TabletTool(start_data.clone()));
131 tablet_tool = Some(tool.clone());
132 return true;
133 }
134 }
135 }
136 }
137 false
138 });
139 if found == Some(true) {
140 break;
141 }
142 }
143
144 let Some(start_data) = grab_start_data else {
145 return;
146 };
147
148 let Some((mapped, output)) = self.niri.layout.find_window_and_output(wl_surface) else {
149 return;
150 };
151
152 let Some(output) = output else {
153 return;
154 };
155
156 let window = mapped.window.clone();
157 let output = output.clone();
158
159 match &start_data {
160 AnyStartData::Pointer(_) => {
161 if let Some(grab) = MoveGrab::new(self, start_data, window.clone(), true, None) {
162 pointer.set_grab(self, grab, serial, Focus::Clear);
163 }
164 }
165 AnyStartData::Touch(_) => {
166 let touch = self.niri.seat.get_touch().unwrap();
167 if let Some(grab) = MoveGrab::new(self, start_data, window.clone(), true, None) {
168 touch.set_grab(self, grab, serial);
169 }
170 }
171 AnyStartData::TabletTool(_) => {
172 if let Some(grab) = MoveGrab::new(self, start_data, window.clone(), true, None) {
173 let time = InputTime::now();
174 tablet_tool
175 .unwrap()
176 .set_grab(self, grab, time, serial, Focus::Clear);
177 }
178 }
179 }
180
181 self.niri.queue_redraw(&output);
182 }
183
184 fn resize_request(
185 &mut self,
186 surface: ToplevelSurface,
187 _seat: WlSeat,
188 serial: Serial,
189 edges: xdg_toplevel::ResizeEdge,
190 ) {
191 let wl_surface = surface.wl_surface();
192
193 let mut grab_start_data = None;
194
195 // See if this comes from a pointer grab.
196 let pointer = self.niri.seat.get_pointer().unwrap();
197 if pointer.has_grab(serial) {
198 if let Some(start_data) = pointer.grab_start_data() {
199 if let Some((focus, _)) = &start_data.focus {
200 if focus.id().same_client_as(&wl_surface.id()) {
201 grab_start_data = Some(AnyStartData::Pointer(start_data));
202 }
203 }
204 }
205 }
206
207 // See if this comes from a touch grab.
208 if let Some(touch) = self.niri.seat.get_touch() {
209 if touch.has_grab(serial) {
210 if let Some(start_data) = touch.grab_start_data() {
211 if let Some((focus, _)) = &start_data.focus {
212 if focus.id().same_client_as(&wl_surface.id()) {
213 grab_start_data = Some(AnyStartData::Touch(start_data));
214 }
215 }
216 }
217 }
218 }
219
220 // See if this comes from a tablet tool grab.
221 let mut tablet_tool = None;
222 let tools = self.niri.seat.tablet_seat().get_tools();
223 'outer: for tool in tools.values() {
224 if tool.has_grab(serial) {
225 if let Some(start_data) = tool.grab_start_data() {
226 if let Some((focus, _)) = &start_data.focus {
227 if focus.id().same_client_as(&wl_surface.id()) {
228 grab_start_data = Some(AnyStartData::TabletTool(start_data));
229 tablet_tool = Some(tool.clone());
230 break 'outer;
231 }
232 }
233 }
234 }
235 }
236
237 let Some(start_data) = grab_start_data else {
238 return;
239 };
240
241 let Some((mapped, _)) = self.niri.layout.find_window_and_output(wl_surface) else {
242 return;
243 };
244
245 let edges = ResizeEdge::from(edges);
246 let window = mapped.window.clone();
247
248 // See if we got a double resize-click gesture.
249 let time = get_monotonic_time();
250 let last_cell = mapped.last_interactive_resize_start();
251 let mut last = last_cell.get();
252 last_cell.set(Some((time, edges)));
253
254 // Floating windows don't have either of the double-resize-click gestures, so just allow it
255 // to resize.
256 if mapped.is_floating() {
257 last = None;
258 last_cell.set(None);
259 }
260
261 if let Some((last_time, last_edges)) = last {
262 if time.saturating_sub(last_time) <= DOUBLE_CLICK_TIME {
263 // Allow quick resize after a triple click.
264 last_cell.set(None);
265
266 let intersection = edges.intersection(last_edges);
267 if intersection.intersects(ResizeEdge::LEFT_RIGHT) {
268 // FIXME: don't activate once we can pass specific windows to actions.
269 self.niri.layout.activate_window(&window);
270 self.niri.layer_shell_on_demand_focus = None;
271 self.niri.layout.toggle_full_width();
272 }
273 if intersection.intersects(ResizeEdge::TOP_BOTTOM) {
274 self.niri.layer_shell_on_demand_focus = None;
275 self.niri.layout.reset_window_height(Some(&window));
276 }
277 // FIXME: granular.
278 self.niri.queue_redraw_all();
279 return;
280 }
281 }
282
283 if !self
284 .niri
285 .layout
286 .interactive_resize_begin(window.clone(), edges)
287 {
288 return;
289 }
290
291 match start_data {
292 AnyStartData::Pointer(_) => {
293 let grab = ResizeGrab::new(start_data, window);
294 pointer.set_grab(self, grab, serial, Focus::Clear);
295 }
296 AnyStartData::Touch(_) => {
297 let touch = self.niri.seat.get_touch().unwrap();
298 let grab = ResizeGrab::new(start_data, window);
299 touch.set_grab(self, grab, serial);
300 }
301 AnyStartData::TabletTool(_) => {
302 let grab = ResizeGrab::new(start_data, window);
303 let time = InputTime::now();
304 tablet_tool
305 .unwrap()
306 .set_grab(self, grab, time, serial, Focus::Clear);
307 }
308 }
309 }
310
311 fn reposition_request(
312 &mut self,
313 surface: PopupSurface,
314 positioner: PositionerState,
315 token: u32,
316 ) {
317 surface.with_pending_state(|state| {
318 let geometry = positioner.get_geometry();
319 state.geometry = geometry;
320 state.positioner = positioner;
321 });
322 self.unconstrain_popup(&PopupKind::Xdg(surface.clone()));
323 surface.send_repositioned(token);
324 }
325
326 fn grab(&mut self, surface: PopupSurface, _seat: WlSeat, serial: Serial) {
327 let popup = PopupKind::Xdg(surface);
328 let Ok(root) = find_popup_root_surface(&popup) else {
329 trace!("ignoring popup grab because no root surface");
330 return;
331 };
332
333 // We need to hand out the grab in a way consistent with what update_keyboard_focus()
334 // thinks the current focus is, otherwise it will desync and cause weird issues with
335 // keyboard focus being at the wrong place.
336 if self.niri.exit_confirm_dialog.is_open() {
337 trace!("ignoring popup grab because the exit confirm dialog is open");
338 let _ = PopupManager::dismiss_popup(&root, &popup);
339 return;
340 } else if self.niri.is_locked() {
341 if Some(&root) != self.niri.lock_surface_focus().as_ref() {
342 trace!("ignoring popup grab because the session is locked");
343 let _ = PopupManager::dismiss_popup(&root, &popup);
344 return;
345 }
346 } else if self.niri.screenshot_ui.is_open() {
347 trace!("ignoring popup grab because the screenshot UI is open");
348 let _ = PopupManager::dismiss_popup(&root, &popup);
349 return;
350 } else if let Some(output) = self.niri.layout.active_output() {
351 let layers = layer_map_for_output(output);
352
353 // FIXME: somewhere here we probably need to check is_overview_open to match the logic
354 // in update_keyboard_focus().
355
356 if let Some(layer) = layers.layer_for_surface(&root, WindowSurfaceType::TOPLEVEL) {
357 // This is a grab for a layer surface.
358
359 if let Some(mapped) = self.niri.mapped_layer_surfaces.get(layer) {
360 if mapped.place_within_backdrop() {
361 trace!("ignoring popup grab for a layer surface within overview backdrop");
362 let _ = PopupManager::dismiss_popup(&root, &popup);
363 return;
364 }
365 }
366 } else {
367 // This is a grab for a regular window; check that there's no layer surface with a
368 // higher input priority.
369
370 if layers.layers_on(Layer::Overlay).any(|l| {
371 (l.cached_state().keyboard_interactivity
372 == wlr_layer::KeyboardInteractivity::Exclusive
373 || Some(l) == self.niri.layer_shell_on_demand_focus.as_ref())
374 && self.niri.mapped_layer_surfaces.contains_key(l)
375 }) {
376 trace!("ignoring toplevel popup grab because the overlay layer has focus");
377 let _ = PopupManager::dismiss_popup(&root, &popup);
378 return;
379 }
380
381 let mon = self.niri.layout.monitor_for_output(output).unwrap();
382 if !mon.render_above_top_layer()
383 && layers.layers_on(Layer::Top).any(|l| {
384 (l.cached_state().keyboard_interactivity
385 == wlr_layer::KeyboardInteractivity::Exclusive
386 || Some(l) == self.niri.layer_shell_on_demand_focus.as_ref())
387 && self.niri.mapped_layer_surfaces.contains_key(l)
388 })
389 {
390 trace!("ignoring toplevel popup grab because the top layer has focus");
391 let _ = PopupManager::dismiss_popup(&root, &popup);
392 return;
393 }
394
395 let layout_focus = self.niri.layout.focus();
396 if Some(&root) != layout_focus.map(|win| win.toplevel().wl_surface()) {
397 trace!("ignoring toplevel popup grab because another window has focus");
398 let _ = PopupManager::dismiss_popup(&root, &popup);
399 return;
400 }
401 }
402 } else {
403 trace!("ignoring popup grab because no output is active");
404 let _ = PopupManager::dismiss_popup(&root, &popup);
405 return;
406 }
407
408 let seat = &self.niri.seat;
409 let mut grab = match self
410 .niri
411 .popups
412 .grab_popup(root.clone(), popup, seat, serial)
413 {
414 Ok(grab) => grab,
415 Err(err) => {
416 trace!("ignoring popup grab: {err:?}");
417 return;
418 }
419 };
420
421 let keyboard = seat.get_keyboard().unwrap();
422 let pointer = seat.get_pointer().unwrap();
423
424 // Smithay cannot do overlapping grabs, so if we have an IME keyboard grab, don't overwrite
425 // it with a popup keyboard grab. This makes the popup menu work in Telegram while an IME
426 // is active (otherwise it hits the grab mismatch check below).
427 //
428 // The second check is for layer surfaces that can't receive keyboard focus, without it
429 // popups don't work properly in Waybar (GTK 3).
430 let can_receive_keyboard_focus = !self.niri.seat.input_method().keyboard_grabbed()
431 && self
432 .niri
433 .layout
434 .active_output()
435 .and_then(|output| {
436 layer_map_for_output(output)
437 .layer_for_surface(&root, WindowSurfaceType::TOPLEVEL)
438 .map(|layer_surface| layer_surface.can_receive_keyboard_focus())
439 })
440 .unwrap_or(true);
441
442 let keyboard_grab_mismatches = keyboard.is_grabbed()
443 && !(keyboard.has_grab(serial)
444 || grab.previous_serial().is_none_or(|s| keyboard.has_grab(s)));
445 let pointer_grab_mismatches = pointer.is_grabbed()
446 && !(pointer.has_grab(serial)
447 || grab.previous_serial().is_none_or(|s| pointer.has_grab(s)));
448 if (can_receive_keyboard_focus && keyboard_grab_mismatches) || pointer_grab_mismatches {
449 trace!("ignoring popup grab because of current grab mismatch");
450 grab.ungrab(PopupUngrabStrategy::All);
451 return;
452 }
453
454 trace!("new grab for root {:?}", root);
455 if can_receive_keyboard_focus {
456 keyboard.set_grab(self, PopupKeyboardGrab::new(&grab), serial);
457 }
458 pointer.set_grab(self, PopupPointerGrab::new(&grab), serial, Focus::Keep);
459 self.niri.popup_grab = Some(PopupGrabState {
460 root,
461 grab,
462 has_keyboard_grab: can_receive_keyboard_focus,
463 });
464 }
465
466 fn maximize_request(&mut self, toplevel: ToplevelSurface) {
467 if let Some((mapped, _)) = self
468 .niri
469 .layout
470 .find_window_and_output_mut(toplevel.wl_surface())
471 {
472 // A configure is required in response to this event regardless if there are pending
473 // changes.
474 mapped.set_needs_configure();
475
476 let window = mapped.window.clone();
477 self.niri.layout.set_maximized(&window, true);
478 } else if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
479 match &mut unmapped.state {
480 InitialConfigureState::NotConfigured {
481 wants_maximized, ..
482 } => {
483 *wants_maximized = true;
484
485 // The required configure will be the initial configure.
486 }
487 InitialConfigureState::Configured {
488 rules,
489 output,
490 is_pending_maximized,
491 ..
492 } => {
493 // Figure out the monitor following a similar logic to initial configure.
494 // FIXME: deduplicate.
495 let mon = output
496 .as_ref()
497 .and_then(|o| self.niri.layout.monitor_for_output(o))
498 .map(|mon| (mon, false))
499 // If not, check if we have a parent with a monitor.
500 .or_else(|| {
501 toplevel
502 .parent()
503 .and_then(|parent| self.niri.layout.find_window_and_output(&parent))
504 .and_then(|(_win, output)| output)
505 .and_then(|o| self.niri.layout.monitor_for_output(o))
506 .map(|mon| (mon, true))
507 })
508 // If not, fall back to the active monitor.
509 .or_else(|| {
510 self.niri
511 .layout
512 .active_monitor_ref()
513 .map(|mon| (mon, false))
514 });
515
516 *output = mon
517 .filter(|(_, parent)| !parent)
518 .map(|(mon, _)| mon.output().clone());
519 let mon = mon.map(|(mon, _)| mon);
520
521 let ws = mon
522 .map(|mon| mon.active_workspace_ref())
523 .or_else(|| self.niri.layout.active_workspace());
524
525 if let Some(ws) = ws {
526 // If the window is pending fullscreen, then this will do nothing. But
527 // that's expected: the window remains fullscreen, and we simply remember
528 // that it is now pending maximized.
529 *is_pending_maximized = true;
530 toplevel.with_pending_state(|state| {
531 if !state.states.contains(xdg_toplevel::State::Fullscreen) {
532 state.states.set(xdg_toplevel::State::Maximized);
533 }
534 });
535 ws.configure_new_window(&unmapped.window, None, None, false, rules);
536 }
537
538 // We already sent the initial configure, so we need to reconfigure.
539 toplevel.send_configure();
540 }
541 }
542 } else {
543 error!("couldn't find the toplevel in maximize_request()");
544 toplevel.send_configure();
545 }
546 }
547
548 fn unmaximize_request(&mut self, toplevel: ToplevelSurface) {
549 if let Some((mapped, _)) = self
550 .niri
551 .layout
552 .find_window_and_output_mut(toplevel.wl_surface())
553 {
554 // A configure is required in response to this event regardless if there are pending
555 // changes.
556 mapped.set_needs_configure();
557
558 let window = mapped.window.clone();
559 self.niri.layout.set_maximized(&window, false);
560 } else if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
561 match &mut unmapped.state {
562 InitialConfigureState::NotConfigured {
563 wants_maximized, ..
564 } => {
565 *wants_maximized = false;
566
567 // The required configure will be the initial configure.
568 }
569 InitialConfigureState::Configured {
570 rules,
571 width,
572 height,
573 floating_width,
574 floating_height,
575 is_full_width,
576 output,
577 workspace_name,
578 is_pending_maximized,
579 } => {
580 // Figure out the monitor following a similar logic to initial configure.
581 // FIXME: deduplicate.
582 let mon = workspace_name
583 .as_deref()
584 .and_then(|name| self.niri.layout.monitor_for_workspace(name))
585 .map(|mon| (mon, false));
586
587 let mon = mon.or_else(|| {
588 output
589 .as_ref()
590 .and_then(|o| self.niri.layout.monitor_for_output(o))
591 .map(|mon| (mon, false))
592 // If not, check if we have a parent with a monitor.
593 .or_else(|| {
594 toplevel
595 .parent()
596 .and_then(|parent| {
597 self.niri.layout.find_window_and_output(&parent)
598 })
599 .and_then(|(_win, output)| output)
600 .and_then(|o| self.niri.layout.monitor_for_output(o))
601 .map(|mon| (mon, true))
602 })
603 // If not, fall back to the active monitor.
604 .or_else(|| {
605 self.niri
606 .layout
607 .active_monitor_ref()
608 .map(|mon| (mon, false))
609 })
610 });
611
612 *output = mon
613 .filter(|(_, parent)| !parent)
614 .map(|(mon, _)| mon.output().clone());
615 let mon = mon.map(|(mon, _)| mon);
616
617 let ws = workspace_name
618 .as_deref()
619 .and_then(|name| mon.map(|mon| mon.find_named_workspace(name)))
620 .unwrap_or_else(|| {
621 mon.map(|mon| mon.active_workspace_ref())
622 .or_else(|| self.niri.layout.active_workspace())
623 });
624
625 if let Some(ws) = ws {
626 // If the window is pending fullscreen, then this will do nothing since
627 // then the Maximized state is already unset. But that's expected: the
628 // window remains fullscreen, and we simply remember that it is no
629 // longer pending maximized.
630 *is_pending_maximized = false;
631 toplevel.with_pending_state(|state| {
632 state.states.unset(xdg_toplevel::State::Maximized);
633 });
634
635 let is_floating = rules.compute_open_floating(&toplevel);
636 let configure_width = if is_floating {
637 *floating_width
638 } else if *is_full_width {
639 Some(PresetSize::Proportion(1.))
640 } else {
641 *width
642 };
643 let configure_height = if is_floating {
644 *floating_height
645 } else {
646 *height
647 };
648 ws.configure_new_window(
649 &unmapped.window,
650 configure_width,
651 configure_height,
652 is_floating,
653 rules,
654 );
655 }
656
657 // We already sent the initial configure, so we need to reconfigure.
658 toplevel.send_configure();
659 }
660 }
661 } else {
662 error!("couldn't find the toplevel in unmaximize_request()");
663 toplevel.send_configure();
664 }
665 }
666
667 fn fullscreen_request(
668 &mut self,
669 toplevel: ToplevelSurface,
670 wl_output: Option<wl_output::WlOutput>,
671 ) {
672 let requested_output = wl_output.and_then(|o| self.niri.output_from_resource(&o));
673
674 if let Some((mapped, current_output)) = self
675 .niri
676 .layout
677 .find_window_and_output_mut(toplevel.wl_surface())
678 {
679 // A configure is required in response to this event regardless if there are pending
680 // changes.
681 mapped.set_needs_configure();
682
683 let window = mapped.window.clone();
684
685 if let Some(requested_output) = requested_output {
686 if Some(&requested_output) != current_output {
687 self.niri.layout.move_to_output(
688 Some(&window),
689 &requested_output,
690 None,
691 ActivateWindow::Smart,
692 );
693 }
694 }
695
696 self.niri.layout.set_fullscreen(&window, true);
697 } else if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
698 match &mut unmapped.state {
699 InitialConfigureState::NotConfigured {
700 wants_fullscreen, ..
701 } => {
702 *wants_fullscreen = Some(requested_output);
703
704 // The required configure will be the initial configure.
705 }
706 InitialConfigureState::Configured { rules, output, .. } => {
707 // Figure out the monitor following a similar logic to initial configure.
708 // FIXME: deduplicate.
709 let mon = requested_output
710 .as_ref()
711 // If none requested, try currently configured output.
712 .or(output.as_ref())
713 .and_then(|o| self.niri.layout.monitor_for_output(o))
714 .map(|mon| (mon, false))
715 // If not, check if we have a parent with a monitor.
716 .or_else(|| {
717 toplevel
718 .parent()
719 .and_then(|parent| self.niri.layout.find_window_and_output(&parent))
720 .and_then(|(_win, output)| output)
721 .and_then(|o| self.niri.layout.monitor_for_output(o))
722 .map(|mon| (mon, true))
723 })
724 // If not, fall back to the active monitor.
725 .or_else(|| {
726 self.niri
727 .layout
728 .active_monitor_ref()
729 .map(|mon| (mon, false))
730 });
731
732 *output = mon
733 .filter(|(_, parent)| !parent)
734 .map(|(mon, _)| mon.output().clone());
735 let mon = mon.map(|(mon, _)| mon);
736
737 let ws = mon
738 .map(|mon| mon.active_workspace_ref())
739 .or_else(|| self.niri.layout.active_workspace());
740
741 if let Some(ws) = ws {
742 toplevel.with_pending_state(|state| {
743 state.states.set(xdg_toplevel::State::Fullscreen);
744 state.states.unset(xdg_toplevel::State::Maximized);
745 });
746 ws.configure_new_window(&unmapped.window, None, None, false, rules);
747 }
748
749 // We already sent the initial configure, so we need to reconfigure.
750 toplevel.send_configure();
751 }
752 }
753 } else {
754 error!("couldn't find the toplevel in fullscreen_request()");
755 toplevel.send_configure();
756 }
757 }
758
759 fn unfullscreen_request(&mut self, toplevel: ToplevelSurface) {
760 if let Some((mapped, _)) = self
761 .niri
762 .layout
763 .find_window_and_output_mut(toplevel.wl_surface())
764 {
765 // A configure is required in response to this event regardless if there are pending
766 // changes.
767 mapped.set_needs_configure();
768
769 let window = mapped.window.clone();
770 self.niri.layout.set_fullscreen(&window, false);
771 } else if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
772 match &mut unmapped.state {
773 InitialConfigureState::NotConfigured {
774 wants_fullscreen, ..
775 } => {
776 *wants_fullscreen = None;
777
778 // The required configure will be the initial configure.
779 }
780 InitialConfigureState::Configured {
781 rules,
782 width,
783 height,
784 floating_width,
785 floating_height,
786 is_full_width,
787 output,
788 workspace_name,
789 is_pending_maximized,
790 } => {
791 // Figure out the monitor following a similar logic to initial configure.
792 // FIXME: deduplicate.
793 let mon = workspace_name
794 .as_deref()
795 .and_then(|name| self.niri.layout.monitor_for_workspace(name))
796 .map(|mon| (mon, false));
797
798 let mon = mon.or_else(|| {
799 output
800 .as_ref()
801 .and_then(|o| self.niri.layout.monitor_for_output(o))
802 .map(|mon| (mon, false))
803 // If not, check if we have a parent with a monitor.
804 .or_else(|| {
805 toplevel
806 .parent()
807 .and_then(|parent| {
808 self.niri.layout.find_window_and_output(&parent)
809 })
810 .and_then(|(_win, output)| output)
811 .and_then(|o| self.niri.layout.monitor_for_output(o))
812 .map(|mon| (mon, true))
813 })
814 // If not, fall back to the active monitor.
815 .or_else(|| {
816 self.niri
817 .layout
818 .active_monitor_ref()
819 .map(|mon| (mon, false))
820 })
821 });
822
823 *output = mon
824 .filter(|(_, parent)| !parent)
825 .map(|(mon, _)| mon.output().clone());
826 let mon = mon.map(|(mon, _)| mon);
827
828 let ws = workspace_name
829 .as_deref()
830 .and_then(|name| mon.map(|mon| mon.find_named_workspace(name)))
831 .unwrap_or_else(|| {
832 mon.map(|mon| mon.active_workspace_ref())
833 .or_else(|| self.niri.layout.active_workspace())
834 });
835
836 if let Some(ws) = ws {
837 toplevel.with_pending_state(|state| {
838 state.states.unset(xdg_toplevel::State::Fullscreen);
839
840 if *is_pending_maximized {
841 state.states.set(xdg_toplevel::State::Maximized);
842 }
843 });
844
845 let is_floating = rules.compute_open_floating(&toplevel);
846 let configure_width = if is_floating {
847 *floating_width
848 } else if *is_full_width {
849 Some(PresetSize::Proportion(1.))
850 } else {
851 *width
852 };
853 let configure_height = if is_floating {
854 *floating_height
855 } else {
856 *height
857 };
858 ws.configure_new_window(
859 &unmapped.window,
860 configure_width,
861 configure_height,
862 is_floating,
863 rules,
864 );
865 }
866
867 // We already sent the initial configure, so we need to reconfigure.
868 toplevel.send_configure();
869 }
870 }
871 } else {
872 error!("couldn't find the toplevel in unfullscreen_request()");
873 toplevel.send_configure();
874 }
875 }
876
877 fn toplevel_destroyed(&mut self, surface: ToplevelSurface) {
878 if self
879 .niri
880 .unmapped_windows
881 .remove(surface.wl_surface())
882 .is_some()
883 {
884 // An unmapped toplevel got destroyed.
885 return;
886 }
887
888 let win_out = self
889 .niri
890 .layout
891 .find_window_and_output(surface.wl_surface());
892
893 let Some((mapped, output)) = win_out else {
894 // I have no idea how this can happen, but I saw it happen once, in a weird interaction
895 // involving laptop going to sleep and resuming.
896 error!("toplevel missing from both unmapped_windows and layout");
897 return;
898 };
899 let window = mapped.window.clone();
900 let output = output.cloned();
901
902 let id = mapped.id();
903 self.niri
904 .stop_casts_for_target(CastTarget::Window { id: id.get() });
905
906 self.store_unmap_snapshot(&window, output.as_ref());
907
908 let transaction = Transaction::new();
909 let blocker = transaction.blocker();
910 self.backend.with_primary_renderer(|renderer| {
911 self.niri
912 .layout
913 .start_close_animation_for_window(renderer, &window, blocker);
914 });
915
916 let active_window = self.niri.layout.focus().map(|m| &m.window);
917 let was_active = active_window == Some(&window);
918
919 self.niri.window_mru_ui.remove_window(id);
920 self.niri.layout.remove_window(&window, transaction.clone());
921
922 let surface = surface.wl_surface();
923 // This check is necessary because implicit resource destruction is done with
924 // undefined order, so the surface might get destroyed before toplevel_destroyed() is
925 // called. In this case, adding the default pre-commit hook here would leak it, since the
926 // place that removes it is WlSurface::destroyed(), which had already been called by now.
927 if surface.is_alive() {
928 self.add_default_dmabuf_pre_commit_hook(surface);
929 }
930
931 // If this is the only instance, then this transaction will complete immediately, so no
932 // need to set the timer.
933 if !transaction.is_last() {
934 transaction.register_deadline_timer(&self.niri.event_loop);
935 }
936
937 if was_active {
938 self.maybe_warp_cursor_to_focus();
939 }
940
941 if let Some(output) = output {
942 self.niri.queue_redraw(&output);
943 self.niri.queue_redraw_mru_output();
944 }
945 }
946
947 fn popup_destroyed(&mut self, surface: PopupSurface) {
948 if let Some(output) = self.output_for_popup(&PopupKind::Xdg(surface)) {
949 self.niri.queue_redraw(&output.clone());
950 }
951 }
952
953 fn app_id_changed(&mut self, toplevel: ToplevelSurface) {
954 self.update_window_rules(&toplevel);
955 }
956
957 fn title_changed(&mut self, toplevel: ToplevelSurface) {
958 self.update_window_rules(&toplevel);
959 }
960
961 fn parent_changed(&mut self, toplevel: ToplevelSurface) {
962 let Some(parent) = toplevel.parent() else {
963 return;
964 };
965
966 if let Some((mapped, output)) = self.niri.layout.find_window_and_output_mut(&parent) {
967 let output = output.cloned();
968 let window = mapped.window.clone();
969 if self.niri.layout.descendants_added(&window) {
970 if let Some(output) = output {
971 self.niri.queue_redraw(&output);
972 }
973 }
974 }
975 }
976}
977
978impl XdgDecorationHandler for State {
979 fn new_decoration(&mut self, toplevel: ToplevelSurface) {
980 // If we want CSD, we hide this global altogether.
981 toplevel.with_pending_state(|state| {
982 state.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide);
983 });
984 }
985
986 fn request_mode(&mut self, toplevel: ToplevelSurface, mode: zxdg_toplevel_decoration_v1::Mode) {
987 // Set whatever the client wants, rather than our preferred mode. This especially matters
988 // for SDL2 which has a bug where forcing a different (client-side) decoration mode during
989 // their window creation sequence would leave the window permanently hidden.
990 //
991 // https://github.com/libsdl-org/SDL/issues/8173
992 //
993 // The bug has been fixed, but there's a ton of apps which will use the buggy version for a
994 // long while...
995 toplevel.with_pending_state(|state| {
996 state.decoration_mode = Some(mode);
997 });
998
999 // A configure is required in response to this event. However, if an initial configure
1000 // wasn't sent, then we will send this as part of the initial configure later.
1001 if toplevel.is_initial_configure_sent() {
1002 // If this is a mapped window, flag it as needs configure to avoid duplicate configures.
1003 let surface = toplevel.wl_surface();
1004 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
1005 mapped.set_needs_configure();
1006 } else {
1007 toplevel.send_configure();
1008 }
1009 }
1010 }
1011
1012 fn unset_mode(&mut self, toplevel: ToplevelSurface) {
1013 // If we want CSD, we hide this global altogether.
1014 toplevel.with_pending_state(|state| {
1015 state.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide);
1016 });
1017
1018 // A configure is required in response to this event. However, if an initial configure
1019 // wasn't sent, then we will send this as part of the initial configure later.
1020 if toplevel.is_initial_configure_sent() {
1021 // If this is a mapped window, flag it as needs configure to avoid duplicate configures.
1022 let surface = toplevel.wl_surface();
1023 if let Some((mapped, _)) = self.niri.layout.find_window_and_output_mut(surface) {
1024 mapped.set_needs_configure();
1025 } else {
1026 toplevel.send_configure();
1027 }
1028 }
1029 }
1030}
1031
1032/// Whether KDE server decorations are in use.
1033#[derive(Default, Clone)]
1034pub struct KdeDecorationsModeState {
1035 server: Cell<bool>,
1036}
1037
1038impl KdeDecorationsModeState {
1039 pub fn is_server(&self) -> bool {
1040 self.server.get()
1041 }
1042}
1043
1044impl KdeDecorationHandler for State {
1045 fn kde_decoration_state(&self) -> &KdeDecorationState {
1046 &self.niri.kde_decoration_state
1047 }
1048
1049 fn request_mode(
1050 &mut self,
1051 surface: &WlSurface,
1052 decoration: &org_kde_kwin_server_decoration::OrgKdeKwinServerDecoration,
1053 mode: wayland_server::WEnum<org_kde_kwin_server_decoration::Mode>,
1054 ) {
1055 let WEnum::Value(mode) = mode else {
1056 return;
1057 };
1058
1059 decoration.mode(mode);
1060
1061 with_states(surface, |states| {
1062 let state = states
1063 .data_map
1064 .get_or_insert(KdeDecorationsModeState::default);
1065 state
1066 .server
1067 .set(mode == org_kde_kwin_server_decoration::Mode::Server);
1068 });
1069 }
1070}
1071
1072impl XdgForeignHandler for State {
1073 fn xdg_foreign_state(&mut self) -> &mut XdgForeignState {
1074 &mut self.niri.xdg_foreign_state
1075 }
1076}
1077
1078impl State {
1079 pub fn send_initial_configure(&mut self, toplevel: &ToplevelSurface) {
1080 let _span = tracy_client::span!("State::send_initial_configure");
1081
1082 let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) else {
1083 error!("window must be present in unmapped_windows in send_initial_configure()");
1084 return;
1085 };
1086
1087 let config = self.niri.config.borrow();
1088 let rules = ResolvedWindowRules::compute(
1089 &config.window_rules,
1090 WindowRef::Unmapped(unmapped),
1091 self.niri.is_at_startup,
1092 );
1093
1094 let Unmapped { window, state, .. } = unmapped;
1095
1096 let InitialConfigureState::NotConfigured {
1097 wants_fullscreen,
1098 wants_maximized,
1099 } = state
1100 else {
1101 error!("window must not be already configured in send_initial_configure()");
1102 return;
1103 };
1104
1105 // Pick the target monitor. First, check if we had a workspace set in the window rules.
1106 let mon = rules
1107 .open_on_workspace
1108 .as_deref()
1109 .and_then(|name| self.niri.layout.monitor_for_workspace(name));
1110
1111 // If not, check if we had an output set in the window rules.
1112 let mon = mon.or_else(|| {
1113 rules
1114 .open_on_output
1115 .as_deref()
1116 .and_then(|name| {
1117 self.niri
1118 .global_space
1119 .outputs()
1120 .find(|output| output_matches_name(output, name))
1121 })
1122 .and_then(|o| self.niri.layout.monitor_for_output(o))
1123 });
1124
1125 // If not, check if the window requested one for fullscreen.
1126 let mon = mon.or_else(|| {
1127 wants_fullscreen
1128 .as_ref()
1129 .and_then(|x| x.as_ref())
1130 // The monitor might not exist if the output was disconnected.
1131 .and_then(|o| self.niri.layout.monitor_for_output(o))
1132 });
1133
1134 // If not, check if this is a dialog with a parent, to place it next to the parent.
1135 let mon = mon.map(|mon| (mon, false)).or_else(|| {
1136 toplevel
1137 .parent()
1138 .and_then(|parent| self.niri.layout.find_window_and_output(&parent))
1139 .and_then(|(_win, output)| output)
1140 .and_then(|o| self.niri.layout.monitor_for_output(o))
1141 .map(|mon| (mon, true))
1142 });
1143
1144 // If not, use the active monitor.
1145 let mon = mon.or_else(|| {
1146 self.niri
1147 .layout
1148 .active_monitor_ref()
1149 .map(|mon| (mon, false))
1150 });
1151
1152 // If we're following the parent, don't set the target output, so that when the window is
1153 // mapped, it fetches the possibly changed parent's output again, and shows up there.
1154 let output = mon
1155 .filter(|(_, parent)| !parent)
1156 .map(|(mon, _)| mon.output().clone());
1157 let mon = mon.map(|(mon, _)| mon);
1158
1159 let mut width = None;
1160 let mut floating_width = None;
1161 let mut height = None;
1162 let mut floating_height = None;
1163 let is_full_width = rules.open_maximized.unwrap_or(false);
1164 let is_floating = rules.compute_open_floating(toplevel);
1165
1166 // Tell the surface the preferred size and bounds for its likely output.
1167 let ws = rules
1168 .open_on_workspace
1169 .as_deref()
1170 .and_then(|name| mon.map(|mon| mon.find_named_workspace(name)))
1171 .unwrap_or_else(|| {
1172 mon.map(|mon| mon.active_workspace_ref())
1173 .or_else(|| self.niri.layout.active_workspace())
1174 });
1175
1176 let mut is_pending_maximized = false;
1177 if let Some(ws) = ws {
1178 // Set a fullscreen and maximized state based on window request and window rule.
1179 is_pending_maximized = (*wants_maximized && rules.open_maximized_to_edges.is_none())
1180 || rules.open_maximized_to_edges == Some(true);
1181
1182 if (wants_fullscreen.is_some() && rules.open_fullscreen.is_none())
1183 || rules.open_fullscreen == Some(true)
1184 {
1185 toplevel.with_pending_state(|state| {
1186 state.states.set(xdg_toplevel::State::Fullscreen);
1187 });
1188 } else if is_pending_maximized {
1189 toplevel.with_pending_state(|state| {
1190 state.states.set(xdg_toplevel::State::Maximized);
1191 });
1192 }
1193
1194 width = ws.resolve_default_width(rules.default_width, false);
1195 floating_width = ws.resolve_default_width(rules.default_width, true);
1196 height = ws.resolve_default_height(rules.default_height, false);
1197 floating_height = ws.resolve_default_height(rules.default_height, true);
1198
1199 let configure_width = if is_floating {
1200 floating_width
1201 } else if is_full_width {
1202 Some(PresetSize::Proportion(1.))
1203 } else {
1204 width
1205 };
1206 let configure_height = if is_floating { floating_height } else { height };
1207 ws.configure_new_window(
1208 window,
1209 configure_width,
1210 configure_height,
1211 is_floating,
1212 &rules,
1213 );
1214 }
1215
1216 // Set the tiled state for the initial configure.
1217 update_tiled_state(toplevel, config.prefer_no_csd, rules.tiled_state);
1218
1219 // Set the configured settings.
1220 *state = InitialConfigureState::Configured {
1221 rules,
1222 width,
1223 height,
1224 floating_width,
1225 floating_height,
1226 is_full_width,
1227 output,
1228 workspace_name: ws.and_then(|w| w.name().cloned()),
1229 is_pending_maximized,
1230 };
1231
1232 trace!(surface = %toplevel.wl_surface().id(), "sending initial configure");
1233 toplevel.send_configure();
1234 }
1235
1236 pub fn queue_initial_configure(&self, toplevel: ToplevelSurface) {
1237 // Send the initial configure in an idle, in case the client sent some more info after the
1238 // initial commit.
1239 self.niri.event_loop.insert_idle(move |state| {
1240 if !toplevel.alive() {
1241 return;
1242 }
1243
1244 if let Some(unmapped) = state.niri.unmapped_windows.get(toplevel.wl_surface()) {
1245 if unmapped.needs_initial_configure() {
1246 state.send_initial_configure(&toplevel);
1247 }
1248 }
1249 });
1250 }
1251
1252 /// Should be called on `WlSurface::commit`
1253 pub fn popups_handle_commit(&mut self, surface: &WlSurface) {
1254 self.niri.popups.commit(surface);
1255
1256 if let Some(popup) = self.niri.popups.find_popup(surface) {
1257 match popup {
1258 PopupKind::Xdg(ref popup) => {
1259 if !popup.is_initial_configure_sent() {
1260 if let Some(output) = self.output_for_popup(&PopupKind::Xdg(popup.clone()))
1261 {
1262 let scale = output.current_scale();
1263 let transform = output.current_transform();
1264 with_states(surface, |data| {
1265 send_scale_transform(surface, data, scale, transform);
1266 });
1267 }
1268 popup.send_configure().expect("initial configure failed");
1269 }
1270 }
1271 // Input method popup can arbitrary change its geometry, so we need to unconstrain
1272 // it on commit.
1273 PopupKind::InputMethod(_) => {
1274 self.unconstrain_popup(&popup);
1275 }
1276 }
1277 }
1278 }
1279
1280 pub fn output_for_popup(&self, popup: &PopupKind) -> Option<&Output> {
1281 let root = find_popup_root_surface(popup).ok()?;
1282 self.niri.output_for_root(&root)
1283 }
1284
1285 pub fn unconstrain_popup(&self, popup: &PopupKind) {
1286 let _span = tracy_client::span!("Niri::unconstrain_popup");
1287
1288 // Popups with a NULL parent will get repositioned in their respective protocol handlers
1289 // (i.e. layer-shell).
1290 let Ok(root) = find_popup_root_surface(popup) else {
1291 return;
1292 };
1293
1294 // Figure out if the root is a window or a layer surface.
1295 if let Some((mapped, _)) = self.niri.layout.find_window_and_output(&root) {
1296 self.unconstrain_window_popup(popup, &mapped.window);
1297 } else if let Some((layer_surface, output)) = self.niri.layout.outputs().find_map(|o| {
1298 let map = layer_map_for_output(o);
1299 let layer_surface = map.layer_for_surface(&root, WindowSurfaceType::TOPLEVEL)?;
1300 Some((layer_surface.clone(), o))
1301 }) {
1302 self.unconstrain_layer_shell_popup(popup, &layer_surface, output);
1303 }
1304 }
1305
1306 fn unconstrain_window_popup(&self, popup: &PopupKind, window: &Window) {
1307 let ime = matches!(popup, PopupKind::InputMethod(_));
1308
1309 // The target geometry for the positioner should be relative to its parent's geometry, so
1310 // we will compute that here.
1311 let mut target = self.niri.layout.popup_target_rect(window, ime);
1312 target.loc -= get_popup_toplevel_coords(popup).to_f64();
1313
1314 let geo_off = window.geometry().loc.to_f64();
1315
1316 // Don't add padding for IME popups; better to give them more space.
1317 self.position_popup_within_rect(popup, geo_off, target, !ime);
1318 }
1319
1320 pub fn unconstrain_layer_shell_popup(
1321 &self,
1322 popup: &PopupKind,
1323 layer_surface: &LayerSurface,
1324 output: &Output,
1325 ) {
1326 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
1327 let map = layer_map_for_output(output);
1328 let Some(layer_geo) = map.layer_geometry(layer_surface) else {
1329 return;
1330 };
1331
1332 // The target geometry for the positioner should be relative to its parent's geometry, so
1333 // we will compute that here.
1334 let mut target = Rectangle::from_size(output_geo.size);
1335
1336 // Background and bottom layer popups render below the top and the overlay layer, so let's
1337 // put them into the non-exclusive zone.
1338 //
1339 // FIXME: ideally this should use the "top and overlay layer" non-exclusive zone, but
1340 // Smithay only computes the "all layers" non-exclusive zone atm.
1341 //
1342 // FIXME: related to the above, top layer popups should use the "overlay layer"
1343 // non-exclusive zone.
1344 if matches!(layer_surface.layer(), Layer::Background | Layer::Bottom) {
1345 target = map.non_exclusive_zone();
1346 }
1347
1348 target.loc -= layer_geo.loc;
1349 target.loc -= get_popup_toplevel_coords(popup);
1350
1351 // Layer surfaces don't have geometry.
1352 let geo_off = Point::new(0., 0.);
1353
1354 // Don't add padding to layer-shell popups. It's not really needed, and it's unexpected.
1355 self.position_popup_within_rect(popup, geo_off, target.to_f64(), false);
1356 }
1357
1358 fn position_popup_within_rect(
1359 &self,
1360 popup: &PopupKind,
1361 geo_off: Point<f64, Logical>,
1362 target: Rectangle<f64, Logical>,
1363 padding: bool,
1364 ) {
1365 match popup {
1366 PopupKind::Xdg(popup) => {
1367 popup.with_pending_state(|state| {
1368 state.geometry = if padding {
1369 unconstrain_with_padding(state.positioner, target)
1370 } else {
1371 state
1372 .positioner
1373 .get_unconstrained_geometry(target.to_i32_round())
1374 };
1375 });
1376 }
1377 PopupKind::InputMethod(popup) => {
1378 // IME popups are positioned in surface-local coordinates, but target is in
1379 // geometry-relative coordinates.
1380 let mut target = target;
1381 target.loc += geo_off;
1382
1383 let text_input_rectangle = popup.text_input_rectangle();
1384 let mut bbox =
1385 utils::bbox_from_surface_tree(popup.wl_surface(), text_input_rectangle.loc)
1386 .to_f64();
1387
1388 // Position bbox horizontally first.
1389 let overflow_x = (bbox.loc.x + bbox.size.w) - (target.loc.x + target.size.w);
1390 if overflow_x > 0. {
1391 bbox.loc.x -= overflow_x;
1392 }
1393
1394 // Ensure that the popup starts within the target rect.
1395 bbox.loc.x = f64::max(bbox.loc.x, target.loc.x);
1396
1397 // Try to position IME popup below the text input rectangle.
1398 let mut below = bbox;
1399 below.loc.y += f64::from(text_input_rectangle.size.h);
1400
1401 let mut above = bbox;
1402 above.loc.y -= bbox.size.h;
1403
1404 if target.loc.y + target.size.h >= below.loc.y + below.size.h {
1405 popup.set_location(below.loc.to_i32_round());
1406 } else {
1407 popup.set_location(above.loc.to_i32_round());
1408 }
1409 }
1410 }
1411 }
1412
1413 pub fn update_reactive_popups(&self, window: &Window) {
1414 let _span = tracy_client::span!("Niri::update_reactive_popups");
1415
1416 for (popup, _) in PopupManager::popups_for_surface(
1417 window.toplevel().expect("no x11 support").wl_surface(),
1418 ) {
1419 match &popup {
1420 xdg_popup @ PopupKind::Xdg(popup) => {
1421 if popup.with_pending_state(|state| state.positioner.reactive) {
1422 self.unconstrain_window_popup(xdg_popup, window);
1423 if let Err(err) = popup.send_pending_configure() {
1424 warn!("error re-configuring reactive popup: {err:?}");
1425 }
1426 }
1427 }
1428 PopupKind::InputMethod(_) => (),
1429 }
1430 }
1431 }
1432
1433 pub fn update_window_rules(&mut self, toplevel: &ToplevelSurface) {
1434 let config = self.niri.config.borrow();
1435 let window_rules = &config.window_rules;
1436
1437 if let Some(unmapped) = self.niri.unmapped_windows.get_mut(toplevel.wl_surface()) {
1438 let new_rules = ResolvedWindowRules::compute(
1439 window_rules,
1440 WindowRef::Unmapped(unmapped),
1441 self.niri.is_at_startup,
1442 );
1443 if let InitialConfigureState::Configured { rules, .. } = &mut unmapped.state {
1444 *rules = new_rules;
1445 }
1446 } else if let Some((mapped, output)) = self
1447 .niri
1448 .layout
1449 .find_window_and_output_mut(toplevel.wl_surface())
1450 {
1451 if mapped.recompute_window_rules(window_rules, self.niri.is_at_startup) {
1452 drop(config);
1453 let output = output.cloned();
1454 let window = mapped.window.clone();
1455 self.niri.layout.update_window(&window, None);
1456
1457 if let Some(output) = output {
1458 self.niri.queue_redraw(&output);
1459 }
1460 }
1461 }
1462 }
1463}
1464
1465fn unconstrain_with_padding(
1466 positioner: PositionerState,
1467 target: Rectangle<f64, Logical>,
1468) -> Rectangle<i32, Logical> {
1469 // Try unconstraining with a small padding first which looks nicer, then if it doesn't fit try
1470 // unconstraining without padding.
1471 const PADDING: f64 = 8.;
1472
1473 let mut padded = target;
1474 if PADDING * 2. < padded.size.w {
1475 padded.loc.x += PADDING;
1476 padded.size.w -= PADDING * 2.;
1477 }
1478 if PADDING * 2. < padded.size.h {
1479 padded.loc.y += PADDING;
1480 padded.size.h -= PADDING * 2.;
1481 }
1482
1483 // No padding, so just unconstrain with the original target.
1484 if padded == target {
1485 return positioner.get_unconstrained_geometry(target.to_i32_round());
1486 }
1487
1488 // Do not try to resize to fit the padded target rectangle.
1489 let mut no_resize = positioner;
1490 no_resize
1491 .constraint_adjustment
1492 .remove(ConstraintAdjustment::ResizeX);
1493 no_resize
1494 .constraint_adjustment
1495 .remove(ConstraintAdjustment::ResizeY);
1496
1497 let geo = no_resize.get_unconstrained_geometry(padded.to_i32_round());
1498 if padded.contains_rect(geo.to_f64()) {
1499 return geo;
1500 }
1501
1502 // Could not unconstrain into the padded target, so resort to the regular one.
1503 positioner.get_unconstrained_geometry(target.to_i32_round())
1504}
1505
1506pub fn add_mapped_toplevel_pre_commit_hook(toplevel: &ToplevelSurface) -> HookId {
1507 add_pre_commit_hook::<State, _>(toplevel.wl_surface(), move |state, _dh, surface| {
1508 let _span = tracy_client::span!("mapped toplevel pre-commit");
1509 let span =
1510 trace_span!("toplevel pre-commit", surface = %surface.id(), serial = Empty).entered();
1511
1512 let Some((mapped, output)) = state.niri.layout.find_window_and_output_mut(surface) else {
1513 error!("pre-commit hook for mapped surfaces must be removed upon unmapping");
1514 return;
1515 };
1516
1517 let (got_unmapped, dmabuf, commit_serial) = with_states(surface, |states| {
1518 let (got_unmapped, dmabuf) = {
1519 let mut guard = states.cached_state.get::<SurfaceAttributes>();
1520 match guard.pending().buffer.as_ref() {
1521 Some(BufferAssignment::NewBuffer(buffer)) => {
1522 let dmabuf = get_dmabuf(buffer).cloned().ok();
1523 (false, dmabuf)
1524 }
1525 Some(BufferAssignment::Removed) => (true, None),
1526 None => (false, None),
1527 }
1528 };
1529
1530 let role = states
1531 .data_map
1532 .get::<XdgToplevelSurfaceData>()
1533 .unwrap()
1534 .lock()
1535 .unwrap();
1536 let serial = role.last_acked.as_ref().map(|c| c.serial);
1537
1538 (got_unmapped, dmabuf, serial)
1539 });
1540
1541 let mut transaction_for_dmabuf = None;
1542 let mut animate = false;
1543 if let Some(serial) = commit_serial {
1544 if !span.is_disabled() {
1545 span.record("serial", format!("{serial:?}"));
1546 }
1547
1548 // trace!("taking pending transaction");
1549 if let Some(transaction) = mapped.take_pending_transaction(serial) {
1550 // Transaction can be already completed if it ran past the deadline.
1551 let disable = state.niri.config.borrow().debug.disable_transactions;
1552 if !transaction.is_completed() && !disable {
1553 // Register the deadline even if this is the last pending, since dmabuf
1554 // rendering can still run over the deadline.
1555 transaction.register_deadline_timer(&state.niri.event_loop);
1556
1557 let is_last = transaction.is_last();
1558
1559 // If this is the last transaction, we don't need to add a separate
1560 // notification, because the transaction will complete in our dmabuf blocker
1561 // callback, which already calls blocker_cleared(), or by the end of this
1562 // function, in which case there would be no blocker in the first place.
1563 if !is_last {
1564 // Waiting for some other surface; register a notification and add a
1565 // transaction blocker.
1566 if let Some(client) = surface.client() {
1567 transaction.add_notification(
1568 state.niri.blocker_cleared_tx.clone(),
1569 client.clone(),
1570 );
1571 add_blocker(surface, transaction.blocker());
1572 }
1573 }
1574
1575 // Delay dropping (and completing) the transaction until the dmabuf is ready.
1576 // If there's no dmabuf, this will be dropped by the end of this pre-commit
1577 // hook.
1578 transaction_for_dmabuf = Some(transaction);
1579 }
1580 }
1581
1582 animate = mapped.should_animate_commit(serial);
1583 } else if !got_unmapped {
1584 error!("commit on a mapped surface without a configured serial");
1585 };
1586
1587 if let Some((blocker, source)) =
1588 dmabuf.and_then(|dmabuf| dmabuf.generate_blocker(Interest::READ).ok())
1589 {
1590 if let Some(client) = surface.client() {
1591 let res = state
1592 .niri
1593 .event_loop
1594 .insert_source(source, move |_, _, state| {
1595 // This surface is now ready for the transaction.
1596 drop(transaction_for_dmabuf.take());
1597
1598 let display_handle = state.niri.display_handle.clone();
1599 state
1600 .client_compositor_state(&client)
1601 .blocker_cleared(state, &display_handle);
1602
1603 Ok(())
1604 });
1605 if res.is_ok() {
1606 add_blocker(surface, blocker);
1607 trace!("added dmabuf blocker");
1608 }
1609 }
1610 }
1611
1612 let window = mapped.window.clone();
1613 if got_unmapped {
1614 let output = output.cloned();
1615 state.store_unmap_snapshot(&window, output.as_ref());
1616 } else {
1617 if animate {
1618 state.backend.with_primary_renderer(|renderer| {
1619 mapped.store_animation_snapshot(renderer);
1620 });
1621 }
1622
1623 // The toplevel remains mapped; clear any stored unmap snapshot.
1624 state.niri.layout.clear_unmap_snapshot(&window);
1625 }
1626 })
1627}