forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB055a94dIvan Molodetskikh1 year ago2247 commits

mapped.rs1241 lines, 46.0 KiBHistoryRawDownload
1use std::cell::{Cell, Ref, RefCell};
2use std::time::Duration;
3
4use niri_config::{Color, CornerRadius, GradientInterpolation, WindowRule};
5use smithay::backend::renderer::element::surface::render_elements_from_surface_tree;
6use smithay::backend::renderer::element::Kind;
7use smithay::backend::renderer::gles::GlesRenderer;
8use smithay::desktop::space::SpaceElement as _;
9use smithay::desktop::{PopupManager, Window};
10use smithay::output::{self, Output};
11use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1;
12use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
13use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
14use smithay::reexports::wayland_server::Resource as _;
15use smithay::utils::{Logical, Point, Rectangle, Scale, Serial, Size, Transform};
16use smithay::wayland::compositor::{remove_pre_commit_hook, with_states, HookId, SurfaceData};
17use smithay::wayland::seat::WaylandFocus;
18use smithay::wayland::shell::xdg::{SurfaceCachedState, ToplevelSurface};
19use wayland_backend::server::Credentials;
20
21use super::{ResolvedWindowRules, WindowRef};
22use crate::handlers::KdeDecorationsModeState;
23use crate::layout::{
24 ConfigureIntent, InteractiveResizeData, LayoutElement, LayoutElementRenderElement,
25 LayoutElementRenderSnapshot,
26};
27use crate::niri_render_elements;
28use crate::render_helpers::border::BorderRenderElement;
29use crate::render_helpers::offscreen::OffscreenData;
30use crate::render_helpers::renderer::NiriRenderer;
31use crate::render_helpers::snapshot::RenderSnapshot;
32use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
33use crate::render_helpers::surface::render_snapshot_from_surface_tree;
34use crate::render_helpers::{BakedBuffer, RenderTarget, SplitElements};
35use crate::utils::id::IdCounter;
36use crate::utils::transaction::Transaction;
37use crate::utils::{
38 get_credentials_for_surface, send_scale_transform, update_tiled_state, with_toplevel_role,
39 ResizeEdge,
40};
41
42#[derive(Debug)]
43pub struct Mapped {
44 pub window: Window,
45
46 /// Unique ID of this `Mapped`.
47 id: MappedId,
48
49 /// Credentials of the process that created the Wayland connection.
50 credentials: Option<Credentials>,
51
52 /// Pre-commit hook that we have on all mapped toplevel surfaces.
53 pre_commit_hook: HookId,
54
55 /// Up-to-date rules.
56 rules: ResolvedWindowRules,
57
58 /// Whether the window rules need to be recomputed.
59 ///
60 /// This is not used in all cases; for example, app ID and title changes recompute the rules
61 /// immediately, rather than setting this flag.
62 need_to_recompute_rules: bool,
63
64 /// Whether this window needs a configure this loop cycle.
65 ///
66 /// Certain Wayland requests require a configure in response, like un/fullscreen.
67 needs_configure: bool,
68
69 /// Whether this window needs a frame callback.
70 ///
71 /// We set this after sending a configure to give invisible windows a chance to respond to
72 /// resizes immediately, without waiting for a 1 second throttled callback.
73 needs_frame_callback: bool,
74
75 /// Data of the offscreen element rendered in place of this window.
76 ///
77 /// If `None`, then the window is not offscreened.
78 offscreen_data: RefCell<Option<OffscreenData>>,
79
80 /// Whether this has an urgent indicator.
81 is_urgent: bool,
82
83 /// Whether this window has the keyboard focus.
84 is_focused: bool,
85
86 /// Whether this window is the active window in its column.
87 is_active_in_column: bool,
88
89 /// Whether this window is floating.
90 is_floating: bool,
91
92 /// Whether this window is a target of a window cast.
93 is_window_cast_target: bool,
94
95 /// Whether this window should ignore opacity set through window rules.
96 ignore_opacity_window_rule: bool,
97
98 /// Buffer to draw instead of the window when it should be blocked out.
99 block_out_buffer: RefCell<SolidColorBuffer>,
100
101 /// Whether the next configure should be animated, if the configured state changed.
102 animate_next_configure: bool,
103
104 /// Serials of commits that should be animated.
105 animate_serials: Vec<Serial>,
106
107 /// Snapshot right before an animated commit, without popups.
108 animation_snapshot: Option<LayoutElementRenderSnapshot>,
109
110 /// State for the logic to request a size once (for floating windows).
111 request_size_once: Option<RequestSizeOnce>,
112
113 /// Transaction that the next configure should take part in, if any.
114 transaction_for_next_configure: Option<Transaction>,
115
116 /// Pending transactions that have not been added as blockers for this window yet.
117 pending_transactions: Vec<(Serial, Transaction)>,
118
119 /// State of an ongoing interactive resize.
120 interactive_resize: Option<InteractiveResize>,
121
122 /// Last time interactive resize was started.
123 ///
124 /// Used for double-resize-click tracking.
125 last_interactive_resize_start: Cell<Option<(Duration, ResizeEdge)>>,
126
127 /// Whether this window is in windowed (fake) fullscreen.
128 ///
129 /// In this mode, the underlying window is told that it's fullscreen, while keeping it as
130 /// a regular, non-fullscreen tile.
131 is_windowed_fullscreen: bool,
132
133 /// Whether this window is pending to go to windowed (fake) fullscreen.
134 ///
135 /// Several places in the layout code assume that is_fullscreen() can flip only on a commit.
136 /// Which is something that we do want to flip when changing is_windowed_fullscreen. Flipping
137 /// it right away would mean remembering to call layout.update_window() after any operation
138 /// that may change is_windowed_fullscreen, which is quite tricky and error-prone, especially
139 /// for deeply nested operations.
140 ///
141 /// It's also not clear what's the best way to go about it. Ideally we'd wait for configure ack
142 /// and commit before "committing" to is_windowed_fullscreen, however, since it's not real
143 /// Wayland state, we may end up with no Wayland state change to configure at all.
144 ///
145 /// For example: when the window is in real fullscreen, but its non-fullscreen size matches
146 /// its fullscreen size. Then turning on is_windowed_fullscreen will both keep the
147 /// fullscreen state, and keep the size (since it matches), resulting in no configure.
148 ///
149 /// So we work around this by emulating a configure-ack/commit cycle through
150 /// is_pending_windowed_fullscreen and uncommitted_windowed_fullscreen. We ensure we send
151 /// actual configures in all cases through needs_configure. This can result in unnecessary
152 /// configures (like in the example above), but in most cases there will be a configure
153 /// anyway to change the Fullscreen state and/or the size. What this gives us is being able
154 /// to synchronize our windowed fullscreen state to the real window updates to avoid any
155 /// flickering.
156 is_pending_windowed_fullscreen: bool,
157
158 /// Pending windowed fullscreen updates.
159 ///
160 /// These have been "sent" to the window in form of configures, but the window hadn't committed
161 /// in response yet.
162 uncommitted_windowed_fullscreen: Vec<(Serial, bool)>,
163}
164
165niri_render_elements! {
166 WindowCastRenderElements<R> => {
167 Layout = LayoutElementRenderElement<R>,
168 // Blocked-out window with rounded corners.
169 Border = BorderRenderElement,
170 }
171}
172
173static MAPPED_ID_COUNTER: IdCounter = IdCounter::new();
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
176pub struct MappedId(u64);
177
178impl MappedId {
179 pub fn next() -> MappedId {
180 MappedId(MAPPED_ID_COUNTER.next())
181 }
182
183 pub fn get(self) -> u64 {
184 self.0
185 }
186}
187
188/// Interactive resize state.
189#[derive(Debug)]
190enum InteractiveResize {
191 /// The resize is ongoing.
192 Ongoing(InteractiveResizeData),
193 /// The resize has stopped and we're waiting to send the last configure.
194 WaitingForLastConfigure(InteractiveResizeData),
195 /// We had sent the last resize configure and are waiting for the corresponding commit.
196 WaitingForLastCommit {
197 data: InteractiveResizeData,
198 serial: Serial,
199 },
200}
201
202impl InteractiveResize {
203 fn data(&self) -> InteractiveResizeData {
204 match self {
205 InteractiveResize::Ongoing(data) => *data,
206 InteractiveResize::WaitingForLastConfigure(data) => *data,
207 InteractiveResize::WaitingForLastCommit { data, .. } => *data,
208 }
209 }
210}
211
212/// Request-size-once logic state.
213#[derive(Debug, Clone, Copy)]
214enum RequestSizeOnce {
215 /// Waiting for configure to be sent with the requested size.
216 WaitingForConfigure,
217 /// Waiting for the window to commit in response to the configure.
218 WaitingForCommit(Serial),
219 /// When configuring, use the current window size.
220 UseWindowSize,
221}
222
223impl Mapped {
224 pub fn new(window: Window, rules: ResolvedWindowRules, hook: HookId) -> Self {
225 let surface = window.wl_surface().expect("no X11 support");
226 let credentials = get_credentials_for_surface(&surface);
227
228 Self {
229 window,
230 id: MappedId::next(),
231 credentials,
232 pre_commit_hook: hook,
233 rules,
234 need_to_recompute_rules: false,
235 needs_configure: false,
236 needs_frame_callback: false,
237 offscreen_data: RefCell::new(None),
238 is_urgent: false,
239 is_focused: false,
240 is_active_in_column: true,
241 is_floating: false,
242 is_window_cast_target: false,
243 ignore_opacity_window_rule: false,
244 block_out_buffer: RefCell::new(SolidColorBuffer::new((0., 0.), [0., 0., 0., 1.])),
245 animate_next_configure: false,
246 animate_serials: Vec::new(),
247 animation_snapshot: None,
248 request_size_once: None,
249 transaction_for_next_configure: None,
250 pending_transactions: Vec::new(),
251 interactive_resize: None,
252 last_interactive_resize_start: Cell::new(None),
253 is_windowed_fullscreen: false,
254 is_pending_windowed_fullscreen: false,
255 uncommitted_windowed_fullscreen: Vec::new(),
256 }
257 }
258
259 pub fn toplevel(&self) -> &ToplevelSurface {
260 self.window.toplevel().expect("no X11 support")
261 }
262
263 /// Recomputes the resolved window rules and returns whether they changed.
264 pub fn recompute_window_rules(&mut self, rules: &[WindowRule], is_at_startup: bool) -> bool {
265 self.need_to_recompute_rules = false;
266
267 let new_rules = ResolvedWindowRules::compute(rules, WindowRef::Mapped(self), is_at_startup);
268 if new_rules == self.rules {
269 return false;
270 }
271
272 // If the opacity window rule no longer makes the window semitransparent, reset the ignore
273 // flag to reduce surprises down the line.
274 if !new_rules.opacity.is_some_and(|o| o < 1.) {
275 self.ignore_opacity_window_rule = false;
276 }
277
278 self.rules = new_rules;
279 true
280 }
281
282 pub fn recompute_window_rules_if_needed(
283 &mut self,
284 rules: &[WindowRule],
285 is_at_startup: bool,
286 ) -> bool {
287 if !self.need_to_recompute_rules {
288 return false;
289 }
290
291 self.recompute_window_rules(rules, is_at_startup)
292 }
293
294 pub fn set_needs_configure(&mut self) {
295 self.needs_configure = true;
296 }
297
298 pub fn id(&self) -> MappedId {
299 self.id
300 }
301
302 pub fn credentials(&self) -> Option<&Credentials> {
303 self.credentials.as_ref()
304 }
305
306 pub fn offscreen_data(&self) -> Ref<Option<OffscreenData>> {
307 self.offscreen_data.borrow()
308 }
309
310 pub fn is_focused(&self) -> bool {
311 self.is_focused
312 }
313
314 pub fn is_active_in_column(&self) -> bool {
315 self.is_active_in_column
316 }
317
318 pub fn is_floating(&self) -> bool {
319 self.is_floating
320 }
321
322 pub fn is_window_cast_target(&self) -> bool {
323 self.is_window_cast_target
324 }
325
326 pub fn toggle_ignore_opacity_window_rule(&mut self) {
327 self.ignore_opacity_window_rule = !self.ignore_opacity_window_rule;
328 }
329
330 pub fn set_is_focused(&mut self, is_focused: bool) {
331 if self.is_focused == is_focused {
332 return;
333 }
334
335 self.is_focused = is_focused;
336 self.is_urgent = false;
337 self.need_to_recompute_rules = true;
338 }
339
340 pub fn set_is_window_cast_target(&mut self, value: bool) {
341 if self.is_window_cast_target == value {
342 return;
343 }
344
345 self.is_window_cast_target = value;
346 self.need_to_recompute_rules = true;
347 }
348
349 /// Renders a snapshot of the window without popups.
350 fn render_snapshot(&self, renderer: &mut GlesRenderer) -> LayoutElementRenderSnapshot {
351 let _span = tracy_client::span!("Mapped::render_snapshot");
352
353 let size = self.size().to_f64();
354
355 let mut buffer = self.block_out_buffer.borrow_mut();
356 buffer.resize(size);
357 let blocked_out_contents = vec![BakedBuffer {
358 buffer: buffer.clone(),
359 location: Point::from((0., 0.)),
360 src: None,
361 dst: None,
362 }];
363
364 let buf_pos = self.window.geometry().loc.upscale(-1).to_f64();
365
366 let mut contents = vec![];
367
368 let surface = self.toplevel().wl_surface();
369 render_snapshot_from_surface_tree(renderer, surface, buf_pos, &mut contents);
370
371 RenderSnapshot {
372 contents,
373 blocked_out_contents,
374 block_out_from: self.rules().block_out_from,
375 size,
376 texture: Default::default(),
377 blocked_out_texture: Default::default(),
378 }
379 }
380
381 pub fn should_animate_commit(&mut self, commit_serial: Serial) -> bool {
382 let mut should_animate = false;
383 self.animate_serials.retain_mut(|serial| {
384 if commit_serial.is_no_older_than(serial) {
385 should_animate = true;
386 false
387 } else {
388 true
389 }
390 });
391 should_animate
392 }
393
394 pub fn store_animation_snapshot(&mut self, renderer: &mut GlesRenderer) {
395 self.animation_snapshot = Some(self.render_snapshot(renderer));
396 }
397
398 pub fn take_pending_transaction(&mut self, commit_serial: Serial) -> Option<Transaction> {
399 let mut rv = None;
400
401 // Pending transactions are appended in order by serial, so we can loop from the start
402 // until we hit a serial that is too new.
403 while let Some((serial, _)) = self.pending_transactions.first() {
404 // In this loop, we will complete the transaction corresponding to the commit, as well
405 // as all transactions corresponding to previous serials. This can happen when we
406 // request resizes too quickly, and the surface only responds to the last one.
407 //
408 // Note that in this case, completing the previous transactions can result in an
409 // inconsistent visual state, if another window is waiting for this window to assume a
410 // specific size (in a previous transaction), which is now different (in this commit).
411 //
412 // However, there isn't really a good way to deal with that. We cannot cancel any
413 // transactions because we need to keep sending frame callbacks, and cancelling a
414 // transaction will make the corresponding frame callbacks get lost, and the window
415 // will hang.
416 //
417 // This is why resize throttling (implemented separately) is important: it prevents
418 // visually inconsistent states by way of never having more than one transaction in
419 // flight.
420 if commit_serial.is_no_older_than(serial) {
421 let (_, transaction) = self.pending_transactions.remove(0);
422 // Previous transaction is dropped here, signaling completion.
423 rv = Some(transaction);
424 } else {
425 break;
426 }
427 }
428
429 rv
430 }
431
432 pub fn last_interactive_resize_start(&self) -> &Cell<Option<(Duration, ResizeEdge)>> {
433 &self.last_interactive_resize_start
434 }
435
436 pub fn render_for_screen_cast<R: NiriRenderer>(
437 &self,
438 renderer: &mut R,
439 scale: Scale<f64>,
440 ) -> impl DoubleEndedIterator<Item = WindowCastRenderElements<R>> {
441 let bbox = self.window.bbox_with_popups().to_physical_precise_up(scale);
442
443 let has_border_shader = BorderRenderElement::has_shader(renderer);
444 let rules = self.rules();
445 let radius = rules.geometry_corner_radius.unwrap_or_default();
446 let window_size = self
447 .size()
448 .to_f64()
449 .to_physical_precise_round(scale)
450 .to_logical(scale);
451 let radius = radius.fit_to(window_size.w as f32, window_size.h as f32);
452
453 let location = self.window.geometry().loc.to_f64() - bbox.loc.to_logical(scale);
454 let elements = self.render(renderer, location, scale, 1., RenderTarget::Screencast);
455
456 elements.into_iter().map(move |elem| {
457 if let LayoutElementRenderElement::SolidColor(elem) = &elem {
458 // In this branch we're rendering a blocked-out window with a solid color. We need
459 // to render it with a rounded corner shader even if clip_to_geometry is false,
460 // because in this case we're assuming that the unclipped window CSD already has
461 // corners rounded to the user-provided radius, so our blocked-out rendering should
462 // match that radius.
463 if radius != CornerRadius::default() && has_border_shader {
464 let geo = elem.geo();
465 return BorderRenderElement::new(
466 geo.size,
467 Rectangle::from_size(geo.size),
468 GradientInterpolation::default(),
469 Color::from_color32f(elem.color()),
470 Color::from_color32f(elem.color()),
471 0.,
472 Rectangle::from_size(geo.size),
473 0.,
474 radius,
475 scale.x as f32,
476 1.,
477 )
478 .with_location(geo.loc)
479 .into();
480 }
481 }
482
483 WindowCastRenderElements::from(elem)
484 })
485 }
486
487 pub fn send_frame<T, F>(
488 &mut self,
489 output: &Output,
490 time: T,
491 throttle: Option<Duration>,
492 mut primary_scan_out_output: F,
493 ) where
494 T: Into<Duration>,
495 F: FnMut(&WlSurface, &SurfaceData) -> Option<Output> + Copy,
496 {
497 let needs_frame_callback = self.needs_frame_callback;
498 self.needs_frame_callback = false;
499
500 let should_send = move |surface: &WlSurface, states: &SurfaceData| {
501 // Let primary_scan_out_output() run its logic and update internal state.
502 if let Some(output) = primary_scan_out_output(surface, states) {
503 return Some(output);
504 }
505
506 // Send unconditionally to all surfaces if the window needs a surface callback.
507 needs_frame_callback.then(|| output.clone())
508 };
509 self.window.send_frame(output, time, throttle, should_send);
510 }
511
512 pub fn update_tiled_state(&self, prefer_no_csd: bool) {
513 update_tiled_state(self.toplevel(), prefer_no_csd, self.rules.tiled_state);
514 }
515
516 pub fn is_windowed_fullscreen(&self) -> bool {
517 self.is_windowed_fullscreen
518 }
519
520 pub fn set_urgent(&mut self, urgent: bool) {
521 if self.is_focused && urgent {
522 return;
523 }
524
525 let changed = self.is_urgent != urgent;
526 self.is_urgent = urgent;
527 self.need_to_recompute_rules |= changed;
528 }
529
530 pub fn is_urgent(&self) -> bool {
531 self.is_urgent
532 }
533}
534
535impl Drop for Mapped {
536 fn drop(&mut self) {
537 remove_pre_commit_hook(self.toplevel().wl_surface(), self.pre_commit_hook.clone());
538 }
539}
540
541impl LayoutElement for Mapped {
542 type Id = Window;
543
544 fn id(&self) -> &Self::Id {
545 &self.window
546 }
547
548 fn size(&self) -> Size<i32, Logical> {
549 self.window.geometry().size
550 }
551
552 fn buf_loc(&self) -> Point<i32, Logical> {
553 Point::from((0, 0)) - self.window.geometry().loc
554 }
555
556 fn is_in_input_region(&self, point: Point<f64, Logical>) -> bool {
557 let surface_local = point + self.window.geometry().loc.to_f64();
558 self.window.is_in_input_region(&surface_local)
559 }
560
561 fn render<R: NiriRenderer>(
562 &self,
563 renderer: &mut R,
564 location: Point<f64, Logical>,
565 scale: Scale<f64>,
566 alpha: f32,
567 target: RenderTarget,
568 ) -> SplitElements<LayoutElementRenderElement<R>> {
569 let mut rv = SplitElements::default();
570
571 if target.should_block_out(self.rules.block_out_from) {
572 let mut buffer = self.block_out_buffer.borrow_mut();
573 buffer.resize(self.window.geometry().size.to_f64());
574 let elem =
575 SolidColorRenderElement::from_buffer(&buffer, location, alpha, Kind::Unspecified);
576 rv.normal.push(elem.into());
577 } else {
578 let buf_pos = location - self.window.geometry().loc.to_f64();
579
580 let surface = self.toplevel().wl_surface();
581 for (popup, popup_offset) in PopupManager::popups_for_surface(surface) {
582 let offset = self.window.geometry().loc + popup_offset - popup.geometry().loc;
583
584 rv.popups.extend(render_elements_from_surface_tree(
585 renderer,
586 popup.wl_surface(),
587 (buf_pos + offset.to_f64()).to_physical_precise_round(scale),
588 scale,
589 alpha,
590 Kind::Unspecified,
591 ));
592 }
593
594 rv.normal = render_elements_from_surface_tree(
595 renderer,
596 surface,
597 buf_pos.to_physical_precise_round(scale),
598 scale,
599 alpha,
600 Kind::Unspecified,
601 );
602 }
603
604 rv
605 }
606
607 fn render_normal<R: NiriRenderer>(
608 &self,
609 renderer: &mut R,
610 location: Point<f64, Logical>,
611 scale: Scale<f64>,
612 alpha: f32,
613 target: RenderTarget,
614 ) -> Vec<LayoutElementRenderElement<R>> {
615 if target.should_block_out(self.rules.block_out_from) {
616 let mut buffer = self.block_out_buffer.borrow_mut();
617 buffer.resize(self.window.geometry().size.to_f64());
618 let elem =
619 SolidColorRenderElement::from_buffer(&buffer, location, alpha, Kind::Unspecified);
620 vec![elem.into()]
621 } else {
622 let buf_pos = location - self.window.geometry().loc.to_f64();
623 let surface = self.toplevel().wl_surface();
624 render_elements_from_surface_tree(
625 renderer,
626 surface,
627 buf_pos.to_physical_precise_round(scale),
628 scale,
629 alpha,
630 Kind::Unspecified,
631 )
632 }
633 }
634
635 fn render_popups<R: NiriRenderer>(
636 &self,
637 renderer: &mut R,
638 location: Point<f64, Logical>,
639 scale: Scale<f64>,
640 alpha: f32,
641 target: RenderTarget,
642 ) -> Vec<LayoutElementRenderElement<R>> {
643 if target.should_block_out(self.rules.block_out_from) {
644 vec![]
645 } else {
646 let mut rv = vec![];
647
648 let buf_pos = location - self.window.geometry().loc.to_f64();
649 let surface = self.toplevel().wl_surface();
650 for (popup, popup_offset) in PopupManager::popups_for_surface(surface) {
651 let offset = self.window.geometry().loc + popup_offset - popup.geometry().loc;
652
653 rv.extend(render_elements_from_surface_tree(
654 renderer,
655 popup.wl_surface(),
656 (buf_pos + offset.to_f64()).to_physical_precise_round(scale),
657 scale,
658 alpha,
659 Kind::Unspecified,
660 ));
661 }
662
663 rv
664 }
665 }
666
667 fn request_size(
668 &mut self,
669 size: Size<i32, Logical>,
670 is_fullscreen: bool,
671 animate: bool,
672 transaction: Option<Transaction>,
673 ) {
674 // Going into real fullscreen resets windowed fullscreen.
675 if is_fullscreen {
676 self.is_pending_windowed_fullscreen = false;
677
678 if self.is_windowed_fullscreen {
679 // Make sure we receive a commit to update self.is_windowed_fullscreen to false
680 // later on.
681 self.needs_configure = true;
682 }
683 }
684
685 let changed = self.toplevel().with_pending_state(|state| {
686 let changed = state.size != Some(size);
687 state.size = Some(size);
688 if is_fullscreen || self.is_pending_windowed_fullscreen {
689 state.states.set(xdg_toplevel::State::Fullscreen);
690 } else {
691 state.states.unset(xdg_toplevel::State::Fullscreen);
692 }
693 changed
694 });
695
696 if changed && animate {
697 self.animate_next_configure = true;
698 }
699
700 self.request_size_once = None;
701
702 // Store the transaction regardless of whether the size changed. This is because with 3+
703 // windows in a column, the size may change among windows 1 and 2 and then right away among
704 // windows 2 and 3, and we want all windows 1, 2 and 3 to use the last transaction, rather
705 // than window 1 getting stuck with the previous transaction that is immediately released
706 // by 2.
707 if let Some(transaction) = transaction {
708 self.transaction_for_next_configure = Some(transaction);
709 }
710 }
711
712 fn request_size_once(&mut self, size: Size<i32, Logical>, animate: bool) {
713 // Assume that when calling this function, the window is going floating, so it can no
714 // longer participate in any transactions with other windows.
715 self.transaction_for_next_configure = None;
716
717 // If our last requested size already matches the size we want to request-once, clear the
718 // size request right away. However, we must also check if we're unfullscreening, because
719 // in that case the window itself will restore its previous size upon receiving a (0, 0)
720 // configure, whereas what we potentially want is to unfullscreen the window into its
721 // fullscreen size.
722 let already_sent = with_toplevel_role(self.toplevel(), |role| {
723 let (last_sent, last_serial) = if let Some(configure) = role.pending_configures().last()
724 {
725 // FIXME: it would be more optimal to find the *oldest* pending configure that
726 // has the same size and fullscreen state to the last pending configure.
727 (&configure.state, configure.serial)
728 } else {
729 (
730 role.last_acked.as_ref().unwrap(),
731 role.configure_serial.unwrap(),
732 )
733 };
734
735 let same_size = last_sent.size.unwrap_or_default() == size;
736 let has_fullscreen = last_sent.states.contains(xdg_toplevel::State::Fullscreen);
737 let same_fullscreen = has_fullscreen == self.is_pending_windowed_fullscreen;
738 (same_size && same_fullscreen).then_some(last_serial)
739 });
740
741 if let Some(serial) = already_sent {
742 if let Some(current_serial) =
743 with_toplevel_role(self.toplevel(), |role| role.current_serial)
744 {
745 // God this triple negative...
746 if !current_serial.is_no_older_than(&serial) {
747 // We have already sent a request for the new size, but the surface has not
748 // committed in response yet, so we will wait for that commit.
749 self.request_size_once = Some(RequestSizeOnce::WaitingForCommit(serial));
750 } else {
751 // We have already sent a request for the new size, and the surface has
752 // committed in response, so we will start using the current size right away.
753 self.request_size_once = Some(RequestSizeOnce::UseWindowSize);
754 }
755 } else {
756 warn!("no current serial; did the surface not ack the initial configure?");
757 self.request_size_once = Some(RequestSizeOnce::UseWindowSize);
758 };
759 return;
760 }
761
762 let changed = self.toplevel().with_pending_state(|state| {
763 let changed = state.size != Some(size);
764 state.size = Some(size);
765 if !self.is_pending_windowed_fullscreen {
766 state.states.unset(xdg_toplevel::State::Fullscreen);
767 }
768 changed
769 });
770
771 if changed && animate {
772 self.animate_next_configure = true;
773 }
774
775 self.request_size_once = Some(RequestSizeOnce::WaitingForConfigure);
776 }
777
778 fn min_size(&self) -> Size<i32, Logical> {
779 let min_size = with_states(self.toplevel().wl_surface(), |state| {
780 let mut guard = state.cached_state.get::<SurfaceCachedState>();
781 guard.current().min_size
782 });
783
784 self.rules.apply_min_size(min_size)
785 }
786
787 fn max_size(&self) -> Size<i32, Logical> {
788 let max_size = with_states(self.toplevel().wl_surface(), |state| {
789 let mut guard = state.cached_state.get::<SurfaceCachedState>();
790 guard.current().max_size
791 });
792
793 self.rules.apply_max_size(max_size)
794 }
795
796 fn is_wl_surface(&self, wl_surface: &WlSurface) -> bool {
797 self.toplevel().wl_surface() == wl_surface
798 }
799
800 fn set_preferred_scale_transform(&self, scale: output::Scale, transform: Transform) {
801 self.window.with_surfaces(|surface, data| {
802 send_scale_transform(surface, data, scale, transform);
803 });
804 }
805
806 fn has_ssd(&self) -> bool {
807 let toplevel = self.toplevel();
808 let mode = with_toplevel_role(self.toplevel(), |role| role.current.decoration_mode);
809
810 match mode {
811 Some(zxdg_toplevel_decoration_v1::Mode::ServerSide) => true,
812 // Check KDE decorations when XDG are not in use.
813 None => with_states(toplevel.wl_surface(), |states| {
814 states
815 .data_map
816 .get::<KdeDecorationsModeState>()
817 .map(KdeDecorationsModeState::is_server)
818 == Some(true)
819 }),
820 _ => false,
821 }
822 }
823
824 fn output_enter(&self, output: &Output) {
825 let overlap = Rectangle::from_size(Size::from((i32::MAX, i32::MAX)));
826 self.window.output_enter(output, overlap)
827 }
828
829 fn output_leave(&self, output: &Output) {
830 self.window.output_leave(output)
831 }
832
833 fn set_offscreen_data(&self, data: Option<OffscreenData>) {
834 let Some(data) = data else {
835 self.offscreen_data.replace(None);
836 return;
837 };
838
839 let mut offscreen_data = self.offscreen_data.borrow_mut();
840 match &mut *offscreen_data {
841 None => {
842 *offscreen_data = Some(data);
843 }
844 Some(existing) => {
845 // Replace the id, amend existing element states. This is necessary to handle
846 // multiple layers of offscreen (e.g. resize animation + alpha animation).
847 existing.id = data.id;
848 existing.states.states.extend(data.states.states);
849 }
850 }
851 }
852
853 fn is_urgent(&self) -> bool {
854 self.is_urgent
855 }
856
857 fn set_activated(&mut self, active: bool) {
858 let changed = self.toplevel().with_pending_state(|state| {
859 if active {
860 state.states.set(xdg_toplevel::State::Activated)
861 } else {
862 state.states.unset(xdg_toplevel::State::Activated)
863 }
864 });
865 self.need_to_recompute_rules |= changed;
866 }
867
868 fn set_active_in_column(&mut self, active: bool) {
869 let changed = self.is_active_in_column != active;
870 self.is_active_in_column = active;
871 self.need_to_recompute_rules |= changed;
872 }
873
874 fn set_floating(&mut self, floating: bool) {
875 let changed = self.is_floating != floating;
876 self.is_floating = floating;
877 self.need_to_recompute_rules |= changed;
878 }
879
880 fn set_bounds(&self, bounds: Size<i32, Logical>) {
881 self.toplevel().with_pending_state(|state| {
882 state.bounds = Some(bounds);
883 });
884 }
885
886 fn configure_intent(&self) -> ConfigureIntent {
887 let _span =
888 trace_span!("configure_intent", surface = ?self.toplevel().wl_surface().id()).entered();
889
890 if self.needs_configure {
891 trace!("the window needs_configure");
892 return ConfigureIntent::ShouldSend;
893 }
894
895 with_toplevel_role(self.toplevel(), |attributes| {
896 if let Some(server_pending) = &attributes.server_pending {
897 let current_server = attributes.current_server_state();
898 if server_pending != current_server {
899 // Something changed. Check if the only difference is the size, and if the
900 // current server size matches the current committed size.
901 let mut current_server_same_size = current_server.clone();
902 current_server_same_size.size = server_pending.size;
903 if current_server_same_size == *server_pending {
904 // Only the size changed. Check if the window committed our previous size
905 // request.
906 if attributes.current.size == current_server.size {
907 // The window had committed for our previous size change, so we can
908 // change the size again.
909 trace!(
910 "current size matches server size: {:?}",
911 attributes.current.size
912 );
913 ConfigureIntent::CanSend
914 } else {
915 // The window had not committed for our previous size change yet. Since
916 // nothing else changed, do not send the new size request yet. This
917 // throttling is done because some clients do not batch size requests,
918 // leading to bad behavior with very fast input devices (i.e. a 1000 Hz
919 // mouse). This throttling also helps interactive resize transactions
920 // preserve visual consistency.
921 trace!("throttling resize");
922 ConfigureIntent::Throttled
923 }
924 } else {
925 // Something else changed other than the size; send it.
926 trace!("something changed other than the size");
927 ConfigureIntent::ShouldSend
928 }
929 } else {
930 // Nothing changed since the last configure.
931 ConfigureIntent::NotNeeded
932 }
933 } else {
934 // Nothing changed since the last configure.
935 ConfigureIntent::NotNeeded
936 }
937 })
938 }
939
940 fn send_pending_configure(&mut self) {
941 let toplevel = self.toplevel();
942 let _span =
943 trace_span!("send_pending_configure", surface = ?toplevel.wl_surface().id()).entered();
944
945 // If the window needs a configure, send it regardless.
946 let has_pending_changes = self.needs_configure
947 || with_toplevel_role(self.toplevel(), |role| {
948 // Check for pending changes manually to account for RequestSizeOnce::UseWindowSize.
949 if role.server_pending.is_none() {
950 return false;
951 }
952
953 let current_server_size = role.current_server_state().size;
954 let server_pending = role.server_pending.as_mut().unwrap();
955
956 // With UseWindowSize, we do not consider size-only changes, because we will
957 // request the current window size and do not expect it to actually change.
958 if let Some(RequestSizeOnce::UseWindowSize) = self.request_size_once {
959 server_pending.size = current_server_size;
960 }
961
962 let server_pending = role.server_pending.as_ref().unwrap();
963 server_pending != role.current_server_state()
964 });
965
966 if has_pending_changes {
967 // If needed, replace the pending size with the current window size.
968 if let Some(RequestSizeOnce::UseWindowSize) = self.request_size_once {
969 let size = self.window.geometry().size;
970 toplevel.with_pending_state(|state| {
971 state.size = Some(size);
972 });
973 }
974
975 let serial = toplevel.send_configure();
976 trace!(?serial, "sending configure");
977
978 self.needs_configure = false;
979
980 // Send the window a frame callback unconditionally to let it respond to size changes
981 // and such immediately, even when it's hidden. This especially matters for cases like
982 // tabbed columns which compute their width based on all windows in the column, even
983 // hidden ones.
984 self.needs_frame_callback = true;
985
986 if self.animate_next_configure {
987 self.animate_serials.push(serial);
988 }
989
990 if let Some(transaction) = self.transaction_for_next_configure.take() {
991 self.pending_transactions.push((serial, transaction));
992 }
993
994 self.interactive_resize = match self.interactive_resize.take() {
995 Some(InteractiveResize::WaitingForLastConfigure(data)) => {
996 Some(InteractiveResize::WaitingForLastCommit { data, serial })
997 }
998 x => x,
999 };
1000
1001 if let Some(RequestSizeOnce::WaitingForConfigure) = self.request_size_once {
1002 self.request_size_once = Some(RequestSizeOnce::WaitingForCommit(serial));
1003 }
1004
1005 // If is_pending_windowed_fullscreen changed compared to the last value that we "sent"
1006 // to the window, store the configure serial.
1007 let last_sent_windowed_fullscreen = self
1008 .uncommitted_windowed_fullscreen
1009 .last()
1010 .map(|(_, value)| *value)
1011 .unwrap_or(self.is_windowed_fullscreen);
1012 if last_sent_windowed_fullscreen != self.is_pending_windowed_fullscreen {
1013 self.uncommitted_windowed_fullscreen
1014 .push((serial, self.is_pending_windowed_fullscreen));
1015 }
1016 } else {
1017 self.interactive_resize = match self.interactive_resize.take() {
1018 // We probably started and stopped resizing in the same loop cycle without anything
1019 // changing.
1020 Some(InteractiveResize::WaitingForLastConfigure { .. }) => None,
1021 x => x,
1022 };
1023 }
1024
1025 self.animate_next_configure = false;
1026 self.transaction_for_next_configure = None;
1027 }
1028
1029 fn is_fullscreen(&self) -> bool {
1030 if self.is_windowed_fullscreen {
1031 return false;
1032 }
1033
1034 with_toplevel_role(self.toplevel(), |role| {
1035 role.current
1036 .states
1037 .contains(xdg_toplevel::State::Fullscreen)
1038 })
1039 }
1040
1041 fn is_pending_fullscreen(&self) -> bool {
1042 if self.is_pending_windowed_fullscreen {
1043 return false;
1044 }
1045
1046 self.toplevel()
1047 .with_pending_state(|state| state.states.contains(xdg_toplevel::State::Fullscreen))
1048 }
1049
1050 fn is_ignoring_opacity_window_rule(&self) -> bool {
1051 self.ignore_opacity_window_rule
1052 }
1053
1054 fn requested_size(&self) -> Option<Size<i32, Logical>> {
1055 self.toplevel().with_pending_state(|state| state.size)
1056 }
1057
1058 fn expected_size(&self) -> Option<Size<i32, Logical>> {
1059 // We can only use current size if it's not fullscreen.
1060 let current_size = (!self.is_fullscreen()).then(|| self.window.geometry().size);
1061
1062 // Check if we should be using the current window size.
1063 //
1064 // This branch can be useful (give different result than the logic below) in this example
1065 // case:
1066 //
1067 // 1. We request_size_once a size change.
1068 // 2. We send a second configure requesting a state change.
1069 // 3. The window acks and commits-to the first configure but not the second, with a
1070 // different size.
1071 //
1072 // In this case self.request_size_once will already flip to UseWindowSize and this branch
1073 // will return the window's own new size, but the logic below would see an uncommitted size
1074 // change and return our size.
1075 if let Some(RequestSizeOnce::UseWindowSize) = self.request_size_once {
1076 return current_size;
1077 }
1078
1079 let pending = with_toplevel_role(self.toplevel(), |role| {
1080 // If we have a server-pending size change that we haven't sent yet, use that size.
1081 if let Some(server_pending) = &role.server_pending {
1082 let current_server = role.current_server_state();
1083 if server_pending.size != current_server.size {
1084 return Some((
1085 server_pending.size.unwrap_or_default(),
1086 server_pending
1087 .states
1088 .contains(xdg_toplevel::State::Fullscreen),
1089 ));
1090 }
1091 }
1092
1093 // If we have a sent-but-not-committed-to size, use that.
1094 let (last_sent, last_serial) = if let Some(configure) = role.pending_configures().last()
1095 {
1096 (&configure.state, configure.serial)
1097 } else {
1098 (
1099 role.last_acked.as_ref().unwrap(),
1100 role.configure_serial.unwrap(),
1101 )
1102 };
1103
1104 if let Some(current_serial) = role.current_serial {
1105 if !current_serial.is_no_older_than(&last_serial) {
1106 return Some((
1107 last_sent.size.unwrap_or_default(),
1108 last_sent.states.contains(xdg_toplevel::State::Fullscreen),
1109 ));
1110 }
1111 }
1112
1113 None
1114 });
1115
1116 if let Some((mut size, fullscreen)) = pending {
1117 // If the pending change is fullscreen, we can't use that size.
1118 if fullscreen && !self.is_pending_windowed_fullscreen {
1119 return None;
1120 }
1121
1122 // If some component of the pending size is zero, substitute it with the current window
1123 // size. But only if the current size is not fullscreen.
1124 if size.w == 0 {
1125 size.w = current_size?.w;
1126 }
1127 if size.h == 0 {
1128 size.h = current_size?.h;
1129 }
1130
1131 Some(size)
1132 } else {
1133 // No pending size, return the current size if it's non-fullscreen.
1134 current_size
1135 }
1136 }
1137
1138 fn is_pending_windowed_fullscreen(&self) -> bool {
1139 self.is_pending_windowed_fullscreen
1140 }
1141
1142 fn request_windowed_fullscreen(&mut self, value: bool) {
1143 if self.is_pending_windowed_fullscreen == value {
1144 return;
1145 }
1146
1147 self.is_pending_windowed_fullscreen = value;
1148
1149 // Set the fullscreen state to match.
1150 //
1151 // When going from windowed to real fullscreen, we'll use request_size() which will set the
1152 // fullscreen state back.
1153 self.toplevel().with_pending_state(|state| {
1154 if value {
1155 state.states.set(xdg_toplevel::State::Fullscreen);
1156 } else {
1157 state.states.unset(xdg_toplevel::State::Fullscreen);
1158 }
1159 });
1160
1161 // Make sure we receive a commit later to update self.is_windowed_fullscreen.
1162 self.needs_configure = true;
1163 }
1164
1165 fn is_child_of(&self, parent: &Self) -> bool {
1166 self.toplevel().parent().as_ref() == Some(parent.toplevel().wl_surface())
1167 }
1168
1169 fn refresh(&self) {
1170 self.window.refresh();
1171 }
1172
1173 fn rules(&self) -> &ResolvedWindowRules {
1174 &self.rules
1175 }
1176
1177 fn animation_snapshot(&self) -> Option<&LayoutElementRenderSnapshot> {
1178 self.animation_snapshot.as_ref()
1179 }
1180
1181 fn take_animation_snapshot(&mut self) -> Option<LayoutElementRenderSnapshot> {
1182 self.animation_snapshot.take()
1183 }
1184
1185 fn set_interactive_resize(&mut self, data: Option<InteractiveResizeData>) {
1186 self.toplevel().with_pending_state(|state| {
1187 if data.is_some() {
1188 state.states.set(xdg_toplevel::State::Resizing);
1189 } else {
1190 state.states.unset(xdg_toplevel::State::Resizing);
1191 }
1192 });
1193
1194 if let Some(data) = data {
1195 self.interactive_resize = Some(InteractiveResize::Ongoing(data));
1196 } else {
1197 self.interactive_resize = match self.interactive_resize.take() {
1198 Some(InteractiveResize::Ongoing(data)) => {
1199 Some(InteractiveResize::WaitingForLastConfigure(data))
1200 }
1201 x => x,
1202 }
1203 }
1204 }
1205
1206 fn cancel_interactive_resize(&mut self) {
1207 self.set_interactive_resize(None);
1208 self.interactive_resize = None;
1209 }
1210
1211 fn interactive_resize_data(&self) -> Option<InteractiveResizeData> {
1212 Some(self.interactive_resize.as_ref()?.data())
1213 }
1214
1215 fn on_commit(&mut self, commit_serial: Serial) {
1216 if let Some(InteractiveResize::WaitingForLastCommit { serial, .. }) =
1217 &self.interactive_resize
1218 {
1219 if commit_serial.is_no_older_than(serial) {
1220 self.interactive_resize = None;
1221 }
1222 }
1223
1224 if let Some(RequestSizeOnce::WaitingForCommit(serial)) = &self.request_size_once {
1225 if commit_serial.is_no_older_than(serial) {
1226 self.request_size_once = Some(RequestSizeOnce::UseWindowSize);
1227 }
1228 }
1229
1230 // "Commit" our "acked" pending windowed fullscreen state.
1231 self.uncommitted_windowed_fullscreen
1232 .retain_mut(|(serial, value)| {
1233 if commit_serial.is_no_older_than(serial) {
1234 self.is_windowed_fullscreen = *value;
1235 false
1236 } else {
1237 true
1238 }
1239 });
1240 }
1241}