1use crate::config::Host;
2
3#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4pub enum Direction {
5 Vertical,
6 Horizontal,
7}
8
9impl Direction {
10 pub fn wt_flag(self) -> &'static str {
11 match self {
12 Self::Vertical => "-V",
13 Self::Horizontal => "-H",
14 }
15 }
16 pub fn json_name(self) -> &'static str {
17 match self {
18 Self::Vertical => "vertical",
19 Self::Horizontal => "horizontal",
20 }
21 }
22}
23
24#[derive(Clone, Debug)]
25pub enum Step<'a, T = Host> {
26 New(&'a T),
27 Split {
28 direction: Direction,
29 size: f64,
30 target: &'a T,
31 },
32 FocusLeft,
33}
34
35pub fn grid_steps<T>(targets: &[T]) -> Vec<Step<'_, T>> {
36 if targets.is_empty() {
37 return Vec::new();
38 }
39 let columns_count = (targets.len() as f64).sqrt().ceil() as usize;
40 let base = targets.len() / columns_count;
41 let extra = targets.len() % columns_count;
42 let mut columns = Vec::new();
43 let mut start = 0;
44 for column in 0..columns_count {
45 let count = base + usize::from(column < extra);
46 columns.push(&targets[start..start + count]);
47 start += count;
48 }
49
50 let mut steps = vec![Step::New(&columns[0][0])];
51 for (column, members) in columns.iter().enumerate().skip(1) {
52 steps.push(Step::Split {
53 direction: Direction::Vertical,
54 size: (columns_count - column) as f64 / (columns_count - column + 1) as f64,
55 target: &members[0],
56 });
57 }
58 for column in (0..columns_count).rev() {
59 for row in 1..columns[column].len() {
60 steps.push(Step::Split {
61 direction: Direction::Horizontal,
62 size: (columns[column].len() - row) as f64
63 / (columns[column].len() - row + 1) as f64,
64 target: &columns[column][row],
65 });
66 }
67 if column > 0 {
68 steps.push(Step::FocusLeft);
69 }
70 }
71 steps
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
79 fn seven_hosts_form_three_columns() {
80 let hosts: Vec<_> = (1..=7)
81 .map(|n| Host {
82 name: n.to_string(),
83 group: "g".into(),
84 color: None,
85 })
86 .collect();
87 let steps = grid_steps(&hosts);
88 assert_eq!(steps.len(), 9);
89 assert!(matches!(steps[0], Step::New(_)));
90 assert!(matches!(
91 steps[1],
92 Step::Split {
93 direction: Direction::Vertical,
94 ..
95 }
96 ));
97 }
98}