Skip to main content

xrack_layout/
split.rs

1use crate::{
2    LayoutNode, Point, Rect, Size, SplitResize, TextMeasurer,
3    linear::{self, Axis},
4    place_in_direction,
5};
6use xrack_runtime::{LayoutDirection, Node, Orientation};
7
8const RESIZE_EPSILON: f32 = 0.01;
9
10/// The leading pane's size and reachable range in logical pixels.
11#[derive(Clone, Copy, Debug, PartialEq)]
12pub struct SplitHandleRange {
13    pub orientation: Orientation,
14    pub leading_pane: usize,
15    pub trailing_pane: usize,
16    pub value: f64,
17    pub minimum: f64,
18    pub maximum: f64,
19}
20
21impl SplitHandleRange {
22    pub const STEP: f64 = 8.0;
23
24    pub fn can_increase(self) -> bool {
25        self.maximum - self.value > f64::from(RESIZE_EPSILON)
26    }
27
28    pub fn can_decrease(self) -> bool {
29        self.value - self.minimum > f64::from(RESIZE_EPSILON)
30    }
31}
32
33impl LayoutNode {
34    pub fn split_handle_range(&self, path: &[usize]) -> Option<SplitHandleRange> {
35        let (&slot, parent) = path.split_last()?;
36        let split = self.at_path(parent)?.split.as_deref()?;
37        Some(split.handle_range(split.handle(slot)?))
38    }
39}
40
41#[derive(Clone, Debug, PartialEq)]
42struct Pane {
43    slot: usize,
44    length: f32,
45}
46
47#[derive(Clone, Debug, PartialEq)]
48pub struct SplitHandle {
49    pub slot: usize,
50    pub bounds: Rect,
51    before: usize,
52    after: usize,
53    pub(crate) minimum: f32,
54    pub(crate) maximum: f32,
55}
56
57impl SplitHandle {
58    pub(crate) fn adjustable(&self) -> bool {
59        self.maximum - self.minimum > RESIZE_EPSILON
60    }
61}
62
63#[derive(Clone, Debug, PartialEq)]
64pub struct SplitGeometry {
65    pub orientation: Orientation,
66    pub handles: Vec<SplitHandle>,
67    pub(crate) mirrored: bool,
68    hit_radius: Option<f32>,
69    panes: Vec<Pane>,
70    weight: f64,
71    sized: bool,
72    sides_constrained: bool,
73}
74
75pub(crate) fn axis_point(orientation: Orientation, point: Point) -> f32 {
76    match orientation {
77        Orientation::Horizontal => point.x,
78        Orientation::Vertical => point.y,
79    }
80}
81
82impl SplitGeometry {
83    pub(crate) fn new(
84        node: &Node,
85        bounds: Rect,
86        layout_direction: LayoutDirection,
87        text: &mut impl TextMeasurer,
88    ) -> (Self, Vec<Rect>) {
89        let orientation = node.orientation();
90        let direction = if orientation == Orientation::Horizontal {
91            layout_direction
92        } else {
93            LayoutDirection::LeftToRight
94        };
95        let (axis, cross) = match orientation {
96            Orientation::Horizontal => (Axis::Horizontal, bounds.height),
97            Orientation::Vertical => (Axis::Vertical, bounds.width),
98        };
99        let size = Size::new(bounds.width, bounds.height);
100        let total = axis.extent(size);
101        let visible: Vec<_> = node.split_panes().collect();
102        let gaps = visible.len().saturating_sub(1) as f32;
103        let gap = node
104            .length("handle-size")
105            .unwrap_or(8.0)
106            .clamp(1.0, 48.0)
107            .min(total / gaps.max(1.0));
108        let hit_size = node
109            .length("handle-hit-size")
110            .unwrap_or(gap)
111            .clamp(gap, total);
112        let available = (total - gaps * gap).max(0.0);
113        let mut constraints: Vec<_> = visible
114            .iter()
115            .map(|(_, pane)| linear::measure(pane, size, text).along(axis))
116            .collect();
117        let min_total: f64 = constraints.iter().map(|info| f64::from(info.min)).sum();
118        if min_total > f64::from(available) {
119            let scale = f64::from(available) / min_total;
120            for info in &mut constraints {
121                info.min = (f64::from(info.min) * scale) as f32;
122                info.preferred = info.min;
123            }
124        }
125        let (lengths, weight, sides_constrained) = if node.has_split_fill() && !visible.is_empty() {
126            let target = node.split_fill_slot();
127            let fill = visible
128                .iter()
129                .position(|(slot, _)| Some(*slot) == target)
130                .unwrap_or(visible.len() - 1);
131            let fill_info = constraints[fill];
132            let fixed: Vec<_> = visible
133                .iter()
134                .zip(&constraints)
135                .enumerate()
136                .filter(|(index, _)| *index != fill)
137                .map(|(_, ((slot, _), info))| {
138                    let mut info = *info;
139                    if let Some(saved) = node
140                        .split_sizes
141                        .as_ref()
142                        .and_then(|sizes| sizes.get(*slot))
143                        .copied()
144                        .flatten()
145                    {
146                        info.preferred = info.clamp(saved);
147                    }
148                    info
149                })
150                .collect();
151            let preferred: f64 = fixed.iter().map(|info| f64::from(info.preferred)).sum();
152            let fill_length = fill_info.clamp((f64::from(available) - preferred) as f32);
153            let side_space = (available - fill_length).max(0.0);
154            let constrained = (preferred - f64::from(side_space)).abs() > 0.01;
155            let mut lengths = linear::fit_axis(fixed, side_space);
156            lengths.insert(fill, fill_length);
157            (lengths, 1.0, constrained)
158        } else {
159            let baseline = linear::fit_axis(constraints.iter().copied(), available);
160            let baseline_total: f64 = baseline.iter().map(|length| f64::from(*length)).sum();
161            let weights: Vec<_> = visible
162                .iter()
163                .zip(&baseline)
164                .map(|((slot, _), length)| {
165                    node.split_weights
166                        .as_deref()
167                        .and_then(|saved| saved.get(*slot))
168                        .copied()
169                        .flatten()
170                        .map_or_else(
171                            || {
172                                if baseline_total > 0.0 {
173                                    f64::from(*length) / baseline_total
174                                } else {
175                                    0.0
176                                }
177                            },
178                            f64::from,
179                        )
180                })
181                .collect();
182            let weight: f64 = weights.iter().sum();
183            let lengths = if node.split_weights.is_some() && weight > 0.0 {
184                linear::fit_axis(
185                    constraints
186                        .iter()
187                        .copied()
188                        .zip(weights)
189                        .map(|(mut info, share)| {
190                            info.preferred = info.clamp((share * baseline_total / weight) as f32);
191                            info
192                        }),
193                    available,
194                )
195            } else {
196                baseline
197            };
198            (lengths, weight, false)
199        };
200        let panes: Vec<_> = visible
201            .iter()
202            .zip(lengths)
203            .map(|((slot, _), length)| Pane {
204                slot: *slot,
205                length,
206            })
207            .collect();
208        let mut handles = Vec::new();
209        let mut rects = vec![Rect::new(bounds.x, bounds.y, 0.0, 0.0); node.children.len()];
210        let mut cursor = 0.0;
211        let first_handle = node.split_pane_count();
212        let rect = |start, length| {
213            place_in_direction(
214                axis.rect(bounds, start, 0.0, length, cross),
215                bounds,
216                direction,
217            )
218        };
219        for (index, pane) in panes.iter().enumerate() {
220            rects[pane.slot] = rect(cursor, pane.length);
221            cursor += pane.length;
222            if let Some(next) = panes.get(index + 1) {
223                let a = constraints[index];
224                let b = constraints[index + 1];
225                let slot = first_handle + pane.slot;
226                if let Some(handle_rect) = rects.get_mut(slot) {
227                    *handle_rect = rect(cursor, gap);
228                    handles.push(SplitHandle {
229                        slot,
230                        bounds: *handle_rect,
231                        before: index,
232                        after: next.slot,
233                        minimum: (a.min - pane.length).max(next.length - b.max).min(0.0),
234                        maximum: (a.max - pane.length).min(next.length - b.min).max(0.0),
235                    });
236                }
237                cursor += gap;
238            }
239        }
240        (
241            Self {
242                orientation,
243                handles,
244                mirrored: direction == LayoutDirection::RightToLeft,
245                hit_radius: (hit_size > gap).then_some(hit_size * 0.5),
246                panes,
247                weight,
248                sized: node.has_split_fill(),
249                sides_constrained,
250            },
251            rects,
252        )
253    }
254
255    pub(crate) fn handle(&self, slot: usize) -> Option<&SplitHandle> {
256        self.handles.iter().find(|handle| handle.slot == slot)
257    }
258
259    pub(crate) fn handle_range(&self, handle: &SplitHandle) -> SplitHandleRange {
260        let before = &self.panes[handle.before];
261        let value = f64::from(before.length);
262        SplitHandleRange {
263            orientation: self.orientation,
264            leading_pane: before.slot,
265            trailing_pane: handle.after,
266            value,
267            minimum: value + f64::from(handle.minimum),
268            maximum: value + f64::from(handle.maximum),
269        }
270    }
271
272    pub(crate) fn expanded_hit(&self, point: Point) -> Option<usize> {
273        let radius = self.hit_radius?;
274        let position = axis_point(self.orientation, point);
275        let distance = |handle: &SplitHandle| (position - handle.center(self.orientation)).abs();
276        self.handles
277            .iter()
278            .filter(|handle| handle.adjustable() && distance(handle) <= radius)
279            .min_by(|a, b| distance(a).total_cmp(&distance(b)))
280            .map(|handle| handle.slot)
281    }
282
283    /// Convert screen-axis travel into a change of the leading pane's size.
284    pub(crate) fn logical_delta(&self, delta: f32) -> f32 {
285        if self.mirrored { -delta } else { delta }
286    }
287
288    pub(crate) fn resize(
289        &self,
290        path: Vec<usize>,
291        handle: &SplitHandle,
292        delta: f32,
293    ) -> Option<SplitResize> {
294        let delta = delta.clamp(handle.minimum, handle.maximum);
295        let total: f64 = self.panes.iter().map(|pane| f64::from(pane.length)).sum();
296        if !delta.is_finite() || delta.abs() <= RESIZE_EPSILON || total <= 0.0 {
297            return None;
298        }
299        let mass = if self.weight > 0.0 { self.weight } else { 1.0 };
300        let lengths = || {
301            self.panes.iter().enumerate().map(|(index, pane)| {
302                let length = match index {
303                    i if i == handle.before => pane.length + delta,
304                    i if i == handle.before + 1 => pane.length - delta,
305                    _ => pane.length,
306                };
307                (pane.slot, length.max(0.0))
308            })
309        };
310        Some(SplitResize {
311            path,
312            weights: lengths()
313                .map(|(slot, length)| (slot, (f64::from(length) * mass / total) as f32))
314                .collect(),
315            sizes: self.sized.then(|| {
316                if self.sides_constrained {
317                    // Preserve the visible result of the drag even when the old
318                    // preferred widths could not fit the window.
319                    lengths().collect()
320                } else {
321                    lengths().skip(handle.before).take(2).collect()
322                }
323            }),
324        })
325    }
326}
327
328impl SplitHandle {
329    pub(crate) fn after_pane(&self) -> usize {
330        self.after
331    }
332
333    pub(crate) fn center(&self, orientation: Orientation) -> f32 {
334        axis_point(
335            orientation,
336            Point {
337                x: self.bounds.x + self.bounds.width * 0.5,
338                y: self.bounds.y + self.bounds.height * 0.5,
339            },
340        )
341    }
342}