Lines
96.72 %
Functions
100 %
Branches
//! TV's Tile and Cascade layouts (`tdesktop.cpp`): the rects of `count` windows over an area.
use ratatui::layout::Rect;
use super::MIN_SIZE;
/// The near-square `(columns, rows)` grid of `count` cells, rows first as TV's default does.
fn grid(count: u32) -> (u32, u32) {
let mut side = count.isqrt();
if !count.is_multiple_of(side) && count.is_multiple_of(side + 1) {
side += 1;
}
side = side.max(count / side);
(count / side, side)
/// The cell edge at `pos` of `num` along `len` cells from `lo`.
fn divide(lo: u16, len: u16, num: u32, pos: u32) -> u16 {
let offset = u32::from(len) * pos / num;
lo.saturating_add(u16::try_from(offset).unwrap_or(u16::MAX))
/// Where cell `pos` of a `cols` by `rows` grid lies in `area`; the last `count % cols` columns
/// have one row more.
fn cell(pos: u32, grid: (u32, u32), left_over: u32, area: Rect) -> Rect {
let (cols, rows) = grid;
let full = (cols - left_over) * rows;
let (col, row, column_rows) = match pos < full {
true => (pos / rows, pos % rows, rows),
false => (
(pos - full) / (rows + 1) + cols - left_over,
(pos - full) % (rows + 1),
rows + 1,
),
};
let left = divide(area.x, area.width, cols, col);
let right = divide(area.x, area.width, cols, col + 1);
let top = divide(area.y, area.height, column_rows, row);
let bottom = divide(area.y, area.height, column_rows, row + 1);
let width = (right - left).max(MIN_SIZE.0.min(area.width));
let height = (bottom - top).max(MIN_SIZE.1.min(area.height));
Rect::new(left, top, width, height)
/// The rects of `count` tiled windows, indexed by position: TV counts the cells up from the
/// rearmost window, so the front one takes the last. `None` when
/// a cell would have no room at all, TV's "too many windows".
pub(super) fn tile(count: usize, area: Rect) -> Option<Vec<Rect>> {
let Ok(count) = u32::try_from(count) else {
return None;
if count == 0 {
return Some(Vec::new());
let grid = grid(count);
if u32::from(area.width) < grid.0 || u32::from(area.height) < grid.1 {
let left_over = count % grid.0;
Some(
(0..count)
.map(|pos| cell(pos, grid, left_over, area))
.collect(),
)
/// The rects of `count` cascaded windows, back to front: each is one cell further down and right
/// than the one behind it, all reaching the area's bottom-right corner. `None` when the minimum
/// does not fit beside `count` steps, as in TV.
pub(super) fn cascade(count: usize, area: Rect) -> Option<Vec<Rect>> {
let total = u16::try_from(count).ok()?;
if MIN_SIZE.0 > area.width.saturating_sub(total)
|| MIN_SIZE.1 > area.height.saturating_sub(total)
{
.filter_map(|step| u16::try_from(step).ok())
.map(|step| {
Rect::new(
area.x.saturating_add(step),
area.y.saturating_add(step),
area.width - step,
area.height - step,
})
#[cfg(test)]
mod tests;