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