pane_group.rs

  1use crate::{pane_group::element::pane_axis, AppState, FollowerState, Pane, Workspace};
  2use anyhow::{anyhow, Result};
  3use call::{ActiveCall, ParticipantLocation};
  4use collections::HashMap;
  5use gpui::{
  6    point, size, AnyWeakView, Axis, Bounds, Entity as _, IntoElement, Model, Pixels, Point, View,
  7    ViewContext,
  8};
  9use parking_lot::Mutex;
 10use project::Project;
 11use serde::Deserialize;
 12use std::sync::Arc;
 13use ui::{prelude::*, Button};
 14
 15const HANDLE_HITBOX_SIZE: f32 = 10.0; //todo!(change this back to 4)
 16const HORIZONTAL_MIN_SIZE: f32 = 80.;
 17const VERTICAL_MIN_SIZE: f32 = 100.;
 18
 19#[derive(Clone)]
 20pub struct PaneGroup {
 21    pub(crate) root: Member,
 22}
 23
 24impl PaneGroup {
 25    pub(crate) fn with_root(root: Member) -> Self {
 26        Self { root }
 27    }
 28
 29    pub fn new(pane: View<Pane>) -> Self {
 30        Self {
 31            root: Member::Pane(pane),
 32        }
 33    }
 34
 35    pub fn split(
 36        &mut self,
 37        old_pane: &View<Pane>,
 38        new_pane: &View<Pane>,
 39        direction: SplitDirection,
 40    ) -> Result<()> {
 41        match &mut self.root {
 42            Member::Pane(pane) => {
 43                if pane == old_pane {
 44                    self.root = Member::new_axis(old_pane.clone(), new_pane.clone(), direction);
 45                    Ok(())
 46                } else {
 47                    Err(anyhow!("Pane not found"))
 48                }
 49            }
 50            Member::Axis(axis) => axis.split(old_pane, new_pane, direction),
 51        }
 52    }
 53
 54    pub fn bounding_box_for_pane(&self, pane: &View<Pane>) -> Option<Bounds<Pixels>> {
 55        match &self.root {
 56            Member::Pane(_) => None,
 57            Member::Axis(axis) => axis.bounding_box_for_pane(pane),
 58        }
 59    }
 60
 61    pub fn pane_at_pixel_position(&self, coordinate: Point<Pixels>) -> Option<&View<Pane>> {
 62        match &self.root {
 63            Member::Pane(pane) => Some(pane),
 64            Member::Axis(axis) => axis.pane_at_pixel_position(coordinate),
 65        }
 66    }
 67
 68    /// Returns:
 69    /// - Ok(true) if it found and removed a pane
 70    /// - Ok(false) if it found but did not remove the pane
 71    /// - Err(_) if it did not find the pane
 72    pub fn remove(&mut self, pane: &View<Pane>) -> Result<bool> {
 73        match &mut self.root {
 74            Member::Pane(_) => Ok(false),
 75            Member::Axis(axis) => {
 76                if let Some(last_pane) = axis.remove(pane)? {
 77                    self.root = last_pane;
 78                }
 79                Ok(true)
 80            }
 81        }
 82    }
 83
 84    pub fn swap(&mut self, from: &View<Pane>, to: &View<Pane>) {
 85        match &mut self.root {
 86            Member::Pane(_) => {}
 87            Member::Axis(axis) => axis.swap(from, to),
 88        };
 89    }
 90
 91    pub(crate) fn render(
 92        &self,
 93        project: &Model<Project>,
 94        follower_states: &HashMap<View<Pane>, FollowerState>,
 95        active_call: Option<&Model<ActiveCall>>,
 96        active_pane: &View<Pane>,
 97        zoomed: Option<&AnyWeakView>,
 98        app_state: &Arc<AppState>,
 99        cx: &mut ViewContext<Workspace>,
100    ) -> impl IntoElement {
101        self.root.render(
102            project,
103            0,
104            follower_states,
105            active_call,
106            active_pane,
107            zoomed,
108            app_state,
109            cx,
110        )
111    }
112
113    pub(crate) fn panes(&self) -> Vec<&View<Pane>> {
114        let mut panes = Vec::new();
115        self.root.collect_panes(&mut panes);
116        panes
117    }
118
119    pub(crate) fn first_pane(&self) -> View<Pane> {
120        self.root.first_pane()
121    }
122}
123
124#[derive(Clone)]
125pub(crate) enum Member {
126    Axis(PaneAxis),
127    Pane(View<Pane>),
128}
129
130impl Member {
131    fn new_axis(old_pane: View<Pane>, new_pane: View<Pane>, direction: SplitDirection) -> Self {
132        use Axis::*;
133        use SplitDirection::*;
134
135        let axis = match direction {
136            Up | Down => Vertical,
137            Left | Right => Horizontal,
138        };
139
140        let members = match direction {
141            Up | Left => vec![Member::Pane(new_pane), Member::Pane(old_pane)],
142            Down | Right => vec![Member::Pane(old_pane), Member::Pane(new_pane)],
143        };
144
145        Member::Axis(PaneAxis::new(axis, members))
146    }
147
148    fn contains(&self, needle: &View<Pane>) -> bool {
149        match self {
150            Member::Axis(axis) => axis.members.iter().any(|member| member.contains(needle)),
151            Member::Pane(pane) => pane == needle,
152        }
153    }
154
155    fn first_pane(&self) -> View<Pane> {
156        match self {
157            Member::Axis(axis) => axis.members[0].first_pane(),
158            Member::Pane(pane) => pane.clone(),
159        }
160    }
161
162    pub fn render(
163        &self,
164        project: &Model<Project>,
165        basis: usize,
166        follower_states: &HashMap<View<Pane>, FollowerState>,
167        active_call: Option<&Model<ActiveCall>>,
168        active_pane: &View<Pane>,
169        zoomed: Option<&AnyWeakView>,
170        app_state: &Arc<AppState>,
171        cx: &mut ViewContext<Workspace>,
172    ) -> impl IntoElement {
173        match self {
174            Member::Pane(pane) => {
175                if zoomed == Some(&pane.downgrade().into()) {
176                    return div().into_any();
177                }
178
179                let leader = follower_states.get(pane).and_then(|state| {
180                    let room = active_call?.read(cx).room()?.read(cx);
181                    room.remote_participant_for_peer_id(state.leader_id)
182                });
183
184                let mut leader_border = None;
185                let mut leader_status_box = None;
186                if let Some(leader) = &leader {
187                    let mut leader_color = cx
188                        .theme()
189                        .players()
190                        .color_for_participant(leader.participant_index.0)
191                        .cursor;
192                    leader_color.fade_out(0.3);
193                    leader_border = Some(leader_color);
194
195                    leader_status_box = match leader.location {
196                        ParticipantLocation::SharedProject {
197                            project_id: leader_project_id,
198                        } => {
199                            if Some(leader_project_id) == project.read(cx).remote_id() {
200                                None
201                            } else {
202                                let leader_user = leader.user.clone();
203                                let leader_user_id = leader.user.id;
204                                Some(
205                                    Button::new(
206                                        ("leader-status", pane.entity_id()),
207                                        format!(
208                                            "Follow {} to their active project",
209                                            leader_user.github_login,
210                                        ),
211                                    )
212                                    .on_click(cx.listener(
213                                        move |this, _, cx| {
214                                            crate::join_remote_project(
215                                                leader_project_id,
216                                                leader_user_id,
217                                                this.app_state().clone(),
218                                                cx,
219                                            )
220                                            .detach_and_log_err(cx);
221                                        },
222                                    )),
223                                )
224                            }
225                        }
226                        ParticipantLocation::UnsharedProject => Some(Button::new(
227                            ("leader-status", pane.entity_id()),
228                            format!(
229                                "{} is viewing an unshared Zed project",
230                                leader.user.github_login
231                            ),
232                        )),
233                        ParticipantLocation::External => Some(Button::new(
234                            ("leader-status", pane.entity_id()),
235                            format!(
236                                "{} is viewing a window outside of Zed",
237                                leader.user.github_login
238                            ),
239                        )),
240                    };
241                }
242
243                div()
244                    .relative()
245                    .flex_1()
246                    .size_full()
247                    .child(pane.clone())
248                    .when_some(leader_border, |this, color| {
249                        this.border_2().border_color(color)
250                    })
251                    .when_some(leader_status_box, |this, status_box| {
252                        this.child(
253                            div()
254                                .absolute()
255                                .w_96()
256                                .bottom_3()
257                                .right_3()
258                                .z_index(1)
259                                .child(status_box),
260                        )
261                    })
262                    .into_any()
263
264                // let el = div()
265                //     .flex()
266                //     .flex_1()
267                //     .gap_px()
268                //     .w_full()
269                //     .h_full()
270                //     .bg(cx.theme().colors().editor)
271                //     .children();
272            }
273            Member::Axis(axis) => axis
274                .render(
275                    project,
276                    basis + 1,
277                    follower_states,
278                    active_call,
279                    active_pane,
280                    zoomed,
281                    app_state,
282                    cx,
283                )
284                .into_any(),
285        }
286    }
287
288    fn collect_panes<'a>(&'a self, panes: &mut Vec<&'a View<Pane>>) {
289        match self {
290            Member::Axis(axis) => {
291                for member in &axis.members {
292                    member.collect_panes(panes);
293                }
294            }
295            Member::Pane(pane) => panes.push(pane),
296        }
297    }
298}
299
300#[derive(Clone)]
301pub(crate) struct PaneAxis {
302    pub axis: Axis,
303    pub members: Vec<Member>,
304    pub flexes: Arc<Mutex<Vec<f32>>>,
305    pub bounding_boxes: Arc<Mutex<Vec<Option<Bounds<Pixels>>>>>,
306}
307
308impl PaneAxis {
309    pub fn new(axis: Axis, members: Vec<Member>) -> Self {
310        let flexes = Arc::new(Mutex::new(vec![1.; members.len()]));
311        let bounding_boxes = Arc::new(Mutex::new(vec![None; members.len()]));
312        Self {
313            axis,
314            members,
315            flexes,
316            bounding_boxes,
317        }
318    }
319
320    pub fn load(axis: Axis, members: Vec<Member>, flexes: Option<Vec<f32>>) -> Self {
321        let flexes = flexes.unwrap_or_else(|| vec![1.; members.len()]);
322        debug_assert!(members.len() == flexes.len());
323
324        let flexes = Arc::new(Mutex::new(flexes));
325        let bounding_boxes = Arc::new(Mutex::new(vec![None; members.len()]));
326        Self {
327            axis,
328            members,
329            flexes,
330            bounding_boxes,
331        }
332    }
333
334    fn split(
335        &mut self,
336        old_pane: &View<Pane>,
337        new_pane: &View<Pane>,
338        direction: SplitDirection,
339    ) -> Result<()> {
340        for (mut idx, member) in self.members.iter_mut().enumerate() {
341            match member {
342                Member::Axis(axis) => {
343                    if axis.split(old_pane, new_pane, direction).is_ok() {
344                        return Ok(());
345                    }
346                }
347                Member::Pane(pane) => {
348                    if pane == old_pane {
349                        if direction.axis() == self.axis {
350                            if direction.increasing() {
351                                idx += 1;
352                            }
353
354                            self.members.insert(idx, Member::Pane(new_pane.clone()));
355                            *self.flexes.lock() = vec![1.; self.members.len()];
356                        } else {
357                            *member =
358                                Member::new_axis(old_pane.clone(), new_pane.clone(), direction);
359                        }
360                        return Ok(());
361                    }
362                }
363            }
364        }
365        Err(anyhow!("Pane not found"))
366    }
367
368    fn remove(&mut self, pane_to_remove: &View<Pane>) -> Result<Option<Member>> {
369        let mut found_pane = false;
370        let mut remove_member = None;
371        for (idx, member) in self.members.iter_mut().enumerate() {
372            match member {
373                Member::Axis(axis) => {
374                    if let Ok(last_pane) = axis.remove(pane_to_remove) {
375                        if let Some(last_pane) = last_pane {
376                            *member = last_pane;
377                        }
378                        found_pane = true;
379                        break;
380                    }
381                }
382                Member::Pane(pane) => {
383                    if pane == pane_to_remove {
384                        found_pane = true;
385                        remove_member = Some(idx);
386                        break;
387                    }
388                }
389            }
390        }
391
392        if found_pane {
393            if let Some(idx) = remove_member {
394                self.members.remove(idx);
395                *self.flexes.lock() = vec![1.; self.members.len()];
396            }
397
398            if self.members.len() == 1 {
399                let result = self.members.pop();
400                *self.flexes.lock() = vec![1.; self.members.len()];
401                Ok(result)
402            } else {
403                Ok(None)
404            }
405        } else {
406            Err(anyhow!("Pane not found"))
407        }
408    }
409
410    fn swap(&mut self, from: &View<Pane>, to: &View<Pane>) {
411        for member in self.members.iter_mut() {
412            match member {
413                Member::Axis(axis) => axis.swap(from, to),
414                Member::Pane(pane) => {
415                    if pane == from {
416                        *member = Member::Pane(to.clone());
417                    } else if pane == to {
418                        *member = Member::Pane(from.clone())
419                    }
420                }
421            }
422        }
423    }
424
425    fn bounding_box_for_pane(&self, pane: &View<Pane>) -> Option<Bounds<Pixels>> {
426        debug_assert!(self.members.len() == self.bounding_boxes.lock().len());
427
428        for (idx, member) in self.members.iter().enumerate() {
429            match member {
430                Member::Pane(found) => {
431                    if pane == found {
432                        return self.bounding_boxes.lock()[idx];
433                    }
434                }
435                Member::Axis(axis) => {
436                    if let Some(rect) = axis.bounding_box_for_pane(pane) {
437                        return Some(rect);
438                    }
439                }
440            }
441        }
442        None
443    }
444
445    fn pane_at_pixel_position(&self, coordinate: Point<Pixels>) -> Option<&View<Pane>> {
446        debug_assert!(self.members.len() == self.bounding_boxes.lock().len());
447
448        let bounding_boxes = self.bounding_boxes.lock();
449
450        for (idx, member) in self.members.iter().enumerate() {
451            if let Some(coordinates) = bounding_boxes[idx] {
452                if coordinates.contains(&coordinate) {
453                    return match member {
454                        Member::Pane(found) => Some(found),
455                        Member::Axis(axis) => axis.pane_at_pixel_position(coordinate),
456                    };
457                }
458            }
459        }
460        None
461    }
462
463    fn render(
464        &self,
465        project: &Model<Project>,
466        basis: usize,
467        follower_states: &HashMap<View<Pane>, FollowerState>,
468        active_call: Option<&Model<ActiveCall>>,
469        active_pane: &View<Pane>,
470        zoomed: Option<&AnyWeakView>,
471        app_state: &Arc<AppState>,
472        cx: &mut ViewContext<Workspace>,
473    ) -> gpui::AnyElement {
474        debug_assert!(self.members.len() == self.flexes.lock().len());
475        let mut active_pane_ix = None;
476
477        pane_axis(
478            self.axis,
479            basis,
480            self.flexes.clone(),
481            self.bounding_boxes.clone(),
482        )
483        .children(self.members.iter().enumerate().map(|(ix, member)| {
484            if member.contains(active_pane) {
485                active_pane_ix = Some(ix);
486            }
487            member
488                .render(
489                    project,
490                    (basis + ix) * 10,
491                    follower_states,
492                    active_call,
493                    active_pane,
494                    zoomed,
495                    app_state,
496                    cx,
497                )
498                .into_any_element()
499        }))
500        .with_active_pane(active_pane_ix)
501        .into_any_element()
502    }
503}
504
505#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
506pub enum SplitDirection {
507    Up,
508    Down,
509    Left,
510    Right,
511}
512
513impl SplitDirection {
514    pub fn all() -> [Self; 4] {
515        [Self::Up, Self::Down, Self::Left, Self::Right]
516    }
517
518    pub fn edge(&self, rect: Bounds<Pixels>) -> Pixels {
519        match self {
520            Self::Up => rect.origin.y,
521            Self::Down => rect.lower_left().y,
522            Self::Left => rect.lower_left().x,
523            Self::Right => rect.lower_right().x,
524        }
525    }
526
527    pub fn along_edge(&self, bounds: Bounds<Pixels>, length: Pixels) -> Bounds<Pixels> {
528        match self {
529            Self::Up => Bounds {
530                origin: bounds.origin,
531                size: size(bounds.size.width, length),
532            },
533            Self::Down => Bounds {
534                origin: point(bounds.lower_left().x, bounds.lower_left().y - length),
535                size: size(bounds.size.width, length),
536            },
537            Self::Left => Bounds {
538                origin: bounds.origin,
539                size: size(length, bounds.size.height),
540            },
541            Self::Right => Bounds {
542                origin: point(bounds.lower_right().x - length, bounds.lower_left().y),
543                size: size(length, bounds.size.height),
544            },
545        }
546    }
547
548    pub fn axis(&self) -> Axis {
549        match self {
550            Self::Up | Self::Down => Axis::Vertical,
551            Self::Left | Self::Right => Axis::Horizontal,
552        }
553    }
554
555    pub fn increasing(&self) -> bool {
556        match self {
557            Self::Left | Self::Up => false,
558            Self::Down | Self::Right => true,
559        }
560    }
561}
562
563mod element {
564
565    use std::{cell::RefCell, iter, rc::Rc, sync::Arc};
566
567    use gpui::{
568        px, relative, Along, AnyElement, Axis, Bounds, CursorStyle, Element, InteractiveBounds,
569        IntoElement, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point,
570        Size, Style, WindowContext,
571    };
572    use parking_lot::Mutex;
573    use smallvec::SmallVec;
574    use ui::prelude::*;
575
576    use super::{HANDLE_HITBOX_SIZE, HORIZONTAL_MIN_SIZE, VERTICAL_MIN_SIZE};
577
578    const DIVIDER_SIZE: f32 = 1.0;
579
580    pub fn pane_axis(
581        axis: Axis,
582        basis: usize,
583        flexes: Arc<Mutex<Vec<f32>>>,
584        bounding_boxes: Arc<Mutex<Vec<Option<Bounds<Pixels>>>>>,
585    ) -> PaneAxisElement {
586        PaneAxisElement {
587            axis,
588            basis,
589            flexes,
590            bounding_boxes,
591            children: SmallVec::new(),
592            active_pane_ix: None,
593        }
594    }
595
596    pub struct PaneAxisElement {
597        axis: Axis,
598        basis: usize,
599        flexes: Arc<Mutex<Vec<f32>>>,
600        bounding_boxes: Arc<Mutex<Vec<Option<Bounds<Pixels>>>>>,
601        children: SmallVec<[AnyElement; 2]>,
602        active_pane_ix: Option<usize>,
603    }
604
605    impl PaneAxisElement {
606        pub fn with_active_pane(mut self, active_pane_ix: Option<usize>) -> Self {
607            self.active_pane_ix = active_pane_ix;
608            self
609        }
610
611        fn compute_resize(
612            flexes: &Arc<Mutex<Vec<f32>>>,
613            e: &MouseMoveEvent,
614            ix: usize,
615            axis: Axis,
616            child_start: Point<Pixels>,
617            container_size: Size<Pixels>,
618            cx: &mut WindowContext,
619        ) {
620            let min_size = match axis {
621                Axis::Horizontal => px(HORIZONTAL_MIN_SIZE),
622                Axis::Vertical => px(VERTICAL_MIN_SIZE),
623            };
624            let mut flexes = flexes.lock();
625            debug_assert!(flex_values_in_bounds(flexes.as_slice()));
626
627            let size = move |ix, flexes: &[f32]| {
628                container_size.along(axis) * (flexes[ix] / flexes.len() as f32)
629            };
630
631            // Don't allow resizing to less than the minimum size, if elements are already too small
632            if min_size - px(1.) > size(ix, flexes.as_slice()) {
633                return;
634            }
635
636            let mut proposed_current_pixel_change =
637                (e.position - child_start).along(axis) - size(ix, flexes.as_slice());
638
639            let flex_changes = |pixel_dx, target_ix, next: isize, flexes: &[f32]| {
640                let flex_change = pixel_dx / container_size.along(axis);
641                let current_target_flex = flexes[target_ix] + flex_change;
642                let next_target_flex = flexes[(target_ix as isize + next) as usize] - flex_change;
643                (current_target_flex, next_target_flex)
644            };
645
646            let mut successors = iter::from_fn({
647                let forward = proposed_current_pixel_change > px(0.);
648                let mut ix_offset = 0;
649                let len = flexes.len();
650                move || {
651                    let result = if forward {
652                        (ix + 1 + ix_offset < len).then(|| ix + ix_offset)
653                    } else {
654                        (ix as isize - ix_offset as isize >= 0).then(|| ix - ix_offset)
655                    };
656
657                    ix_offset += 1;
658
659                    result
660                }
661            });
662
663            while proposed_current_pixel_change.abs() > px(0.) {
664                let Some(current_ix) = successors.next() else {
665                    break;
666                };
667
668                let next_target_size = Pixels::max(
669                    size(current_ix + 1, flexes.as_slice()) - proposed_current_pixel_change,
670                    min_size,
671                );
672
673                let current_target_size = Pixels::max(
674                    size(current_ix, flexes.as_slice()) + size(current_ix + 1, flexes.as_slice())
675                        - next_target_size,
676                    min_size,
677                );
678
679                let current_pixel_change =
680                    current_target_size - size(current_ix, flexes.as_slice());
681
682                let (current_target_flex, next_target_flex) =
683                    flex_changes(current_pixel_change, current_ix, 1, flexes.as_slice());
684
685                flexes[current_ix] = current_target_flex;
686                flexes[current_ix + 1] = next_target_flex;
687
688                proposed_current_pixel_change -= current_pixel_change;
689            }
690
691            // todo!(schedule serialize)
692            // workspace.schedule_serialize(cx);
693            cx.notify();
694        }
695
696        fn push_handle(
697            flexes: Arc<Mutex<Vec<f32>>>,
698            dragged_handle: Rc<RefCell<Option<usize>>>,
699            axis: Axis,
700            ix: usize,
701            pane_bounds: Bounds<Pixels>,
702            axis_bounds: Bounds<Pixels>,
703            cx: &mut WindowContext,
704        ) {
705            let handle_bounds = Bounds {
706                origin: pane_bounds.origin.apply_along(axis, |origin| {
707                    origin + pane_bounds.size.along(axis) - px(HANDLE_HITBOX_SIZE / 2.)
708                }),
709                size: pane_bounds
710                    .size
711                    .apply_along(axis, |_| px(HANDLE_HITBOX_SIZE)),
712            };
713            let divider_bounds = Bounds {
714                origin: pane_bounds
715                    .origin
716                    .apply_along(axis, |origin| origin + pane_bounds.size.along(axis)),
717                size: pane_bounds.size.apply_along(axis, |_| px(DIVIDER_SIZE)),
718            };
719
720            cx.with_z_index(3, |cx| {
721                let interactive_handle_bounds = InteractiveBounds {
722                    bounds: handle_bounds,
723                    stacking_order: cx.stacking_order().clone(),
724                };
725                if interactive_handle_bounds.visibly_contains(&cx.mouse_position(), cx) {
726                    cx.set_cursor_style(match axis {
727                        Axis::Vertical => CursorStyle::ResizeUpDown,
728                        Axis::Horizontal => CursorStyle::ResizeLeftRight,
729                    })
730                }
731
732                cx.add_opaque_layer(handle_bounds);
733                cx.paint_quad(gpui::fill(divider_bounds, cx.theme().colors().border));
734
735                cx.on_mouse_event({
736                    let dragged_handle = dragged_handle.clone();
737                    move |e: &MouseDownEvent, phase, _cx| {
738                        if phase.bubble() && handle_bounds.contains(&e.position) {
739                            dragged_handle.replace(Some(ix));
740                        }
741                    }
742                });
743                cx.on_mouse_event(move |e: &MouseMoveEvent, phase, cx| {
744                    let dragged_handle = dragged_handle.borrow();
745                    if phase.bubble() && *dragged_handle == Some(ix) {
746                        Self::compute_resize(
747                            &flexes,
748                            e,
749                            ix,
750                            axis,
751                            pane_bounds.origin,
752                            axis_bounds.size,
753                            cx,
754                        )
755                    }
756                });
757            });
758        }
759    }
760
761    impl IntoElement for PaneAxisElement {
762        type Element = Self;
763
764        fn element_id(&self) -> Option<ui::prelude::ElementId> {
765            Some(self.basis.into())
766        }
767
768        fn into_element(self) -> Self::Element {
769            self
770        }
771    }
772
773    impl Element for PaneAxisElement {
774        type State = Rc<RefCell<Option<usize>>>;
775
776        fn request_layout(
777            &mut self,
778            state: Option<Self::State>,
779            cx: &mut ui::prelude::WindowContext,
780        ) -> (gpui::LayoutId, Self::State) {
781            let mut style = Style::default();
782            style.flex_grow = 1.;
783            style.flex_shrink = 1.;
784            style.flex_basis = relative(0.).into();
785            style.size.width = relative(1.).into();
786            style.size.height = relative(1.).into();
787            let layout_id = cx.request_layout(&style, None);
788            let dragged_pane = state.unwrap_or_else(|| Rc::new(RefCell::new(None)));
789            (layout_id, dragged_pane)
790        }
791
792        fn paint(
793            &mut self,
794            bounds: gpui::Bounds<ui::prelude::Pixels>,
795            state: &mut Self::State,
796            cx: &mut ui::prelude::WindowContext,
797        ) {
798            let flexes = self.flexes.lock().clone();
799            let len = self.children.len();
800            debug_assert!(flexes.len() == len);
801            debug_assert!(flex_values_in_bounds(flexes.as_slice()));
802
803            let mut origin = bounds.origin;
804            let space_per_flex = bounds.size.along(self.axis) / len as f32;
805
806            let mut bounding_boxes = self.bounding_boxes.lock();
807            bounding_boxes.clear();
808
809            for (ix, child) in self.children.iter_mut().enumerate() {
810                //todo!(active_pane_magnification)
811                // If using active pane magnification, need to switch to using
812                // 1 for all non-active panes, and then the magnification for the
813                // active pane.
814                let child_size = bounds
815                    .size
816                    .apply_along(self.axis, |_| space_per_flex * flexes[ix]);
817
818                let child_bounds = Bounds {
819                    origin,
820                    size: child_size,
821                };
822                bounding_boxes.push(Some(child_bounds));
823                cx.with_z_index(0, |cx| {
824                    child.draw(origin, child_size.into(), cx);
825                });
826                cx.with_z_index(1, |cx| {
827                    if ix < len - 1 {
828                        Self::push_handle(
829                            self.flexes.clone(),
830                            state.clone(),
831                            self.axis,
832                            ix,
833                            child_bounds,
834                            bounds,
835                            cx,
836                        );
837                    }
838                });
839
840                origin = origin.apply_along(self.axis, |val| val + child_size.along(self.axis));
841            }
842
843            cx.with_z_index(1, |cx| {
844                cx.on_mouse_event({
845                    let state = state.clone();
846                    move |_: &MouseUpEvent, phase, _cx| {
847                        if phase.bubble() {
848                            state.replace(None);
849                        }
850                    }
851                });
852            })
853        }
854    }
855
856    impl ParentElement for PaneAxisElement {
857        fn children_mut(&mut self) -> &mut smallvec::SmallVec<[AnyElement; 2]> {
858            &mut self.children
859        }
860    }
861
862    fn flex_values_in_bounds(flexes: &[f32]) -> bool {
863        (flexes.iter().copied().sum::<f32>() - flexes.len() as f32).abs() < 0.001
864    }
865}