forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBdde9214Ivan Molodetskikh1 year ago1835 commits

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