| 1 | use monolith_planner::Rect; |
| 2 | use slotmap::{SlotMap, new_key_type}; |
| 3 | use std::collections::HashMap; |
| 4 | use std::hash::Hash; |
| 5 | |
| 6 | new_key_type! { pub struct NodeId; } |
| 7 | |
| 8 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 9 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] |
| 10 | #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] |
| 11 | pub enum Axis { |
| 12 | Horizontal, |
| 13 | Vertical, |
| 14 | } |
| 15 | |
| 16 | impl Axis { |
| 17 | pub fn other(self) -> Self { |
| 18 | match self { |
| 19 | Self::Horizontal => Self::Vertical, |
| 20 | Self::Vertical => Self::Horizontal, |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 26 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] |
| 27 | #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] |
| 28 | pub enum Dir { |
| 29 | Left, |
| 30 | Right, |
| 31 | Up, |
| 32 | Down, |
| 33 | } |
| 34 | |
| 35 | impl Dir { |
| 36 | pub fn axis(self) -> Axis { |
| 37 | match self { |
| 38 | Self::Left | Self::Right => Axis::Horizontal, |
| 39 | Self::Up | Self::Down => Axis::Vertical, |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | pub fn forward(self) -> bool { |
| 44 | matches!(self, Self::Right | Self::Down) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | const MIN_SHARE: f64 = 0.05; |
| 49 | |
| 50 | #[derive(Clone, Debug)] |
| 51 | struct Child { |
| 52 | node: NodeId, |
| 53 | weight: f64, |
| 54 | } |
| 55 | |
| 56 | #[derive(Clone, Debug)] |
| 57 | enum Kind<W> { |
| 58 | Leaf(W), |
| 59 | Container { |
| 60 | axis: Axis, |
| 61 | children: Vec<Child>, |
| 62 | expanded: Option<NodeId>, |
| 63 | }, |
| 64 | } |
| 65 | |
| 66 | #[derive(Clone, Debug)] |
| 67 | struct Node<W> { |
| 68 | parent: Option<NodeId>, |
| 69 | kind: Kind<W>, |
| 70 | } |
| 71 | |
| 72 | /// One output's tiling tree. Every tiled window of every tag lives here, the |
| 73 | /// caller's visibility filter decides which ones take space. |
| 74 | /// |
| 75 | /// Children run on the axis opposite their parent. Containers hold at least |
| 76 | /// two children, hidden ones included, and a container left with one child |
| 77 | /// is replaced by it. |
| 78 | #[derive(Clone, Debug)] |
| 79 | pub struct Tree<W> { |
| 80 | nodes: SlotMap<NodeId, Node<W>>, |
| 81 | root: Option<NodeId>, |
| 82 | leaves: HashMap<W, NodeId>, |
| 83 | stack: Axis, |
| 84 | } |
| 85 | |
| 86 | impl<W: Copy + Eq + Hash> Default for Tree<W> { |
| 87 | fn default() -> Self { |
| 88 | Self { |
| 89 | nodes: SlotMap::with_key(), |
| 90 | root: None, |
| 91 | leaves: HashMap::new(), |
| 92 | stack: Axis::Vertical, |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | impl<W: Copy + Eq + Hash> Tree<W> { |
| 98 | /// The axis tag rows stack along. |
| 99 | pub fn stack_axis(&self) -> Axis { |
| 100 | self.stack |
| 101 | } |
| 102 | |
| 103 | pub fn contains(&self, w: W) -> bool { |
| 104 | self.leaves.contains_key(&w) |
| 105 | } |
| 106 | |
| 107 | pub fn is_empty(&self) -> bool { |
| 108 | self.root.is_none() |
| 109 | } |
| 110 | |
| 111 | pub fn windows(&self) -> impl Iterator<Item = W> + '_ { |
| 112 | self.leaves.keys().copied() |
| 113 | } |
| 114 | |
| 115 | /// Inserts `w` as the next sibling of `anchor`, or as a new row if |
| 116 | /// `anchor` is not in the tree. |
| 117 | pub fn insert_after(&mut self, w: W, anchor: W) { |
| 118 | let Some(&a) = self.leaves.get(&anchor) else { |
| 119 | return self.insert_row(w); |
| 120 | }; |
| 121 | let n = self.new_leaf(w); |
| 122 | match self.position(a) { |
| 123 | Some((p, i)) if Some(p) == self.root && self.axis(p) == Some(self.stack) => { |
| 124 | let weight = self.unlink(p, i).weight; |
| 125 | let c = self.new_container(self.stack.other()); |
| 126 | self.attach(c, 0, a, 1.0); |
| 127 | self.attach(c, 1, n, 1.0); |
| 128 | self.attach(p, i, c, weight); |
| 129 | } |
| 130 | Some((p, i)) => { |
| 131 | let weight = self.mean_weight(p); |
| 132 | self.attach(p, i + 1, n, weight); |
| 133 | } |
| 134 | None => { |
| 135 | let c = self.new_container(self.stack.other()); |
| 136 | self.attach(c, 0, a, 1.0); |
| 137 | self.attach(c, 1, n, 1.0); |
| 138 | self.root = Some(c); |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | /// Appends `w` as a row of its own along the stacking axis. |
| 144 | pub fn insert_row(&mut self, w: W) { |
| 145 | let n = self.new_leaf(w); |
| 146 | match self.root { |
| 147 | None => self.root = Some(n), |
| 148 | Some(r) if self.axis(r) == Some(self.stack) => { |
| 149 | let weight = self.mean_weight(r); |
| 150 | let end = self.children(r).len(); |
| 151 | self.attach(r, end, n, weight); |
| 152 | } |
| 153 | Some(r) => { |
| 154 | let c = self.new_container(self.stack); |
| 155 | self.attach(c, 0, r, 1.0); |
| 156 | self.attach(c, 1, n, 1.0); |
| 157 | self.root = Some(c); |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | pub fn remove(&mut self, w: W) -> bool { |
| 163 | let Some(n) = self.leaves.remove(&w) else { |
| 164 | return false; |
| 165 | }; |
| 166 | self.detach(n); |
| 167 | self.nodes.remove(n); |
| 168 | true |
| 169 | } |
| 170 | |
| 171 | pub fn retain(&mut self, mut keep: impl FnMut(W) -> bool) { |
| 172 | let gone: Vec<W> = self.windows().filter(|&w| !keep(w)).collect(); |
| 173 | for w in gone { |
| 174 | self.remove(w); |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// Moves a window one step in `dir`. Leaves swap slots with the next |
| 179 | /// visible sibling, enter a sibling container, or step out beside their |
| 180 | /// container. Hidden windows never move. |
| 181 | pub fn move_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool { |
| 182 | let Some(&n) = self.leaves.get(&w) else { |
| 183 | return false; |
| 184 | }; |
| 185 | self.move_node(n, dir, &vis, true) |
| 186 | } |
| 187 | |
| 188 | /// Moves the container holding `w` as a rigid block. A window sitting |
| 189 | /// directly in the root is its own block. |
| 190 | pub fn move_container(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool { |
| 191 | let Some(&n) = self.leaves.get(&w) else { |
| 192 | return false; |
| 193 | }; |
| 194 | let block = self.nodes[n] |
| 195 | .parent |
| 196 | .filter(|&p| Some(p) != self.root) |
| 197 | .unwrap_or(n); |
| 198 | self.move_node(block, dir, &vis, false) |
| 199 | } |
| 200 | |
| 201 | /// Moves a window to the end of the next visible lane in `dir`, stepping |
| 202 | /// up a level when its container has none that way. A lone window there |
| 203 | /// becomes a stack with it. |
| 204 | pub fn merge_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool { |
| 205 | let Some(&n) = self.leaves.get(&w) else { |
| 206 | return false; |
| 207 | }; |
| 208 | let mut cur = n; |
| 209 | while let Some((p, i)) = self.position(cur) { |
| 210 | if self.axis(p) == Some(dir.axis()) |
| 211 | && let Some(j) = self.next_shown(p, i, dir, &vis) |
| 212 | { |
| 213 | self.join_lane(n, p, j); |
| 214 | return true; |
| 215 | } |
| 216 | cur = p; |
| 217 | } |
| 218 | false |
| 219 | } |
| 220 | |
| 221 | /// Whether every container above `w` is expanded towards it. |
| 222 | pub fn maximized(&self, w: W) -> bool { |
| 223 | let Some(&leaf) = self.leaves.get(&w) else { |
| 224 | return false; |
| 225 | }; |
| 226 | let mut cur = leaf; |
| 227 | let mut any = false; |
| 228 | while let Some(p) = self.nodes[cur].parent { |
| 229 | if self.expanded(p) != Some(cur) { |
| 230 | return false; |
| 231 | } |
| 232 | any = true; |
| 233 | cur = p; |
| 234 | } |
| 235 | any |
| 236 | } |
| 237 | |
| 238 | /// Transposes the whole tree. |
| 239 | pub fn flip(&mut self) { |
| 240 | self.stack = self.stack.other(); |
| 241 | for node in self.nodes.values_mut() { |
| 242 | if let Kind::Container { axis, .. } = &mut node.kind { |
| 243 | *axis = axis.other(); |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | /// Toggles expansion for `count` levels of `w`'s ancestry, starting |
| 249 | /// `skip` levels up. Level 0 expands the window inside its container. |
| 250 | pub fn toggle_expand(&mut self, w: W, skip: usize, count: usize) -> bool { |
| 251 | let Some(&leaf) = self.leaves.get(&w) else { |
| 252 | return false; |
| 253 | }; |
| 254 | let mut path = Vec::new(); |
| 255 | let mut cur = leaf; |
| 256 | while let Some(p) = self.nodes[cur].parent { |
| 257 | path.push((p, cur)); |
| 258 | cur = p; |
| 259 | } |
| 260 | let path: Vec<_> = path.into_iter().skip(skip).take(count).collect(); |
| 261 | if path.is_empty() { |
| 262 | return false; |
| 263 | } |
| 264 | let all = path.iter().all(|&(p, c)| self.expanded(p) == Some(c)); |
| 265 | for (p, c) in path { |
| 266 | if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind { |
| 267 | *expanded = (!all).then_some(c); |
| 268 | } |
| 269 | } |
| 270 | true |
| 271 | } |
| 272 | |
| 273 | /// Grows `w` by `delta`, a fraction of the visible length of the nearest |
| 274 | /// container along `axis` where it has a visible sibling. Hidden siblings |
| 275 | /// keep their weights, and with them their share. |
| 276 | pub fn resize(&mut self, w: W, axis: Axis, delta: f64, vis: impl Fn(W) -> bool) -> bool { |
| 277 | let Some(&leaf) = self.leaves.get(&w) else { |
| 278 | return false; |
| 279 | }; |
| 280 | let mut cur = leaf; |
| 281 | while let Some((p, i)) = self.position(cur) { |
| 282 | if self.axis(p) == Some(axis) { |
| 283 | let shown: Vec<usize> = (0..self.children(p).len()) |
| 284 | .filter(|&j| self.visible(self.children(p)[j].node, &vis)) |
| 285 | .collect(); |
| 286 | if shown.len() >= 2 { |
| 287 | let children = self.children_mut(p); |
| 288 | let sum: f64 = shown.iter().map(|&j| children[j].weight).sum(); |
| 289 | let old = children[i].weight; |
| 290 | let max = 1.0 - MIN_SHARE * (shown.len() - 1) as f64; |
| 291 | let new = (old / sum + delta).clamp(MIN_SHARE, max) * sum; |
| 292 | let scale = (sum - new) / (sum - old); |
| 293 | for j in shown { |
| 294 | children[j].weight = if j == i { |
| 295 | new |
| 296 | } else { |
| 297 | children[j].weight * scale |
| 298 | }; |
| 299 | } |
| 300 | return true; |
| 301 | } |
| 302 | } |
| 303 | cur = p; |
| 304 | } |
| 305 | false |
| 306 | } |
| 307 | |
| 308 | /// Lays the tree out in `area`. Hidden windows come back as zero-size |
| 309 | /// rects on the boundary where they would reappear. |
| 310 | pub fn arrange(&self, area: Rect, gap: f64, vis: impl Fn(W) -> bool) -> Vec<(W, Rect)> { |
| 311 | let mut out = Vec::with_capacity(self.leaves.len()); |
| 312 | if let Some(r) = self.root { |
| 313 | let area = if self.visible(r, &vis) { |
| 314 | area |
| 315 | } else { |
| 316 | Rect::new(area.x + area.w / 2.0, area.y, 0.0, area.h) |
| 317 | }; |
| 318 | self.place(r, area, gap, &vis, &mut out); |
| 319 | } |
| 320 | out |
| 321 | } |
| 322 | |
| 323 | fn place( |
| 324 | &self, |
| 325 | n: NodeId, |
| 326 | r: Rect, |
| 327 | gap: f64, |
| 328 | vis: &impl Fn(W) -> bool, |
| 329 | out: &mut Vec<(W, Rect)>, |
| 330 | ) { |
| 331 | let (axis, children, expanded) = match &self.nodes[n].kind { |
| 332 | Kind::Leaf(w) => return out.push((*w, r)), |
| 333 | Kind::Container { |
| 334 | axis, |
| 335 | children, |
| 336 | expanded, |
| 337 | } => (*axis, children, *expanded), |
| 338 | }; |
| 339 | let shown: Vec<bool> = children.iter().map(|c| self.visible(c.node, vis)).collect(); |
| 340 | let (start, len) = span(r, axis); |
| 341 | if let Some(e) = expanded.and_then(|e| children.iter().position(|c| c.node == e)) |
| 342 | && shown[e] |
| 343 | { |
| 344 | for (i, c) in children.iter().enumerate() { |
| 345 | let sub = match i.cmp(&e) { |
| 346 | std::cmp::Ordering::Equal => r, |
| 347 | std::cmp::Ordering::Less => with_span(r, axis, start, 0.0), |
| 348 | std::cmp::Ordering::Greater => with_span(r, axis, start + len, 0.0), |
| 349 | }; |
| 350 | self.place(c.node, sub, gap, vis, out); |
| 351 | } |
| 352 | return; |
| 353 | } |
| 354 | let count = shown.iter().filter(|s| **s).count(); |
| 355 | let total: f64 = children |
| 356 | .iter() |
| 357 | .zip(&shown) |
| 358 | .filter(|(_, s)| **s) |
| 359 | .map(|(c, _)| c.weight) |
| 360 | .sum(); |
| 361 | let gaps = count.saturating_sub(1) as f64; |
| 362 | let gap = if gaps > 0.0 { gap.min(len / gaps) } else { gap }; |
| 363 | let avail = len - gap * gaps; |
| 364 | let last = shown.iter().rposition(|s| *s); |
| 365 | let mut pos = start; |
| 366 | let mut seen = false; |
| 367 | for (i, c) in children.iter().enumerate() { |
| 368 | if shown[i] { |
| 369 | if seen { |
| 370 | pos += gap; |
| 371 | } |
| 372 | let l = avail * c.weight / total; |
| 373 | self.place(c.node, with_span(r, axis, pos, l), gap, vis, out); |
| 374 | pos += l; |
| 375 | seen = true; |
| 376 | } else { |
| 377 | let between = seen && last.is_some_and(|l| l > i); |
| 378 | let at = if between { pos + gap / 2.0 } else { pos }; |
| 379 | self.place(c.node, with_span(r, axis, at, 0.0), gap, vis, out); |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | fn move_node(&mut self, n: NodeId, dir: Dir, vis: &impl Fn(W) -> bool, enter: bool) -> bool { |
| 385 | let mut cur = n; |
| 386 | while let Some((p, i)) = self.position(cur) { |
| 387 | if self.axis(p) == Some(dir.axis()) { |
| 388 | let hidden_lane = self |
| 389 | .adjacent(p, i, dir) |
| 390 | .filter(|&j| enter && !self.visible(self.children(p)[j].node, vis)); |
| 391 | if cur != n { |
| 392 | if let Some(j) = hidden_lane { |
| 393 | self.join_lane(n, p, j); |
| 394 | } else { |
| 395 | let at = if dir.forward() { i + 1 } else { i }; |
| 396 | self.relocate(n, p, at); |
| 397 | } |
| 398 | return true; |
| 399 | } |
| 400 | if let Some(j) = self.next_shown(p, i, dir, vis) { |
| 401 | let sib = self.children(p)[j].node; |
| 402 | if enter && self.axis(sib).is_some() { |
| 403 | let end = self.children(sib).len(); |
| 404 | self.relocate(n, sib, end); |
| 405 | } else { |
| 406 | let children = self.children_mut(p); |
| 407 | children[i].node = sib; |
| 408 | children[j].node = n; |
| 409 | } |
| 410 | return true; |
| 411 | } |
| 412 | if let Some(j) = hidden_lane { |
| 413 | self.join_lane(n, p, j); |
| 414 | return true; |
| 415 | } |
| 416 | } |
| 417 | cur = p; |
| 418 | } |
| 419 | if cur == n || self.axis(cur) == Some(dir.axis()) { |
| 420 | return false; |
| 421 | } |
| 422 | let (old, i) = self.position(n).expect("n is below the root"); |
| 423 | self.unlink(old, i); |
| 424 | self.normalize(old); |
| 425 | let r = self.root.expect("the rest of the tree survives"); |
| 426 | if self.axis(r) == Some(dir.axis()) { |
| 427 | let weight = self.mean_weight(r); |
| 428 | let at = if dir.forward() { |
| 429 | self.children(r).len() |
| 430 | } else { |
| 431 | 0 |
| 432 | }; |
| 433 | self.attach(r, at, n, weight); |
| 434 | } else { |
| 435 | let c = self.new_container(dir.axis()); |
| 436 | self.attach(c, 0, r, 1.0); |
| 437 | let at = if dir.forward() { |
| 438 | self.children(c).len() |
| 439 | } else { |
| 440 | 0 |
| 441 | }; |
| 442 | self.attach(c, at, n, 1.0); |
| 443 | self.root = Some(c); |
| 444 | } |
| 445 | true |
| 446 | } |
| 447 | |
| 448 | fn next_shown(&self, p: NodeId, i: usize, dir: Dir, vis: &impl Fn(W) -> bool) -> Option<usize> { |
| 449 | let children = self.children(p); |
| 450 | if dir.forward() { |
| 451 | (i + 1..children.len()).find(|&j| self.visible(children[j].node, vis)) |
| 452 | } else { |
| 453 | (0..i).rev().find(|&j| self.visible(children[j].node, vis)) |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | fn adjacent(&self, p: NodeId, i: usize, dir: Dir) -> Option<usize> { |
| 458 | let j = if dir.forward() { |
| 459 | i + 1 |
| 460 | } else { |
| 461 | i.checked_sub(1)? |
| 462 | }; |
| 463 | (j < self.children(p).len()).then_some(j) |
| 464 | } |
| 465 | |
| 466 | /// Moves `n` to the end of the lane at `p`'s child `j`. A lone window |
| 467 | /// there becomes a lane of its own, perpendicular to `p`. |
| 468 | fn join_lane(&mut self, n: NodeId, p: NodeId, j: usize) { |
| 469 | let lane = self.children(p)[j].node; |
| 470 | let lane = if self.axis(lane).is_some() { |
| 471 | lane |
| 472 | } else { |
| 473 | let c = self.new_container(self.axis(p).expect("p is a container").other()); |
| 474 | self.children_mut(p)[j].node = c; |
| 475 | self.nodes[c].parent = Some(p); |
| 476 | if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind |
| 477 | && *expanded == Some(lane) |
| 478 | { |
| 479 | *expanded = Some(c); |
| 480 | } |
| 481 | self.attach(c, 0, lane, 1.0); |
| 482 | c |
| 483 | }; |
| 484 | let end = self.children(lane).len(); |
| 485 | self.relocate(n, lane, end); |
| 486 | } |
| 487 | |
| 488 | fn relocate(&mut self, n: NodeId, p: NodeId, at: usize) { |
| 489 | let (old, i) = self.position(n).expect("relocated nodes have a parent"); |
| 490 | let weight = self.mean_weight(p); |
| 491 | let at = if old == p && i < at { at - 1 } else { at }; |
| 492 | self.unlink(old, i); |
| 493 | self.attach(p, at, n, weight); |
| 494 | self.normalize(old); |
| 495 | } |
| 496 | |
| 497 | /// Places `node` among `p`'s children. A container running along `p`'s |
| 498 | /// axis is dissolved into `p` so axes keep alternating. |
| 499 | fn attach(&mut self, p: NodeId, at: usize, node: NodeId, weight: f64) { |
| 500 | if self.axis(node) == self.axis(p) { |
| 501 | let Some(Node { |
| 502 | kind: Kind::Container { children, .. }, |
| 503 | .. |
| 504 | }) = self.nodes.remove(node) |
| 505 | else { |
| 506 | unreachable!("only containers have an axis"); |
| 507 | }; |
| 508 | let total: f64 = children.iter().map(|c| c.weight).sum(); |
| 509 | for (k, c) in children.into_iter().enumerate() { |
| 510 | self.nodes[c.node].parent = Some(p); |
| 511 | let weight = weight * c.weight / total; |
| 512 | self.children_mut(p).insert( |
| 513 | at + k, |
| 514 | Child { |
| 515 | node: c.node, |
| 516 | weight, |
| 517 | }, |
| 518 | ); |
| 519 | } |
| 520 | } else { |
| 521 | self.nodes[node].parent = Some(p); |
| 522 | self.children_mut(p).insert(at, Child { node, weight }); |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | fn unlink(&mut self, p: NodeId, i: usize) -> Child { |
| 527 | let Kind::Container { |
| 528 | children, expanded, .. |
| 529 | } = &mut self.nodes[p].kind |
| 530 | else { |
| 531 | unreachable!("parents are containers"); |
| 532 | }; |
| 533 | let child = children.remove(i); |
| 534 | if *expanded == Some(child.node) { |
| 535 | *expanded = None; |
| 536 | } |
| 537 | self.nodes[child.node].parent = None; |
| 538 | child |
| 539 | } |
| 540 | |
| 541 | fn detach(&mut self, n: NodeId) { |
| 542 | match self.position(n) { |
| 543 | Some((p, i)) => { |
| 544 | self.unlink(p, i); |
| 545 | self.normalize(p); |
| 546 | } |
| 547 | None => self.root = None, |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | /// Repairs a container that lost a child. |
| 552 | fn normalize(&mut self, c: NodeId) { |
| 553 | if self.children(c).len() >= 2 { |
| 554 | return; |
| 555 | } |
| 556 | let pos = self.position(c); |
| 557 | let was_expanded = pos.is_some_and(|(p, _)| self.expanded(p) == Some(c)); |
| 558 | let Some(Node { |
| 559 | kind: Kind::Container { children, .. }, |
| 560 | .. |
| 561 | }) = self.nodes.remove(c) |
| 562 | else { |
| 563 | unreachable!("only containers are normalized"); |
| 564 | }; |
| 565 | let only = children.into_iter().next(); |
| 566 | match (only, pos) { |
| 567 | (None, Some((p, i))) => { |
| 568 | self.unlink_dead(p, i); |
| 569 | self.normalize(p); |
| 570 | } |
| 571 | (None, None) => self.root = None, |
| 572 | (Some(only), Some((p, i))) => { |
| 573 | let weight = self.unlink_dead(p, i).weight; |
| 574 | let leaf_like = self.axis(only.node) != self.axis(p); |
| 575 | self.attach(p, i, only.node, weight); |
| 576 | if was_expanded |
| 577 | && leaf_like |
| 578 | && let Kind::Container { expanded, .. } = &mut self.nodes[p].kind |
| 579 | { |
| 580 | *expanded = Some(only.node); |
| 581 | } |
| 582 | } |
| 583 | (Some(only), None) => { |
| 584 | self.nodes[only.node].parent = None; |
| 585 | self.root = Some(only.node); |
| 586 | } |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | /// Like `unlink`, for a child whose node is already gone. |
| 591 | fn unlink_dead(&mut self, p: NodeId, i: usize) -> Child { |
| 592 | let Kind::Container { |
| 593 | children, expanded, .. |
| 594 | } = &mut self.nodes[p].kind |
| 595 | else { |
| 596 | unreachable!("parents are containers"); |
| 597 | }; |
| 598 | let child = children.remove(i); |
| 599 | if *expanded == Some(child.node) { |
| 600 | *expanded = None; |
| 601 | } |
| 602 | child |
| 603 | } |
| 604 | |
| 605 | fn new_leaf(&mut self, w: W) -> NodeId { |
| 606 | let n = self.nodes.insert(Node { |
| 607 | parent: None, |
| 608 | kind: Kind::Leaf(w), |
| 609 | }); |
| 610 | self.leaves.insert(w, n); |
| 611 | n |
| 612 | } |
| 613 | |
| 614 | fn new_container(&mut self, axis: Axis) -> NodeId { |
| 615 | self.nodes.insert(Node { |
| 616 | parent: None, |
| 617 | kind: Kind::Container { |
| 618 | axis, |
| 619 | children: Vec::new(), |
| 620 | expanded: None, |
| 621 | }, |
| 622 | }) |
| 623 | } |
| 624 | |
| 625 | fn position(&self, n: NodeId) -> Option<(NodeId, usize)> { |
| 626 | let p = self.nodes[n].parent?; |
| 627 | let i = self.children(p).iter().position(|c| c.node == n)?; |
| 628 | Some((p, i)) |
| 629 | } |
| 630 | |
| 631 | fn axis(&self, n: NodeId) -> Option<Axis> { |
| 632 | match &self.nodes[n].kind { |
| 633 | Kind::Container { axis, .. } => Some(*axis), |
| 634 | Kind::Leaf(_) => None, |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | fn expanded(&self, n: NodeId) -> Option<NodeId> { |
| 639 | match &self.nodes[n].kind { |
| 640 | Kind::Container { expanded, .. } => *expanded, |
| 641 | Kind::Leaf(_) => None, |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | fn children(&self, n: NodeId) -> &[Child] { |
| 646 | match &self.nodes[n].kind { |
| 647 | Kind::Container { children, .. } => children, |
| 648 | Kind::Leaf(_) => &[], |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | fn children_mut(&mut self, n: NodeId) -> &mut Vec<Child> { |
| 653 | match &mut self.nodes[n].kind { |
| 654 | Kind::Container { children, .. } => children, |
| 655 | Kind::Leaf(_) => unreachable!("leaves have no children"), |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | fn mean_weight(&self, p: NodeId) -> f64 { |
| 660 | let children = self.children(p); |
| 661 | if children.is_empty() { |
| 662 | 1.0 |
| 663 | } else { |
| 664 | children.iter().map(|c| c.weight).sum::<f64>() / children.len() as f64 |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | fn visible(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> bool { |
| 669 | match &self.nodes[n].kind { |
| 670 | Kind::Leaf(w) => vis(*w), |
| 671 | Kind::Container { children, .. } => children.iter().any(|c| self.visible(c.node, vis)), |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | #[cfg(test)] |
| 676 | pub(crate) fn check(&self) { |
| 677 | let reachable = match self.root { |
| 678 | Some(r) => { |
| 679 | assert!(self.nodes[r].parent.is_none()); |
| 680 | self.check_node(r) |
| 681 | } |
| 682 | None => 0, |
| 683 | }; |
| 684 | assert_eq!(reachable, self.nodes.len(), "orphaned nodes"); |
| 685 | for (&w, &n) in &self.leaves { |
| 686 | assert!(matches!(self.nodes[n].kind, Kind::Leaf(x) if x == w)); |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | #[cfg(test)] |
| 691 | fn check_node(&self, n: NodeId) -> usize { |
| 692 | match &self.nodes[n].kind { |
| 693 | Kind::Leaf(_) => 1, |
| 694 | Kind::Container { |
| 695 | axis, |
| 696 | children, |
| 697 | expanded, |
| 698 | } => { |
| 699 | assert!( |
| 700 | children.len() >= 2, |
| 701 | "container with {} children", |
| 702 | children.len() |
| 703 | ); |
| 704 | if let Some(e) = expanded { |
| 705 | assert!(children.iter().any(|c| c.node == *e)); |
| 706 | } |
| 707 | let mut count = 1; |
| 708 | for c in children { |
| 709 | assert!(c.weight > 0.0 && c.weight.is_finite()); |
| 710 | assert_eq!(self.nodes[c.node].parent, Some(n)); |
| 711 | assert_ne!(self.axis(c.node), Some(*axis), "axes must alternate"); |
| 712 | count += self.check_node(c.node); |
| 713 | } |
| 714 | count |
| 715 | } |
| 716 | } |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | fn span(r: Rect, axis: Axis) -> (f64, f64) { |
| 721 | match axis { |
| 722 | Axis::Horizontal => (r.x, r.w), |
| 723 | Axis::Vertical => (r.y, r.h), |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | fn with_span(r: Rect, axis: Axis, start: f64, len: f64) -> Rect { |
| 728 | match axis { |
| 729 | Axis::Horizontal => Rect::new(start, r.y, len, r.h), |
| 730 | Axis::Vertical => Rect::new(r.x, start, r.w, len), |
| 731 | } |
| 732 | } |