forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBad3847fIvan Molodetskikh1 year ago2457 commits

floating.rs1385 lines, 45.5 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.is_pending_fullscreen() {
417 // If the window was fullscreen 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 new_pos = self.data[idx].logical_pos;
965 match x {
966 PositionChange::SetFixed(x) => new_pos.x = x + self.working_area.loc.x,
967 PositionChange::AdjustFixed(x) => new_pos.x += x,
968 }
969 match y {
970 PositionChange::SetFixed(y) => new_pos.y = y + self.working_area.loc.y,
971 PositionChange::AdjustFixed(y) => new_pos.y += y,
972 }
973
974 self.move_to(idx, new_pos, animate);
975 }
976
977 pub fn center_window(&mut self, id: Option<&W::Id>) {
978 let Some(id) = id.or(self.active_window_id.as_ref()).cloned() else {
979 return;
980 };
981 let idx = self.idx_of(&id).unwrap();
982
983 let new_pos = center_preferring_top_left_in_area(self.working_area, self.data[idx].size);
984 self.move_to(idx, new_pos, true);
985 }
986
987 pub fn descendants_added(&mut self, id: &W::Id) -> bool {
988 let Some(idx) = self.idx_of(id) else {
989 return false;
990 };
991
992 self.bring_up_descendants_of(idx);
993 true
994 }
995
996 pub fn update_window(&mut self, id: &W::Id, serial: Option<Serial>) -> bool {
997 let Some(tile_idx) = self.idx_of(id) else {
998 return false;
999 };
1000
1001 let tile = &mut self.tiles[tile_idx];
1002 let data = &mut self.data[tile_idx];
1003
1004 let resize = tile.window_mut().interactive_resize_data();
1005
1006 // Do this before calling update_window() so it can get up-to-date info.
1007 if let Some(serial) = serial {
1008 tile.window_mut().on_commit(serial);
1009 }
1010
1011 let prev_size = data.size;
1012
1013 tile.update_window();
1014 data.update(tile);
1015
1016 // When resizing by top/left edge, update the position accordingly.
1017 if let Some(resize) = resize {
1018 let mut offset = Point::from((0., 0.));
1019 if resize.edges.contains(ResizeEdge::LEFT) {
1020 offset.x += prev_size.w - data.size.w;
1021 }
1022 if resize.edges.contains(ResizeEdge::TOP) {
1023 offset.y += prev_size.h - data.size.h;
1024 }
1025 data.set_logical_pos(data.logical_pos + offset);
1026 }
1027
1028 true
1029 }
1030
1031 pub fn render_elements<R: NiriRenderer>(
1032 &self,
1033 renderer: &mut R,
1034 view_rect: Rectangle<f64, Logical>,
1035 target: RenderTarget,
1036 focus_ring: bool,
1037 ) -> Vec<FloatingSpaceRenderElement<R>> {
1038 let mut rv = Vec::new();
1039
1040 let scale = Scale::from(self.scale);
1041
1042 // Draw the closing windows on top of the other windows.
1043 //
1044 // FIXME: I guess this should rather preserve the stacking order when the window is closed.
1045 for closing in self.closing_windows.iter().rev() {
1046 let elem = closing.render(renderer.as_gles_renderer(), view_rect, scale, target);
1047 rv.push(elem.into());
1048 }
1049
1050 let active = self.active_window_id.clone();
1051 for (tile, tile_pos) in self.tiles_with_render_positions() {
1052 // For the active tile, draw the focus ring.
1053 let focus_ring = focus_ring && Some(tile.window().id()) == active.as_ref();
1054
1055 rv.extend(
1056 tile.render(renderer, tile_pos, focus_ring, target)
1057 .map(Into::into),
1058 );
1059 }
1060
1061 rv
1062 }
1063
1064 pub fn interactive_resize_begin(&mut self, window: W::Id, edges: ResizeEdge) -> bool {
1065 if self.interactive_resize.is_some() {
1066 return false;
1067 }
1068
1069 let tile = self
1070 .tiles
1071 .iter_mut()
1072 .find(|tile| tile.window().id() == &window)
1073 .unwrap();
1074
1075 let original_window_size = tile.window_size();
1076
1077 let resize = InteractiveResize {
1078 window,
1079 original_window_size,
1080 data: InteractiveResizeData { edges },
1081 };
1082 self.interactive_resize = Some(resize);
1083
1084 true
1085 }
1086
1087 pub fn interactive_resize_update(
1088 &mut self,
1089 window: &W::Id,
1090 delta: Point<f64, Logical>,
1091 ) -> bool {
1092 let Some(resize) = &self.interactive_resize else {
1093 return false;
1094 };
1095
1096 if window != &resize.window {
1097 return false;
1098 }
1099
1100 let original_window_size = resize.original_window_size;
1101 let edges = resize.data.edges;
1102
1103 if edges.intersects(ResizeEdge::LEFT_RIGHT) {
1104 let mut dx = delta.x;
1105 if edges.contains(ResizeEdge::LEFT) {
1106 dx = -dx;
1107 };
1108
1109 let window_width = (original_window_size.w + dx).round() as i32;
1110 self.set_window_width(Some(window), SizeChange::SetFixed(window_width), false);
1111 }
1112
1113 if edges.intersects(ResizeEdge::TOP_BOTTOM) {
1114 let mut dy = delta.y;
1115 if edges.contains(ResizeEdge::TOP) {
1116 dy = -dy;
1117 };
1118
1119 let window_height = (original_window_size.h + dy).round() as i32;
1120 self.set_window_height(Some(window), SizeChange::SetFixed(window_height), false);
1121 }
1122
1123 true
1124 }
1125
1126 pub fn interactive_resize_end(&mut self, window: Option<&W::Id>) {
1127 let Some(resize) = &self.interactive_resize else {
1128 return;
1129 };
1130
1131 if let Some(window) = window {
1132 if window != &resize.window {
1133 return;
1134 }
1135 }
1136
1137 self.interactive_resize = None;
1138 }
1139
1140 pub fn refresh(&mut self, is_active: bool, is_focused: bool) {
1141 let active = self.active_window_id.clone();
1142 for tile in &mut self.tiles {
1143 let win = tile.window_mut();
1144
1145 win.set_active_in_column(true);
1146 win.set_floating(true);
1147
1148 let mut is_active = is_active && Some(win.id()) == active.as_ref();
1149 if self.options.deactivate_unfocused_windows {
1150 is_active &= is_focused;
1151 }
1152 win.set_activated(is_active);
1153
1154 let resize_data = self
1155 .interactive_resize
1156 .as_ref()
1157 .filter(|resize| &resize.window == win.id())
1158 .map(|resize| resize.data);
1159 win.set_interactive_resize(resize_data);
1160
1161 let border_config = self.options.layout.border.merged_with(&win.rules().border);
1162 let bounds = compute_toplevel_bounds(border_config, self.working_area.size);
1163 win.set_bounds(bounds);
1164
1165 // If transactions are disabled, also disable combined throttling, for more
1166 // intuitive behavior.
1167 let intent = if self.options.disable_resize_throttling {
1168 ConfigureIntent::CanSend
1169 } else {
1170 win.configure_intent()
1171 };
1172
1173 if matches!(
1174 intent,
1175 ConfigureIntent::CanSend | ConfigureIntent::ShouldSend
1176 ) {
1177 win.send_pending_configure();
1178 }
1179
1180 win.refresh();
1181 }
1182 }
1183
1184 pub fn clamp_within_working_area(
1185 &self,
1186 pos: Point<f64, Logical>,
1187 size: Size<f64, Logical>,
1188 ) -> Point<f64, Logical> {
1189 let mut rect = Rectangle::new(pos, size);
1190 clamp_preferring_top_left_in_area(self.working_area, &mut rect);
1191 rect.loc
1192 }
1193
1194 pub fn scale_by_working_area(&self, pos: Point<f64, SizeFrac>) -> Point<f64, Logical> {
1195 Data::scale_by_working_area(self.working_area, pos)
1196 }
1197
1198 pub fn logical_to_size_frac(&self, logical_pos: Point<f64, Logical>) -> Point<f64, SizeFrac> {
1199 Data::logical_to_size_frac_in_working_area(self.working_area, logical_pos)
1200 }
1201
1202 fn move_and_animate(&mut self, idx: usize, new_pos: Point<f64, Logical>) {
1203 // Moves up to this logical pixel distance are not animated.
1204 const ANIMATION_THRESHOLD_SQ: f64 = 10. * 10.;
1205
1206 let tile = &mut self.tiles[idx];
1207 let data = &mut self.data[idx];
1208
1209 let prev_pos = data.logical_pos;
1210 data.set_logical_pos(new_pos);
1211 let new_pos = data.logical_pos;
1212
1213 let diff = prev_pos - new_pos;
1214 if diff.x * diff.x + diff.y * diff.y > ANIMATION_THRESHOLD_SQ {
1215 tile.animate_move_from(prev_pos - new_pos);
1216 }
1217 }
1218
1219 pub fn new_window_size(
1220 &self,
1221 width: Option<PresetSize>,
1222 height: Option<PresetSize>,
1223 rules: &ResolvedWindowRules,
1224 ) -> Size<i32, Logical> {
1225 let border = self.options.layout.border.merged_with(&rules.border);
1226
1227 let resolve = |size: Option<PresetSize>, working_area_size: f64| {
1228 if let Some(size) = size {
1229 let size = match resolve_preset_size(size, working_area_size) {
1230 ResolvedSize::Tile(mut size) => {
1231 if !border.off {
1232 size -= border.width * 2.;
1233 }
1234 size
1235 }
1236 ResolvedSize::Window(size) => size,
1237 };
1238
1239 max(1, size.floor() as i32)
1240 } else {
1241 0
1242 }
1243 };
1244
1245 let width = resolve(width, self.working_area.size.w);
1246 let height = resolve(height, self.working_area.size.h);
1247
1248 Size::from((width, height))
1249 }
1250
1251 pub fn stored_or_default_tile_pos(&self, tile: &Tile<W>) -> Option<Point<f64, Logical>> {
1252 let pos = tile.floating_pos.map(|pos| self.scale_by_working_area(pos));
1253 pos.or_else(|| {
1254 tile.window().rules().default_floating_position.map(|pos| {
1255 let relative_to = pos.relative_to;
1256 let size = tile.tile_size();
1257 let area = self.working_area;
1258
1259 let mut pos = Point::from((pos.x.0, pos.y.0));
1260 if relative_to == RelativeTo::TopRight
1261 || relative_to == RelativeTo::BottomRight
1262 || relative_to == RelativeTo::Right
1263 {
1264 pos.x = area.size.w - size.w - pos.x;
1265 }
1266 if relative_to == RelativeTo::BottomLeft
1267 || relative_to == RelativeTo::BottomRight
1268 || relative_to == RelativeTo::Bottom
1269 {
1270 pos.y = area.size.h - size.h - pos.y;
1271 }
1272 if relative_to == RelativeTo::Top || relative_to == RelativeTo::Bottom {
1273 pos.x += area.size.w / 2.0 - size.w / 2.0
1274 }
1275 if relative_to == RelativeTo::Left || relative_to == RelativeTo::Right {
1276 pos.y += area.size.h / 2.0 - size.h / 2.0
1277 }
1278
1279 pos + self.working_area.loc
1280 })
1281 })
1282 }
1283
1284 #[cfg(test)]
1285 pub fn view_size(&self) -> Size<f64, Logical> {
1286 self.view_size
1287 }
1288
1289 pub fn working_area(&self) -> Rectangle<f64, Logical> {
1290 self.working_area
1291 }
1292
1293 #[cfg(test)]
1294 pub fn scale(&self) -> f64 {
1295 self.scale
1296 }
1297
1298 #[cfg(test)]
1299 pub fn clock(&self) -> &Clock {
1300 &self.clock
1301 }
1302
1303 #[cfg(test)]
1304 pub fn options(&self) -> &Rc<Options> {
1305 &self.options
1306 }
1307
1308 #[cfg(test)]
1309 pub fn verify_invariants(&self) {
1310 assert!(self.scale > 0.);
1311 assert!(self.scale.is_finite());
1312 assert_eq!(self.tiles.len(), self.data.len());
1313
1314 for (i, (tile, data)) in zip(&self.tiles, &self.data).enumerate() {
1315 assert!(Rc::ptr_eq(&self.options, &tile.options));
1316 assert_eq!(self.view_size, tile.view_size());
1317 assert_eq!(self.clock, tile.clock);
1318 assert_eq!(self.scale, tile.scale());
1319 tile.verify_invariants();
1320
1321 if let Some(idx) = tile.floating_preset_width_idx {
1322 assert!(idx < self.options.layout.preset_column_widths.len());
1323 }
1324 if let Some(idx) = tile.floating_preset_height_idx {
1325 assert!(idx < self.options.layout.preset_window_heights.len());
1326 }
1327
1328 assert!(
1329 !tile.window().is_pending_fullscreen(),
1330 "floating windows cannot be fullscreen"
1331 );
1332
1333 data.verify_invariants();
1334
1335 let mut data2 = *data;
1336 data2.update(tile);
1337 data2.update_config(self.working_area);
1338 assert_eq!(data, &data2, "tile data must be up to date");
1339
1340 for tile_below in &self.tiles[i + 1..] {
1341 assert!(
1342 !tile_below.window().is_child_of(tile.window()),
1343 "children must be stacked above parents"
1344 );
1345 }
1346 }
1347
1348 if let Some(id) = &self.active_window_id {
1349 assert!(!self.tiles.is_empty());
1350 assert!(self.contains(id), "active window must be present in tiles");
1351 } else {
1352 assert!(self.tiles.is_empty());
1353 }
1354
1355 if let Some(resize) = &self.interactive_resize {
1356 assert!(
1357 self.contains(&resize.window),
1358 "interactive resize window must be present in tiles"
1359 );
1360 }
1361 }
1362}
1363
1364fn compute_toplevel_bounds(
1365 border_config: niri_config::Border,
1366 working_area_size: Size<f64, Logical>,
1367) -> Size<i32, Logical> {
1368 let mut border = 0.;
1369 if !border_config.off {
1370 border = border_config.width * 2.;
1371 }
1372
1373 Size::from((
1374 f64::max(working_area_size.w - border, 1.),
1375 f64::max(working_area_size.h - border, 1.),
1376 ))
1377 .to_i32_floor()
1378}
1379
1380fn resolve_preset_size(preset: PresetSize, view_size: f64) -> ResolvedSize {
1381 match preset {
1382 PresetSize::Proportion(proportion) => ResolvedSize::Tile(view_size * proportion),
1383 PresetSize::Fixed(width) => ResolvedSize::Window(f64::from(width)),
1384 }
1385}