forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB90ef202Ivan Molodetskikh1 year ago2349 commits

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