egui_stack 0.33.0

Docking system for egui, continuing egui_dock
Documentation
//! The junctions where perpendicular separators meet: a grid's crossing, or a separator ending
//! on another one. Dragging a junction moves all its separators at once.

use egui::{CursorIcon, Id, Rect, Sense, Ui, Vec2};

use super::{SeparatorOf, separator_shares};
use crate::dock_state::tree::node::shares;
use crate::widgets::line_highlight;
use crate::{DockArea, NodePath, PartState, SeparatorAxis, SeparatorPaint, Style, SurfaceIndex};

/// A separator shown this frame, for its junctions.
#[derive(Clone, Copy, Debug)]
pub(super) struct SeparatorHandle {
    pub(super) path: NodePath,
    pub(super) of: SeparatorOf,
    /// Whether the line runs up and down, moving sideways.
    pub(super) vertical: bool,
    /// The line as painted.
    pub(super) rect: Rect,
    /// Where it takes the pointer.
    pub(super) interact: Rect,
}

/// A separator as a junction remembers it across frames.
type Member = (NodePath, SeparatorOf);

/// Separators that drag as one: indices in the frame's handles, and where they meet.
#[derive(Debug, PartialEq)]
struct Junction {
    members: Vec<usize>,
    rect: Rect,
}

/// The junctions of `handles`: each crossing of a vertical and a horizontal separator, those
/// closer than `merge_distance` taken as one.
fn find_junctions(handles: &[SeparatorHandle], merge_distance: f32) -> Vec<Junction> {
    let mut junctions = Vec::new();
    for (a, across) in handles.iter().enumerate().filter(|(_, h)| h.vertical) {
        for (b, along) in handles.iter().enumerate().filter(|(_, h)| !h.vertical) {
            if across.interact.intersects(along.interact) {
                junctions.push(Junction {
                    members: vec![a.min(b), a.max(b)],
                    rect: across.interact.intersect(along.interact),
                });
            }
        }
    }
    let pad = merge_distance / 2.0;
    loop {
        let close = (0..junctions.len())
            .flat_map(|a| (a + 1..junctions.len()).map(move |b| (a, b)))
            .find(|&(a, b)| {
                junctions[a]
                    .rect
                    .expand(pad)
                    .intersects(junctions[b].rect.expand(pad))
            });
        let Some((a, b)) = close else {
            break;
        };
        let other = junctions.remove(b);
        let junction = &mut junctions[a];
        junction.rect = junction.rect.union(other.rect);
        junction.members.extend(other.members);
        junction.members.sort_unstable();
        junction.members.dedup();
    }
    junctions
}

/// Where the perpendicular separators among `members` cross, or nothing if they no longer do.
fn crossing(handles: &[SeparatorHandle], members: &[usize]) -> Rect {
    let mut rect = Rect::NOTHING;
    for &a in members.iter().filter(|&&m| handles[m].vertical) {
        for &b in members.iter().filter(|&&m| !handles[m].vertical) {
            let (a, b) = (handles[a].interact, handles[b].interact);
            if a.intersects(b) {
                rect = rect.union(a.intersect(b));
            }
        }
    }
    rect
}

impl<Tab> DockArea<'_, Tab> {
    /// The id of the junction of `members`, sorted.
    fn junction_id(&self, members: &[Member]) -> Id {
        self.id.with("separator_junction").with(members)
    }

    /// Shows the junctions of the separators of `surface` shown this frame: dragging one moves
    /// its separators together, each along its own axis and within its own bounds, and a double
    /// click evens them all. Off with [`SeparatorStyle::junctions`](crate::SeparatorStyle::junctions).
    pub(super) fn show_junctions(
        &mut self,
        ui: &mut Ui,
        surface: SurfaceIndex,
        handles: &[SeparatorHandle],
        fade_style: Option<&Style>,
    ) {
        let style = fade_style.unwrap_or_else(|| self.style.as_ref().unwrap());
        // The separators of the junction being dragged, kept from its start: the drag keeps its
        // id, and a separator coming close on the way does not join it.
        let dragged_id = self.id.with(("separator_junction_dragged", surface));
        if !style.separator.junctions {
            ui.data_mut(|d| d.remove::<Vec<Member>>(dragged_id));
            return;
        }
        let painter = self.painter.0;

        let mut junctions = find_junctions(handles, style.separator.junction_merge_distance);
        let dragged = ui
            .data(|d| d.get_temp::<Vec<Member>>(dragged_id))
            .filter(|members| ui.ctx().is_being_dragged(self.junction_id(members)))
            .and_then(|members| {
                members
                    .iter()
                    .map(|&(path, of)| handles.iter().position(|h| h.path == path && h.of == of))
                    .collect::<Option<Vec<_>>>()
            });
        match dragged {
            Some(members) => {
                junctions.retain(|j| !j.members.iter().any(|m| members.contains(m)));
                let mut rect = crossing(handles, &members);
                if rect == Rect::NOTHING {
                    // Their bounds pulled the lines apart: the drag goes on under the pointer.
                    let at = ui.input(|i| i.pointer.interact_pos());
                    rect = at.map_or(Rect::NOTHING, |at| Rect::from_center_size(at, Vec2::ZERO));
                }
                junctions.insert(0, Junction { members, rect });
            }
            None => ui.data_mut(|d| d.remove::<Vec<Member>>(dragged_id)),
        }

        for junction in junctions {
            let mut members: Vec<Member> = junction
                .members
                .iter()
                .map(|&m| (handles[m].path, handles[m].of))
                .collect();
            members.sort_unstable_by_key(|&(path, of)| (path.surface.0, path.node.0, of));
            let id = self.junction_id(&members);
            // A pointer gesture only: the keyboard moves each separator on its own, so the
            // junction takes no focus.
            let response = ui
                .interact(
                    junction
                        .rect
                        .expand(style.separator.extra_interact_width / 2.0),
                    id,
                    Sense::CLICK | Sense::DRAG,
                )
                .on_hover_and_drag_cursor(CursorIcon::Move);
            if response.drag_started() {
                ui.data_mut(|d| d.insert_temp(dragged_id, members));
            }

            let highlight = line_highlight(ui, &response);
            if highlight > 0.0 {
                let state = PartState::NONE
                    .with(PartState::HOVERED, response.hovered())
                    .with(PartState::PRESSED, response.is_pointer_button_down_on())
                    .with(PartState::DRAGGED, response.dragged());
                for &m in &junction.members {
                    let handle = handles[m];
                    painter.separator(
                        ui.painter(),
                        &SeparatorPaint {
                            rect: handle.rect,
                            axis: if handle.vertical {
                                SeparatorAxis::Vertical
                            } else {
                                SeparatorAxis::Horizontal
                            },
                            state,
                            highlight,
                            style,
                        },
                    );
                }
            }

            // Moved after painting, as a separator is: the lines stay where they were drawn.
            let delta = response.drag_delta();
            let reset = response.double_clicked();
            if delta == Vec2::ZERO && !reset {
                continue;
            }
            for &m in &junction.members {
                let handle = handles[m];
                let (across, rect, shares, index) = separator_shares(
                    &mut self.dock_state[handle.path.surface][handle.path.node],
                    handle.of,
                );
                if reset {
                    shares::even_pair(shares, index);
                    continue;
                }
                let (range, delta) = if across {
                    (rect.width(), delta.x)
                } else {
                    (rect.height(), delta.y)
                };
                if range > 0.0 && delta != 0.0 {
                    let min_part = (style.separator.extra / range).min(1.0);
                    shares::move_boundary(shares, index, delta / range, min_part);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use egui::{pos2, vec2};

    use super::*;
    use crate::NodeIndex;

    fn handle(node: usize, of: SeparatorOf, vertical: bool, interact: Rect) -> SeparatorHandle {
        SeparatorHandle {
            path: NodePath {
                surface: SurfaceIndex::main(),
                node: NodeIndex(node),
            },
            of,
            vertical,
            rect: interact,
            interact,
        }
    }

    /// A vertical line at `x` and a horizontal one at `y`, 4 points thick for the pointer.
    fn line(node: usize, vertical: bool, at: f32) -> SeparatorHandle {
        let interact = if vertical {
            Rect::from_center_size(pos2(at, 50.0), vec2(4.0, 100.0))
        } else {
            Rect::from_center_size(pos2(50.0, at), vec2(100.0, 4.0))
        };
        handle(node, SeparatorOf::Linear(0), vertical, interact)
    }

    #[test]
    fn a_crossing_is_a_junction() {
        let handles = [line(0, true, 50.0), line(1, false, 30.0)];
        let junctions = find_junctions(&handles, 8.0);
        assert_eq!(junctions.len(), 1);
        assert_eq!(junctions[0].members, [0, 1]);
        assert!(junctions[0].rect.contains(pos2(50.0, 30.0)));
    }

    #[test]
    fn parallel_separators_make_none() {
        let handles = [line(0, true, 30.0), line(1, true, 60.0)];
        assert!(find_junctions(&handles, 8.0).is_empty());
    }

    #[test]
    fn close_crossings_merge_and_far_ones_do_not() {
        // Two vertical lines 5 points apart crossing one horizontal line: one junction of
        // three. A third vertical line far away makes its own.
        let handles = [
            line(0, true, 50.0),
            line(1, true, 55.0),
            line(2, false, 30.0),
            line(3, true, 90.0),
        ];
        let junctions = find_junctions(&handles, 8.0);
        assert_eq!(junctions.len(), 2);
        assert_eq!(junctions[0].members, [0, 1, 2]);
        assert_eq!(junctions[1].members, [2, 3]);
        // With no merge distance, the two close crossings stay apart.
        assert_eq!(find_junctions(&handles, 0.0).len(), 3);
    }

    #[test]
    fn the_crossing_of_members_that_drifted_apart_is_nothing() {
        let handles = [line(0, true, 50.0), line(1, false, 30.0)];
        assert!(crossing(&handles, &[0, 1]).contains(pos2(50.0, 30.0)));
        let apart = [
            handle(
                0,
                SeparatorOf::Linear(0),
                true,
                Rect::from_center_size(pos2(50.0, 20.0), vec2(4.0, 20.0)),
            ),
            line(1, false, 80.0),
        ];
        assert_eq!(crossing(&apart, &[0, 1]), Rect::NOTHING);
    }
}