Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431use std::cmp::max;use std::iter::zip;use std::rc::Rc;
use niri_config::utils::MergeWith as _;use niri_config::{PresetSize, RelativeTo};use niri_ipc::{PositionChange, SizeChange, WindowLayout};use smithay::backend::renderer::gles::GlesRenderer;use smithay::utils::{Logical, Point, Rectangle, Scale, Serial, Size};
use super::closing_window::{ClosingWindow, ClosingWindowRenderElement};use super::scrolling::ColumnWidth;use super::tile::{Tile, TileRenderElement, TileRenderSnapshot};use super::workspace::{InteractiveResize, ResolvedSize};use super::{ ConfigureIntent, InteractiveResizeData, LayoutElement, Options, RemovedTile, SizeFrac,};use crate::animation::{Animation, Clock};use crate::layout::RenderLayer;use crate::niri_render_elements;use crate::render_helpers::renderer::NiriRenderer;use crate::render_helpers::xray::XrayPos;use crate::render_helpers::RenderCtx;use crate::utils::transaction::TransactionBlocker;use crate::utils::{ center_preferring_top_left_in_area, clamp_preferring_top_left_in_area, ensure_min_max_size, ensure_min_max_size_maybe_zero, ResizeEdge,};use crate::window::ResolvedWindowRules;
/// By how many logical pixels the directional move commands move floating windows.pub const DIRECTIONAL_MOVE_PX: f64 = 50.;
/// Space for floating windows.#[derive(Debug)]pub struct FloatingSpace<W: LayoutElement> { /// Tiles in top-to-bottom order. tiles: Vec<Tile<W>>,
/// Extra per-tile data. data: Vec<Data>,
/// Id of the active window. /// /// The active window is not necessarily the topmost window. Focus-follows-mouse should /// activate a window, but not bring it to the top, because that's very annoying. /// /// This is always set to `Some()` when `tiles` isn't empty. active_window_id: Option<W::Id>,
/// Ongoing interactive resize. interactive_resize: Option<InteractiveResize<W>>,
/// Windows in the closing animation. closing_windows: Vec<ClosingWindow>,
/// View size for this space. view_size: Size<f64, Logical>,
/// Working area for this space. working_area: Rectangle<f64, Logical>,
/// Scale of the output the space is on (and rounds its sizes to). scale: f64,
/// Clock for driving animations. clock: Clock,
/// Configurable properties of the layout. options: Rc<Options>,}
niri_render_elements! { FloatingSpaceRenderElement<R> => { Tile = TileRenderElement<R>, ClosingWindow = ClosingWindowRenderElement, }}
/// Extra per-tile data.#[derive(Debug, Clone, Copy, PartialEq)]struct Data { /// Position relative to the working area. pos: Point<f64, SizeFrac>,
/// Cached position in logical coordinates. /// /// Not rounded to physical pixels. logical_pos: Point<f64, Logical>,
/// Cached actual size of the tile. size: Size<f64, Logical>,
/// Working area used for conversions. working_area: Rectangle<f64, Logical>,}
impl Data { pub fn new<W: LayoutElement>( working_area: Rectangle<f64, Logical>, tile: &Tile<W>, logical_pos: Point<f64, Logical>, ) -> Self { let mut rv = Self { pos: Point::default(), logical_pos: Point::default(), size: Size::default(), working_area, }; rv.update(tile); rv.set_logical_pos(logical_pos); rv }
pub fn scale_by_working_area( area: Rectangle<f64, Logical>, pos: Point<f64, SizeFrac>, ) -> Point<f64, Logical> { let mut logical_pos = Point::from((pos.x, pos.y)); logical_pos.x *= area.size.w; logical_pos.y *= area.size.h; logical_pos += area.loc; logical_pos }
pub fn logical_to_size_frac_in_working_area( area: Rectangle<f64, Logical>, logical_pos: Point<f64, Logical>, ) -> Point<f64, SizeFrac> { let pos = logical_pos - area.loc; let mut pos = Point::from((pos.x, pos.y)); pos.x /= f64::max(area.size.w, 1.0); pos.y /= f64::max(area.size.h, 1.0); pos }
fn recompute_logical_pos(&mut self) { let mut logical_pos = Self::scale_by_working_area(self.working_area, self.pos);
// Make sure the window doesn't go too much off-screen. Numbers taken from Mutter. let min_on_screen_hor = f64::clamp(self.size.w / 4., 10., 75.); let min_on_screen_ver = f64::clamp(self.size.h / 4., 10., 75.); let max_off_screen_hor = f64::max(0., self.size.w - min_on_screen_hor); let max_off_screen_ver = f64::max(0., self.size.h - min_on_screen_ver);
logical_pos -= self.working_area.loc; logical_pos.x = f64::max(logical_pos.x, -max_off_screen_hor); logical_pos.y = f64::max(logical_pos.y, -max_off_screen_ver); logical_pos.x = f64::min( logical_pos.x, self.working_area.size.w - self.size.w + max_off_screen_hor, ); logical_pos.y = f64::min( logical_pos.y, self.working_area.size.h - self.size.h + max_off_screen_ver, ); logical_pos += self.working_area.loc;
self.logical_pos = logical_pos; }
pub fn update_config(&mut self, working_area: Rectangle<f64, Logical>) { if self.working_area == working_area { return; }
self.working_area = working_area; self.recompute_logical_pos(); }
pub fn update<W: LayoutElement>(&mut self, tile: &Tile<W>) { let size = tile.tile_size(); if self.size == size { return; }
self.size = size; self.recompute_logical_pos(); }
pub fn set_logical_pos(&mut self, logical_pos: Point<f64, Logical>) { self.pos = Self::logical_to_size_frac_in_working_area(self.working_area, logical_pos);
// This will clamp the logical position to the current working area. self.recompute_logical_pos(); }
pub fn center(&self) -> Point<f64, Logical> { self.logical_pos + self.size.downscale(2.) }
#[cfg(test)] fn verify_invariants(&self) { let mut temp = *self; temp.recompute_logical_pos(); assert_eq!( self.logical_pos, temp.logical_pos, "cached logical pos must be up to date" ); }}
impl<W: LayoutElement> FloatingSpace<W> { pub fn new( view_size: Size<f64, Logical>, working_area: Rectangle<f64, Logical>, scale: f64, clock: Clock, options: Rc<Options>, ) -> Self { Self { tiles: Vec::new(), data: Vec::new(), active_window_id: None, interactive_resize: None, closing_windows: Vec::new(), view_size, working_area, scale, clock, options, } }
pub fn update_config( &mut self, view_size: Size<f64, Logical>, working_area: Rectangle<f64, Logical>, scale: f64, options: Rc<Options>, ) { for (tile, data) in zip(&mut self.tiles, &mut self.data) { tile.update_config(view_size, scale, options.clone()); data.update(tile); data.update_config(working_area); }
self.view_size = view_size; self.working_area = working_area; self.scale = scale; self.options = options; }
pub fn update_shaders(&mut self) { for tile in &mut self.tiles { tile.update_shaders(); } }
pub fn advance_animations(&mut self) { for tile in &mut self.tiles { tile.advance_animations(); }
self.closing_windows.retain_mut(|closing| { closing.advance_animations(); closing.are_animations_ongoing() }); }
pub fn are_animations_ongoing(&self) -> bool { self.tiles.iter().any(Tile::are_animations_ongoing) || !self.closing_windows.is_empty() }
pub fn are_transitions_ongoing(&self) -> bool { self.tiles.iter().any(Tile::are_transitions_ongoing) || !self.closing_windows.is_empty() }
pub fn update_render_elements( &mut self, is_active: bool, view_rect: Rectangle<f64, Logical>, layer: RenderLayer, ) { let active = self.active_window_id.clone(); for (tile, offset) in self.tiles_with_offsets_mut() { // Skip tiles belonging to a different render layer. if layer.is_normal() == tile.is_moving_between_workspaces() { continue; }
let id = tile.window().id(); let is_active = is_active && Some(id) == active.as_ref();
let mut tile_view_rect = view_rect; tile_view_rect.loc -= offset + tile.render_offset(); tile.update_render_elements(is_active, tile_view_rect); } }
pub fn tiles(&self) -> impl Iterator<Item = &Tile<W>> + '_ { self.tiles.iter() }
pub fn tiles_mut(&mut self) -> impl Iterator<Item = &mut Tile<W>> + '_ { self.tiles.iter_mut() }
pub fn tiles_with_offsets(&self) -> impl Iterator<Item = (&Tile<W>, Point<f64, Logical>)> + '_ { let offsets = self.data.iter().map(|d| d.logical_pos); zip(&self.tiles, offsets) }
pub fn tiles_with_offsets_mut( &mut self, ) -> impl Iterator<Item = (&mut Tile<W>, Point<f64, Logical>)> + '_ { let offsets = self.data.iter().map(|d| d.logical_pos); zip(&mut self.tiles, offsets) }
pub fn tiles_with_render_positions( &self, ) -> impl Iterator<Item = (&Tile<W>, Point<f64, Logical>)> { let scale = self.scale; self.tiles_with_offsets().map(move |(tile, offset)| { let pos = offset + tile.render_offset(); // Round to physical pixels. let pos = pos.to_physical_precise_round(scale).to_logical(scale); (tile, pos) }) }
pub fn tiles_with_render_positions_mut( &mut self, round: bool, ) -> impl Iterator<Item = (&mut Tile<W>, Point<f64, Logical>)> { let scale = self.scale; self.tiles_with_offsets_mut().map(move |(tile, offset)| { let mut pos = offset + tile.render_offset(); // Round to physical pixels. if round { pos = pos.to_physical_precise_round(scale).to_logical(scale); } (tile, pos) }) }
pub fn tiles_with_ipc_layouts(&self) -> impl Iterator<Item = (&Tile<W>, WindowLayout)> { let scale = self.scale; self.tiles_with_offsets().map(move |(tile, offset)| { // Do not include animated render offset here to avoid IPC spam. let pos = offset; // Round to physical pixels. let pos = pos.to_physical_precise_round(scale).to_logical(scale);
let layout = WindowLayout { tile_pos_in_workspace_view: Some(pos.into()), ..tile.ipc_layout_template() }; (tile, layout) }) }
pub fn new_window_toplevel_bounds(&self, rules: &ResolvedWindowRules) -> Size<i32, Logical> { let border_config = self.options.layout.border.merged_with(&rules.border); compute_toplevel_bounds(border_config, self.working_area.size) }
/// Returns the geometry of the active window relative to and clamped to the working area. /// /// During animations, assumes the final tile position. pub fn active_window_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> { let active_id = self.active_window_id.as_ref()?; let (tile, offset) = self .tiles_with_offsets() .find(|(tile, _)| tile.window().id() == active_id)?;
let window_pos = offset + tile.window_loc(); let window_size = tile.window_size(); let window_rect = Rectangle::new(window_pos, window_size);
self.working_area.intersection(window_rect) }
pub fn popup_target_rect(&self, id: &W::Id) -> Option<Rectangle<f64, Logical>> { for (tile, pos) in self.tiles_with_offsets() { if tile.window().id() == id { // Position within the working area. let mut target = self.working_area; target.loc -= pos; target.loc -= tile.window_loc();
return Some(target); } } None }
fn idx_of(&self, id: &W::Id) -> Option<usize> { self.tiles.iter().position(|tile| tile.window().id() == id) }
fn contains(&self, id: &W::Id) -> bool { self.idx_of(id).is_some() }
pub fn active_window(&self) -> Option<&W> { let id = self.active_window_id.as_ref()?; self.tiles .iter() .find(|tile| tile.window().id() == id) .map(Tile::window) }
pub fn active_window_mut(&mut self) -> Option<&mut W> { let id = self.active_window_id.as_ref()?; self.tiles .iter_mut() .find(|tile| tile.window().id() == id) .map(Tile::window_mut) }
pub fn has_window(&self, id: &W::Id) -> bool { self.tiles.iter().any(|tile| tile.window().id() == id) }
pub fn is_empty(&self) -> bool { self.tiles.is_empty() }
pub fn add_tile(&mut self, tile: Tile<W>, activate: bool) { self.add_tile_at(0, tile, activate); }
fn add_tile_at(&mut self, mut idx: usize, mut tile: Tile<W>, activate: bool) { tile.update_config(self.view_size, self.scale, self.options.clone());
// Restore the previous floating window size, and in case the tile is fullscreen, // unfullscreen it. let floating_size = tile.floating_window_size; let win = tile.window_mut(); let mut size = if !win.pending_sizing_mode().is_normal() { // If the window was fullscreen or maximized without a floating size, ask for (0, 0). floating_size.unwrap_or_default() } else { // If the window wasn't fullscreen without a floating size (e.g. it was tiled before), // ask for the current size. If the current size is unknown (the window was only ever // fullscreen until now), fall back to (0, 0). floating_size.unwrap_or_else(|| win.expected_size().unwrap_or_default()) };
// Apply min/max size window rules. If requesting a concrete size, apply completely; if // requesting (0, 0), apply only when min/max results in a fixed size. let min_size = win.min_size(); let max_size = win.max_size(); size.w = ensure_min_max_size_maybe_zero(size.w, min_size.w, max_size.w); size.h = ensure_min_max_size_maybe_zero(size.h, min_size.h, max_size.h);
win.request_size_once(size, true);
if activate || self.tiles.is_empty() { self.active_window_id = Some(win.id().clone()); }
// Make sure the tile isn't inserted below its parent. for (i, tile_above) in self.tiles.iter().enumerate().take(idx) { if win.is_child_of(tile_above.window()) { idx = i; break; } }
let pos = self.stored_or_default_tile_pos(&tile).unwrap_or_else(|| { center_preferring_top_left_in_area(self.working_area, tile.tile_size()) });
let data = Data::new(self.working_area, &tile, pos); self.data.insert(idx, data); self.tiles.insert(idx, tile);
self.bring_up_descendants_of(idx); }
pub fn add_tile_above(&mut self, above: &W::Id, mut tile: Tile<W>, activate: bool) { let idx = self.idx_of(above).unwrap();
let above_pos = self.data[idx].logical_pos; let above_size = self.data[idx].size; let tile_size = tile.tile_size(); let pos = above_pos + (above_size.to_point() - tile_size.to_point()).downscale(2.); let pos = self.clamp_within_working_area(pos, tile_size); tile.floating_pos = Some(self.logical_to_size_frac(pos));
self.add_tile_at(idx, tile, activate); }
fn bring_up_descendants_of(&mut self, idx: usize) { let tile = &self.tiles[idx]; let win = tile.window();
// We always maintain the correct stacking order, so walking descendants back to front // should give us all of them. let mut descendants: Vec<usize> = Vec::new(); for (i, tile_below) in self.tiles.iter().enumerate().skip(idx + 1).rev() { let win_below = tile_below.window(); if win_below.is_child_of(win) || descendants .iter() .any(|idx| win_below.is_child_of(self.tiles[*idx].window())) { descendants.push(i); } }
// Now, descendants is in back-to-front order, and repositioning them in the front-to-back // order will preserve the subsequent indices and work out right. let mut idx = idx; #[allow(clippy::explicit_counter_loop)] for descendant_idx in descendants.into_iter().rev() { self.raise_window(descendant_idx, idx); idx += 1; } }
pub fn remove_tile(&mut self, id: &W::Id) -> RemovedTile<W> { let idx = self.idx_of(id).unwrap(); self.remove_tile_by_idx(idx) }
fn remove_tile_by_idx(&mut self, idx: usize) -> RemovedTile<W> { let mut tile = self.tiles.remove(idx); let data = self.data.remove(idx);
if self.tiles.is_empty() { self.active_window_id = None; } else if Some(tile.window().id()) == self.active_window_id.as_ref() { // The active tile was removed, make the topmost tile active. self.active_window_id = Some(self.tiles[0].window().id().clone()); }
// Stop interactive resize. if let Some(resize) = &self.interactive_resize { if tile.window().id() == &resize.window { self.interactive_resize = None; } }
// Store the floating size if we have one. if let Some(size) = tile.window().expected_size() { tile.floating_window_size = Some(size); } // Store the floating position. tile.floating_pos = Some(data.pos);
let width = ColumnWidth::Fixed(tile.tile_expected_or_current_size().w); RemovedTile { tile, width, is_full_width: false, is_floating: true, } }
pub fn start_close_animation_for_window( &mut self, renderer: &mut GlesRenderer, id: &W::Id, blocker: TransactionBlocker, ) { let (tile, tile_pos) = self .tiles_with_render_positions_mut(false) .find(|(tile, _)| tile.window().id() == id) .unwrap();
let Some(snapshot) = tile.take_unmap_snapshot() else { return; };
let tile_size = tile.tile_size();
self.start_close_animation_for_tile(renderer, snapshot, tile_size, tile_pos, blocker); }
pub fn activate_window_without_raising(&mut self, id: &W::Id) -> bool { if !self.contains(id) { return false; }
self.active_window_id = Some(id.clone()); true }
pub fn activate_window(&mut self, id: &W::Id) -> bool { let Some(idx) = self.idx_of(id) else { return false; };
self.raise_window(idx, 0); self.active_window_id = Some(id.clone()); self.bring_up_descendants_of(0);
true }
fn raise_window(&mut self, from_idx: usize, to_idx: usize) { assert!(to_idx <= from_idx);
let tile = self.tiles.remove(from_idx); let data = self.data.remove(from_idx); self.tiles.insert(to_idx, tile); self.data.insert(to_idx, data); }
pub fn start_close_animation_for_tile( &mut self, renderer: &mut GlesRenderer, snapshot: TileRenderSnapshot, tile_size: Size<f64, Logical>, tile_pos: Point<f64, Logical>, blocker: TransactionBlocker, ) { let anim = Animation::new( self.clock.clone(), 0., 1., 0., self.options.animations.window_close.anim, );
let blocker = if self.options.disable_transactions { TransactionBlocker::completed() } else { blocker };
let scale = Scale::from(self.scale); let res = ClosingWindow::new( renderer, snapshot, scale, tile_size, tile_pos, blocker, anim, ); match res { Ok(closing) => { self.closing_windows.push(closing); } Err(err) => { warn!("error creating a closing window animation: {err:?}"); } } }
pub fn toggle_window_width(&mut self, id: Option<&W::Id>, forwards: bool) { let Some(id) = id.or(self.active_window_id.as_ref()).cloned() else { return; }; let idx = self.idx_of(&id).unwrap();
let available_size = self.working_area.size.w;
let len = self.options.layout.preset_column_widths.len(); let tile = &mut self.tiles[idx]; let preset_idx = if let Some(idx) = tile.floating_preset_width_idx { (idx + if forwards { 1 } else { len - 1 }) % len } else { let current_window = tile.window_expected_or_current_size().w; let current_tile = tile.tile_expected_or_current_size().w;
let mut it = self .options .layout .preset_column_widths .iter() .map(|preset| resolve_preset_size(*preset, available_size));
if forwards { it.position(|resolved| { match resolved { // Some allowance for fractional scaling purposes. ResolvedSize::Tile(resolved) => current_tile + 1. < resolved, ResolvedSize::Window(resolved) => current_window + 1. < resolved, } }) .unwrap_or(0) } else { it.rposition(|resolved| { match resolved { // Some allowance for fractional scaling purposes. ResolvedSize::Tile(resolved) => resolved + 1. < current_tile, ResolvedSize::Window(resolved) => resolved + 1. < current_window, } }) .unwrap_or(len - 1) } };
let preset = self.options.layout.preset_column_widths[preset_idx]; self.set_window_width(Some(&id), SizeChange::from(preset), true);
self.tiles[idx].floating_preset_width_idx = Some(preset_idx);
self.interactive_resize_end(Some(&id)); }
pub fn start_open_animation(&mut self, id: &W::Id) -> bool { let Some(idx) = self.idx_of(id) else { return false; };
self.tiles[idx].start_open_animation(); true }
pub fn toggle_window_height(&mut self, id: Option<&W::Id>, forwards: bool) { let Some(id) = id.or(self.active_window_id.as_ref()).cloned() else { return; }; let idx = self.idx_of(&id).unwrap();
let available_size = self.working_area.size.h;
let len = self.options.layout.preset_window_heights.len(); let tile = &mut self.tiles[idx]; let preset_idx = if let Some(idx) = tile.floating_preset_height_idx { (idx + if forwards { 1 } else { len - 1 }) % len } else { let current_window = tile.window_expected_or_current_size().h; let current_tile = tile.tile_expected_or_current_size().h;
let mut it = self .options .layout .preset_window_heights .iter() .map(|preset| resolve_preset_size(*preset, available_size));
if forwards { it.position(|resolved| { match resolved { // Some allowance for fractional scaling purposes. ResolvedSize::Tile(resolved) => current_tile + 1. < resolved, ResolvedSize::Window(resolved) => current_window + 1. < resolved, } }) .unwrap_or(0) } else { it.rposition(|resolved| { match resolved { // Some allowance for fractional scaling purposes. ResolvedSize::Tile(resolved) => resolved + 1. < current_tile, ResolvedSize::Window(resolved) => resolved + 1. < current_window, } }) .unwrap_or(len - 1) } };
let preset = self.options.layout.preset_window_heights[preset_idx]; self.set_window_height(Some(&id), SizeChange::from(preset), true);
let tile = &mut self.tiles[idx]; tile.floating_preset_height_idx = Some(preset_idx);
self.interactive_resize_end(Some(&id)); }
pub fn set_window_width(&mut self, id: Option<&W::Id>, change: SizeChange, animate: bool) { let Some(id) = id.or(self.active_window_id.as_ref()) else { return; }; let idx = self.idx_of(id).unwrap();
let tile = &mut self.tiles[idx]; tile.floating_preset_width_idx = None;
let available_size = self.working_area.size.w; let win = tile.window(); let current_window = win.expected_size().unwrap_or_else(|| win.size()).w; let current_tile = tile.tile_expected_or_current_size().w;
const MAX_PX: f64 = 100000.; const MAX_F: f64 = 10000.;
let win_width = match change { SizeChange::SetFixed(win_width) => f64::from(win_width), SizeChange::SetProportion(prop) => { let prop = (prop / 100.).clamp(0., MAX_F); let tile_width = available_size * prop; tile.window_width_for_tile_width(tile_width) } SizeChange::AdjustFixed(delta) => f64::from(current_window.saturating_add(delta)), SizeChange::AdjustProportion(delta) => { let current_prop = current_tile / available_size; let prop = (current_prop + delta / 100.).clamp(0., MAX_F); let tile_width = available_size * prop; tile.window_width_for_tile_width(tile_width) } }; let win_width = win_width.round().clamp(1., MAX_PX) as i32;
let win = tile.window_mut(); let min_size = win.min_size(); let max_size = win.max_size();
let win_width = ensure_min_max_size(win_width, min_size.w, max_size.w);
let win_height = win.expected_size().unwrap_or_default().h; let win_height = ensure_min_max_size(win_height, min_size.h, max_size.h);
let win_size = Size::from((win_width, win_height)); win.request_size_once(win_size, animate); }
pub fn set_window_height(&mut self, id: Option<&W::Id>, change: SizeChange, animate: bool) { let Some(id) = id.or(self.active_window_id.as_ref()) else { return; }; let idx = self.idx_of(id).unwrap();
let tile = &mut self.tiles[idx]; tile.floating_preset_height_idx = None;
let available_size = self.working_area.size.h; let win = tile.window(); let current_window = win.expected_size().unwrap_or_else(|| win.size()).h; let current_tile = tile.tile_expected_or_current_size().h;
const MAX_PX: f64 = 100000.; const MAX_F: f64 = 10000.;
let win_height = match change { SizeChange::SetFixed(win_height) => f64::from(win_height), SizeChange::SetProportion(prop) => { let prop = (prop / 100.).clamp(0., MAX_F); let tile_height = available_size * prop; tile.window_height_for_tile_height(tile_height) } SizeChange::AdjustFixed(delta) => f64::from(current_window.saturating_add(delta)), SizeChange::AdjustProportion(delta) => { let current_prop = current_tile / available_size; let prop = (current_prop + delta / 100.).clamp(0., MAX_F); let tile_height = available_size * prop; tile.window_height_for_tile_height(tile_height) } }; let win_height = win_height.round().clamp(1., MAX_PX) as i32;
let win = tile.window_mut(); let min_size = win.min_size(); let max_size = win.max_size();
let win_height = ensure_min_max_size(win_height, min_size.h, max_size.h);
let win_width = win.expected_size().unwrap_or_default().w; let win_width = ensure_min_max_size(win_width, min_size.w, max_size.w);
let win_size = Size::from((win_width, win_height)); win.request_size_once(win_size, animate); }
fn focus_directional( &mut self, distance: impl Fn(Point<f64, Logical>, Point<f64, Logical>) -> f64, ) -> bool { let Some(active_id) = &self.active_window_id else { return false; }; let active_idx = self.idx_of(active_id).unwrap(); let center = self.data[active_idx].center();
let result = zip(&self.tiles, &self.data) .filter(|(tile, _)| tile.window().id() != active_id) .map(|(tile, data)| (tile, distance(center, data.center()))) .filter(|(_, dist)| *dist > 0.) .min_by(|(_, dist_a), (_, dist_b)| f64::total_cmp(dist_a, dist_b)); if let Some((tile, _)) = result { let id = tile.window().id().clone(); self.activate_window(&id); true } else { false } }
pub fn focus_left(&mut self) -> bool { self.focus_directional(|focus, other| focus.x - other.x) }
pub fn focus_right(&mut self) -> bool { self.focus_directional(|focus, other| other.x - focus.x) }
pub fn focus_up(&mut self) -> bool { self.focus_directional(|focus, other| focus.y - other.y) }
pub fn focus_down(&mut self) -> bool { self.focus_directional(|focus, other| other.y - focus.y) }
pub fn focus_leftmost(&mut self) { let result = self .tiles_with_offsets() .min_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.x, &pos_b.x)); if let Some((tile, _)) = result { let id = tile.window().id().clone(); self.activate_window(&id); } }
pub fn focus_rightmost(&mut self) { let result = self .tiles_with_offsets() .max_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.x, &pos_b.x)); if let Some((tile, _)) = result { let id = tile.window().id().clone(); self.activate_window(&id); } }
pub fn focus_topmost(&mut self) { let result = self .tiles_with_offsets() .min_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.y, &pos_b.y)); if let Some((tile, _)) = result { let id = tile.window().id().clone(); self.activate_window(&id); } }
pub fn focus_bottommost(&mut self) { let result = self .tiles_with_offsets() .max_by(|(_, pos_a), (_, pos_b)| f64::total_cmp(&pos_a.y, &pos_b.y)); if let Some((tile, _)) = result { let id = tile.window().id().clone(); self.activate_window(&id); } }
fn move_to(&mut self, idx: usize, new_pos: Point<f64, Logical>, animate: bool) { if animate { self.move_and_animate(idx, new_pos); } else { self.data[idx].set_logical_pos(new_pos); }
self.interactive_resize_end(None); }
fn move_by(&mut self, amount: Point<f64, Logical>) { let Some(active_id) = &self.active_window_id else { return; }; let idx = self.idx_of(active_id).unwrap();
let new_pos = self.data[idx].logical_pos + amount; self.move_to(idx, new_pos, true) }
pub fn move_left(&mut self) { self.move_by(Point::from((-DIRECTIONAL_MOVE_PX, 0.))); }
pub fn move_right(&mut self) { self.move_by(Point::from((DIRECTIONAL_MOVE_PX, 0.))); }
pub fn move_up(&mut self) { self.move_by(Point::from((0., -DIRECTIONAL_MOVE_PX))); }
pub fn move_down(&mut self) { self.move_by(Point::from((0., DIRECTIONAL_MOVE_PX))); }
pub fn move_window( &mut self, id: Option<&W::Id>, x: PositionChange, y: PositionChange, animate: bool, ) { let Some(id) = id.or(self.active_window_id.as_ref()) else { return; }; let idx = self.idx_of(id).unwrap();
let mut pos = self.data[idx].logical_pos;
let available_width = self.working_area.size.w; let available_height = self.working_area.size.h; let working_area_loc = self.working_area.loc;
const MAX_F: f64 = 10000.;
match x { PositionChange::SetFixed(x) => pos.x = x + working_area_loc.x, PositionChange::SetProportion(prop) => { let prop = (prop / 100.).clamp(0., MAX_F); pos.x = available_width * prop + working_area_loc.x; } PositionChange::AdjustFixed(x) => pos.x += x, PositionChange::AdjustProportion(prop) => { let current_prop = (pos.x - working_area_loc.x) / available_width.max(1.); let prop = (current_prop + prop / 100.).clamp(0., MAX_F); pos.x = available_width * prop + working_area_loc.x; } } match y { PositionChange::SetFixed(y) => pos.y = y + working_area_loc.y, PositionChange::SetProportion(prop) => { let prop = (prop / 100.).clamp(0., MAX_F); pos.y = available_height * prop + working_area_loc.y; } PositionChange::AdjustFixed(y) => pos.y += y, PositionChange::AdjustProportion(prop) => { let current_prop = (pos.y - working_area_loc.y) / available_height.max(1.); let prop = (current_prop + prop / 100.).clamp(0., MAX_F); pos.y = available_height * prop + working_area_loc.y; } }
self.move_to(idx, pos, animate); }
pub fn center_window(&mut self, id: Option<&W::Id>) { let Some(id) = id.or(self.active_window_id.as_ref()).cloned() else { return; }; let idx = self.idx_of(&id).unwrap();
let new_pos = center_preferring_top_left_in_area(self.working_area, self.data[idx].size); self.move_to(idx, new_pos, true); }
pub fn descendants_added(&mut self, id: &W::Id) -> bool { let Some(idx) = self.idx_of(id) else { return false; };
self.bring_up_descendants_of(idx); true }
pub fn update_window(&mut self, id: &W::Id, serial: Option<Serial>) -> bool { let Some(tile_idx) = self.idx_of(id) else { return false; };
let tile = &mut self.tiles[tile_idx]; let data = &mut self.data[tile_idx];
let resize = tile.window_mut().interactive_resize_data();
// Do this before calling update_window() so it can get up-to-date info. if let Some(serial) = serial { tile.window_mut().on_commit(serial); }
let prev_size = data.size;
tile.update_window(); data.update(tile);
// When resizing by top/left edge, update the position accordingly. if let Some(resize) = resize { let mut offset = Point::from((0., 0.)); if resize.edges.contains(ResizeEdge::LEFT) { offset.x += prev_size.w - data.size.w; } if resize.edges.contains(ResizeEdge::TOP) { offset.y += prev_size.h - data.size.h; } data.set_logical_pos(data.logical_pos + offset); }
true }
pub fn render<R: NiriRenderer>( &self, mut ctx: RenderCtx<R>, xray_pos: XrayPos, view_rect: Rectangle<f64, Logical>, focus_ring: bool, layer: RenderLayer, push: &mut dyn FnMut(FloatingSpaceRenderElement<R>), ) { let scale = Scale::from(self.scale);
// Draw the closing windows on top of the other windows. // // FIXME: I guess this should rather preserve the stacking order when the window is closed. if layer.is_normal() { for closing in self.closing_windows.iter().rev() { let elem = closing.render(ctx.as_gles(), view_rect, scale); push(elem.into()); } }
let active = self.active_window_id.clone(); for (tile, tile_pos) in self.tiles_with_render_positions() { // Skip tiles belonging to a different render layer. if layer.is_normal() == tile.is_moving_between_workspaces() { continue; }
// For the active tile, draw the focus ring. let focus_ring = focus_ring && Some(tile.window().id()) == active.as_ref();
let xray_pos = xray_pos.offset(tile_pos); tile.render(ctx.r(), tile_pos, xray_pos, focus_ring, &mut |elem| { push(elem.into()) }); } }
pub fn interactive_resize_begin(&mut self, window: W::Id, edges: ResizeEdge) -> bool { if self.interactive_resize.is_some() { return false; }
let tile = self .tiles .iter_mut() .find(|tile| tile.window().id() == &window) .unwrap();
let original_window_size = tile.window_size();
let resize = InteractiveResize { window, original_window_size, data: InteractiveResizeData { edges }, }; self.interactive_resize = Some(resize);
true }
pub fn interactive_resize_update( &mut self, window: &W::Id, delta: Point<f64, Logical>, ) -> bool { let Some(resize) = &self.interactive_resize else { return false; };
if window != &resize.window { return false; }
let original_window_size = resize.original_window_size; let edges = resize.data.edges;
if edges.intersects(ResizeEdge::LEFT_RIGHT) { let mut dx = delta.x; if edges.contains(ResizeEdge::LEFT) { dx = -dx; };
let window_width = (original_window_size.w + dx).round() as i32; self.set_window_width(Some(window), SizeChange::SetFixed(window_width), false); }
if edges.intersects(ResizeEdge::TOP_BOTTOM) { let mut dy = delta.y; if edges.contains(ResizeEdge::TOP) { dy = -dy; };
let window_height = (original_window_size.h + dy).round() as i32; self.set_window_height(Some(window), SizeChange::SetFixed(window_height), false); }
true }
pub fn interactive_resize_end(&mut self, window: Option<&W::Id>) { let Some(resize) = &self.interactive_resize else { return; };
if let Some(window) = window { if window != &resize.window { return; } }
self.interactive_resize = None; }
pub fn refresh(&mut self, is_active: bool, is_focused: bool) { let active = self.active_window_id.clone(); for tile in &mut self.tiles { let win = tile.window_mut();
win.set_active_in_column(true); win.set_floating(true);
let mut is_active = is_active && Some(win.id()) == active.as_ref(); if self.options.deactivate_unfocused_windows { is_active &= is_focused; } win.set_activated(is_active);
let resize_data = self .interactive_resize .as_ref() .filter(|resize| &resize.window == win.id()) .map(|resize| resize.data); win.set_interactive_resize(resize_data);
let border_config = self.options.layout.border.merged_with(&win.rules().border); let bounds = compute_toplevel_bounds(border_config, self.working_area.size); win.set_bounds(bounds);
// If transactions are disabled, also disable combined throttling, for more // intuitive behavior. let intent = if self.options.disable_resize_throttling { ConfigureIntent::CanSend } else { win.configure_intent() };
if matches!( intent, ConfigureIntent::CanSend | ConfigureIntent::ShouldSend ) { win.send_pending_configure(); }
win.refresh(); } }
pub fn clamp_within_working_area( &self, pos: Point<f64, Logical>, size: Size<f64, Logical>, ) -> Point<f64, Logical> { let mut rect = Rectangle::new(pos, size); clamp_preferring_top_left_in_area(self.working_area, &mut rect); rect.loc }
pub fn scale_by_working_area(&self, pos: Point<f64, SizeFrac>) -> Point<f64, Logical> { Data::scale_by_working_area(self.working_area, pos) }
pub fn logical_to_size_frac(&self, logical_pos: Point<f64, Logical>) -> Point<f64, SizeFrac> { Data::logical_to_size_frac_in_working_area(self.working_area, logical_pos) }
fn move_and_animate(&mut self, idx: usize, new_pos: Point<f64, Logical>) { // Moves up to this logical pixel distance are not animated. const ANIMATION_THRESHOLD_SQ: f64 = 10. * 10.;
let tile = &mut self.tiles[idx]; let data = &mut self.data[idx];
let prev_pos = data.logical_pos; data.set_logical_pos(new_pos); let new_pos = data.logical_pos;
let diff = prev_pos - new_pos; if diff.x * diff.x + diff.y * diff.y > ANIMATION_THRESHOLD_SQ { tile.animate_move_from(prev_pos - new_pos); } }
pub fn new_window_size( &self, width: Option<PresetSize>, height: Option<PresetSize>, rules: &ResolvedWindowRules, ) -> Size<i32, Logical> { let border = self.options.layout.border.merged_with(&rules.border);
let resolve = |size: Option<PresetSize>, working_area_size: f64| { if let Some(size) = size { let size = match resolve_preset_size(size, working_area_size) { ResolvedSize::Tile(mut size) => { if !border.off { size -= border.width * 2.; } size } ResolvedSize::Window(size) => size, };
max(1, size.floor() as i32) } else { 0 } };
let width = resolve(width, self.working_area.size.w); let height = resolve(height, self.working_area.size.h);
Size::from((width, height)) }
pub fn stored_or_default_tile_pos(&self, tile: &Tile<W>) -> Option<Point<f64, Logical>> { let pos = tile.floating_pos.map(|pos| self.scale_by_working_area(pos)); pos.or_else(|| { tile.window().rules().default_floating_position.map(|pos| { let relative_to = pos.relative_to; let size = tile.tile_size(); let area = self.working_area;
let mut pos = Point::from((pos.x.0, pos.y.0)); if relative_to == RelativeTo::TopRight || relative_to == RelativeTo::BottomRight || relative_to == RelativeTo::Right { pos.x = area.size.w - size.w - pos.x; } if relative_to == RelativeTo::BottomLeft || relative_to == RelativeTo::BottomRight || relative_to == RelativeTo::Bottom { pos.y = area.size.h - size.h - pos.y; } if relative_to == RelativeTo::Top || relative_to == RelativeTo::Bottom { pos.x += area.size.w / 2.0 - size.w / 2.0 } if relative_to == RelativeTo::Left || relative_to == RelativeTo::Right { pos.y += area.size.h / 2.0 - size.h / 2.0 }
pos + self.working_area.loc }) }) }
#[cfg(test)] pub fn view_size(&self) -> Size<f64, Logical> { self.view_size }
pub fn working_area(&self) -> Rectangle<f64, Logical> { self.working_area }
#[cfg(test)] pub fn scale(&self) -> f64 { self.scale }
#[cfg(test)] pub fn clock(&self) -> &Clock { &self.clock }
#[cfg(test)] pub fn options(&self) -> &Rc<Options> { &self.options }
#[cfg(test)] pub fn verify_invariants(&self) { assert!(self.scale > 0.); assert!(self.scale.is_finite()); assert_eq!(self.tiles.len(), self.data.len());
for (i, (tile, data)) in zip(&self.tiles, &self.data).enumerate() { use crate::layout::SizingMode;
assert!(Rc::ptr_eq(&self.options, &tile.options)); assert_eq!(self.view_size, tile.view_size()); assert_eq!(self.clock, tile.clock); assert_eq!(self.scale, tile.scale()); tile.verify_invariants();
if let Some(idx) = tile.floating_preset_width_idx { assert!(idx < self.options.layout.preset_column_widths.len()); } if let Some(idx) = tile.floating_preset_height_idx { assert!(idx < self.options.layout.preset_window_heights.len()); }
assert_eq!( tile.window().pending_sizing_mode(), SizingMode::Normal, "floating windows cannot be maximized or fullscreen" );
data.verify_invariants();
let mut data2 = *data; data2.update(tile); data2.update_config(self.working_area); assert_eq!(data, &data2, "tile data must be up to date");
for tile_below in &self.tiles[i + 1..] { assert!( !tile_below.window().is_child_of(tile.window()), "children must be stacked above parents" ); } }
if let Some(id) = &self.active_window_id { assert!(!self.tiles.is_empty()); assert!(self.contains(id), "active window must be present in tiles"); } else { assert!(self.tiles.is_empty()); }
if let Some(resize) = &self.interactive_resize { assert!( self.contains(&resize.window), "interactive resize window must be present in tiles" ); } }}
fn compute_toplevel_bounds( border_config: niri_config::Border, working_area_size: Size<f64, Logical>,) -> Size<i32, Logical> { let mut border = 0.; if !border_config.off { border = border_config.width * 2.; }
Size::from(( f64::max(working_area_size.w - border, 1.), f64::max(working_area_size.h - border, 1.), )) .to_i32_floor()}
fn resolve_preset_size(preset: PresetSize, view_size: f64) -> ResolvedSize { match preset { PresetSize::Proportion(proportion) => ResolvedSize::Tile(view_size * proportion), PresetSize::Fixed(width) => ResolvedSize::Window(f64::from(width)), }}