use crate::model::{Group, GroupId, PanelId};
#[derive(Clone, Copy, Debug)]
pub struct Step(pub u32);
impl From<Step> for u32 {
fn from(s: Step) -> u32 {
s.0
}
}
#[derive(Clone, Copy, Debug)]
pub enum MinSize {
Steps { w: Step, h: Step },
Rem { w: f64, h: f64 },
}
impl MinSize {
pub fn resolve(&self, step_w: f64, step_h: f64, rem_px: f64) -> (u32, u32) {
match self {
MinSize::Steps { w, h } => (w.0.max(1), h.0.max(1)),
MinSize::Rem { w, h } => (((w * rem_px / step_w).ceil() as u32).max(1), ((h * rem_px / step_h).ceil() as u32).max(1)),
}
}
}
#[derive(Clone, Debug, serde::Deserialize, PartialEq, serde::Serialize)]
pub struct Cell {
pub group: Group,
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
pub min_w: u32,
pub min_h: u32,
#[serde(default)]
pub desired_w: Option<u32>,
#[serde(default)]
pub desired_x: Option<u32>,
#[serde(default)]
pub rank: u32,
}
#[derive(Clone, Copy, Debug, Default, serde::Deserialize, Eq, PartialEq, serde::Serialize)]
pub enum GridState {
#[default]
Settled,
Resizing,
}
#[derive(Clone, Debug, Default, serde::Deserialize, PartialEq, serde::Serialize)]
pub struct PackedGrid {
pub cells: Vec<Cell>,
pub state: GridState,
next_group_id: u64,
}
impl PackedGrid {
pub fn mint_group_id(&mut self) -> GroupId {
let id = GroupId(self.next_group_id);
self.next_group_id += 1;
id
}
fn locate(&self, id: GroupId) -> Option<usize> {
self.cells.iter().position(|c| c.group.id == id)
}
pub fn place(&mut self, group: Group, w: u32, h: u32, min: (u32, u32), cols: u32) {
let eff_w = w.min(cols);
let (x, y) = pack(&self.cells, eff_w, h, cols);
self.cells.push(Cell {
group,
x,
y,
w: eff_w,
h,
min_w: min.0,
min_h: min.1,
desired_w: (eff_w != w).then_some(w),
desired_x: None,
rank: 0,
});
self.reassign_ranks();
debug_assert!(self.overlaps().is_none(), "place produced an overlap");
}
fn reassign_ranks(&mut self) {
let mut order: Vec<usize> = (0..self.cells.len()).collect();
order.sort_by_key(|&i| (self.cells[i].y, self.cells[i].x));
for (rank, &i) in order.iter().enumerate() {
self.cells[i].rank = rank as u32;
}
}
pub fn resize(&mut self, idx: usize, new_w: u32, new_h: u32, cols: u32) {
let (x, min_w, min_h) = {
let c = &self.cells[idx];
(c.x, c.min_w, c.min_h)
};
let span = cols.saturating_sub(x).max(1);
let c = &mut self.cells[idx];
c.w = new_w.max(min_w).min(span);
c.h = new_h.max(min_h);
c.desired_w = None;
c.desired_x = None;
gravity(&mut self.cells, Some(idx));
self.reassign_ranks();
debug_assert!(self.overlaps().is_none(), "resize left an overlap");
}
pub fn refit(&mut self, cols: u32) {
for c in &mut self.cells {
let want_w = c.desired_w.unwrap_or(c.w);
let want_x = c.desired_x.unwrap_or(c.x);
let floor = c.min_w.min(cols).max(1);
let eff_w = want_w.clamp(floor, cols);
let eff_x = want_x.min(cols - eff_w);
c.desired_w = (eff_w != want_w).then_some(want_w);
c.desired_x = (eff_x != want_x).then_some(want_x);
c.w = eff_w;
c.x = eff_x;
}
let mut order: Vec<usize> = (0..self.cells.len()).collect();
order.sort_by_key(|&i| (self.cells[i].rank, i));
for k in 0..order.len() {
let i = order[k];
let (x, w) = (self.cells[i].x, self.cells[i].w);
self.cells[i].y = order[..k]
.iter()
.filter(|&&j| self.cells[j].x < x + w && x < self.cells[j].x + self.cells[j].w)
.map(|&j| self.cells[j].y + self.cells[j].h)
.max()
.unwrap_or(0);
}
debug_assert!(self.overlaps().is_none(), "refit produced an overlap");
}
pub fn close_active(&mut self, id: GroupId) {
let idx = self.locate(id).expect("close_active: group exists");
let active = self.cells[idx].group.active_panel().clone();
if self.cells[idx].group.remove_tab(&active) {
self.cells.remove(idx);
gravity(&mut self.cells, None);
self.reassign_ranks();
debug_assert!(self.overlaps().is_none(), "close left an overlap");
}
}
pub fn overlaps(&self) -> Option<(usize, usize)> {
for i in 0..self.cells.len() {
for j in i + 1..self.cells.len() {
let (a, b) = (&self.cells[i], &self.cells[j]);
if a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h {
return Some((i, j));
}
}
}
None
}
pub fn unsupported(&self) -> Option<usize> {
(0..self.cells.len()).find(|&i| {
let c = &self.cells[i];
c.y > 0 && !self.cells.iter().enumerate().any(|(j, o)| j != i && o.x < c.x + c.w && c.x < o.x + o.w && o.y + o.h == c.y)
})
}
pub fn assert_packed(&self) {
assert_eq!(self.state, GridState::Settled, "assert_packed on a mid-gesture grid");
if let Some((i, j)) = self.overlaps() {
panic!("overlap: {:?} vs {:?}", self.cells[i], self.cells[j]);
}
if let Some(i) = self.unsupported() {
panic!("floating tile (gap above): {:?}", self.cells[i]);
}
}
pub fn add_tab(&mut self, id: GroupId, panel: PanelId) {
let idx = self.locate(id).expect("add_tab: group exists");
let group = &mut self.cells[idx].group;
let at = group.tabs.len();
group.insert_tab(panel, at);
}
pub fn resolve_target(&self, source: &DragSource, px: f64, py: f64, mx: f64, my: f64, step_w: f64, step_h: f64, chrome: f64, cols: u32, src_w: u32, src_h: u32) -> DropTarget {
let col = (((px - src_w as f64 * step_w / 2.0) / step_w).round().max(0.0) as u32).min(cols.saturating_sub(src_w));
for c in &self.cells {
let (l, t) = (c.x as f64 * step_w, c.y as f64 * step_h);
let (r, b) = ((c.x + c.w) as f64 * step_w, (c.y + c.h) as f64 * step_h);
if mx >= l && mx < r && my >= t && my < b {
let self_no_join = c.group.id == source.group()
&& !matches!(source, DragSource::Tab { from, .. }
if self.cells[self.locate(*from).expect("drag source group exists")].group.tabs.len() > 1);
return if my < t + chrome && !self_no_join {
DropTarget::Tab {
group: c.group.id,
index: c.group.tabs.len(),
}
} else {
DropTarget::Displace { x: col, y: c.y + c.h }
};
}
}
let row = ((py - src_h as f64 * step_h / 2.0) / step_h).round().max(0.0) as u32;
if row < skyline(&self.cells, col, src_w) {
DropTarget::Displace { x: col, y: row }
} else {
DropTarget::Pack { x: col }
}
}
pub fn drop(&mut self, source: DragSource, target: DropTarget, cols: u32) {
if let DropTarget::Tab { group, .. } = target {
if group == source.group() {
let reorder = matches!(&source, DragSource::Tab { from, .. }
if self.cells[self.locate(*from).expect("drop: source group exists")].group.tabs.len() > 1);
if !reorder {
return;
}
}
}
let (group, w, h, min_w, min_h) = match source {
DragSource::Tile(g) => {
let idx = self.locate(g).expect("drop: source tile exists");
let c = self.cells.remove(idx);
(c.group, c.w, c.h, c.min_w, c.min_h)
}
DragSource::Tab { panel, from } => {
let idx = self.locate(from).expect("drop: source group exists");
let (w, h, min_w, min_h) = {
let c = &self.cells[idx];
(c.w, c.h, c.min_w, c.min_h)
};
if self.cells[idx].group.remove_tab(&panel) {
self.cells.remove(idx);
}
(Group::new(self.mint_group_id(), panel), w, h, min_w, min_h)
}
};
let clamp_x = |x: u32| x.min(cols.saturating_sub(w));
match target {
DropTarget::Tab { group: t, index } => {
let dst = self.locate(t).expect("drop: tab target exists");
let mut at = index.min(self.cells[dst].group.tabs.len());
for p in group.tabs {
self.cells[dst].group.insert_tab(p, at);
at += 1;
}
gravity(&mut self.cells, None);
}
DropTarget::Displace { x, y } => {
self.cells.push(Cell {
group,
x: clamp_x(x),
y,
w,
h,
min_w,
min_h,
desired_w: None,
desired_x: None,
rank: 0,
});
let pin = self.cells.len() - 1;
gravity(&mut self.cells, Some(pin));
}
DropTarget::Pack { x } => {
let x = clamp_x(x);
let y = skyline(&self.cells, x, w);
self.cells.push(Cell {
group,
x,
y,
w,
h,
min_w,
min_h,
desired_w: None,
desired_x: None,
rank: 0,
});
gravity(&mut self.cells, None);
}
}
self.reassign_ranks();
debug_assert!(self.overlaps().is_none(), "drop produced an overlap");
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum DragSource {
Tile(GroupId),
Tab { panel: PanelId, from: GroupId },
}
impl DragSource {
fn group(&self) -> GroupId {
match self {
DragSource::Tile(g) => *g,
DragSource::Tab { from, .. } => *from,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum DropTarget {
Tab {
group: GroupId,
index: usize,
},
Displace {
x: u32,
y: u32,
},
Pack {
x: u32,
},
}
fn pack(cells: &[Cell], w: u32, h: u32, cols: u32) -> (u32, u32) {
let mut best: Option<(u32, u32)> = None; for x in 0..=cols.saturating_sub(w) {
let y = skyline(cells, x, w);
best = Some(match best {
Some(b) if (b.1 + h, b.0) <= (y + h, x) => b,
_ => (x, y),
});
}
best.unwrap_or((0, 0))
}
fn skyline(cells: &[Cell], x: u32, w: u32) -> u32 {
cells.iter().filter(|c| c.x < x + w && x < c.x + c.w).map(|c| c.y + c.h).max().unwrap_or(0)
}
fn gravity(cells: &mut [Cell], pin: Option<usize>) {
let mut order: Vec<usize> = (0..cells.len()).collect();
order.sort_by_key(|&i| (cells[i].y, (Some(i) != pin) as u8, cells[i].x));
for k in 0..order.len() {
let i = order[k];
let (x, w) = (cells[i].x, cells[i].w);
cells[i].y = order[..k]
.iter()
.filter(|&&j| cells[j].x < x + w && x < cells[j].x + cells[j].w)
.map(|&j| cells[j].y + cells[j].h)
.max()
.unwrap_or(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cell(x: u32, y: u32, w: u32, h: u32) -> Cell {
Cell {
group: Group::new(GroupId(0), PanelId("p".into())),
x,
y,
w,
h,
min_w: 1,
min_h: 1,
desired_w: None,
desired_x: None,
rank: 0,
}
}
#[test]
fn pack_skyline() {
assert_eq!(pack(&[], 2, 2, 6), (0, 0), "empty grid → origin");
let tall = [cell(0, 0, 2, 4)];
assert_eq!(pack(&tall, 2, 2, 6), (2, 0), "nestle beside the tall cell, leftmost");
let full = [cell(0, 0, 6, 4)];
assert_eq!(pack(&full, 2, 2, 6), (0, 4), "stack below when nothing fits beside");
}
fn no_overlap(cells: &[Cell]) {
for (i, a) in cells.iter().enumerate() {
for b in &cells[i + 1..] {
assert!(!(a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h), "tiles overlap: {a:?} vs {b:?}");
}
}
}
#[test]
fn resize_pushes_stack_down() {
let mut g = PackedGrid::default();
g.cells = vec![cell(0, 0, 2, 2), cell(0, 2, 2, 2), cell(0, 4, 2, 2), cell(2, 0, 2, 2)];
g.resize(0, 2, 4, 6);
no_overlap(&g.cells);
assert_eq!((g.cells[0].y, g.cells[0].h), (0, 4), "anchor stays, grows");
assert_eq!(g.cells[1].y, 4, "middle pushed below the grown top");
assert_eq!(g.cells[2].y, 6, "bottom pushed below the middle");
g.resize(0, 4, 4, 6);
no_overlap(&g.cells);
assert_eq!(g.cells[3].y, 4, "right neighbour displaced below the widened tile");
g.resize(0, 2, 2, 6);
no_overlap(&g.cells);
assert_eq!(g.cells[1].y, 2, "middle rises onto the shrunk anchor");
assert_eq!((g.cells[3].y, g.cells[2].y), (0, 4), "neighbour rises to top, bottom follows the stack");
}
fn grid_with(cells: Vec<Cell>) -> PackedGrid {
let mut g = PackedGrid::default();
g.cells = cells;
for (n, c) in g.cells.iter_mut().enumerate() {
c.group.id = GroupId(n as u64);
}
g.next_group_id = g.cells.len() as u64;
g
}
#[test]
fn drop_displaces_stack() {
let mut g = grid_with(vec![cell(0, 0, 2, 2), cell(0, 2, 2, 2), cell(0, 4, 2, 2), cell(2, 0, 2, 2)]);
let y = |g: &PackedGrid, id: u64| g.cells.iter().find(|c| c.group.id == GroupId(id)).expect("cell present").y;
g.drop(DragSource::Tile(GroupId(3)), DropTarget::Displace { x: 0, y: 2 }, 6);
no_overlap(&g.cells);
assert_eq!(y(&g, 0), 0, "A untouched at the top");
assert_eq!(y(&g, 3), 2, "D (shadow) lands on the hovered cell");
assert_eq!(y(&g, 1), 4, "B shoved below the shadow");
assert_eq!(y(&g, 2), 6, "C follows B down");
}
#[test]
fn drop_tears_tab_into_new_tile() {
let mut g = grid_with(vec![cell(0, 0, 2, 2)]);
g.cells[0].group.insert_tab(PanelId("q".into()), 1);
assert_eq!(g.cells[0].group.tabs.len(), 2);
g.drop(
DragSource::Tab {
panel: PanelId("q".into()),
from: GroupId(0),
},
DropTarget::Pack { x: 3 },
6,
);
no_overlap(&g.cells);
assert_eq!(g.cells.len(), 2, "torn tab forms a second tile");
let origin = g.cells.iter().find(|c| c.group.id == GroupId(0)).expect("origin survives");
assert_eq!(origin.group.tabs, vec![PanelId("p".into())], "origin keeps the remainder");
let torn = g.cells.iter().find(|c| c.group.tabs.contains(&PanelId("q".into()))).expect("torn tile");
assert_eq!((torn.x, torn.w, torn.h), (3, 2, 2), "new tile at the column, inheriting size");
}
#[test]
fn drop_packs_at_column() {
let mut g = grid_with(vec![cell(0, 0, 4, 2), cell(4, 0, 2, 2)]);
g.drop(DragSource::Tile(GroupId(1)), DropTarget::Pack { x: 0 }, 6);
no_overlap(&g.cells);
let c = g.cells.iter().find(|c| c.group.id == GroupId(1)).expect("cell present");
assert_eq!((c.x, c.y), (0, 2), "packed at the hovered column, on its skyline");
}
#[test]
fn refit_clamps_into_narrower_band() {
let mut g = PackedGrid::default();
g.cells = vec![cell(0, 0, 4, 2), cell(8, 0, 4, 2)];
g.refit(6);
no_overlap(&g.cells);
for c in &g.cells {
assert!(c.x + c.w <= 6, "tile spills past the narrowed band: {c:?}");
}
}
#[test]
fn close_compacts_upward() {
let mut g = PackedGrid::default();
let mut cells = vec![cell(0, 0, 2, 2), cell(0, 2, 2, 2), cell(0, 4, 2, 2), cell(2, 4, 2, 2)];
for (n, c) in cells.iter_mut().enumerate() {
c.group.id = GroupId(n as u64);
}
g.cells = cells;
g.close_active(GroupId(1));
no_overlap(&g.cells);
let y = |id: u64| g.cells.iter().find(|c| c.group.id == GroupId(id)).expect("cell present").y;
assert_eq!(y(2), 2, "C rises only as far as the tile above it in its column");
assert_eq!(y(3), 0, "D's column is free, so it floats all the way up");
}
}