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 mut columns = [PaneRole::Primary; 3];
170        let mut column_count = 0;
171        for role in self.order {
172            if value[role] == PanePlacement::Expanded {
173                columns[column_count] = role;
174                column_count += 1;
175            }
176        }
177        let columns = &columns[..column_count];
178        let mut result = LayoutGeometry::default();
179        let mut start = 0;
180        for (band, count) in allocate_bands(&bands, columns.len()) {
181            self.place_band(
182                &columns[start..start + count],
183                band,
184                height,
185                value,
186                &expansion,
187                &mut result,
188            );
189            start += count;
190        }
191        if let Some(band) = bands.iter().max_by(|a, b| span(a).total_cmp(&span(b))) {
192            for role in self.order {
193                if let PanePlacement::Levitate(alignment) = value[role] {
194                    let (x, y) = alignment.factors();
195                    let measures = self.measures[role.index()];
196                    let width = preferred(measures.preferred_width, self.directive.preferred_width)
197                        .min(band.end - band.start);
198                    let pane_height =
199                        preferred(measures.preferred_height, self.directive.preferred_height)
200                            .min(height);
201                    let bounds = Bounds::new(
202                        point(
203                            band.start + (band.end - band.start - width) * x,
204                            (height - pane_height) * y,
205                        ),
206                        size(width, pane_height),
207                    );
208                    result.panes[role.index()] = Some(inset(bounds, measures.margins));
209                }
210            }
211        }
212        if self.direction == Direction::Rtl {
213            for bounds in result.panes.iter_mut().flatten() {
214                bounds.origin.x = width - bounds.right();
215            }
216            for boundary in &mut result.boundaries {
217                boundary.center = width - boundary.center;
218            }
219        }
220        result
221    }
222
223    fn place_band(
224        &self,
225        roles: &[PaneRole],
226        band: Range<Pixels>,
227        height: Pixels,
228        value: PaneLayoutValue,
229        expansion: &impl Fn(PaneRole, PaneRole) -> Option<PaneExpansionAnchor>,
230        result: &mut LayoutGeometry,
231    ) {
232        let count = roles.len();
233        if count == 0 {
234            return;
235        }
236        let gutter = gap(self.directive.horizontal_gap, band.end - band.start, count);
237        let extent = band.end - band.start - gutter * (count - 1) as f32;
238        let mut targets = [px(0.); 3];
239        let mut minima = [px(0.); 3];
240        for (ix, role) in roles.iter().enumerate() {
241            let measure = self.measures[role.index()];
242            targets[ix] = preferred(measure.preferred_width, self.directive.preferred_width);
243            minima[ix] = length(measure.minimum_width);
244        }
245        let targets = &targets[..count];
246        let minima = &minima[..count];
247        let widths = distribute(
248            targets,
249            minima,
250            extent,
251            roles.iter().position(|role| *role == PaneRole::Primary),
252        );
253        let mut boundaries = [px(0.); 4];
254        let mut wanted = px(0.);
255        for i in 1..count {
256            wanted += widths[i - 1];
257            let min = boundaries[i - 1] + scaled_minimum(minima, i - 1, extent);
258            let after: Pixels = (i..count)
259                .map(|ix| scaled_minimum(minima, ix, extent))
260                .sum();
261            let max = (extent - after).max(min);
262            boundaries[i] = expansion(roles[i - 1], roles[i])
263                .and_then(|anchor| anchor.position(extent))
264                .unwrap_or(wanted)
265                .clamp(min, max);
266        }
267        boundaries[count] = extent;
268        for (i, &role) in roles.iter().enumerate() {
269            let origin = band.start + boundaries[i] + gutter * i as f32;
270            let width = (boundaries[i + 1] - boundaries[i]).max(px(0.));
271            let mut stack = [role; 3];
272            let mut stack_len = 1;
273            for child in self.order {
274                if value[child] == PanePlacement::Reflow(role) {
275                    stack[stack_len] = child;
276                    stack_len += 1;
277                }
278            }
279            let stack = &stack[..stack_len];
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 mut stack_targets = [px(0.); 3];
283            for (ix, pane) in stack.iter().enumerate() {
284                stack_targets[ix] = preferred(
285                    self.measures[pane.index()].preferred_height,
286                    self.directive.preferred_height,
287                );
288            }
289            let zero_minima = [px(0.); 3];
290            let heights = distribute(
291                &stack_targets[..stack.len()],
292                &zero_minima[..stack.len()],
293                stack_space,
294                Some(0),
295            );
296            let mut y = px(0.);
297            for (&pane, pane_height) in stack.iter().zip(heights) {
298                result.panes[pane.index()] = Some(inset(
299                    Bounds::new(point(origin, y), size(width, pane_height)),
300                    self.measures[pane.index()].margins,
301                ));
302                y += pane_height + vertical_gap;
303            }
304            if let Some(&next) = roles.get(i + 1) {
305                result.boundaries.push(Boundary {
306                    start: role,
307                    end: next,
308                    center: origin + width + gutter / 2.,
309                    position: boundaries[i + 1],
310                    min: boundaries[i] + scaled_minimum(minima, i, extent),
311                    max: boundaries[i + 2] - scaled_minimum(minima, i + 1, extent),
312                    extent,
313                });
314            }
315        }
316    }
317}
318
319pub(super) fn length(value: Pixels) -> Pixels {
320    let number = f32::from(value);
321    // Capping to GPUI's representable viewport geometry also keeps intermediate sums finite.
322    px(if number.is_finite() {
323        number.clamp(0., 1_000_000.)
324    } else {
325        0.
326    })
327}
328
329fn preferred(value: Option<Pixels>, fallback: Pixels) -> Pixels {
330    value
331        .map(length)
332        .filter(|value| *value > px(0.))
333        .unwrap_or_else(|| length(fallback))
334}
335
336fn gap(value: Pixels, extent: Pixels, count: usize) -> Pixels {
337    length(value).min(extent / count.max(1) as f32)
338}
339
340fn span(range: &Range<Pixels>) -> f32 {
341    (range.end - range.start).into()
342}
343
344fn available_bands(width: Pixels, excluded: &[Range<Pixels>]) -> Vec<Range<Pixels>> {
345    let mut cuts: Vec<_> = excluded
346        .iter()
347        .filter(|cut| f32::from(cut.start).is_finite() && f32::from(cut.end).is_finite())
348        .map(|cut| length(cut.start).min(width)..length(cut.end).min(width))
349        .filter(|cut| cut.start < cut.end)
350        .collect();
351    cuts.sort_by(|a, b| f32::from(a.start).total_cmp(&f32::from(b.start)));
352    let mut bands = Vec::new();
353    let mut start = px(0.);
354    for cut in cuts {
355        if cut.start > start {
356            bands.push(start..cut.start);
357        }
358        start = start.max(cut.end);
359    }
360    if width > start {
361        bands.push(start..width);
362    }
363    bands
364}
365
366fn allocate_bands(bands: &[Range<Pixels>], columns: usize) -> Vec<(Range<Pixels>, usize)> {
367    if columns == 0 || bands.is_empty() {
368        return Vec::new();
369    }
370    let mut available: Vec<_> = bands.iter().cloned().map(|band| (band, 1)).collect();
371    if available.len() > columns {
372        available.sort_by(|a, b| span(&b.0).total_cmp(&span(&a.0)));
373        available.truncate(columns);
374        available.sort_by(|a, b| f32::from(a.0.start).total_cmp(&f32::from(b.0.start)));
375    }
376    for _ in available.len()..columns {
377        if let Some((_, count)) = available.iter_mut().max_by(|a, b| {
378            (span(&a.0) / (a.1 + 1) as f32).total_cmp(&(span(&b.0) / (b.1 + 1) as f32))
379        }) {
380            *count += 1;
381        }
382    }
383    available
384}
385
386fn scaled_minimum(minima: &[Pixels], ix: usize, extent: Pixels) -> Pixels {
387    let sum: Pixels = minima.iter().copied().sum();
388    if sum > extent {
389        minima[ix] * (extent / sum)
390    } else {
391        minima[ix]
392    }
393}
394
395fn distribute(
396    targets: &[Pixels],
397    minima: &[Pixels],
398    extent: Pixels,
399    flexible: Option<usize>,
400) -> [Pixels; 3] {
401    let count = targets.len();
402    let mut minimum_sum = px(0.);
403    let minimums: [Pixels; 3] = std::array::from_fn(|ix| {
404        if ix < count {
405            let min = scaled_minimum(minima, ix, extent);
406            minimum_sum += min;
407            min
408        } else {
409            px(0.)
410        }
411    });
412    let available = (extent - minimum_sum).max(px(0.));
413    let mut needed = px(0.);
414    let extras: [Pixels; 3] = std::array::from_fn(|ix| {
415        if ix < count {
416            let extra = (targets[ix] - minimums[ix]).max(px(0.));
417            needed += extra;
418            extra
419        } else {
420            px(0.)
421        }
422    });
423    std::array::from_fn(|ix| {
424        if ix >= count {
425            return px(0.);
426        }
427        let minimum = minimums[ix];
428        let extra = extras[ix];
429        let additional = if needed > available {
430            extra * (available / needed)
431        } else if flexible == Some(ix) {
432            extra + available - needed
433        } else if flexible.is_none() {
434            extra + (available - needed) / count as f32
435        } else {
436            extra
437        };
438        minimum + additional
439    })
440}
441
442fn inset(bounds: Bounds<Pixels>, margins: PaneMargins) -> Bounds<Pixels> {
443    let left = length(margins.start).min(bounds.size.width);
444    let right = length(margins.end).min(bounds.size.width - left);
445    let top = length(margins.top).min(bounds.size.height);
446    let bottom = length(margins.bottom).min(bounds.size.height - top);
447    Bounds::new(
448        bounds.origin + point(left, top),
449        size(
450            bounds.size.width - left - right,
451            bounds.size.height - top - bottom,
452        ),
453    )
454}
455
456#[cfg(test)]
457mod tests {
458    use gpui::size;
459
460    use super::*;
461    use PanePlacement::{Expanded, Hidden};
462    use PaneRole::{Primary, Secondary, Tertiary};
463
464    #[test]
465    fn material_breakpoints_choose_horizontal_and_tall_vertical_partitions() {
466        for (width, height, counts) in [
467            (300., 500., (1, 1)),
468            (650., 950., (1, 2)),
469            (840., 490., (2, 1)),
470            (1300., 490., (3, 1)),
471        ] {
472            let directive = PaneLayoutDirective::for_size(size(px(width), px(height)));
473            assert_eq!(
474                (
475                    directive.horizontal_partitions,
476                    directive.vertical_partitions
477                ),
478                counts
479            );
480        }
481    }
482
483    #[test]
484    fn occlusion_and_oversized_preferences_keep_panes_in_finite_nonoverlapping_bands() {
485        for direction in [Direction::Ltr, Direction::Rtl] {
486            let mut directive = PaneLayoutDirective::for_size(size(px(1600.), px(900.)));
487            directive.horizontal_gap = px(f32::MAX);
488            directive.vertical_gap = px(f32::NAN);
489            directive.excluded_widths =
490                vec![px(250.)..px(340.), px(300.)..px(400.), px(70.)..px(45.)];
491            let measures = Measures {
492                preferred_width: Some(px(f32::INFINITY)),
493                preferred_height: Some(px(20_000.)),
494                minimum_width: px(1800.),
495                margins: PaneMargins {
496                    start: px(5.),
497                    end: px(5.),
498                    top: px(-4.),
499                    bottom: px(7.),
500                },
501            };
502            let input = GeometryInput {
503                viewport: size(px(680.), px(240.)),
504                direction,
505                directive: &directive,
506                order: [Secondary, Primary, Tertiary],
507                measures: [measures; 3],
508            };
509            let geometry = input.layout(
510                PaneLayoutValue::new(Expanded, Expanded, Expanded),
511                |_, _| Some(PaneExpansionAnchor::FromEnd(px(-400.))),
512            );
513            let (occlusion_left, occlusion_right) = if direction == Direction::Ltr {
514                (px(250.), px(400.))
515            } else {
516                (px(280.), px(430.))
517            };
518            let mut bounds: Vec<_> = geometry.panes.into_iter().flatten().collect();
519            bounds.sort_by(|a, b| f32::from(a.left()).total_cmp(&f32::from(b.left())));
520            assert_eq!(bounds.len(), 3);
521            for pane in &bounds {
522                assert!(pane.left() >= px(0.) && pane.right() <= px(680.));
523                assert!(pane.top() >= px(0.) && pane.bottom() <= px(240.));
524                assert!(pane.right() <= occlusion_left || pane.left() >= occlusion_right);
525                assert!(pane.size.width > px(0.) && pane.size.height > px(0.));
526            }
527            assert!(
528                bounds
529                    .windows(2)
530                    .all(|pair| pair[0].right() <= pair[1].left())
531            );
532            assert_eq!(geometry.boundaries.len(), 1);
533            let boundary = geometry.boundaries[0];
534            assert!(boundary.min <= boundary.position && boundary.position <= boundary.max);
535            let narrow = GeometryInput {
536                viewport: size(px(1.), px(1.)),
537                ..input
538            };
539            let limited =
540                narrow.layout(PaneLayoutValue::new(Expanded, Hidden, Hidden), |_, _| None);
541            assert_eq!(
542                limited.panes[Primary.index()].unwrap().size,
543                size(px(0.), px(0.))
544            );
545        }
546    }
547}