forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9ff2f83Ivan Molodetskikh1 year ago2099 commits

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