| 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 | fn index(self) -> usize { |
| 25 | match self { |
| 26 | Self::Horizontal => 0, |
| 27 | Self::Vertical => 1, |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 33 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] |
| 34 | #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] |
| 35 | pub enum Dir { |
| 36 | Left, |
| 37 | Right, |
| 38 | Up, |
| 39 | Down, |
| 40 | } |
| 41 | |
| 42 | impl Dir { |
| 43 | pub fn axis(self) -> Axis { |
| 44 | match self { |
| 45 | Self::Left | Self::Right => Axis::Horizontal, |
| 46 | Self::Up | Self::Down => Axis::Vertical, |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | pub fn forward(self) -> bool { |
| 51 | matches!(self, Self::Right | Self::Down) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | const MIN_SHARE: f64 = 0.05; |
| 56 | |
| 57 | /// A window's width and height relative to its neighbours'. |
| 58 | type Size = [f64; 2]; |
| 59 | |
| 60 | #[derive(Clone, Debug)] |
| 61 | enum Kind<W> { |
| 62 | Leaf(W, Size), |
| 63 | Container { |
| 64 | axis: Axis, |
| 65 | children: Vec<NodeId>, |
| 66 | expanded: Option<NodeId>, |
| 67 | }, |
| 68 | } |
| 69 | |
| 70 | #[derive(Clone, Debug)] |
| 71 | struct Node<W> { |
| 72 | parent: Option<NodeId>, |
| 73 | kind: Kind<W>, |
| 74 | } |
| 75 | |
| 76 | /// One output's tiling tree. Every tiled window of every tag lives here, the |
| 77 | /// caller's visibility filter decides which ones take space. |
| 78 | /// |
| 79 | /// Children run on the axis opposite their parent. Containers hold at least |
| 80 | /// two children, hidden ones included, and a container left with one child |
| 81 | /// is replaced by it. |
| 82 | #[derive(Clone, Debug)] |
| 83 | pub struct Tree<W> { |
| 84 | nodes: SlotMap<NodeId, Node<W>>, |
| 85 | root: Option<NodeId>, |
| 86 | leaves: HashMap<W, NodeId>, |
| 87 | stack: Axis, |
| 88 | } |
| 89 | |
| 90 | impl<W: Copy + Eq + Hash> Default for Tree<W> { |
| 91 | fn default() -> Self { |
| 92 | Self { |
| 93 | nodes: SlotMap::with_key(), |
| 94 | root: None, |
| 95 | leaves: HashMap::new(), |
| 96 | stack: Axis::Vertical, |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | impl<W: Copy + Eq + Hash> Tree<W> { |
| 102 | /// The axis tag rows stack along. |
| 103 | pub fn stack_axis(&self) -> Axis { |
| 104 | self.stack |
| 105 | } |
| 106 | |
| 107 | pub fn contains(&self, w: W) -> bool { |
| 108 | self.leaves.contains_key(&w) |
| 109 | } |
| 110 | |
| 111 | pub fn is_empty(&self) -> bool { |
| 112 | self.root.is_none() |
| 113 | } |
| 114 | |
| 115 | pub fn windows(&self) -> impl Iterator<Item = W> + '_ { |
| 116 | self.leaves.keys().copied() |
| 117 | } |
| 118 | |
| 119 | /// Inserts `w` as the next sibling of `anchor`, or as a new row if |
| 120 | /// `anchor` is not in the tree. |
| 121 | pub fn insert_after(&mut self, w: W, anchor: W) { |
| 122 | let Some(&a) = self.leaves.get(&anchor) else { |
| 123 | return self.insert_row(w); |
| 124 | }; |
| 125 | match self.position(a) { |
| 126 | Some((p, i)) if Some(p) == self.root && self.axis(p) == Some(self.stack) => { |
| 127 | let n = self.new_leaf(w, self.size(a)); |
| 128 | self.unlink(p, i); |
| 129 | let c = self.new_container(self.stack.other()); |
| 130 | self.attach(c, 0, a); |
| 131 | self.attach(c, 1, n); |
| 132 | self.attach(p, i, c); |
| 133 | self.reveal(n, true); |
| 134 | } |
| 135 | Some((p, i)) => { |
| 136 | let n = self.new_leaf(w, self.size(p)); |
| 137 | self.attach(p, i + 1, n); |
| 138 | self.reveal(n, true); |
| 139 | } |
| 140 | None => { |
| 141 | let n = self.new_leaf(w, self.size(a)); |
| 142 | let c = self.new_container(self.stack.other()); |
| 143 | self.attach(c, 0, a); |
| 144 | self.attach(c, 1, n); |
| 145 | self.root = Some(c); |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /// Inserts `w` after `anchor` by splitting `anchor` along `axis`. They |
| 151 | /// share the space `anchor` had, and its siblings keep theirs. |
| 152 | pub fn insert_split(&mut self, w: W, anchor: W, axis: Axis) { |
| 153 | let Some(&a) = self.leaves.get(&anchor) else { |
| 154 | return self.insert_row(w); |
| 155 | }; |
| 156 | let size = self.size(a); |
| 157 | let n = self.new_leaf(w, size); |
| 158 | match self.position(a) { |
| 159 | Some((p, i)) if self.axis(p) == Some(axis) => { |
| 160 | self.halve(a, axis); |
| 161 | self.halve(n, axis); |
| 162 | self.attach(p, i + 1, n); |
| 163 | } |
| 164 | Some((p, i)) => { |
| 165 | self.unlink(p, i); |
| 166 | let c = self.new_container(axis); |
| 167 | self.attach(c, 0, a); |
| 168 | self.attach(c, 1, n); |
| 169 | self.attach(p, i, c); |
| 170 | } |
| 171 | None => { |
| 172 | let c = self.new_container(axis); |
| 173 | self.attach(c, 0, a); |
| 174 | self.attach(c, 1, n); |
| 175 | self.root = Some(c); |
| 176 | } |
| 177 | } |
| 178 | self.reveal(n, true); |
| 179 | } |
| 180 | |
| 181 | fn halve(&mut self, leaf: NodeId, axis: Axis) { |
| 182 | if let Kind::Leaf(_, size) = &mut self.nodes[leaf].kind { |
| 183 | size[axis.index()] /= 2.0; |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// Appends `w` as a row of its own along the stacking axis. |
| 188 | pub fn insert_row(&mut self, w: W) { |
| 189 | let size = self.root.map_or([1.0; 2], |r| self.size(r)); |
| 190 | let n = self.new_leaf(w, size); |
| 191 | match self.root { |
| 192 | None => self.root = Some(n), |
| 193 | Some(r) if self.axis(r) == Some(self.stack) => { |
| 194 | let end = self.children(r).len(); |
| 195 | self.attach(r, end, n); |
| 196 | } |
| 197 | Some(r) => { |
| 198 | let c = self.new_container(self.stack); |
| 199 | self.attach(c, 0, r); |
| 200 | self.attach(c, 1, n); |
| 201 | self.root = Some(c); |
| 202 | } |
| 203 | } |
| 204 | self.reveal(n, true); |
| 205 | } |
| 206 | |
| 207 | pub fn remove(&mut self, w: W) -> bool { |
| 208 | let Some(n) = self.leaves.remove(&w) else { |
| 209 | return false; |
| 210 | }; |
| 211 | self.detach(n); |
| 212 | self.nodes.remove(n); |
| 213 | true |
| 214 | } |
| 215 | |
| 216 | pub fn retain(&mut self, mut keep: impl FnMut(W) -> bool) { |
| 217 | let gone: Vec<W> = self.windows().filter(|&w| !keep(w)).collect(); |
| 218 | for w in gone { |
| 219 | self.remove(w); |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | /// Moves a window one step in `dir`. Leaves swap slots with the next |
| 224 | /// visible sibling, enter a sibling container, or step out beside their |
| 225 | /// container. Hidden windows never move. |
| 226 | pub fn move_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool { |
| 227 | let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else { |
| 228 | return false; |
| 229 | }; |
| 230 | self.until_seen(&vis, |t| { |
| 231 | let moved = t.move_node(n, dir, &vis, true); |
| 232 | t.reveal(n, moved) |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | /// Moves the container holding `w` as a rigid block. A window sitting |
| 237 | /// directly in the root is its own block. |
| 238 | pub fn move_container(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool { |
| 239 | let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else { |
| 240 | return false; |
| 241 | }; |
| 242 | self.until_seen(&vis, |t| { |
| 243 | let block = t.nodes[n] |
| 244 | .parent |
| 245 | .filter(|&p| Some(p) != t.root) |
| 246 | .unwrap_or(n); |
| 247 | let moved = t.move_node(block, dir, &vis, false); |
| 248 | t.reveal(n, moved) |
| 249 | }) |
| 250 | } |
| 251 | |
| 252 | /// Moves a window to the end of the next visible lane in `dir` among its |
| 253 | /// siblings. A lone window there becomes a stack with it. A window with no |
| 254 | /// sibling lane that way leaves its stack as `move_window` would, so it |
| 255 | /// takes one press to step out and another to merge. |
| 256 | pub fn merge_window(&mut self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool { |
| 257 | let Some(&n) = self.leaves.get(&w).filter(|_| vis(w)) else { |
| 258 | return false; |
| 259 | }; |
| 260 | self.until_seen(&vis, |t| { |
| 261 | if let Some((p, i)) = t.position(n) |
| 262 | && t.axis(p) == Some(dir.axis()) |
| 263 | && let Some(j) = t.next_shown(p, i, dir, &vis) |
| 264 | { |
| 265 | t.join_lane(n, p, j); |
| 266 | return t.reveal(n, true); |
| 267 | } |
| 268 | let moved = t.move_node(n, dir, &vis, true); |
| 269 | t.reveal(n, moved) |
| 270 | }) |
| 271 | } |
| 272 | |
| 273 | /// Repeats `step` until the visible layout changes, or undoes it all when |
| 274 | /// it never does. Steps around hidden windows otherwise ate keypresses |
| 275 | /// and rearranged windows the user could not see. |
| 276 | fn until_seen( |
| 277 | &mut self, |
| 278 | vis: &impl Fn(W) -> bool, |
| 279 | mut step: impl FnMut(&mut Self) -> bool, |
| 280 | ) -> bool { |
| 281 | let seen = |t: &Self| -> Vec<(W, Rect)> { |
| 282 | t.arrange(Rect::new(0.0, 0.0, 1000.0, 1000.0), 0.0, vis) |
| 283 | .into_iter() |
| 284 | .filter(|p| vis(p.0)) |
| 285 | .collect() |
| 286 | }; |
| 287 | let same = |a: &[(W, Rect)], b: &[(W, Rect)]| { |
| 288 | a.len() == b.len() |
| 289 | && a.iter().all(|(v, r)| { |
| 290 | b.iter().any(|(w, s)| { |
| 291 | v == w |
| 292 | && [r.x - s.x, r.y - s.y, r.w - s.w, r.h - s.h] |
| 293 | .iter() |
| 294 | .all(|d| d.abs() < 1e-6) |
| 295 | }) |
| 296 | }) |
| 297 | }; |
| 298 | let before = self.clone(); |
| 299 | let start = seen(self); |
| 300 | for _ in 0..=before.nodes.len() { |
| 301 | if !step(self) { |
| 302 | break; |
| 303 | } |
| 304 | if !same(&start, &seen(self)) { |
| 305 | return true; |
| 306 | } |
| 307 | } |
| 308 | *self = before; |
| 309 | false |
| 310 | } |
| 311 | |
| 312 | /// Undoes any expansion along `leaf`'s ancestry that favours another |
| 313 | /// child, once it has `moved` or arrived. An expanded container gives its |
| 314 | /// other children no room, so a window moved into one vanished while |
| 315 | /// staying focused. |
| 316 | fn reveal(&mut self, leaf: NodeId, moved: bool) -> bool { |
| 317 | let mut cur = leaf; |
| 318 | while moved && let Some(p) = self.nodes[cur].parent { |
| 319 | if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind |
| 320 | && expanded.is_some_and(|e| e != cur) |
| 321 | { |
| 322 | *expanded = None; |
| 323 | } |
| 324 | cur = p; |
| 325 | } |
| 326 | moved |
| 327 | } |
| 328 | |
| 329 | /// Whether every container above `w` is expanded towards it. |
| 330 | pub fn maximized(&self, w: W, vis: impl Fn(W) -> bool) -> bool { |
| 331 | let path = self.shown_path(w, &vis); |
| 332 | !path.is_empty() && path.iter().all(|&(p, c)| self.expanded(p) == Some(c)) |
| 333 | } |
| 334 | |
| 335 | /// `w`'s ancestry as (container, child) pairs, leaving out containers |
| 336 | /// where the child has no visible sibling. Those look like nothing on |
| 337 | /// screen, so expanding there would do nothing the user could see. |
| 338 | fn shown_path(&self, w: W, vis: &impl Fn(W) -> bool) -> Vec<(NodeId, NodeId)> { |
| 339 | let Some(&leaf) = self.leaves.get(&w) else { |
| 340 | return Vec::new(); |
| 341 | }; |
| 342 | let mut path = Vec::new(); |
| 343 | let mut cur = leaf; |
| 344 | while let Some(p) = self.nodes[cur].parent { |
| 345 | let shared = self |
| 346 | .children(p) |
| 347 | .iter() |
| 348 | .any(|&c| c != cur && self.visible(c, vis)); |
| 349 | if shared { |
| 350 | path.push((p, cur)); |
| 351 | } |
| 352 | cur = p; |
| 353 | } |
| 354 | path |
| 355 | } |
| 356 | |
| 357 | /// Transposes the whole tree. |
| 358 | pub fn flip(&mut self) { |
| 359 | self.stack = self.stack.other(); |
| 360 | for node in self.nodes.values_mut() { |
| 361 | match &mut node.kind { |
| 362 | Kind::Container { axis, .. } => *axis = axis.other(), |
| 363 | Kind::Leaf(_, size) => size.reverse(), |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /// Toggles expansion for `count` levels of `w`'s visible ancestry, |
| 369 | /// starting `skip` levels up. Level 0 expands the window inside the |
| 370 | /// nearest container where it has a visible sibling. |
| 371 | pub fn toggle_expand( |
| 372 | &mut self, |
| 373 | w: W, |
| 374 | skip: usize, |
| 375 | count: usize, |
| 376 | vis: impl Fn(W) -> bool, |
| 377 | ) -> bool { |
| 378 | let path: Vec<_> = self |
| 379 | .shown_path(w, &vis) |
| 380 | .into_iter() |
| 381 | .skip(skip) |
| 382 | .take(count) |
| 383 | .collect(); |
| 384 | if path.is_empty() { |
| 385 | return false; |
| 386 | } |
| 387 | let all = path.iter().all(|&(p, c)| self.expanded(p) == Some(c)); |
| 388 | for (p, c) in path { |
| 389 | if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind { |
| 390 | *expanded = (!all).then_some(c); |
| 391 | } |
| 392 | } |
| 393 | true |
| 394 | } |
| 395 | |
| 396 | /// Grows `w` by `delta`, a fraction of the visible length of the nearest |
| 397 | /// container along `axis` where it has a visible sibling. Hidden siblings |
| 398 | /// keep their sizes, and with them their share. |
| 399 | pub fn resize(&mut self, w: W, axis: Axis, delta: f64, vis: impl Fn(W) -> bool) -> bool { |
| 400 | let Some(&leaf) = self.leaves.get(&w) else { |
| 401 | return false; |
| 402 | }; |
| 403 | let mut cur = leaf; |
| 404 | while let Some(p) = self.nodes[cur].parent { |
| 405 | if self.axis(p) == Some(axis) { |
| 406 | let shown: Vec<(NodeId, f64)> = self |
| 407 | .children(p) |
| 408 | .iter() |
| 409 | .filter(|&&c| self.visible(c, &vis)) |
| 410 | .map(|&c| (c, self.extent(c, axis, &vis))) |
| 411 | .collect(); |
| 412 | if shown.len() >= 2 { |
| 413 | let sum: f64 = shown.iter().map(|s| s.1).sum(); |
| 414 | let old = self.extent(cur, axis, &vis); |
| 415 | let max = 1.0 - MIN_SHARE * (shown.len() - 1) as f64; |
| 416 | let new = (old / sum + delta).clamp(MIN_SHARE, max) * sum; |
| 417 | let scale = (sum - new) / (sum - old); |
| 418 | for (c, _) in shown { |
| 419 | self.scale(c, axis, if c == cur { new / old } else { scale }); |
| 420 | } |
| 421 | return true; |
| 422 | } |
| 423 | } |
| 424 | cur = p; |
| 425 | } |
| 426 | false |
| 427 | } |
| 428 | |
| 429 | /// The lane a window's split on side `dir` lives in, as the child holding |
| 430 | /// the window, its parent and the index of the visible sibling across |
| 431 | /// the split. |
| 432 | fn split_across( |
| 433 | &self, |
| 434 | w: W, |
| 435 | dir: Dir, |
| 436 | vis: &impl Fn(W) -> bool, |
| 437 | ) -> Option<(NodeId, NodeId, usize)> { |
| 438 | let mut cur = *self.leaves.get(&w)?; |
| 439 | if !self.visible(cur, vis) { |
| 440 | return None; |
| 441 | } |
| 442 | while let Some((p, i)) = self.position(cur) { |
| 443 | if self.axis(p) == Some(dir.axis()) |
| 444 | && let Some(j) = self.next_shown(p, i, dir, vis) |
| 445 | { |
| 446 | return Some((cur, p, j)); |
| 447 | } |
| 448 | cur = p; |
| 449 | } |
| 450 | None |
| 451 | } |
| 452 | |
| 453 | /// Whether the split on side `dir` of `w` has a visible window across it. |
| 454 | pub fn has_split(&self, w: W, dir: Dir, vis: impl Fn(W) -> bool) -> bool { |
| 455 | self.split_across(w, dir, &vis).is_some() |
| 456 | } |
| 457 | |
| 458 | /// Moves the split on side `dir` of `w` by `px` along that side's axis, |
| 459 | /// positive toward the right or bottom. Only the two children meeting at |
| 460 | /// the split change, so the split follows the pointer. |
| 461 | pub fn move_split( |
| 462 | &mut self, |
| 463 | w: W, |
| 464 | dir: Dir, |
| 465 | px: f64, |
| 466 | area: Rect, |
| 467 | gap: f64, |
| 468 | vis: impl Fn(W) -> bool, |
| 469 | ) -> bool { |
| 470 | let Some((cur, p, j)) = self.split_across(w, dir, &vis) else { |
| 471 | return false; |
| 472 | }; |
| 473 | let axis = dir.axis(); |
| 474 | let other = self.children(p)[j]; |
| 475 | let (first, second) = if dir.forward() { |
| 476 | (cur, other) |
| 477 | } else { |
| 478 | (other, cur) |
| 479 | }; |
| 480 | let mut leaves = Vec::new(); |
| 481 | self.shown_leaves(first, &vis, &mut leaves); |
| 482 | let (start, end) = self |
| 483 | .arrange(area, gap, &vis) |
| 484 | .iter() |
| 485 | .filter(|(l, _)| leaves.contains(l)) |
| 486 | .map(|(_, r)| span(*r, axis)) |
| 487 | .fold((f64::MAX, f64::MIN), |(s, e), (rs, rl)| { |
| 488 | (s.min(rs), e.max(rs + rl)) |
| 489 | }); |
| 490 | let ef = self.extent(first, axis, &vis); |
| 491 | let es = self.extent(second, axis, &vis); |
| 492 | if end <= start || ef <= 0.0 || es <= 0.0 { |
| 493 | return true; |
| 494 | } |
| 495 | let sum: f64 = self |
| 496 | .children(p) |
| 497 | .iter() |
| 498 | .filter(|&&c| self.visible(c, &vis)) |
| 499 | .map(|&c| self.extent(c, axis, &vis)) |
| 500 | .sum(); |
| 501 | let min = MIN_SHARE * sum; |
| 502 | let du = (px * ef / (end - start)).clamp(-(ef - min).max(0.0), (es - min).max(0.0)); |
| 503 | self.scale(first, axis, (ef + du) / ef); |
| 504 | self.scale(second, axis, (es - du) / es); |
| 505 | true |
| 506 | } |
| 507 | |
| 508 | fn shown_leaves(&self, n: NodeId, vis: &impl Fn(W) -> bool, out: &mut Vec<W>) { |
| 509 | match &self.nodes[n].kind { |
| 510 | Kind::Leaf(w, _) => { |
| 511 | if vis(*w) { |
| 512 | out.push(*w); |
| 513 | } |
| 514 | } |
| 515 | Kind::Container { children, .. } => { |
| 516 | for &c in children { |
| 517 | self.shown_leaves(c, vis, out); |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | /// Scales every window under `n` along `axis`, hidden ones too, so they |
| 524 | /// keep their proportions for when they are shown again. |
| 525 | fn scale(&mut self, n: NodeId, axis: Axis, by: f64) { |
| 526 | match &mut self.nodes[n].kind { |
| 527 | Kind::Leaf(_, size) => size[axis.index()] *= by, |
| 528 | Kind::Container { children, .. } => { |
| 529 | for c in children.clone() { |
| 530 | self.scale(c, axis, by); |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | /// How much room `n` asks for along `axis` among its siblings. A |
| 537 | /// container asks for the mean of what its visible children ask for, so |
| 538 | /// windows of other tags sharing a lane change nothing on screen, and a |
| 539 | /// window carries its own size wherever it moves. |
| 540 | fn extent(&self, n: NodeId, axis: Axis, vis: &impl Fn(W) -> bool) -> f64 { |
| 541 | match &self.nodes[n].kind { |
| 542 | Kind::Leaf(_, size) => size[axis.index()], |
| 543 | Kind::Container { children, .. } => { |
| 544 | let shown: Vec<f64> = children |
| 545 | .iter() |
| 546 | .filter(|&&c| self.visible(c, vis)) |
| 547 | .map(|&c| self.extent(c, axis, vis)) |
| 548 | .collect(); |
| 549 | if shown.is_empty() { |
| 550 | children |
| 551 | .iter() |
| 552 | .map(|&c| self.extent(c, axis, vis)) |
| 553 | .sum::<f64>() |
| 554 | / children.len() as f64 |
| 555 | } else { |
| 556 | shown.iter().sum::<f64>() / shown.len() as f64 |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | /// The size a window placed in `n`'s stead would take, ignoring |
| 563 | /// visibility since new windows land on any tag. |
| 564 | fn size(&self, n: NodeId) -> Size { |
| 565 | let all = |_: W| true; |
| 566 | [ |
| 567 | self.extent(n, Axis::Horizontal, &all), |
| 568 | self.extent(n, Axis::Vertical, &all), |
| 569 | ] |
| 570 | } |
| 571 | |
| 572 | /// Lays the tree out in `area`. Hidden windows come back as zero-size |
| 573 | /// rects on the boundary where they would reappear. |
| 574 | pub fn arrange(&self, area: Rect, gap: f64, vis: impl Fn(W) -> bool) -> Vec<(W, Rect)> { |
| 575 | let mut out = Vec::with_capacity(self.leaves.len()); |
| 576 | if let Some(r) = self.root { |
| 577 | let area = if self.visible(r, &vis) { |
| 578 | area |
| 579 | } else { |
| 580 | Rect::new(area.x + area.w / 2.0, area.y, 0.0, area.h) |
| 581 | }; |
| 582 | self.place(r, area, gap, &vis, &mut out); |
| 583 | } |
| 584 | out |
| 585 | } |
| 586 | |
| 587 | fn place( |
| 588 | &self, |
| 589 | n: NodeId, |
| 590 | r: Rect, |
| 591 | gap: f64, |
| 592 | vis: &impl Fn(W) -> bool, |
| 593 | out: &mut Vec<(W, Rect)>, |
| 594 | ) { |
| 595 | let (axis, children, expanded) = match &self.nodes[n].kind { |
| 596 | Kind::Leaf(w, _) => return out.push((*w, r)), |
| 597 | Kind::Container { |
| 598 | axis, |
| 599 | children, |
| 600 | expanded, |
| 601 | } => (*axis, children, *expanded), |
| 602 | }; |
| 603 | let shown: Vec<bool> = children.iter().map(|&c| self.visible(c, vis)).collect(); |
| 604 | let (start, len) = span(r, axis); |
| 605 | if let Some(e) = expanded.and_then(|e| children.iter().position(|&c| c == e)) |
| 606 | && shown[e] |
| 607 | { |
| 608 | for (i, &c) in children.iter().enumerate() { |
| 609 | let sub = match i.cmp(&e) { |
| 610 | std::cmp::Ordering::Equal => r, |
| 611 | std::cmp::Ordering::Less => with_span(r, axis, start, 0.0), |
| 612 | std::cmp::Ordering::Greater => with_span(r, axis, start + len, 0.0), |
| 613 | }; |
| 614 | self.place(c, sub, gap, vis, out); |
| 615 | } |
| 616 | return; |
| 617 | } |
| 618 | let count = shown.iter().filter(|s| **s).count(); |
| 619 | let extents: Vec<f64> = children |
| 620 | .iter() |
| 621 | .zip(&shown) |
| 622 | .map(|(&c, &s)| if s { self.extent(c, axis, vis) } else { 0.0 }) |
| 623 | .collect(); |
| 624 | let total: f64 = extents.iter().sum(); |
| 625 | let gaps = count.saturating_sub(1) as f64; |
| 626 | let gap = if gaps > 0.0 { gap.min(len / gaps) } else { gap }; |
| 627 | let avail = len - gap * gaps; |
| 628 | let last = shown.iter().rposition(|s| *s); |
| 629 | let mut pos = start; |
| 630 | let mut seen = false; |
| 631 | for (i, &c) in children.iter().enumerate() { |
| 632 | if shown[i] { |
| 633 | if seen { |
| 634 | pos += gap; |
| 635 | } |
| 636 | let l = avail * extents[i] / total; |
| 637 | self.place(c, with_span(r, axis, pos, l), gap, vis, out); |
| 638 | pos += l; |
| 639 | seen = true; |
| 640 | } else { |
| 641 | let between = seen && last.is_some_and(|l| l > i); |
| 642 | let at = if between { pos + gap / 2.0 } else { pos }; |
| 643 | self.place(c, with_span(r, axis, at, 0.0), gap, vis, out); |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | fn move_node(&mut self, n: NodeId, dir: Dir, vis: &impl Fn(W) -> bool, enter: bool) -> bool { |
| 649 | let mut cur = n; |
| 650 | while let Some((p, i)) = self.position(cur) { |
| 651 | if self.axis(p) == Some(dir.axis()) { |
| 652 | let hidden_lane = self |
| 653 | .adjacent(p, i, dir) |
| 654 | .filter(|&j| enter && !self.visible(self.children(p)[j], vis)); |
| 655 | if cur != n { |
| 656 | if let Some(j) = hidden_lane { |
| 657 | self.join_lane(n, p, j); |
| 658 | } else { |
| 659 | let at = if dir.forward() { i + 1 } else { i }; |
| 660 | self.relocate(n, p, at); |
| 661 | } |
| 662 | return true; |
| 663 | } |
| 664 | if let Some(j) = self.next_shown(p, i, dir, vis) { |
| 665 | let sib = self.children(p)[j]; |
| 666 | if enter && self.shown_windows(sib, vis) > 1 { |
| 667 | self.join_lane(n, p, j); |
| 668 | } else { |
| 669 | let children = self.children_mut(p); |
| 670 | children.swap(i, j); |
| 671 | } |
| 672 | return true; |
| 673 | } |
| 674 | if let Some(j) = hidden_lane { |
| 675 | self.join_lane(n, p, j); |
| 676 | return true; |
| 677 | } |
| 678 | } |
| 679 | cur = p; |
| 680 | } |
| 681 | if cur == n || self.axis(cur) == Some(dir.axis()) { |
| 682 | return false; |
| 683 | } |
| 684 | let (old, i) = self.position(n).expect("n is below the root"); |
| 685 | self.unlink(old, i); |
| 686 | self.normalize(old); |
| 687 | let r = self.root.expect("the rest of the tree survives"); |
| 688 | if self.axis(r) == Some(dir.axis()) { |
| 689 | let at = if dir.forward() { |
| 690 | self.children(r).len() |
| 691 | } else { |
| 692 | 0 |
| 693 | }; |
| 694 | self.attach(r, at, n); |
| 695 | } else { |
| 696 | let c = self.new_container(dir.axis()); |
| 697 | self.attach(c, 0, r); |
| 698 | let at = if dir.forward() { |
| 699 | self.children(c).len() |
| 700 | } else { |
| 701 | 0 |
| 702 | }; |
| 703 | self.attach(c, at, n); |
| 704 | self.root = Some(c); |
| 705 | } |
| 706 | true |
| 707 | } |
| 708 | |
| 709 | fn next_shown(&self, p: NodeId, i: usize, dir: Dir, vis: &impl Fn(W) -> bool) -> Option<usize> { |
| 710 | let children = self.children(p); |
| 711 | if dir.forward() { |
| 712 | (i + 1..children.len()).find(|&j| self.visible(children[j], vis)) |
| 713 | } else { |
| 714 | (0..i).rev().find(|&j| self.visible(children[j], vis)) |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | fn adjacent(&self, p: NodeId, i: usize, dir: Dir) -> Option<usize> { |
| 719 | let j = if dir.forward() { |
| 720 | i + 1 |
| 721 | } else { |
| 722 | i.checked_sub(1)? |
| 723 | }; |
| 724 | (j < self.children(p).len()).then_some(j) |
| 725 | } |
| 726 | |
| 727 | /// Moves `n` to the end of the lane at `p`'s child `j`. A lone window |
| 728 | /// there becomes a lane of its own, perpendicular to `p`. |
| 729 | fn join_lane(&mut self, n: NodeId, p: NodeId, j: usize) { |
| 730 | let lane = self.children(p)[j]; |
| 731 | let lane = if self.axis(lane).is_some() { |
| 732 | lane |
| 733 | } else { |
| 734 | let c = self.new_container(self.axis(p).expect("p is a container").other()); |
| 735 | self.children_mut(p)[j] = c; |
| 736 | self.nodes[c].parent = Some(p); |
| 737 | if let Kind::Container { expanded, .. } = &mut self.nodes[p].kind |
| 738 | && *expanded == Some(lane) |
| 739 | { |
| 740 | *expanded = Some(c); |
| 741 | } |
| 742 | self.attach(c, 0, lane); |
| 743 | c |
| 744 | }; |
| 745 | let end = self.children(lane).len(); |
| 746 | self.relocate(n, lane, end); |
| 747 | } |
| 748 | |
| 749 | fn relocate(&mut self, n: NodeId, p: NodeId, at: usize) { |
| 750 | let (old, i) = self.position(n).expect("relocated nodes have a parent"); |
| 751 | let at = if old == p && i < at { at - 1 } else { at }; |
| 752 | self.unlink(old, i); |
| 753 | self.attach(p, at, n); |
| 754 | self.normalize(old); |
| 755 | } |
| 756 | |
| 757 | /// Places `node` among `p`'s children. A container running along `p`'s |
| 758 | /// axis is dissolved into `p` so axes keep alternating. |
| 759 | fn attach(&mut self, p: NodeId, at: usize, node: NodeId) { |
| 760 | if self.axis(node).is_some() && self.axis(node) == self.axis(p) { |
| 761 | let children = self.children(node).to_vec(); |
| 762 | self.nodes.remove(node); |
| 763 | for (k, &c) in children.iter().enumerate() { |
| 764 | self.nodes[c].parent = Some(p); |
| 765 | self.children_mut(p).insert(at + k, c); |
| 766 | } |
| 767 | } else { |
| 768 | self.nodes[node].parent = Some(p); |
| 769 | self.children_mut(p).insert(at, node); |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | fn unlink(&mut self, p: NodeId, i: usize) { |
| 774 | let child = self.unlink_dead(p, i); |
| 775 | self.nodes[child].parent = None; |
| 776 | } |
| 777 | |
| 778 | fn detach(&mut self, n: NodeId) { |
| 779 | match self.position(n) { |
| 780 | Some((p, i)) => { |
| 781 | self.unlink(p, i); |
| 782 | self.normalize(p); |
| 783 | } |
| 784 | None => self.root = None, |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | /// Repairs a container that lost a child. |
| 789 | fn normalize(&mut self, c: NodeId) { |
| 790 | if self.children(c).len() >= 2 { |
| 791 | return; |
| 792 | } |
| 793 | let pos = self.position(c); |
| 794 | let was_expanded = pos.is_some_and(|(p, _)| self.expanded(p) == Some(c)); |
| 795 | let Some(Node { |
| 796 | kind: Kind::Container { children, .. }, |
| 797 | .. |
| 798 | }) = self.nodes.remove(c) |
| 799 | else { |
| 800 | unreachable!("only containers are normalized"); |
| 801 | }; |
| 802 | let only = children.into_iter().next(); |
| 803 | match (only, pos) { |
| 804 | (None, Some((p, i))) => { |
| 805 | self.unlink_dead(p, i); |
| 806 | self.normalize(p); |
| 807 | } |
| 808 | (None, None) => self.root = None, |
| 809 | (Some(only), Some((p, i))) => { |
| 810 | self.unlink_dead(p, i); |
| 811 | let leaf_like = self.axis(only) != self.axis(p); |
| 812 | self.attach(p, i, only); |
| 813 | if was_expanded |
| 814 | && leaf_like |
| 815 | && let Kind::Container { expanded, .. } = &mut self.nodes[p].kind |
| 816 | { |
| 817 | *expanded = Some(only); |
| 818 | } |
| 819 | } |
| 820 | (Some(only), None) => { |
| 821 | self.nodes[only].parent = None; |
| 822 | self.root = Some(only); |
| 823 | } |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | /// Like `unlink`, for a child whose node is already gone. |
| 828 | fn unlink_dead(&mut self, p: NodeId, i: usize) -> NodeId { |
| 829 | let Kind::Container { |
| 830 | children, expanded, .. |
| 831 | } = &mut self.nodes[p].kind |
| 832 | else { |
| 833 | unreachable!("parents are containers"); |
| 834 | }; |
| 835 | let child = children.remove(i); |
| 836 | if *expanded == Some(child) { |
| 837 | *expanded = None; |
| 838 | } |
| 839 | child |
| 840 | } |
| 841 | |
| 842 | fn new_leaf(&mut self, w: W, size: Size) -> NodeId { |
| 843 | let n = self.nodes.insert(Node { |
| 844 | parent: None, |
| 845 | kind: Kind::Leaf(w, size), |
| 846 | }); |
| 847 | self.leaves.insert(w, n); |
| 848 | n |
| 849 | } |
| 850 | |
| 851 | fn new_container(&mut self, axis: Axis) -> NodeId { |
| 852 | self.nodes.insert(Node { |
| 853 | parent: None, |
| 854 | kind: Kind::Container { |
| 855 | axis, |
| 856 | children: Vec::new(), |
| 857 | expanded: None, |
| 858 | }, |
| 859 | }) |
| 860 | } |
| 861 | |
| 862 | fn position(&self, n: NodeId) -> Option<(NodeId, usize)> { |
| 863 | let p = self.nodes[n].parent?; |
| 864 | let i = self.children(p).iter().position(|&c| c == n)?; |
| 865 | Some((p, i)) |
| 866 | } |
| 867 | |
| 868 | fn axis(&self, n: NodeId) -> Option<Axis> { |
| 869 | match &self.nodes[n].kind { |
| 870 | Kind::Container { axis, .. } => Some(*axis), |
| 871 | Kind::Leaf(..) => None, |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | fn expanded(&self, n: NodeId) -> Option<NodeId> { |
| 876 | match &self.nodes[n].kind { |
| 877 | Kind::Container { expanded, .. } => *expanded, |
| 878 | Kind::Leaf(..) => None, |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | fn children(&self, n: NodeId) -> &[NodeId] { |
| 883 | match &self.nodes[n].kind { |
| 884 | Kind::Container { children, .. } => children, |
| 885 | Kind::Leaf(..) => &[], |
| 886 | } |
| 887 | } |
| 888 | |
| 889 | fn children_mut(&mut self, n: NodeId) -> &mut Vec<NodeId> { |
| 890 | match &mut self.nodes[n].kind { |
| 891 | Kind::Container { children, .. } => children, |
| 892 | Kind::Leaf(..) => unreachable!("leaves have no children"), |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | fn visible(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> bool { |
| 897 | match &self.nodes[n].kind { |
| 898 | Kind::Leaf(w, _) => vis(*w), |
| 899 | Kind::Container { children, .. } => children.iter().any(|&c| self.visible(c, vis)), |
| 900 | } |
| 901 | } |
| 902 | |
| 903 | fn shown_windows(&self, n: NodeId, vis: &impl Fn(W) -> bool) -> usize { |
| 904 | match &self.nodes[n].kind { |
| 905 | Kind::Leaf(w, _) => usize::from(vis(*w)), |
| 906 | Kind::Container { children, .. } => { |
| 907 | children.iter().map(|&c| self.shown_windows(c, vis)).sum() |
| 908 | } |
| 909 | } |
| 910 | } |
| 911 | |
| 912 | #[cfg(test)] |
| 913 | pub(crate) fn shape(&self) -> String |
| 914 | where |
| 915 | W: std::fmt::Debug, |
| 916 | { |
| 917 | fn go<W: Copy + Eq + Hash + std::fmt::Debug>(t: &Tree<W>, n: NodeId) -> String { |
| 918 | match &t.nodes[n].kind { |
| 919 | Kind::Leaf(w, [x, y]) => format!("{w:?}[{x:.6},{y:.6}]"), |
| 920 | Kind::Container { |
| 921 | axis, |
| 922 | children, |
| 923 | expanded, |
| 924 | } => { |
| 925 | let inner: Vec<String> = children.iter().map(|&c| go(t, c)).collect(); |
| 926 | let e = expanded.and_then(|e| children.iter().position(|&c| c == e)); |
| 927 | format!("{axis:?}{e:?}({})", inner.join(" ")) |
| 928 | } |
| 929 | } |
| 930 | } |
| 931 | self.root.map(|r| go(self, r)).unwrap_or_default() |
| 932 | } |
| 933 | |
| 934 | #[cfg(test)] |
| 935 | pub(crate) fn check(&self) { |
| 936 | let reachable = match self.root { |
| 937 | Some(r) => { |
| 938 | assert!(self.nodes[r].parent.is_none()); |
| 939 | self.check_node(r) |
| 940 | } |
| 941 | None => 0, |
| 942 | }; |
| 943 | assert_eq!(reachable, self.nodes.len(), "orphaned nodes"); |
| 944 | for (&w, &n) in &self.leaves { |
| 945 | assert!(matches!(self.nodes[n].kind, Kind::Leaf(x, _) if x == w)); |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | #[cfg(test)] |
| 950 | fn check_node(&self, n: NodeId) -> usize { |
| 951 | match &self.nodes[n].kind { |
| 952 | Kind::Leaf(_, size) => { |
| 953 | assert!( |
| 954 | size.iter().all(|s| *s > 0.0 && s.is_finite()), |
| 955 | "size {size:?}" |
| 956 | ); |
| 957 | 1 |
| 958 | } |
| 959 | Kind::Container { |
| 960 | axis, |
| 961 | children, |
| 962 | expanded, |
| 963 | } => { |
| 964 | assert!( |
| 965 | children.len() >= 2, |
| 966 | "container with {} children", |
| 967 | children.len() |
| 968 | ); |
| 969 | if let Some(e) = expanded { |
| 970 | assert!(children.contains(e)); |
| 971 | } |
| 972 | let mut count = 1; |
| 973 | for &c in children { |
| 974 | assert_eq!(self.nodes[c].parent, Some(n)); |
| 975 | assert_ne!(self.axis(c), Some(*axis), "axes must alternate"); |
| 976 | count += self.check_node(c); |
| 977 | } |
| 978 | count |
| 979 | } |
| 980 | } |
| 981 | } |
| 982 | } |
| 983 | |
| 984 | fn span(r: Rect, axis: Axis) -> (f64, f64) { |
| 985 | match axis { |
| 986 | Axis::Horizontal => (r.x, r.w), |
| 987 | Axis::Vertical => (r.y, r.h), |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | fn with_span(r: Rect, axis: Axis, start: f64, len: f64) -> Rect { |
| 992 | match axis { |
| 993 | Axis::Horizontal => Rect::new(start, r.y, len, r.h), |
| 994 | Axis::Vertical => Rect::new(r.x, start, r.w, len), |
| 995 | } |
| 996 | } |