Skip to main content

gpui_material_components/navigation/multi_pane/
geometry.rs

1use std::ops::Range;
2
3use gpui::{Bounds, Pixels, Size, point, px, size};
4use gpui_material_theme::{Direction, WidthClass};
5
6use super::{PaneLayoutValue, PanePlacement, PaneRole};
7
8/// Available partitions and preferred pane sizes in logical pixels.
9#[derive(Clone, Debug, PartialEq)]
10pub struct PaneLayoutDirective {
11    pub horizontal_partitions: usize,
12    pub vertical_partitions: usize,
13    pub horizontal_gap: Pixels,
14    pub vertical_gap: Pixels,
15    pub preferred_width: Pixels,
16    pub preferred_height: Pixels,
17    /// Full-height excluded regions measured from logical start.
18    pub excluded_widths: Vec<Range<Pixels>>,
19}
20
21impl Default for PaneLayoutDirective {
22    fn default() -> Self {
23        Self::for_size(size(px(0.), px(0.)))
24    }
25}
26
27impl PaneLayoutDirective {
28    /// Material window size classes for the available viewport.
29    pub fn for_size(viewport: Size<Pixels>) -> Self {
30        let class = WidthClass::from_width(viewport.width.into());
31        let horizontal_partitions = match class {
32            WidthClass::Compact | WidthClass::Medium => 1,
33            WidthClass::Expanded => 2,
34            WidthClass::Large | WidthClass::ExtraLarge => 3,
35        };
36        let tall = horizontal_partitions == 1 && length(viewport.height) >= px(900.);
37        Self {
38            horizontal_partitions,
39            vertical_partitions: if tall { 2 } else { 1 },
40            horizontal_gap: px(if horizontal_partitions == 1 { 0. } else { 24. }),
41            vertical_gap: px(if tall { 24. } else { 0. }),
42            preferred_width: px(if horizontal_partitions == 3 {
43                412.
44            } else {
45                360.
46            }),
47            preferred_height: px(420.),
48            excluded_widths: Vec::new(),
49        }
50    }
51}
52
53/// Pane margins in logical pixels.
54#[derive(Clone, Copy, Debug, Default, PartialEq)]
55pub struct PaneMargins {
56    pub start: Pixels,
57    pub end: Pixels,
58    pub top: Pixels,
59    pub bottom: Pixels,
60}
61
62#[derive(Clone, Copy, Debug, Default, PartialEq)]
63pub(super) struct Measures {
64    pub preferred_width: Option<Pixels>,
65    pub preferred_height: Option<Pixels>,
66    pub minimum_width: Pixels,
67    pub margins: PaneMargins,
68}
69
70/// Anchors relative to the logical extent of one horizontal band excluding its gutters.
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub enum PaneExpansionAnchor {
73    Proportion(f32),
74    FromStart(Pixels),
75    FromEnd(Pixels),
76}
77
78impl PaneExpansionAnchor {
79    pub(super) fn position(self, width: Pixels) -> Option<Pixels> {
80        let value = match self {
81            Self::Proportion(fraction) if fraction.is_finite() => width * fraction.clamp(0., 1.),
82            Self::FromStart(offset) if f32::from(offset).is_finite() => length(offset),
83            Self::FromEnd(offset) if f32::from(offset).is_finite() => width - length(offset),
84            _ => return None,
85        };
86        Some(value.clamp(px(0.), width))
87    }
88}
89
90/// Logical alignment of a levitated pane in its horizontal band and available height.
91#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
92pub enum PaneOverlayAlignment {
93    TopStart,
94    TopCenter,
95    TopEnd,
96    CenterStart,
97    #[default]
98    Center,
99    CenterEnd,
100    BottomStart,
101    BottomCenter,
102    BottomEnd,
103}
104
105impl PaneOverlayAlignment {
106    fn factors(self) -> (f32, f32) {
107        use PaneOverlayAlignment::*;
108        let x = match self {
109            TopStart | CenterStart | BottomStart => 0.,
110            TopCenter | Center | BottomCenter => 0.5,
111            TopEnd | CenterEnd | BottomEnd => 1.,
112        };
113        let y = match self {
114            TopStart | TopCenter | TopEnd => 0.,
115            CenterStart | Center | CenterEnd => 0.5,
116            BottomStart | BottomCenter | BottomEnd => 1.,
117        };
118        (x, y)
119    }
120}
121
122#[derive(Clone, Copy, Debug)]
123pub(super) struct Boundary {
124    pub start: PaneRole,
125    pub end: PaneRole,
126    pub center: Pixels,
127    pub position: Pixels,
128    pub min: Pixels,
129    pub max: Pixels,
130    pub extent: Pixels,
131}
132
133impl Boundary {
134    pub fn anchors(
135        self,
136        anchors: &[PaneExpansionAnchor],
137    ) -> impl Iterator<Item = (PaneExpansionAnchor, Pixels)> {
138        anchors.iter().copied().filter_map(move |anchor| {
139            anchor
140                .position(self.extent)
141                .map(|at| (anchor, at.clamp(self.min, self.max)))
142        })
143    }
144}
145
146#[derive(Default)]
147pub(super) struct LayoutGeometry {
148    pub panes: [Option<Bounds<Pixels>>; 3],
149    pub boundaries: Vec<Boundary>,
150}
151
152pub(super) struct GeometryInput<'a> {
153    pub viewport: Size<Pixels>,
154    pub direction: Direction,
155    pub directive: &'a PaneLayoutDirective,
156    pub order: [PaneRole; 3],
157    pub measures: [Measures; 3],
158}
159
160impl GeometryInput<'_> {
161    pub fn layout(
162        &self,
163        value: PaneLayoutValue,
164        expansion: impl Fn(PaneRole, PaneRole) -> Option<PaneExpansionAnchor>,
165    ) -> LayoutGeometry {
166        let width = length(self.viewport.width);
167        let height = length(self.viewport.height);
168        let bands = available_bands(width, &self.directive.excluded_widths);
169        let columns: Vec<_> = self
170            .order
171            .into_iter()
172            .filter(|role| value[*role] == PanePlacement::Expanded)
173            .collect();
174        let mut result = LayoutGeometry::default();
175        let mut start = 0;
176        for (band, count) in allocate_bands(&bands, columns.len()) {
177            self.place_band(
178                &columns[start..start + count],
179                band,
180                height,
181                value,
182                &expansion,
183                &mut result,
184            );
185            start += count;
186        }
187        if let Some(band) = bands.iter().max_by(|a, b| span(a).total_cmp(&span(b))) {
188            for role in self.order {
189                if let PanePlacement::Levitate(alignment) = value[role] {
190                    let (x, y) = alignment.factors();
191                    let measures = self.measures[role.index()];
192                    let width = preferred(measures.preferred_width, self.directive.preferred_width)
193                        .min(band.end - band.start);
194                    let pane_height =
195                        preferred(measures.preferred_height, self.directive.preferred_height)
196                            .min(height);
197                    let bounds = Bounds::new(
198                        point(
199                            band.start + (band.end - band.start - width) * x,
200                            (height - pane_height) * y,
201                        ),
202                        size(width, pane_height),
203                    );
204                    result.panes[role.index()] = Some(inset(bounds, measures.margins));
205                }
206            }
207        }
208        if self.direction == Direction::Rtl {
209            for bounds in result.panes.iter_mut().flatten() {
210                bounds.origin.x = width - bounds.right();
211            }
212            for boundary in &mut result.boundaries {
213                boundary.center = width - boundary.center;
214            }
215        }
216        result
217    }
218
219    fn place_band(
220        &self,
221        roles: &[PaneRole],
222        band: Range<Pixels>,
223        height: Pixels,
224        value: PaneLayoutValue,
225        expansion: &impl Fn(PaneRole, PaneRole) -> Option<PaneExpansionAnchor>,
226        result: &mut LayoutGeometry,
227    ) {
228        let count = roles.len();
229        if count == 0 {
230            return;
231        }
232        let gutter = gap(self.directive.horizontal_gap, band.end - band.start, count);
233        let extent = band.end - band.start - gutter * (count - 1) as f32;
234        let targets: Vec<_> = roles
235            .iter()
236            .map(|role| {
237                preferred(
238                    self.measures[role.index()].preferred_width,
239                    self.directive.preferred_width,
240                )
241            })
242            .collect();
243        let minima: Vec<_> = roles
244            .iter()
245            .map(|role| length(self.measures[role.index()].minimum_width))
246            .collect();
247        let widths = distribute(
248            &targets,
249            &minima,
250            extent,
251            roles.iter().position(|role| *role == PaneRole::Primary),
252        );
253        let mut boundaries = Vec::with_capacity(count + 1);
254        boundaries.push(px(0.));
255        let mut wanted = px(0.);
256        for i in 1..count {
257            wanted += widths[i - 1];
258            let min = boundaries[i - 1] + scaled_minimum(&minima, i - 1, extent);
259            let after: Pixels = (i..count)
260                .map(|ix| scaled_minimum(&minima, ix, extent))
261                .sum();
262            let max = (extent - after).max(min);
263            boundaries.push(
264                expansion(roles[i - 1], roles[i])
265                    .and_then(|anchor| anchor.position(extent))
266                    .unwrap_or(wanted)
267                    .clamp(min, max),
268            );
269        }
270        boundaries.push(extent);
271        for (i, &role) in roles.iter().enumerate() {
272            let origin = band.start + boundaries[i] + gutter * i as f32;
273            let width = (boundaries[i + 1] - boundaries[i]).max(px(0.));
274            let mut stack = vec![role];
275            stack.extend(
276                self.order
277                    .into_iter()
278                    .filter(|child| value[*child] == PanePlacement::Reflow(role)),
279            );
280            let vertical_gap = gap(self.directive.vertical_gap, height, stack.len());
281            let stack_space = height - vertical_gap * stack.len().saturating_sub(1) as f32;
282            let targets: Vec<_> = stack
283                .iter()
284                .map(|pane| {
285                    preferred(
286                        self.measures[pane.index()].preferred_height,
287                        self.directive.preferred_height,
288                    )
289                })
290                .collect();
291            let heights = distribute(&targets, &vec![px(0.); stack.len()], stack_space, Some(0));
292            let mut y = px(0.);
293            for (pane, pane_height) in stack.into_iter().zip(heights) {
294                result.panes[pane.index()] = Some(inset(
295                    Bounds::new(point(origin, y), size(width, pane_height)),
296                    self.measures[pane.index()].margins,
297                ));
298                y += pane_height + vertical_gap;
299            }
300            if let Some(&next) = roles.get(i + 1) {
301                result.boundaries.push(Boundary {
302                    start: role,
303                    end: next,
304                    center: origin + width + gutter / 2.,
305                    position: boundaries[i + 1],
306                    min: boundaries[i] + scaled_minimum(&minima, i, extent),
307                    max: boundaries[i + 2] - scaled_minimum(&minima, i + 1, extent),
308                    extent,
309                });
310            }
311        }
312    }
313}
314
315pub(super) fn length(value: Pixels) -> Pixels {
316    let number = f32::from(value);
317    // Capping to GPUI's representable viewport geometry also keeps intermediate sums finite.
318    px(if number.is_finite() {
319        number.clamp(0., 1_000_000.)
320    } else {
321        0.
322    })
323}
324
325fn preferred(value: Option<Pixels>, fallback: Pixels) -> Pixels {
326    value
327        .map(length)
328        .filter(|value| *value > px(0.))
329        .unwrap_or_else(|| length(fallback))
330}
331
332fn gap(value: Pixels, extent: Pixels, count: usize) -> Pixels {
333    length(value).min(extent / count.max(1) as f32)
334}
335
336fn span(range: &Range<Pixels>) -> f32 {
337    (range.end - range.start).into()
338}
339
340fn available_bands(width: Pixels, excluded: &[Range<Pixels>]) -> Vec<Range<Pixels>> {
341    let mut cuts: Vec<_> = excluded
342        .iter()
343        .filter(|cut| f32::from(cut.start).is_finite() && f32::from(cut.end).is_finite())
344        .map(|cut| length(cut.start).min(width)..length(cut.end).min(width))
345        .filter(|cut| cut.start < cut.end)
346        .collect();
347    cuts.sort_by(|a, b| f32::from(a.start).total_cmp(&f32::from(b.start)));
348    let mut bands = Vec::new();
349    let mut start = px(0.);
350    for cut in cuts {
351        if cut.start > start {
352            bands.push(start..cut.start);
353        }
354        start = start.max(cut.end);
355    }
356    if width > start {
357        bands.push(start..width);
358    }
359    bands
360}
361
362fn allocate_bands(bands: &[Range<Pixels>], columns: usize) -> Vec<(Range<Pixels>, usize)> {
363    if columns == 0 || bands.is_empty() {
364        return Vec::new();
365    }
366    let mut available: Vec<_> = bands.iter().cloned().map(|band| (band, 1)).collect();
367    if available.len() > columns {
368        available.sort_by(|a, b| span(&b.0).total_cmp(&span(&a.0)));
369        available.truncate(columns);
370        available.sort_by(|a, b| f32::from(a.0.start).total_cmp(&f32::from(b.0.start)));
371    }
372    for _ in available.len()..columns {
373        if let Some((_, count)) = available.iter_mut().max_by(|a, b| {
374            (span(&a.0) / (a.1 + 1) as f32).total_cmp(&(span(&b.0) / (b.1 + 1) as f32))
375        }) {
376            *count += 1;
377        }
378    }
379    available
380}
381
382fn scaled_minimum(minima: &[Pixels], ix: usize, extent: Pixels) -> Pixels {
383    let sum: Pixels = minima.iter().copied().sum();
384    if sum > extent {
385        minima[ix] * (extent / sum)
386    } else {
387        minima[ix]
388    }
389}
390
391fn distribute(
392    targets: &[Pixels],
393    minima: &[Pixels],
394    extent: Pixels,
395    flexible: Option<usize>,
396) -> Vec<Pixels> {
397    let minimums: Vec<_> = (0..minima.len())
398        .map(|ix| scaled_minimum(minima, ix, extent))
399        .collect();
400    let available = (extent - minimums.iter().copied().sum::<Pixels>()).max(px(0.));
401    let extras: Vec<_> = targets
402        .iter()
403        .zip(&minimums)
404        .map(|(target, minimum)| (*target - *minimum).max(px(0.)))
405        .collect();
406    let needed: Pixels = extras.iter().copied().sum();
407    minimums
408        .into_iter()
409        .zip(extras)
410        .enumerate()
411        .map(|(ix, (minimum, extra))| {
412            let additional = if needed > available {
413                extra * (available / needed)
414            } else if flexible == Some(ix) {
415                extra + available - needed
416            } else if flexible.is_none() {
417                extra + (available - needed) / targets.len() as f32
418            } else {
419                extra
420            };
421            minimum + additional
422        })
423        .collect()
424}
425
426fn inset(bounds: Bounds<Pixels>, margins: PaneMargins) -> Bounds<Pixels> {
427    let left = length(margins.start).min(bounds.size.width);
428    let right = length(margins.end).min(bounds.size.width - left);
429    let top = length(margins.top).min(bounds.size.height);
430    let bottom = length(margins.bottom).min(bounds.size.height - top);
431    Bounds::new(
432        bounds.origin + point(left, top),
433        size(
434            bounds.size.width - left - right,
435            bounds.size.height - top - bottom,
436        ),
437    )
438}
439
440#[cfg(test)]
441mod tests {
442    use gpui::size;
443
444    use super::*;
445    use PanePlacement::{Expanded, Hidden};
446    use PaneRole::{Primary, Secondary, Tertiary};
447
448    #[test]
449    fn material_breakpoints_choose_horizontal_and_tall_vertical_partitions() {
450        for (width, height, counts) in [
451            (300., 500., (1, 1)),
452            (650., 950., (1, 2)),
453            (840., 490., (2, 1)),
454            (1300., 490., (3, 1)),
455        ] {
456            let directive = PaneLayoutDirective::for_size(size(px(width), px(height)));
457            assert_eq!(
458                (
459                    directive.horizontal_partitions,
460                    directive.vertical_partitions
461                ),
462                counts
463            );
464        }
465    }
466
467    #[test]
468    fn occlusion_and_oversized_preferences_keep_panes_in_finite_nonoverlapping_bands() {
469        for direction in [Direction::Ltr, Direction::Rtl] {
470            let mut directive = PaneLayoutDirective::for_size(size(px(1600.), px(900.)));
471            directive.horizontal_gap = px(f32::MAX);
472            directive.vertical_gap = px(f32::NAN);
473            directive.excluded_widths =
474                vec![px(250.)..px(340.), px(300.)..px(400.), px(70.)..px(45.)];
475            let measures = Measures {
476                preferred_width: Some(px(f32::INFINITY)),
477                preferred_height: Some(px(20_000.)),
478                minimum_width: px(1800.),
479                margins: PaneMargins {
480                    start: px(5.),
481                    end: px(5.),
482                    top: px(-4.),
483                    bottom: px(7.),
484                },
485            };
486            let input = GeometryInput {
487                viewport: size(px(680.), px(240.)),
488                direction,
489                directive: &directive,
490                order: [Secondary, Primary, Tertiary],
491                measures: [measures; 3],
492            };
493            let geometry = input.layout(
494                PaneLayoutValue::new(Expanded, Expanded, Expanded),
495                |_, _| Some(PaneExpansionAnchor::FromEnd(px(-400.))),
496            );
497            let (occlusion_left, occlusion_right) = if direction == Direction::Ltr {
498                (px(250.), px(400.))
499            } else {
500                (px(280.), px(430.))
501            };
502            let mut bounds: Vec<_> = geometry.panes.into_iter().flatten().collect();
503            bounds.sort_by(|a, b| f32::from(a.left()).total_cmp(&f32::from(b.left())));
504            assert_eq!(bounds.len(), 3);
505            for pane in &bounds {
506                assert!(pane.left() >= px(0.) && pane.right() <= px(680.));
507                assert!(pane.top() >= px(0.) && pane.bottom() <= px(240.));
508                assert!(pane.right() <= occlusion_left || pane.left() >= occlusion_right);
509                assert!(pane.size.width > px(0.) && pane.size.height > px(0.));
510            }
511            assert!(
512                bounds
513                    .windows(2)
514                    .all(|pair| pair[0].right() <= pair[1].left())
515            );
516            assert_eq!(geometry.boundaries.len(), 1);
517            let boundary = geometry.boundaries[0];
518            assert!(boundary.min <= boundary.position && boundary.position <= boundary.max);
519            let narrow = GeometryInput {
520                viewport: size(px(1.), px(1.)),
521                ..input
522            };
523            let limited =
524                narrow.layout(PaneLayoutValue::new(Expanded, Hidden, Hidden), |_, _| None);
525            assert_eq!(
526                limited.panes[Primary.index()].unwrap().size,
527                size(px(0.), px(0.))
528            );
529        }
530    }
531}