1use std::ops::Range;
2
3use gpui::{Bounds, Pixels, Size, point, px, size};
4use gpui_material_theme::{Direction, LogicalEdges, WidthClass};
5
6use super::{PaneLayoutValue, PanePlacement, PaneRole};
7
8#[derive(Clone, Debug, PartialEq)]
10pub struct PaneLayoutDirective {
11 pub horizontal_partitions: usize,
13 pub vertical_partitions: usize,
15 pub horizontal_gap: Pixels,
17 pub vertical_gap: Pixels,
19 pub preferred_width: Pixels,
21 pub preferred_height: Pixels,
23 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 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
60pub(super) struct Measures {
61 pub preferred_width: Option<Pixels>,
62 pub preferred_height: Option<Pixels>,
63 pub minimum_width: Pixels,
64 pub margins: LogicalEdges,
65}
66
67#[derive(Clone, Copy, Debug, PartialEq)]
69pub enum PaneExpansionAnchor {
70 Proportion(f32),
72 FromStart(Pixels),
74 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
92pub enum PaneOverlayAlignment {
93 TopStart,
95 TopCenter,
97 TopEnd,
99 CenterStart,
101 #[default]
103 Center,
104 CenterEnd,
106 BottomStart,
108 BottomCenter,
110 BottomEnd,
112}
113
114impl PaneOverlayAlignment {
115 fn factors(self) -> (f32, f32) {
116 use PaneOverlayAlignment::*;
117 let x = match self {
118 TopStart | CenterStart | BottomStart => 0.,
119 TopCenter | Center | BottomCenter => 0.5,
120 TopEnd | CenterEnd | BottomEnd => 1.,
121 };
122 let y = match self {
123 TopStart | TopCenter | TopEnd => 0.,
124 CenterStart | Center | CenterEnd => 0.5,
125 BottomStart | BottomCenter | BottomEnd => 1.,
126 };
127 (x, y)
128 }
129}
130
131#[derive(Clone, Copy, Debug)]
132pub(super) struct Boundary {
133 pub start: PaneRole,
134 pub end: PaneRole,
135 pub center: Pixels,
136 pub position: Pixels,
137 pub min: Pixels,
138 pub max: Pixels,
139 pub extent: Pixels,
140}
141
142impl Boundary {
143 pub fn anchors(
144 self,
145 anchors: &[PaneExpansionAnchor],
146 ) -> impl Iterator<Item = (PaneExpansionAnchor, Pixels)> {
147 let min = self.min;
148 let max = self.max.max(min);
149 anchors.iter().copied().filter_map(move |anchor| {
150 anchor
151 .position(self.extent)
152 .map(|at| (anchor, at.clamp(min, max)))
153 })
154 }
155}
156
157#[derive(Default)]
158pub(super) struct LayoutGeometry {
159 pub panes: [Option<Bounds<Pixels>>; 3],
160 pub boundaries: Vec<Boundary>,
161}
162
163pub(super) struct GeometryInput<'a> {
164 pub viewport: Size<Pixels>,
165 pub direction: Direction,
166 pub directive: &'a PaneLayoutDirective,
167 pub order: [PaneRole; 3],
168 pub measures: [Measures; 3],
169}
170
171impl GeometryInput<'_> {
172 pub fn layout(
173 &self,
174 value: PaneLayoutValue,
175 expansion: impl Fn(PaneRole, PaneRole) -> Option<PaneExpansionAnchor>,
176 ) -> LayoutGeometry {
177 let width = length(self.viewport.width);
178 let height = length(self.viewport.height);
179 let bands = available_bands(width, &self.directive.excluded_widths);
180 let mut columns = [PaneRole::Primary; 3];
181 let mut column_count = 0;
182 for role in self.order {
183 if value[role] == PanePlacement::Expanded {
184 columns[column_count] = role;
185 column_count += 1;
186 }
187 }
188 let columns = &columns[..column_count];
189 let mut result = LayoutGeometry::default();
190 let mut start = 0;
191 for (band, count) in allocate_bands(&bands, columns.len()) {
192 self.place_band(
193 &columns[start..start + count],
194 band,
195 height,
196 value,
197 &expansion,
198 &mut result,
199 );
200 start += count;
201 }
202 if let Some(band) = bands.iter().max_by(|a, b| span(a).total_cmp(&span(b))) {
203 for role in self.order {
204 if let PanePlacement::Levitate(alignment) = value[role] {
205 let (x, y) = alignment.factors();
206 let measures = self.measures[role.index()];
207 let width = preferred(measures.preferred_width, self.directive.preferred_width)
208 .min(band.end - band.start);
209 let pane_height =
210 preferred(measures.preferred_height, self.directive.preferred_height)
211 .min(height);
212 let bounds = Bounds::new(
213 point(
214 band.start + (band.end - band.start - width) * x,
215 (height - pane_height) * y,
216 ),
217 size(width, pane_height),
218 );
219 result.panes[role.index()] = Some(inset(bounds, measures.margins));
220 }
221 }
222 }
223 if self.direction == Direction::Rtl {
224 for bounds in result.panes.iter_mut().flatten() {
225 bounds.origin.x = width - bounds.right();
226 }
227 for boundary in &mut result.boundaries {
228 boundary.center = width - boundary.center;
229 }
230 }
231 result
232 }
233
234 fn place_band(
235 &self,
236 roles: &[PaneRole],
237 band: Range<Pixels>,
238 height: Pixels,
239 value: PaneLayoutValue,
240 expansion: &impl Fn(PaneRole, PaneRole) -> Option<PaneExpansionAnchor>,
241 result: &mut LayoutGeometry,
242 ) {
243 let count = roles.len();
244 if count == 0 {
245 return;
246 }
247 let gutter = gap(self.directive.horizontal_gap, band.end - band.start, count);
248 let extent = band.end - band.start - gutter * (count - 1) as f32;
249 let mut targets = [px(0.); 3];
250 let mut minima = [px(0.); 3];
251 for (ix, role) in roles.iter().enumerate() {
252 let measure = self.measures[role.index()];
253 targets[ix] = preferred(measure.preferred_width, self.directive.preferred_width);
254 minima[ix] = length(measure.minimum_width);
255 }
256 let targets = &targets[..count];
257 let minima = &minima[..count];
258 let widths = distribute(
259 targets,
260 minima,
261 extent,
262 roles.iter().position(|role| *role == PaneRole::Primary),
263 );
264 let mut boundaries = [px(0.); 4];
265 let mut wanted = px(0.);
266 for i in 1..count {
267 wanted += widths[i - 1];
268 let min = boundaries[i - 1] + scaled_minimum(minima, i - 1, extent);
269 let after: Pixels = (i..count)
270 .map(|ix| scaled_minimum(minima, ix, extent))
271 .sum();
272 let max = (extent - after).max(min);
273 boundaries[i] = expansion(roles[i - 1], roles[i])
274 .and_then(|anchor| anchor.position(extent))
275 .unwrap_or(wanted)
276 .clamp(min, max);
277 }
278 boundaries[count] = extent;
279 for (i, &role) in roles.iter().enumerate() {
280 let origin = band.start + boundaries[i] + gutter * i as f32;
281 let width = (boundaries[i + 1] - boundaries[i]).max(px(0.));
282 let mut stack = [role; 3];
283 let mut stack_len = 1;
284 for child in self.order {
285 if value[child] == PanePlacement::Reflow(role) {
286 stack[stack_len] = child;
287 stack_len += 1;
288 }
289 }
290 let stack = &stack[..stack_len];
291 let vertical_gap = gap(self.directive.vertical_gap, height, stack.len());
292 let stack_space = height - vertical_gap * stack.len().saturating_sub(1) as f32;
293 let mut stack_targets = [px(0.); 3];
294 for (ix, pane) in stack.iter().enumerate() {
295 stack_targets[ix] = preferred(
296 self.measures[pane.index()].preferred_height,
297 self.directive.preferred_height,
298 );
299 }
300 let zero_minima = [px(0.); 3];
301 let heights = distribute(
302 &stack_targets[..stack.len()],
303 &zero_minima[..stack.len()],
304 stack_space,
305 Some(0),
306 );
307 let mut y = px(0.);
308 for (&pane, pane_height) in stack.iter().zip(heights) {
309 result.panes[pane.index()] = Some(inset(
310 Bounds::new(point(origin, y), size(width, pane_height)),
311 self.measures[pane.index()].margins,
312 ));
313 y += pane_height + vertical_gap;
314 }
315 if let Some(&next) = roles.get(i + 1) {
316 let min = boundaries[i] + scaled_minimum(minima, i, extent);
317 let max = (boundaries[i + 2] - scaled_minimum(minima, i + 1, extent)).max(min);
318 result.boundaries.push(Boundary {
319 start: role,
320 end: next,
321 center: origin + width + gutter / 2.,
322 position: boundaries[i + 1].clamp(min, max),
323 min,
324 max,
325 extent,
326 });
327 }
328 }
329 }
330}
331
332pub(super) fn length(value: Pixels) -> Pixels {
333 let number = f32::from(value);
334 px(if number.is_finite() {
336 number.clamp(0., 1_000_000.)
337 } else {
338 0.
339 })
340}
341
342fn preferred(value: Option<Pixels>, fallback: Pixels) -> Pixels {
343 value
344 .map(length)
345 .filter(|value| *value > px(0.))
346 .unwrap_or_else(|| length(fallback))
347}
348
349fn gap(value: Pixels, extent: Pixels, count: usize) -> Pixels {
350 length(value).min(extent / count.max(1) as f32)
351}
352
353fn span(range: &Range<Pixels>) -> f32 {
354 (range.end - range.start).into()
355}
356
357fn available_bands(width: Pixels, excluded: &[Range<Pixels>]) -> Vec<Range<Pixels>> {
358 let mut cuts: Vec<_> = excluded
359 .iter()
360 .filter(|cut| f32::from(cut.start).is_finite() && f32::from(cut.end).is_finite())
361 .map(|cut| length(cut.start).min(width)..length(cut.end).min(width))
362 .filter(|cut| cut.start < cut.end)
363 .collect();
364 cuts.sort_by(|a, b| f32::from(a.start).total_cmp(&f32::from(b.start)));
365 let mut bands = Vec::new();
366 let mut start = px(0.);
367 for cut in cuts {
368 if cut.start > start {
369 bands.push(start..cut.start);
370 }
371 start = start.max(cut.end);
372 }
373 if width > start {
374 bands.push(start..width);
375 }
376 bands
377}
378
379fn allocate_bands(bands: &[Range<Pixels>], columns: usize) -> Vec<(Range<Pixels>, usize)> {
380 if columns == 0 || bands.is_empty() {
381 return Vec::new();
382 }
383 let mut available: Vec<_> = bands.iter().cloned().map(|band| (band, 1)).collect();
384 if available.len() > columns {
385 available.sort_by(|a, b| span(&b.0).total_cmp(&span(&a.0)));
386 available.truncate(columns);
387 available.sort_by(|a, b| f32::from(a.0.start).total_cmp(&f32::from(b.0.start)));
388 }
389 for _ in available.len()..columns {
390 if let Some((_, count)) = available.iter_mut().max_by(|a, b| {
391 (span(&a.0) / (a.1 + 1) as f32).total_cmp(&(span(&b.0) / (b.1 + 1) as f32))
392 }) {
393 *count += 1;
394 }
395 }
396 available
397}
398
399fn scaled_minimum(minima: &[Pixels], ix: usize, extent: Pixels) -> Pixels {
400 let sum: Pixels = minima.iter().copied().sum();
401 if sum > extent {
402 minima[ix] * (extent / sum)
403 } else {
404 minima[ix]
405 }
406}
407
408fn distribute(
409 targets: &[Pixels],
410 minima: &[Pixels],
411 extent: Pixels,
412 flexible: Option<usize>,
413) -> [Pixels; 3] {
414 let count = targets.len();
415 let mut minimum_sum = px(0.);
416 let minimums: [Pixels; 3] = std::array::from_fn(|ix| {
417 if ix < count {
418 let min = scaled_minimum(minima, ix, extent);
419 minimum_sum += min;
420 min
421 } else {
422 px(0.)
423 }
424 });
425 let available = (extent - minimum_sum).max(px(0.));
426 let mut needed = px(0.);
427 let extras: [Pixels; 3] = std::array::from_fn(|ix| {
428 if ix < count {
429 let extra = (targets[ix] - minimums[ix]).max(px(0.));
430 needed += extra;
431 extra
432 } else {
433 px(0.)
434 }
435 });
436 std::array::from_fn(|ix| {
437 if ix >= count {
438 return px(0.);
439 }
440 let minimum = minimums[ix];
441 let extra = extras[ix];
442 let additional = if needed > available {
443 extra * (available / needed)
444 } else if flexible == Some(ix) {
445 extra + available - needed
446 } else if flexible.is_none() {
447 extra + (available - needed) / count as f32
448 } else {
449 extra
450 };
451 minimum + additional
452 })
453}
454
455fn inset(bounds: Bounds<Pixels>, margins: LogicalEdges) -> Bounds<Pixels> {
456 let clean = margins.sanitize();
457 let left = px(clean.start).min(bounds.size.width);
458 let right = px(clean.end).min(bounds.size.width - left);
459 let top = px(clean.top).min(bounds.size.height);
460 let bottom = px(clean.bottom).min(bounds.size.height - top);
461 Bounds::new(
462 bounds.origin + point(left, top),
463 size(
464 bounds.size.width - left - right,
465 bounds.size.height - top - bottom,
466 ),
467 )
468}
469
470#[cfg(test)]
471mod tests {
472 use gpui::size;
473
474 use super::*;
475 use PanePlacement::{Expanded, Hidden};
476 use PaneRole::{Primary, Secondary, Tertiary};
477
478 #[test]
479 fn material_breakpoints_choose_horizontal_and_tall_vertical_partitions() {
480 for (width, height, counts) in [
481 (300., 500., (1, 1)),
482 (650., 950., (1, 2)),
483 (840., 490., (2, 1)),
484 (1300., 490., (3, 1)),
485 ] {
486 let directive = PaneLayoutDirective::for_size(size(px(width), px(height)));
487 assert_eq!(
488 (
489 directive.horizontal_partitions,
490 directive.vertical_partitions
491 ),
492 counts
493 );
494 }
495 }
496
497 #[test]
498 fn occlusion_and_oversized_preferences_keep_panes_in_finite_nonoverlapping_bands() {
499 for direction in [Direction::Ltr, Direction::Rtl] {
500 let mut directive = PaneLayoutDirective::for_size(size(px(1600.), px(900.)));
501 directive.horizontal_gap = px(f32::MAX);
502 directive.vertical_gap = px(f32::NAN);
503 directive.excluded_widths =
504 vec![px(250.)..px(340.), px(300.)..px(400.), px(70.)..px(45.)];
505 let measures = Measures {
506 preferred_width: Some(px(f32::INFINITY)),
507 preferred_height: Some(px(20_000.)),
508 minimum_width: px(1800.),
509 margins: LogicalEdges::new(-4., 5., 7., 5.),
510 };
511 let input = GeometryInput {
512 viewport: size(px(680.), px(240.)),
513 direction,
514 directive: &directive,
515 order: [Secondary, Primary, Tertiary],
516 measures: [measures; 3],
517 };
518 let geometry = input.layout(
519 PaneLayoutValue::new(Expanded, Expanded, Expanded),
520 |_, _| Some(PaneExpansionAnchor::FromEnd(px(-400.))),
521 );
522 let (occlusion_left, occlusion_right) = if direction == Direction::Ltr {
523 (px(250.), px(400.))
524 } else {
525 (px(280.), px(430.))
526 };
527 let mut bounds: Vec<_> = geometry.panes.into_iter().flatten().collect();
528 bounds.sort_by(|a, b| f32::from(a.left()).total_cmp(&f32::from(b.left())));
529 assert_eq!(bounds.len(), 3);
530 for pane in &bounds {
531 assert!(pane.left() >= px(0.) && pane.right() <= px(680.));
532 assert!(pane.top() >= px(0.) && pane.bottom() <= px(240.));
533 assert!(pane.right() <= occlusion_left || pane.left() >= occlusion_right);
534 assert!(pane.size.width > px(0.) && pane.size.height > px(0.));
535 }
536 assert!(
537 bounds
538 .windows(2)
539 .all(|pair| pair[0].right() <= pair[1].left())
540 );
541 assert_eq!(geometry.boundaries.len(), 1);
542 let boundary = geometry.boundaries[0];
543 assert!(boundary.min <= boundary.position && boundary.position <= boundary.max);
544 let narrow = GeometryInput {
545 viewport: size(px(1.), px(1.)),
546 ..input
547 };
548 let limited =
549 narrow.layout(PaneLayoutValue::new(Expanded, Hidden, Hidden), |_, _| None);
550 assert_eq!(
551 limited.panes[Primary.index()].unwrap().size,
552 size(px(0.), px(0.))
553 );
554 }
555 }
556
557 #[test]
558 fn three_pane_boundary_clamp_never_panics_when_min_meets_or_exceeds_max() {
559 let boundary = Boundary {
560 start: Secondary,
561 end: Primary,
562 center: px(200.),
563 position: px(200.),
564 min: px(250.),
565 max: px(240.),
566 extent: px(600.),
567 };
568 let snapped: Vec<_> = boundary
569 .anchors(&[
570 PaneExpansionAnchor::Proportion(0.1),
571 PaneExpansionAnchor::Proportion(0.5),
572 PaneExpansionAnchor::Proportion(0.9),
573 ])
574 .collect();
575 assert_eq!(snapped.len(), 3);
576 for (_, at) in snapped {
577 assert_eq!(at, px(250.));
578 }
579
580 let directive = PaneLayoutDirective::for_size(size(px(1400.), px(800.)));
581 let measures = Measures {
582 preferred_width: Some(px(500.)),
583 preferred_height: None,
584 minimum_width: px(500.),
585 margins: LogicalEdges::ZERO,
586 };
587 let input = GeometryInput {
588 viewport: size(px(1200.), px(800.)),
589 direction: Direction::Ltr,
590 directive: &directive,
591 order: [Secondary, Primary, Tertiary],
592 measures: [measures; 3],
593 };
594 let geometry = input.layout(
595 PaneLayoutValue::new(Expanded, Expanded, Expanded),
596 |_, _| None,
597 );
598 for b in geometry.boundaries {
599 assert!(b.min <= b.position && b.position <= b.max);
600 let _ = b
601 .anchors(&[PaneExpansionAnchor::Proportion(0.5)])
602 .collect::<Vec<_>>();
603 }
604 }
605}