forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB66583cdIvan Molodetskikh1 year ago2489 commits

floating.rs1413 lines, 46.7 KiBHistoryRawDownload
1use std::cmp::max;
2use std::iter::zip;
3use std::rc::Rc;
4
5use niri_config::utils::MergeWith as _;
6use niri_config::{PresetSize, RelativeTo};
7use niri_ipc::{PositionChange, SizeChange, WindowLayout};
8use smithay::backend::renderer::gles::GlesRenderer;
9use smithay::utils::{Logical, Point, Rectangle, Scale, Serial, Size};
10
11use super::closing_window::{ClosingWindow, ClosingWindowRenderElement};
12use super::scrolling::ColumnWidth;
13use super::tile::{Tile, TileRenderElement, TileRenderSnapshot};
14use super::workspace::{InteractiveResize, ResolvedSize};
15use super::{
16 ConfigureIntent, InteractiveResizeData, LayoutElement, Options, RemovedTile, SizeFrac,
17};
18use crate::animation::{Animation, Clock};
19use crate::niri_render_elements;
20use crate::render_helpers::renderer::NiriRenderer;
21use crate::render_helpers::RenderTarget;
22use crate::utils::transaction::TransactionBlocker;
23use crate::utils::{
24 center_preferring_top_left_in_area, clamp_preferring_top_left_in_area, ensure_min_max_size,
25 ensure_min_max_size_maybe_zero, ResizeEdge,
26};
27use crate::window::ResolvedWindowRules;
28
29/// By how many logical pixels the directional move commands move floating windows.
30pub const DIRECTIONAL_MOVE_PX: f64 = 50.;
31
32/// Space for floating windows.
33#[derive(Debug)]
34pub struct FloatingSpace<W: LayoutElement> {
35 /// Tiles in top-to-bottom order.
36 tiles: Vec<Tile<W>>,
37
38 /// Extra per-tile data.
39 data: Vec<Data>,
40
41 /// Id of the active window.
42 ///
43 /// The active window is not necessarily the topmost window. Focus-follows-mouse should
44 /// activate a window, but not bring it to the top, because that's very annoying.
45 ///
46 /// This is always set to `Some()` when `tiles` isn't empty.
47 active_window_id: Option<W::Id>,
48
49 /// Ongoing interactive resize.
50 interactive_resize: Option<InteractiveResize<W>>,
51
52 /// Windows in the closing animation.
53 closing_windows: Vec<ClosingWindow>,
54
55 /// View size for this space.
56 view_size: Size<f64, Logical>,
57
58 /// Working area for this space.
59 working_area: Rectangle<f64, Logical>,
60
61 /// Scale of the output the space is on (and rounds its sizes to).
62 scale: f64,
63
64 /// Clock for driving animations.
65 clock: Clock,
66
67 /// Configurable properties of the layout.
68 options: Rc<Options>,
69}
70
71niri_render_elements! {
72 FloatingSpaceRenderElement<R> => {
73 Tile = TileRenderElement<R>,
74 ClosingWindow = ClosingWindowRenderElement,
75 }
76}
77
78/// Extra per-tile data.
79#[derive(Debug, Clone, Copy, PartialEq)]
80struct Data {
81 /// Position relative to the working area.
82 pos: Point<f64, SizeFrac>,
83
84 /// Cached position in logical coordinates.
85 ///
86 /// Not rounded to physical pixels.
87 logical_pos: Point<f64, Logical>,
88
89 /// Cached actual size of the tile.
90 size: Size<f64, Logical>,
91
92 /// Working area used for conversions.
93 working_area: Rectangle<f64, Logical>,
94}
95
96impl Data {
97 pub fn new<W: LayoutElement>(
98 working_area: Rectangle<f64, Logical>,
99 tile: &Tile<W>,
100 logical_pos: Point<f64, Logical>,
101 ) -> Self {
102 let mut rv = Self {
103 pos: Point::default(),
104 logical_pos: Point::default(),
105 size: Size::default(),
106 working_area,
107 };
108 rv.update(tile);
109 rv.set_logical_pos(logical_pos);
110 rv
111 }
112
113 pub fn scale_by_working_area(
114 area: Rectangle<f64, Logical>,
115 pos: Point<f64, SizeFrac>,
116 ) -> Point<f64, Logical> {
117 let mut logical_pos = Point::from((pos.x, pos.y));
118 logical_pos.x *= area.size.w;
119 logical_pos.y *= area.size.h;
120 logical_pos += area.loc;
121 logical_pos
122 }
123
124 pub fn logical_to_size_frac_in_working_area(
125 area: Rectangle<f64, Logical>,
126 logical_pos: Point<f64, Logical>,
127 ) -> Point<f64, SizeFrac> {
128 let pos = logical_pos - area.loc;
129 let mut pos = Point::from((pos.x, pos.y));
130 pos.x /= f64::max(area.size.w, 1.0);
131 pos.y /= f64::max(area.size.h, 1.0);
132 pos
133 }
134
135 fn recompute_logical_pos(&mut self) {
136 let mut logical_pos = Self::scale_by_working_area(self.working_area, self.pos);
137
138 // Make sure the window doesn't go too much off-screen. Numbers taken from Mutter.
139 let min_on_screen_hor = f64::clamp(self.size.w / 4., 10., 75.);
140 let min_on_screen_ver = f64::clamp(self.size.h / 4., 10., 75.);
141 let max_off_screen_hor = f64::max(0., self.size.w - min_on_screen_hor);
142 let max_off_screen_ver = f64::max(0., self.size.h - min_on_screen_ver);
143
144 logical_pos -= self.working_area.loc;
145 logical_pos.x = f64::max(logical_pos.x, -max_off_screen_hor);
146 logical_pos.y = f64::max(logical_pos.y, -max_off_screen_ver);
147 logical_pos.x = f64::min(
148 logical_pos.x,
149 self.working_area.size.w - self.size.w + max_off_screen_hor,
150 );
151 logical_pos.y = f64::min(
152 logical_pos.y,
153 self.working_area.size.h - self.size.h + max_off_screen_ver,
154 );
155 logical_pos += self.working_area.loc;
156
157 self.logical_pos = logical_pos;
158 }
159
160 pub fn update_config(&mut self, working_area: Rectangle<f64, Logical>) {
161 if self.working_area == working_area {
162 return;
163 }
164
165 self.working_area = working_area;
166 self.recompute_logical_pos();
167 }
168
169 pub fn update<W: LayoutElement>(&mut self, tile: &Tile<W>) {
170 let size = tile.tile_size();
171 if self.size == size {
172 return;
173 }
174
175 self.size = size;
176 self.recompute_logical_pos();
177 }
178
179 pub fn set_logical_pos(&mut self, logical_pos: Point<f64, Logical>) {
180 self.pos = Self::logical_to_size_frac_in_working_area(self.working_area, logical_pos);
181
182 // This will clamp the logical position to the current working area.
183 self.recompute_logical_pos();
184 }
185
186 pub fn center(&self) -> Point<f64, Logical> {
187 self.logical_pos + self.size.downscale(2.)
188 }
189
190 #[cfg(test)]
191 fn verify_invariants(&self) {
192 let mut temp = *self;
193 temp.recompute_logical_pos();
194 assert_eq!(
195 self.logical_pos, temp.logical_pos,
196 "cached logical pos must be up to date"
197 );
198 }
199}
200
201impl<W: LayoutElement> FloatingSpace<W> {
202 pub fn new(
203 view_size: Size<f64, Logical>,
204 working_area: Rectangle<f64, Logical>,
205 scale: f64,
206 clock: Clock,
207 options: Rc<Options>,
208 ) -> Self {
209 Self {
210 tiles: Vec::new(),
211 data: Vec::new(),
212 active_window_id: None,
213 interactive_resize: None,
214 closing_windows: Vec::new(),
215 view_size,
216 working_area,
217 scale,
218 clock,
219 options,
220 }
221 }
222
223 pub fn update_config(
224 &mut self,
225 view_size: Size<f64, Logical>,
226 working_area: Rectangle<f64, Logical>,
227 scale: f64,
228 options: Rc<Options>,
229 ) {
230 for (tile, data) in zip(&mut self.tiles, &mut self.data) {
231 tile.update_config(view_size, scale, options.clone());
232 data.update(tile);
233 data.update_config(working_area);
234 }
235
236 self.view_size = view_size;
237 self.working_area = working_area;
238 self.scale = scale;
239 self.options = options;
240 }
241
242 pub fn update_shaders(&mut self) {
243 for tile in &mut self.tiles {
244 tile.update_shaders();
245 }
246 }
247
248 pub fn advance_animations(&mut self) {
249 for tile in &mut self.tiles {
250 tile.advance_animations();
251 }
252
253 self.closing_windows.retain_mut(|closing| {
254 closing.advance_animations();
255 closing.are_animations_ongoing()
256 });
257 }
258
259 pub fn are_animations_ongoing(&self) -> bool {
260 self.tiles.iter().any(Tile::are_animations_ongoing) || !self.closing_windows.is_empty()
261 }
262
263 pub fn are_transitions_ongoing(&self) -> bool {
264 self.tiles.iter().any(Tile::are_transitions_ongoing) || !self.closing_windows.is_empty()
265 }
266
267 pub fn update_render_elements(&mut self, is_active: bool, view_rect: Rectangle<f64, Logical>) {
268 let active = self.active_window_id.clone();
269 for (tile, offset) in self.tiles_with_offsets_mut() {
270 let id = tile.window().id();
271 let is_active = is_active && Some(id) == active.as_ref();
272
273 let mut tile_view_rect = view_rect;
274 tile_view_rect.loc -= offset + tile.render_offset();
275 tile.update_render_elements(is_active, tile_view_rect);
276 }
277 }
278
279 pub fn tiles(&self) -> impl Iterator<Item = &Tile<W>> + '_ {
280 self.tiles.iter()
281 }
282
283 pub fn tiles_mut(&mut self) -> impl Iterator<Item = &mut Tile<W>> + '_ {
284 self.tiles.iter_mut()
285 }
286
287 pub fn tiles_with_offsets(&self) -> impl Iterator<Item = (&Tile<W>, Point<f64, Logical>)> + '_ {
288 let offsets = self.data.iter().map(|d| d.logical_pos);
289 zip(&self.tiles, offsets)
290 }
291
292 pub fn tiles_with_offsets_mut(
293 &mut self,
294 ) -> impl Iterator<Item = (&mut Tile<W>, Point<f64, Logical>)> + '_ {
295 let offsets = self.data.iter().map(|d| d.logical_pos);
296 zip(&mut self.tiles, offsets)
297 }
298
299 pub fn tiles_with_render_positions(
300 &self,
301 ) -> impl Iterator<Item = (&Tile<W>, Point<f64, Logical>)> {
302 let scale = self.scale;
303 self.tiles_with_offsets().map(move |(tile, offset)| {
304 let pos = offset + tile.render_offset();
305 // Round to physical pixels.
306 let pos = pos.to_physical_precise_round(scale).to_logical(scale);
307 (tile, pos)
308 })
309 }
310
311 pub fn tiles_with_render_positions_mut(
312 &mut self,
313 round: bool,
314 ) -> impl Iterator<Item = (&mut Tile<W>, Point<f64, Logical>)> {
315 let scale = self.scale;
316 self.tiles_with_offsets_mut().map(move |(tile, offset)| {
317 let mut pos = offset + tile.render_offset();
318 // Round to physical pixels.
319 if round {
320 pos = pos.to_physical_precise_round(scale).to_logical(scale);
321 }
322 (tile, pos)
323 })
324 }
325
326 pub fn tiles_with_ipc_layouts(&self) -> impl Iterator<Item = (&Tile<W>, WindowLayout)> {
327 let scale = self.scale;
328 self.tiles_with_offsets().map(move |(tile, offset)| {
329 // Do not include animated render offset here to avoid IPC spam.
330 let pos = offset;
331 // Round to physical pixels.
332 let pos = pos.to_physical_precise_round(scale).to_logical(scale);
333
334 let layout = WindowLayout {
335 tile_pos_in_workspace_view: Some(pos.into()),
336 ..tile.ipc_layout_template()
337 };
338 (tile, layout)
339 })
340 }
341
342 pub fn new_window_toplevel_bounds(&self, rules: &ResolvedWindowRules) -> Size<i32, Logical> {
343 let border_config = self.options.layout.border.merged_with(&rules.border);
344 compute_toplevel_bounds(border_config, self.working_area.size)
345 }
346
347 /// Returns the geometry of the active tile relative to and clamped to the working area.
348 ///
349 /// During animations, assumes the final tile position.
350 pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> {
351 let (tile, offset) = self.tiles_with_offsets().next()?;
352
353 let tile_size = tile.tile_size();
354 let tile_rect = Rectangle::new(offset, tile_size);
355
356 self.working_area.intersection(tile_rect)
357 }
358
359 pub fn popup_target_rect(&self, id: &W::Id) -> Option<Rectangle<f64, Logical>> {
360 for (tile, pos) in self.tiles_with_offsets() {
361 if tile.window().id() == id {
362 // Position within the working area.
363 let mut target = self.working_area;
364 target.loc -= pos;
365 target.loc -= tile.window_loc();
366
367 return Some(target);
368 }
369 }
370 None
371 }
372
373 fn idx_of(&self, id: &W::Id) -> Option<usize> {
374 self.tiles.iter().position(|tile| tile.window().id() == id)
375 }
376
377 fn contains(&self, id: &W::Id) -> bool {
378 self.idx_of(id).is_some()
379 }
380
381 pub fn active_window(&self) -> Option<&W> {
382 let id = self.active_window_id.as_ref()?;
383 self.tiles
384 .iter()
385 .find(|tile| tile.window().id() == id)
386 .map(Tile::window)
387 }
388
389 pub fn active_window_mut(&mut self) -> Option<&mut W> {
390 let id = self.active_window_id.as_ref()?;
391 self.tiles
392 .iter_mut()
393 .find(|tile| tile.window().id() == id)
394 .map(Tile::window_mut)
395 }
396
397 pub fn has_window(&self, id: &W::Id) -> bool {
398 self.tiles.iter().any(|tile| tile.window().id() == id)
399 }
400
401 pub fn is_empty(&self) -> bool {
402 self.tiles.is_empty()
403 }
404
405 pub fn add_tile(&mut self, tile: Tile<W>, activate: bool) {
406 self.add_tile_at(0, tile, activate);
407 }
408
409 fn add_tile_at(&mut self, mut idx: usize, mut tile: Tile<W>, activate: bool) {
410 tile.update_config(self.view_size, self.scale, self.options.clone());
411
412 // Restore the previous floating window size, and in case the tile is fullscreen,
413 // unfullscreen it.
414 let floating_size = tile.floating_window_size;
415 let win = tile.window_mut();
416 let mut size = if !win.pending_sizing_mode().is_normal() {
417 // If the window was fullscreen or maximized without a floating size, ask for (0, 0).
418 floating_size.unwrap_or_default()
419 } else {
420 // If the window wasn't fullscreen without a floating size (e.g. it was tiled before),
421 // ask for the current size. If the current size is unknown (the window was only ever
422 // fullscreen until now), fall back to (0, 0).
423 floating_size.unwrap_or_else(|| win.expected_size().unwrap_or_default())
424 };
425
426 // Apply min/max size window rules. If requesting a concrete size, apply completely; if
427 // requesting (0, 0), apply only when min/max results in a fixed size.
428 let min_size = win.min_size();
429 let max_size = win.max_size();
430 size.w = ensure_min_max_size_maybe_zero(size.w, min_size.w, max_size.w);
431 size.h = ensure_min_max_size_maybe_zero(size.h, min_size.h, max_size.h);
432
433 win.request_size_once(size, true);
434
435 if activate || self.tiles.is_empty() {
436 self.active_window_id = Some(win.id().clone());
437 }
438
439 // Make sure the tile isn't inserted below its parent.
440 for (i, tile_above) in self.tiles.iter().enumerate().take(idx) {
441 if win.is_child_of(tile_above.window()) {
442 idx = i;
443 break;
444 }
445 }
446
447 let pos = self.stored_or_default_tile_pos(&tile).unwrap_or_else(|| {
448 center_preferring_top_left_in_area(self.working_area, tile.tile_size())
449 });
450
451 let data = Data::new(self.working_area, &tile, pos);
452 self.data.insert(idx, data);
453 self.tiles.insert(idx, tile);
454
455 self.bring_up_descendants_of(idx);
456 }
457
458 pub fn add_tile_above(&mut self, above: &W::Id, mut tile: Tile<W>, activate: bool) {
459 let idx = self.idx_of(above).unwrap();
460
461 let above_pos = self.data[idx].logical_pos;
462 let above_size = self.data[idx].size;
463 let tile_size = tile.tile_size();
464 let pos = above_pos + (above_size.to_point() - tile_size.to_point()).downscale(2.);
465 let pos = self.clamp_within_working_area(pos, tile_size);
466 tile.floating_pos = Some(self.logical_to_size_frac(pos));
467
468 self.add_tile_at(idx, tile, activate);
469 }
470
471 fn bring_up_descendants_of(&mut self, idx: usize) {
472 let tile = &self.tiles[idx];
473 let win = tile.window();
474
475 // We always maintain the correct stacking order, so walking descendants back to front
476 // should give us all of them.
477 let mut descendants: Vec<usize> = Vec::new();
478 for (i, tile_below) in self.tiles.iter().enumerate().skip(idx + 1).rev() {
479 let win_below = tile_below.window();
480 if win_below.is_child_of(win)
481 || descendants
482 .iter()
483 .any(|idx| win_below.is_child_of(self.tiles[*idx].window()))
484 {
485 descendants.push(i);
486 }
487 }
488
489 // Now, descendants is in back-to-front order, and repositioning them in the front-to-back
490 // order will preserve the subsequent indices and work out right.
491 let mut idx = idx;
492 for descendant_idx in descendants.into_iter().rev() {
493 self.raise_window(descendant_idx, idx);
494 idx += 1;
495 }
496 }
497
498 pub fn remove_active_tile(&mut self) -> Option<RemovedTile<W>> {
499 let id = self.active_window_id.clone()?;
500 Some(self.remove_tile(&id))
501 }
502
503 pub fn remove_tile(&mut self, id: &W::Id) -> RemovedTile<W> {
504 let idx = self.idx_of(id).unwrap();
505 self.remove_tile_by_idx(idx)
506 }
507
508 fn remove_tile_by_idx(&mut self, idx: usize) -> RemovedTile<W> {
509 let mut tile = self.tiles.remove(idx);
510 let data = self.data.remove(idx);
511
512 if self.tiles.is_empty() {
513 self.active_window_id = None;
514 } else if Some(tile.window().id()) == self.active_window_id.as_ref() {
515 // The active tile was removed, make the topmost tile active.
516 self.active_window_id = Some(self.tiles[0].window().id().clone());
517 }
518
519 // Stop interactive resize.
520 if let Some(resize) = &self.interactive_resize {
521 if tile.window().id() == &resize.window {
522 self.interactive_resize = None;
523 }
524 }
525
526 // Store the floating size if we have one.
527 if let Some(size) = tile.window().expected_size() {
528 tile.floating_window_size = Some(size);
529 }
530 // Store the floating position.
531 tile.floating_pos = Some(data.pos);
532
533 let width = ColumnWidth::Fixed(tile.tile_expected_or_current_size().w);
534 RemovedTile {
535 tile,
536 width,
537 is_full_width: false,
538 is_floating: true,
539 }
540 }
541
542 pub fn start_close_animation_for_window(
543 &mut self,
544 renderer: &mut GlesRenderer,
545 id: &W::Id,
546 blocker: TransactionBlocker,
547 ) {
548 let (tile, tile_pos) = self
549 .tiles_with_render_positions_mut(false)
550 .find(|(tile, _)| tile.window().id() == id)
551 .unwrap();
552
553 let Some(snapshot) = tile.take_unmap_snapshot() else {
554 return;
555 };
556
557 let tile_size = tile.tile_size();
558
559 self.start_close_animation_for_tile(renderer, snapshot, tile_size, tile_pos, blocker);
560 }
561
562 pub fn activate_window_without_raising(&mut self, id: &W::Id) -> bool {
563 if !self.contains(id) {
564 return false;
565 }
566
567 self.active_window_id = Some(id.clone());
568 true
569 }
570
571 pub fn activate_window(&mut self, id: &W::Id) -> bool {
572 let Some(idx) = self.idx_of(id) else {
573 return false;
574 };
575
576 self.raise_window(idx, 0);
577 self.active_window_id = Some(id.clone());
578 self.bring_up_descendants_of(0);
579
580 true
581 }
582
583 fn raise_window(&mut self, from_idx: usize, to_idx: usize) {
584 assert!(to_idx <= from_idx);
585
586 let tile = self.tiles.remove(from_idx);
587 let data = self.data.remove(from_idx);
588 self.tiles.insert(to_idx, tile);
589 self.data.insert(to_idx, data);
590 }
591
592 pub fn start_close_animation_for_tile(
593 &mut self,
594 renderer: &mut GlesRenderer,
595 snapshot: TileRenderSnapshot,
596 tile_size: Size<f64, Logical>,
597 tile_pos: Point<f64, Logical>,
598 blocker: TransactionBlocker,
599 ) {
600 let anim = Animation::new(
601 self.clock.clone(),
602 0.,
603 1.,
604 0.,
605 self.options.animations.window_close.anim,
606 );
607
608 let blocker = if self.options.disable_transactions {
609 TransactionBlocker::completed()
610 } else {
611 blocker
612 };
613
614 let scale = Scale::from(self.scale);
615 let res = ClosingWindow::new(
616 renderer, snapshot, scale, tile_size, tile_pos, blocker, anim,
617 );
618 match res {
619 Ok(closing) => {
620 self.closing_windows.push(closing);
621 }
622 Err(err) => {
623 warn!("error creating a closing window animation: {err:?}");
624 }
625 }
626 }
627
628 pub fn toggle_window_width(&mut self, id: Option<&W::Id>, forwards: bool) {
629 let Some(id) = id.or(self.active_window_id.as_ref()).cloned() else {
630 return;
631 };
632 let idx = self.idx_of(&id).unwrap();
633
634 let available_size = self.working_area.size.w;
635
636 let len = self.options.layout.preset_column_widths.len();
637 let tile = &mut self.tiles[idx];
638 let preset_idx = if let Some(idx) = tile.floating_preset_width_idx {
639 (idx + if forwards { 1 } else { len - 1 }) % len
640 } else {
641 let current_window = tile.window_expected_or_current_size().w;
642 let current_tile = tile.tile_expected_or_current_size().w;
643
644 let mut it = self
645 .options
646 .layout
647 .preset_column_widths
648 .iter()
649 .map(|preset| resolve_preset_size(*preset, available_size));
650
651 if forwards {
652 it.position(|resolved| {
653 match resolved {
654 // Some allowance for fractional scaling purposes.
655 ResolvedSize::Tile(resolved) => current_tile + 1. < resolved,
656 ResolvedSize::Window(resolved) => current_window + 1. < resolved,
657 }
658 })
659 .unwrap_or(0)
660 } else {
661 it.rposition(|resolved| {
662 match resolved {
663 // Some allowance for fractional scaling purposes.
664 ResolvedSize::Tile(resolved) => resolved + 1. < current_tile,
665 ResolvedSize::Window(resolved) => resolved + 1. < current_window,
666 }
667 })
668 .unwrap_or(len - 1)
669 }
670 };
671
672 let preset = self.options.layout.preset_column_widths[preset_idx];
673 self.set_window_width(Some(&id), SizeChange::from(preset), true);
674
675 self.tiles[idx].floating_preset_width_idx = Some(preset_idx);
676
677 self.interactive_resize_end(Some(&id));
678 }
679
680 pub fn start_open_animation(&mut self, id: &W::Id) -> bool {
681 let Some(idx) = self.idx_of(id) else {
682 return false;
683 };
684
685 self.tiles[idx].start_open_animation();
686 true
687 }
688
689 pub fn toggle_window_height(&mut self, id: Option<&W::Id>, forwards: bool) {
690 let Some(id) = id.or(self.active_window_id.as_ref()).cloned() else {
691 return;
692 };
693 let idx = self.idx_of(&id).unwrap();
694
695 let available_size = self.working_area.size.h;
696
697 let len = self.options.layout.preset_window_heights.len();
698 let tile = &mut self.tiles[idx];
699 let preset_idx = if let Some(idx) = tile.floating_preset_height_idx {
700 (idx + if forwards { 1 } else { len - 1 }) % len
701 } else {
702 let current_window = tile.window_expected_or_current_size().h;
703 let current_tile = tile.tile_expected_or_current_size().h;
704
705 let mut it = self
706 .options
707 .layout
708 .preset_window_heights
709 .iter()
710 .map(|preset| resolve_preset_size(*preset, available_size));
711
712 if forwards {
713 it.position(|resolved| {
714 match resolved {
715 // Some allowance for fractional scaling purposes.
716 ResolvedSize::Tile(resolved) => current_tile + 1. < resolved,
717 ResolvedSize::Window(resolved) => current_window + 1. < resolved,
718 }
719 })
720 .unwrap_or(0)
721 } else {
722 it.rposition(|resolved| {
723 match resolved {
724 // Some allowance for fractional scaling purposes.
725 ResolvedSize::Tile(resolved) => resolved + 1. < current_tile,
726 ResolvedSize::Window(resolved) => resolved + 1. < current_window,
727 }
728 })
729 .unwrap_or(len - 1)
730 }
731 };
732
733 let preset = self.options.layout.preset_window_heights[preset_idx];
734 self.set_window_height(Some(&id), SizeChange::from(preset), true);
735
736 let tile = &mut self.tiles[idx];
737 tile.floating_preset_height_idx = Some(preset_idx);
738
739 self.interactive_resize_end(Some(&id));
740 }
741
742 pub fn set_window_width(&mut self, id: Option<&W::Id>, change: SizeChange, animate: bool) {
743 let Some(id) = id.or(self.active_window_id.as_ref()) else {
744 return;
745 };
746 let idx = self.idx_of(id).unwrap();
747
748 let tile = &mut self.tiles[idx];
749 tile.floating_preset_width_idx = None;
750
751 let available_size = self.working_area.size.w;
752 let win = tile.window();
753 let current_window = win.expected_size().unwrap_or_else(|| win.size()).w;
754 let current_tile = tile.tile_expected_or_current_size().w;
755
756 const MAX_PX: f64 = 100000.;
757 const MAX_F: f64 = 10000.;
758
759 let win_width = match change {
760 SizeChange::SetFixed(win_width) => f64::from(win_width),
761 SizeChange::SetProportion(prop) => {
762 let prop = (prop / 100.).clamp(0., MAX_F);
763 let tile_width = available_size * prop;
764 tile.window_width_for_tile_width(tile_width)
765 }
766 SizeChange::AdjustFixed(delta) => f64::from(current_window.saturating_add(delta)),
767 SizeChange::AdjustProportion(delta) => {
768 let current_prop = current_tile / available_size;
769 let prop = (current_prop + delta / 100.).clamp(0., MAX_F);
770 let tile_width = available_size * prop;
771 tile.window_width_for_tile_width(tile_width)
772 }
773 };
774 let win_width = win_width.round().clamp(1., MAX_PX) as i32;
775
776 let win = tile.window_mut();
777 let min_size = win.min_size();
778 let max_size = win.max_size();
779
780 let win_width = ensure_min_max_size(win_width, min_size.w, max_size.w);
781
782 let win_height = win.expected_size().unwrap_or_default().h;
783 let win_height = ensure_min_max_size(win_height, min_size.h, max_size.h);
784
785 let win_size = Size::from((win_width, win_height));
786 win.request_size_once(win_size, animate);
787 }
788
789 pub fn set_window_height(&mut self, id: Option<&W::Id>, change: SizeChange, animate: bool) {
790 let Some(id) = id.or(self.active_window_id.as_ref()) else {
791 return;
792 };
793 let idx = self.idx_of(id).unwrap();
794
795 let tile = &mut self.tiles[idx];
796 tile.floating_preset_height_idx = None;
797
798 let available_size = self.working_area.size.h;
799 let win = tile.window();
800 let current_window = win.expected_size().unwrap_or_else(|| win.size()).h;
801 let current_tile = tile.tile_expected_or_current_size().h;
802
803 const MAX_PX: f64 = 100000.;
804 const MAX_F: f64 = 10000.;
805
806 let win_height = match change {
807 SizeChange::SetFixed(win_height) => f64::from(win_height),
808 SizeChange::SetProportion(prop) => {
809 let prop = (prop / 100.).clamp(0., MAX_F);
810 let tile_height = available_size * prop;
811 tile.window_height_for_tile_height(tile_height)
812 }
813 SizeChange::AdjustFixed(delta) => f64::from(current_window.saturating_add(delta)),
814 SizeChange::AdjustProportion(delta) => {
815 let current_prop = current_tile / available_size;
816 let prop = (current_prop + delta / 100.).clamp(0., MAX_F);
817 let tile_height = available_size * prop;
818 tile.window_height_for_tile_height(tile_height)
819 }
820 };
821 let win_height = win_height.round().clamp(1., MAX_PX) as i32;
822
823 let win = tile.window_mut();
824 let min_size = win.min_size();
825 let max_size = win.max_size();
826
827 let win_height = ensure_min_max_size(win_height, min_size.h, max_size.h);
828
829 let win_width = win.expected_size().unwrap_or_default().w;
830 let win_width = ensure_min_max_size(win_width, min_size.w, max_size.w);
831
832 let win_size = Size::from((win_width, win_height));
833 win.request_size_once(win_size, animate);
834 }
835
836 fn focus_directional(
837 &mut self,
838 distance: impl Fn(Point<f64, Logical>, Point<f64, Logical>) -> f64,
839 ) -> bool {
840 let Some(active_id) = &self.active_window_id else {
841 return false;
842 };
843 let active_idx = self.idx_of(active_id).unwrap();
844 let center = self.data[active_idx].center();
845
846 let result = zip(&self.tiles, &self.data)
847 .filter(|(tile, _)| tile.window().id() != active_id)
848 .map(|(tile, data)| (tile, distance(center, data.center())))
849 .filter(|(_, dist)| *dist > 0.)
850 .min_by(|(_, dist_a), (_, dist_b)| f64::total_cmp(dist_a, dist_b));
851 if let Some((tile, _)) = result {
852 let id = tile.window().id().clone();
853 self.activate_window(&id);
854 true
855 } else {
856 false
857 }
858 }
859
860 pub fn focus_left(&mut self) -> bool {
861 self.focus_directional(|focus, other| focus.x - other.x)
862 }
863
864 pub fn focus_right(&mut self) -> bool {
865 self.focus_directional(|focus, other| other.x - focus.x)
866 }
867
868 pub fn focus_up(&mut self) -> bool {
869 self.focus_directional(|focus, other| focus.y - other.y)
870 }
871
872 pub fn focus_down(&mut self) -> bool {
873 self.focus_directional(|focus, other| other.y - focus.y)
874 }
875
876 pub fn focus_leftmost(&mut self) {
877 let result = self
878 .tiles_with_offsets()
879 .min_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.x, &pos_b.x));
880 if let Some((tile, _)) = result {
881 let id = tile.window().id().clone();
882 self.activate_window(&id);
883 }
884 }
885
886 pub fn focus_rightmost(&mut self) {
887 let result = self
888 .tiles_with_offsets()
889 .max_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.x, &pos_b.x));
890 if let Some((tile, _)) = result {
891 let id = tile.window().id().clone();
892 self.activate_window(&id);
893 }
894 }
895
896 pub fn focus_topmost(&mut self) {
897 let result = self
898 .tiles_with_offsets()
899 .min_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.y, &pos_b.y));
900 if let Some((tile, _)) = result {
901 let id = tile.window().id().clone();
902 self.activate_window(&id);
903 }
904 }
905
906 pub fn focus_bottommost(&mut self) {
907 let result = self
908 .tiles_with_offsets()
909 .max_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.y, &pos_b.y));
910 if let Some((tile, _)) = result {
911 let id = tile.window().id().clone();
912 self.activate_window(&id);
913 }
914 }
915
916 fn move_to(&mut self, idx: usize, new_pos: Point<f64, Logical>, animate: bool) {
917 if animate {
918 self.move_and_animate(idx, new_pos);
919 } else {
920 self.data[idx].set_logical_pos(new_pos);
921 }
922
923 self.interactive_resize_end(None);
924 }
925
926 fn move_by(&mut self, amount: Point<f64, Logical>) {
927 let Some(active_id) = &self.active_window_id else {
928 return;
929 };
930 let idx = self.idx_of(active_id).unwrap();
931
932 let new_pos = self.data[idx].logical_pos + amount;
933 self.move_to(idx, new_pos, true)
934 }
935
936 pub fn move_left(&mut self) {
937 self.move_by(Point::from((-DIRECTIONAL_MOVE_PX, 0.)));
938 }
939
940 pub fn move_right(&mut self) {
941 self.move_by(Point::from((DIRECTIONAL_MOVE_PX, 0.)));
942 }
943
944 pub fn move_up(&mut self) {
945 self.move_by(Point::from((0., -DIRECTIONAL_MOVE_PX)));
946 }
947
948 pub fn move_down(&mut self) {
949 self.move_by(Point::from((0., DIRECTIONAL_MOVE_PX)));
950 }
951
952 pub fn move_window(
953 &mut self,
954 id: Option<&W::Id>,
955 x: PositionChange,
956 y: PositionChange,
957 animate: bool,
958 ) {
959 let Some(id) = id.or(self.active_window_id.as_ref()) else {
960 return;
961 };
962 let idx = self.idx_of(id).unwrap();
963
964 let mut pos = self.data[idx].logical_pos;
965
966 let available_width = self.working_area.size.w;
967 let available_height = self.working_area.size.h;
968 let working_area_loc = self.working_area.loc;
969
970 const MAX_F: f64 = 10000.;
971
972 match x {
973 PositionChange::SetFixed(x) => pos.x = x + working_area_loc.x,
974 PositionChange::SetProportion(prop) => {
975 let prop = (prop / 100.).clamp(0., MAX_F);
976 pos.x = available_width * prop + working_area_loc.x;
977 }
978 PositionChange::AdjustFixed(x) => pos.x += x,
979 PositionChange::AdjustProportion(prop) => {
980 let current_prop = (pos.x - working_area_loc.x) / available_width.max(1.);
981 let prop = (current_prop + prop / 100.).clamp(0., MAX_F);
982 pos.x = available_width * prop + working_area_loc.x;
983 }
984 }
985 match y {
986 PositionChange::SetFixed(y) => pos.y = y + working_area_loc.y,
987 PositionChange::SetProportion(prop) => {
988 let prop = (prop / 100.).clamp(0., MAX_F);
989 pos.y = available_height * prop + working_area_loc.y;
990 }
991 PositionChange::AdjustFixed(y) => pos.y += y,
992 PositionChange::AdjustProportion(prop) => {
993 let current_prop = (pos.y - working_area_loc.y) / available_height.max(1.);
994 let prop = (current_prop + prop / 100.).clamp(0., MAX_F);
995 pos.y = available_height * prop + working_area_loc.y;
996 }
997 }
998
999 self.move_to(idx, pos, animate);
1000 }
1001
1002 pub fn center_window(&mut self, id: Option<&W::Id>) {
1003 let Some(id) = id.or(self.active_window_id.as_ref()).cloned() else {
1004 return;
1005 };
1006 let idx = self.idx_of(&id).unwrap();
1007
1008 let new_pos = center_preferring_top_left_in_area(self.working_area, self.data[idx].size);
1009 self.move_to(idx, new_pos, true);
1010 }
1011
1012 pub fn descendants_added(&mut self, id: &W::Id) -> bool {
1013 let Some(idx) = self.idx_of(id) else {
1014 return false;
1015 };
1016
1017 self.bring_up_descendants_of(idx);
1018 true
1019 }
1020
1021 pub fn update_window(&mut self, id: &W::Id, serial: Option<Serial>) -> bool {
1022 let Some(tile_idx) = self.idx_of(id) else {
1023 return false;
1024 };
1025
1026 let tile = &mut self.tiles[tile_idx];
1027 let data = &mut self.data[tile_idx];
1028
1029 let resize = tile.window_mut().interactive_resize_data();
1030
1031 // Do this before calling update_window() so it can get up-to-date info.
1032 if let Some(serial) = serial {
1033 tile.window_mut().on_commit(serial);
1034 }
1035
1036 let prev_size = data.size;
1037
1038 tile.update_window();
1039 data.update(tile);
1040
1041 // When resizing by top/left edge, update the position accordingly.
1042 if let Some(resize) = resize {
1043 let mut offset = Point::from((0., 0.));
1044 if resize.edges.contains(ResizeEdge::LEFT) {
1045 offset.x += prev_size.w - data.size.w;
1046 }
1047 if resize.edges.contains(ResizeEdge::TOP) {
1048 offset.y += prev_size.h - data.size.h;
1049 }
1050 data.set_logical_pos(data.logical_pos + offset);
1051 }
1052
1053 true
1054 }
1055
1056 pub fn render_elements<R: NiriRenderer>(
1057 &self,
1058 renderer: &mut R,
1059 view_rect: Rectangle<f64, Logical>,
1060 target: RenderTarget,
1061 focus_ring: bool,
1062 ) -> Vec<FloatingSpaceRenderElement<R>> {
1063 let mut rv = Vec::new();
1064
1065 let scale = Scale::from(self.scale);
1066
1067 // Draw the closing windows on top of the other windows.
1068 //
1069 // FIXME: I guess this should rather preserve the stacking order when the window is closed.
1070 for closing in self.closing_windows.iter().rev() {
1071 let elem = closing.render(renderer.as_gles_renderer(), view_rect, scale, target);
1072 rv.push(elem.into());
1073 }
1074
1075 let active = self.active_window_id.clone();
1076 for (tile, tile_pos) in self.tiles_with_render_positions() {
1077 // For the active tile, draw the focus ring.
1078 let focus_ring = focus_ring && Some(tile.window().id()) == active.as_ref();
1079
1080 rv.extend(
1081 tile.render(renderer, tile_pos, focus_ring, target)
1082 .map(Into::into),
1083 );
1084 }
1085
1086 rv
1087 }
1088
1089 pub fn interactive_resize_begin(&mut self, window: W::Id, edges: ResizeEdge) -> bool {
1090 if self.interactive_resize.is_some() {
1091 return false;
1092 }
1093
1094 let tile = self
1095 .tiles
1096 .iter_mut()
1097 .find(|tile| tile.window().id() == &window)
1098 .unwrap();
1099
1100 let original_window_size = tile.window_size();
1101
1102 let resize = InteractiveResize {
1103 window,
1104 original_window_size,
1105 data: InteractiveResizeData { edges },
1106 };
1107 self.interactive_resize = Some(resize);
1108
1109 true
1110 }
1111
1112 pub fn interactive_resize_update(
1113 &mut self,
1114 window: &W::Id,
1115 delta: Point<f64, Logical>,
1116 ) -> bool {
1117 let Some(resize) = &self.interactive_resize else {
1118 return false;
1119 };
1120
1121 if window != &resize.window {
1122 return false;
1123 }
1124
1125 let original_window_size = resize.original_window_size;
1126 let edges = resize.data.edges;
1127
1128 if edges.intersects(ResizeEdge::LEFT_RIGHT) {
1129 let mut dx = delta.x;
1130 if edges.contains(ResizeEdge::LEFT) {
1131 dx = -dx;
1132 };
1133
1134 let window_width = (original_window_size.w + dx).round() as i32;
1135 self.set_window_width(Some(window), SizeChange::SetFixed(window_width), false);
1136 }
1137
1138 if edges.intersects(ResizeEdge::TOP_BOTTOM) {
1139 let mut dy = delta.y;
1140 if edges.contains(ResizeEdge::TOP) {
1141 dy = -dy;
1142 };
1143
1144 let window_height = (original_window_size.h + dy).round() as i32;
1145 self.set_window_height(Some(window), SizeChange::SetFixed(window_height), false);
1146 }
1147
1148 true
1149 }
1150
1151 pub fn interactive_resize_end(&mut self, window: Option<&W::Id>) {
1152 let Some(resize) = &self.interactive_resize else {
1153 return;
1154 };
1155
1156 if let Some(window) = window {
1157 if window != &resize.window {
1158 return;
1159 }
1160 }
1161
1162 self.interactive_resize = None;
1163 }
1164
1165 pub fn refresh(&mut self, is_active: bool, is_focused: bool) {
1166 let active = self.active_window_id.clone();
1167 for tile in &mut self.tiles {
1168 let win = tile.window_mut();
1169
1170 win.set_active_in_column(true);
1171 win.set_floating(true);
1172
1173 let mut is_active = is_active && Some(win.id()) == active.as_ref();
1174 if self.options.deactivate_unfocused_windows {
1175 is_active &= is_focused;
1176 }
1177 win.set_activated(is_active);
1178
1179 let resize_data = self
1180 .interactive_resize
1181 .as_ref()
1182 .filter(|resize| &resize.window == win.id())
1183 .map(|resize| resize.data);
1184 win.set_interactive_resize(resize_data);
1185
1186 let border_config = self.options.layout.border.merged_with(&win.rules().border);
1187 let bounds = compute_toplevel_bounds(border_config, self.working_area.size);
1188 win.set_bounds(bounds);
1189
1190 // If transactions are disabled, also disable combined throttling, for more
1191 // intuitive behavior.
1192 let intent = if self.options.disable_resize_throttling {
1193 ConfigureIntent::CanSend
1194 } else {
1195 win.configure_intent()
1196 };
1197
1198 if matches!(
1199 intent,
1200 ConfigureIntent::CanSend | ConfigureIntent::ShouldSend
1201 ) {
1202 win.send_pending_configure();
1203 }
1204
1205 win.refresh();
1206 }
1207 }
1208
1209 pub fn clamp_within_working_area(
1210 &self,
1211 pos: Point<f64, Logical>,
1212 size: Size<f64, Logical>,
1213 ) -> Point<f64, Logical> {
1214 let mut rect = Rectangle::new(pos, size);
1215 clamp_preferring_top_left_in_area(self.working_area, &mut rect);
1216 rect.loc
1217 }
1218
1219 pub fn scale_by_working_area(&self, pos: Point<f64, SizeFrac>) -> Point<f64, Logical> {
1220 Data::scale_by_working_area(self.working_area, pos)
1221 }
1222
1223 pub fn logical_to_size_frac(&self, logical_pos: Point<f64, Logical>) -> Point<f64, SizeFrac> {
1224 Data::logical_to_size_frac_in_working_area(self.working_area, logical_pos)
1225 }
1226
1227 fn move_and_animate(&mut self, idx: usize, new_pos: Point<f64, Logical>) {
1228 // Moves up to this logical pixel distance are not animated.
1229 const ANIMATION_THRESHOLD_SQ: f64 = 10. * 10.;
1230
1231 let tile = &mut self.tiles[idx];
1232 let data = &mut self.data[idx];
1233
1234 let prev_pos = data.logical_pos;
1235 data.set_logical_pos(new_pos);
1236 let new_pos = data.logical_pos;
1237
1238 let diff = prev_pos - new_pos;
1239 if diff.x * diff.x + diff.y * diff.y > ANIMATION_THRESHOLD_SQ {
1240 tile.animate_move_from(prev_pos - new_pos);
1241 }
1242 }
1243
1244 pub fn new_window_size(
1245 &self,
1246 width: Option<PresetSize>,
1247 height: Option<PresetSize>,
1248 rules: &ResolvedWindowRules,
1249 ) -> Size<i32, Logical> {
1250 let border = self.options.layout.border.merged_with(&rules.border);
1251
1252 let resolve = |size: Option<PresetSize>, working_area_size: f64| {
1253 if let Some(size) = size {
1254 let size = match resolve_preset_size(size, working_area_size) {
1255 ResolvedSize::Tile(mut size) => {
1256 if !border.off {
1257 size -= border.width * 2.;
1258 }
1259 size
1260 }
1261 ResolvedSize::Window(size) => size,
1262 };
1263
1264 max(1, size.floor() as i32)
1265 } else {
1266 0
1267 }
1268 };
1269
1270 let width = resolve(width, self.working_area.size.w);
1271 let height = resolve(height, self.working_area.size.h);
1272
1273 Size::from((width, height))
1274 }
1275
1276 pub fn stored_or_default_tile_pos(&self, tile: &Tile<W>) -> Option<Point<f64, Logical>> {
1277 let pos = tile.floating_pos.map(|pos| self.scale_by_working_area(pos));
1278 pos.or_else(|| {
1279 tile.window().rules().default_floating_position.map(|pos| {
1280 let relative_to = pos.relative_to;
1281 let size = tile.tile_size();
1282 let area = self.working_area;
1283
1284 let mut pos = Point::from((pos.x.0, pos.y.0));
1285 if relative_to == RelativeTo::TopRight
1286 || relative_to == RelativeTo::BottomRight
1287 || relative_to == RelativeTo::Right
1288 {
1289 pos.x = area.size.w - size.w - pos.x;
1290 }
1291 if relative_to == RelativeTo::BottomLeft
1292 || relative_to == RelativeTo::BottomRight
1293 || relative_to == RelativeTo::Bottom
1294 {
1295 pos.y = area.size.h - size.h - pos.y;
1296 }
1297 if relative_to == RelativeTo::Top || relative_to == RelativeTo::Bottom {
1298 pos.x += area.size.w / 2.0 - size.w / 2.0
1299 }
1300 if relative_to == RelativeTo::Left || relative_to == RelativeTo::Right {
1301 pos.y += area.size.h / 2.0 - size.h / 2.0
1302 }
1303
1304 pos + self.working_area.loc
1305 })
1306 })
1307 }
1308
1309 #[cfg(test)]
1310 pub fn view_size(&self) -> Size<f64, Logical> {
1311 self.view_size
1312 }
1313
1314 pub fn working_area(&self) -> Rectangle<f64, Logical> {
1315 self.working_area
1316 }
1317
1318 #[cfg(test)]
1319 pub fn scale(&self) -> f64 {
1320 self.scale
1321 }
1322
1323 #[cfg(test)]
1324 pub fn clock(&self) -> &Clock {
1325 &self.clock
1326 }
1327
1328 #[cfg(test)]
1329 pub fn options(&self) -> &Rc<Options> {
1330 &self.options
1331 }
1332
1333 #[cfg(test)]
1334 pub fn verify_invariants(&self) {
1335 assert!(self.scale > 0.);
1336 assert!(self.scale.is_finite());
1337 assert_eq!(self.tiles.len(), self.data.len());
1338
1339 for (i, (tile, data)) in zip(&self.tiles, &self.data).enumerate() {
1340 use crate::layout::SizingMode;
1341
1342 assert!(Rc::ptr_eq(&self.options, &tile.options));
1343 assert_eq!(self.view_size, tile.view_size());
1344 assert_eq!(self.clock, tile.clock);
1345 assert_eq!(self.scale, tile.scale());
1346 tile.verify_invariants();
1347
1348 if let Some(idx) = tile.floating_preset_width_idx {
1349 assert!(idx < self.options.layout.preset_column_widths.len());
1350 }
1351 if let Some(idx) = tile.floating_preset_height_idx {
1352 assert!(idx < self.options.layout.preset_window_heights.len());
1353 }
1354
1355 assert_eq!(
1356 tile.window().pending_sizing_mode(),
1357 SizingMode::Normal,
1358 "floating windows cannot be maximized or fullscreen"
1359 );
1360
1361 data.verify_invariants();
1362
1363 let mut data2 = *data;
1364 data2.update(tile);
1365 data2.update_config(self.working_area);
1366 assert_eq!(data, &data2, "tile data must be up to date");
1367
1368 for tile_below in &self.tiles[i + 1..] {
1369 assert!(
1370 !tile_below.window().is_child_of(tile.window()),
1371 "children must be stacked above parents"
1372 );
1373 }
1374 }
1375
1376 if let Some(id) = &self.active_window_id {
1377 assert!(!self.tiles.is_empty());
1378 assert!(self.contains(id), "active window must be present in tiles");
1379 } else {
1380 assert!(self.tiles.is_empty());
1381 }
1382
1383 if let Some(resize) = &self.interactive_resize {
1384 assert!(
1385 self.contains(&resize.window),
1386 "interactive resize window must be present in tiles"
1387 );
1388 }
1389 }
1390}
1391
1392fn compute_toplevel_bounds(
1393 border_config: niri_config::Border,
1394 working_area_size: Size<f64, Logical>,
1395) -> Size<i32, Logical> {
1396 let mut border = 0.;
1397 if !border_config.off {
1398 border = border_config.width * 2.;
1399 }
1400
1401 Size::from((
1402 f64::max(working_area_size.w - border, 1.),
1403 f64::max(working_area_size.h - border, 1.),
1404 ))
1405 .to_i32_floor()
1406}
1407
1408fn resolve_preset_size(preset: PresetSize, view_size: f64) -> ResolvedSize {
1409 match preset {
1410 PresetSize::Proportion(proportion) => ResolvedSize::Tile(view_size * proportion),
1411 PresetSize::Fixed(width) => ResolvedSize::Window(f64::from(width)),
1412 }
1413}