Skip to main content

uzor/layout/docking/
presets.rs

1//! Layout presets for panel arrangements.
2//!
3//! Provides standard split/grid patterns for common use cases.
4
5use super::PanelRect;
6
7/// Default gap between panels in multi-panel layouts
8pub const PANEL_GAP: f32 = 0.0;
9
10/// How a separator drag reacts when it would push a neighbour below its
11/// minimum size. Set per [`DockState`](crate::layout::DockState) with
12/// `set_splitter_policy`.
13#[derive(Clone, Copy, Debug, PartialEq, Default)]
14pub enum SplitterPolicy {
15    /// Today's behaviour (the default). Never rejects.
16    ///
17    /// Single-axis splits cascade the delta through the siblings on the
18    /// shrinking side, each down to its pixel minimum; the two-axis presets
19    /// move `cross_ratio` within `0.05..=0.95`; a `rows × cols` grid line
20    /// moves its two adjacent tracks and stops at their pixel minimums.
21    #[default]
22    Cascade,
23    /// A move that would take a neighbour below its minimum is rejected
24    /// whole: proportions stay unchanged, `drag_separator` returns `false`,
25    /// and a [`SnapBackAnimation`](super::SnapBackAnimation) with the
26    /// overshoot is queued for the separator. Only the two children /
27    /// tracks next to the separator move. For the two-axis presets the
28    /// bounds are `cross_ratio` `0.05..=0.95`.
29    RejectSnapBack,
30    /// Stop at the limit: only the two children / tracks next to the
31    /// separator change, and the one shrinking stops at its minimum —
32    /// `min_frac` of the branch along the drag axis, or its pixel minimum
33    /// if that is larger. Never rejects, never snaps back. For the two-axis
34    /// presets (`Grid2x2`, L-shapes) the `cross_ratio` is kept within
35    /// `min_frac..=1 - min_frac` (and never outside `0.05..=0.95`).
36    Clamp {
37        /// Smallest fraction of the branch a child may shrink to; values
38        /// outside `0.0..0.5` are clamped (NaN counts as 0).
39        min_frac: f64,
40    },
41}
42
43/// How to split a container into sub-slots.
44///
45/// Naming reflects WHERE the new sibling appears:
46/// `SplitRight` puts the new panel on the right of the original;
47/// `SplitBottom` puts it below.  Old `Horizontal`/`Vertical` names are
48/// kept as deprecated aliases for backwards compatibility.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
50pub enum SplitKind {
51    /// New panel appears on the RIGHT of the original (Left | Right, 2 slots).
52    SplitRight,
53    /// New panel appears BELOW the original (Top / Bottom, 2 slots).
54    SplitBottom,
55    /// 2×2 grid (4 slots).
56    Grid2x2,
57    /// 1 left + 2 stacked right (3 slots).
58    OneLeftTwoRight,
59    /// 2 stacked left + 1 right (3 slots).
60    TwoLeftOneRight,
61    /// 1 top + 2 side-by-side bottom (3 slots).
62    OneTopTwoBottom,
63    /// 2 side-by-side top + 1 bottom (3 slots).
64    TwoTopOneBottom,
65    /// 3 vertical columns (3 slots).
66    ThreeColumns,
67    /// 3 horizontal rows (3 slots).
68    ThreeRows,
69    /// 1 big + 3 small (4 slots).
70    OneBig3Small,
71}
72
73impl SplitKind {
74    /// Deprecated alias for [`SplitKind::SplitRight`].
75    #[deprecated(note = "use SplitKind::SplitRight — clearer about new panel placement")]
76    #[allow(non_upper_case_globals)]
77    pub const Horizontal: SplitKind = SplitKind::SplitRight;
78    /// Deprecated alias for [`SplitKind::SplitBottom`].
79    #[deprecated(note = "use SplitKind::SplitBottom — clearer about new panel placement")]
80    #[allow(non_upper_case_globals)]
81    pub const Vertical: SplitKind = SplitKind::SplitBottom;
82}
83
84/// Preset layout patterns for panel arrangements
85#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
86pub enum WindowLayout {
87    /// Single panel (tabbed)
88    #[default]
89    Single,
90    /// Two panels side by side
91    SplitHorizontal,
92    /// Two panels stacked
93    SplitVertical,
94    /// Four panels in grid
95    Grid2x2,
96    /// 2 stacked on left, 1 big on right
97    TwoLeftOneRight,
98    /// 1 big on left, 2 stacked on right
99    OneLeftTwoRight,
100    /// 2 side by side on top, 1 big on bottom
101    TwoTopOneBottom,
102    /// 1 big on top, 2 side by side on bottom
103    OneTopTwoBottom,
104    /// 3 vertical columns
105    ThreeColumns,
106    /// 3 horizontal rows
107    ThreeRows,
108    /// Custom layout (computed from child count)
109    Custom,
110}
111
112impl WindowLayout {
113    /// Get required number of panels for this layout
114    pub fn panel_count(&self) -> usize {
115        match self {
116            WindowLayout::Single => 1,
117            WindowLayout::SplitHorizontal | WindowLayout::SplitVertical => 2,
118            WindowLayout::Grid2x2 => 4,
119            WindowLayout::TwoLeftOneRight | WindowLayout::OneLeftTwoRight |
120            WindowLayout::TwoTopOneBottom | WindowLayout::OneTopTwoBottom |
121            WindowLayout::ThreeColumns | WindowLayout::ThreeRows => 3,
122            WindowLayout::Custom => usize::MAX, // dynamic
123        }
124    }
125
126    /// Calculate panel rectangles for this layout with default gap
127    pub fn calculate_rects(&self, total_width: f32, total_height: f32, panel_count: usize) -> Vec<PanelRect> {
128        self.calculate_rects_with_gap(total_width, total_height, panel_count, PANEL_GAP)
129    }
130
131    /// Calculate panel rectangles with custom gap between panels
132    pub fn calculate_rects_with_gap(&self, total_width: f32, total_height: f32, panel_count: usize, gap: f32) -> Vec<PanelRect> {
133        let mut rects = Vec::new();
134
135        match self {
136            WindowLayout::Single => {
137                rects.push(PanelRect::new(0.0, 0.0, total_width, total_height));
138            }
139            WindowLayout::SplitHorizontal => {
140                let half = (total_width - gap) / 2.0;
141                rects.push(PanelRect::new(0.0, 0.0, half, total_height));
142                if panel_count > 1 {
143                    rects.push(PanelRect::new(half + gap, 0.0, half, total_height));
144                }
145            }
146            WindowLayout::SplitVertical => {
147                let half = (total_height - gap) / 2.0;
148                rects.push(PanelRect::new(0.0, 0.0, total_width, half));
149                if panel_count > 1 {
150                    rects.push(PanelRect::new(0.0, half + gap, total_width, half));
151                }
152            }
153            WindowLayout::Grid2x2 => {
154                let half_w = (total_width - gap) / 2.0;
155                let half_h = (total_height - gap) / 2.0;
156                rects.push(PanelRect::new(0.0, 0.0, half_w, half_h));
157                if panel_count > 1 { rects.push(PanelRect::new(half_w + gap, 0.0, half_w, half_h)); }
158                if panel_count > 2 { rects.push(PanelRect::new(0.0, half_h + gap, half_w, half_h)); }
159                if panel_count > 3 { rects.push(PanelRect::new(half_w + gap, half_h + gap, half_w, half_h)); }
160            }
161            WindowLayout::TwoLeftOneRight => {
162                let left_w = (total_width - gap) * 0.4;
163                let right_w = (total_width - gap) * 0.6;
164                let half_h = (total_height - gap) / 2.0;
165                rects.push(PanelRect::new(0.0, 0.0, left_w, half_h));
166                if panel_count > 1 { rects.push(PanelRect::new(0.0, half_h + gap, left_w, half_h)); }
167                if panel_count > 2 { rects.push(PanelRect::new(left_w + gap, 0.0, right_w, total_height)); }
168            }
169            WindowLayout::OneLeftTwoRight => {
170                let left_w = (total_width - gap) * 0.6;
171                let right_w = (total_width - gap) * 0.4;
172                let half_h = (total_height - gap) / 2.0;
173                rects.push(PanelRect::new(0.0, 0.0, left_w, total_height));
174                if panel_count > 1 { rects.push(PanelRect::new(left_w + gap, 0.0, right_w, half_h)); }
175                if panel_count > 2 { rects.push(PanelRect::new(left_w + gap, half_h + gap, right_w, half_h)); }
176            }
177            WindowLayout::TwoTopOneBottom => {
178                let top_h = (total_height - gap) * 0.4;
179                let bottom_h = (total_height - gap) * 0.6;
180                let half_w = (total_width - gap) / 2.0;
181                rects.push(PanelRect::new(0.0, 0.0, half_w, top_h));
182                if panel_count > 1 { rects.push(PanelRect::new(half_w + gap, 0.0, half_w, top_h)); }
183                if panel_count > 2 { rects.push(PanelRect::new(0.0, top_h + gap, total_width, bottom_h)); }
184            }
185            WindowLayout::OneTopTwoBottom => {
186                let top_h = (total_height - gap) * 0.6;
187                let bottom_h = (total_height - gap) * 0.4;
188                let half_w = (total_width - gap) / 2.0;
189                rects.push(PanelRect::new(0.0, 0.0, total_width, top_h));
190                if panel_count > 1 { rects.push(PanelRect::new(0.0, top_h + gap, half_w, bottom_h)); }
191                if panel_count > 2 { rects.push(PanelRect::new(half_w + gap, top_h + gap, half_w, bottom_h)); }
192            }
193            WindowLayout::ThreeColumns => {
194                let col_w = (total_width - gap * 2.0) / 3.0;
195                rects.push(PanelRect::new(0.0, 0.0, col_w, total_height));
196                if panel_count > 1 { rects.push(PanelRect::new(col_w + gap, 0.0, col_w, total_height)); }
197                if panel_count > 2 { rects.push(PanelRect::new(col_w * 2.0 + gap * 2.0, 0.0, col_w, total_height)); }
198            }
199            WindowLayout::ThreeRows => {
200                let row_h = (total_height - gap * 2.0) / 3.0;
201                rects.push(PanelRect::new(0.0, 0.0, total_width, row_h));
202                if panel_count > 1 { rects.push(PanelRect::new(0.0, row_h + gap, total_width, row_h)); }
203                if panel_count > 2 { rects.push(PanelRect::new(0.0, row_h * 2.0 + gap * 2.0, total_width, row_h)); }
204            }
205            WindowLayout::Custom => {
206                // Dynamic NxM grid for any number of panels
207                if panel_count == 0 {
208                    return rects;
209                }
210                let cols = (panel_count as f32).sqrt().ceil() as usize;
211                let rows = panel_count.div_ceil(cols); // ceil division
212                let cell_w = (total_width - gap * (cols as f32 - 1.0).max(0.0)) / cols as f32;
213                let cell_h = (total_height - gap * (rows as f32 - 1.0).max(0.0)) / rows as f32;
214
215                // Guard against negative or zero dimensions
216                if cell_w <= 0.0 || cell_h <= 0.0 {
217                    // Fallback: single rect for all
218                    rects.push(PanelRect::new(0.0, 0.0, total_width, total_height));
219                    return rects;
220                }
221
222                for i in 0..panel_count {
223                    let col = i % cols;
224                    let row = i / cols;
225                    let x = col as f32 * (cell_w + gap);
226                    let y = row as f32 * (cell_h + gap);
227                    rects.push(PanelRect::new(x, y, cell_w, cell_h));
228                }
229            }
230        }
231
232        rects
233    }
234}
235
236/// A `rows × cols` grid shape with independently adjustable row and column
237/// ratios, carried by a [`Branch`](super::Branch) in its `grid` field.
238///
239/// Children of a grid branch are laid out in row-major order: child
240/// `r * cols + c` occupies row `r`, column `c`. `row_ratios` (len = `rows`)
241/// sizes the rows top to bottom, `col_ratios` (len = `cols`) sizes the
242/// columns left to right. Each block is normalised on read, so only the
243/// relative weights inside a block matter, and changing the rows never
244/// touches the columns (and vice versa).
245///
246/// A grid branch keeps `layout == WindowLayout::Custom`, so code that only
247/// knows the closed presets still sees a valid layout value.
248#[derive(Clone, Debug, PartialEq)]
249pub struct GridSpec {
250    /// Number of rows (≥ 1).
251    pub rows: usize,
252    /// Number of columns (≥ 1).
253    pub cols: usize,
254    /// Row weights, top to bottom. Length `rows`.
255    pub row_ratios: Vec<f64>,
256    /// Column weights, left to right. Length `cols`.
257    pub col_ratios: Vec<f64>,
258}
259
260impl GridSpec {
261    /// Equal rows and equal columns. `None` if `rows` or `cols` is zero.
262    pub fn new(rows: usize, cols: usize) -> Option<Self> {
263        if rows == 0 || cols == 0 {
264            return None;
265        }
266        Some(Self {
267            rows,
268            cols,
269            row_ratios: vec![1.0 / rows as f64; rows],
270            col_ratios: vec![1.0 / cols as f64; cols],
271        })
272    }
273
274    /// Grid with explicit weights (the shape is taken from the lengths).
275    /// `None` unless both blocks are non-empty and every weight is finite
276    /// and positive.
277    pub fn with_ratios(row_ratios: Vec<f64>, col_ratios: Vec<f64>) -> Option<Self> {
278        if !Self::valid_block(&row_ratios) || !Self::valid_block(&col_ratios) {
279            return None;
280        }
281        Some(Self {
282            rows: row_ratios.len(),
283            cols: col_ratios.len(),
284            row_ratios,
285            col_ratios,
286        })
287    }
288
289    /// `true` when `ratios` is non-empty and every entry is finite and > 0.
290    pub(crate) fn valid_block(ratios: &[f64]) -> bool {
291        !ratios.is_empty() && ratios.iter().all(|r| r.is_finite() && *r > 0.0)
292    }
293
294    /// Number of cells (`rows * cols`) — the child count the grid lays out.
295    pub fn cell_count(&self) -> usize {
296        self.rows * self.cols
297    }
298
299    /// Row-major child index of cell (`row`, `col`).
300    pub fn cell_index(&self, row: usize, col: usize) -> usize {
301        row * self.cols + col
302    }
303
304    /// Row weights normalised to sum 1 (equal rows if the stored block is
305    /// the wrong length or invalid).
306    pub fn normalized_rows(&self) -> Vec<f64> {
307        Self::normalize(&self.row_ratios, self.rows)
308    }
309
310    /// Column weights normalised to sum 1 (equal columns if the stored block
311    /// is the wrong length or invalid).
312    pub fn normalized_cols(&self) -> Vec<f64> {
313        Self::normalize(&self.col_ratios, self.cols)
314    }
315
316    fn normalize(ratios: &[f64], n: usize) -> Vec<f64> {
317        if n == 0 {
318            return Vec::new();
319        }
320        if ratios.len() != n || !Self::valid_block(ratios) {
321            return vec![1.0 / n as f64; n];
322        }
323        let sum: f64 = ratios.iter().sum();
324        ratios.iter().map(|r| r / sum).collect()
325    }
326
327    /// Cell rects for the grid laid out in `area`, row-major, with `gap`
328    /// pixels between adjacent rows and columns.
329    pub fn cell_rects(&self, area: PanelRect, gap: f32) -> Vec<PanelRect> {
330        let (xs, ws) = Self::tracks(&self.normalized_cols(), area.x, area.width, gap);
331        let (ys, hs) = Self::tracks(&self.normalized_rows(), area.y, area.height, gap);
332        let mut out = Vec::with_capacity(self.cell_count());
333        for r in 0..self.rows {
334            for c in 0..self.cols {
335                out.push(PanelRect::new(xs[c], ys[r], ws[c], hs[r]));
336            }
337        }
338        out
339    }
340
341    /// Start offsets and extents of the tracks along one axis. Track edges
342    /// come from the cumulative fraction, so the last track ends exactly at
343    /// the far edge.
344    pub(crate) fn tracks(fracs: &[f64], start: f32, extent: f32, gap: f32) -> (Vec<f32>, Vec<f32>) {
345        let n = fracs.len();
346        let available = (extent - gap * n.saturating_sub(1) as f32).max(0.0) as f64;
347        let mut starts = Vec::with_capacity(n);
348        let mut sizes = Vec::with_capacity(n);
349        let mut acc = 0.0_f64;
350        for (i, f) in fracs.iter().enumerate() {
351            let a = start + (acc * available) as f32 + gap * i as f32;
352            acc += f;
353            let b = if i + 1 == n {
354                start + extent
355            } else {
356                start + (acc * available) as f32 + gap * i as f32
357            };
358            starts.push(a);
359            sizes.push((b - a).max(0.0));
360        }
361        (starts, sizes)
362    }
363}