Skip to main content

egui_pop_viewport/graph/
minimap.rs

1//! The graph's minimap, after the image navigator: the whole graph
2//! small, the part in view framed, the rest veiled.
3
4use egui::{
5    Key, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, vec2,
6};
7use egui_pop_core::state::Slot;
8use egui_pop_core::strings;
9use egui_pop_core::theme::Tokens;
10
11use super::{GraphState, GraphTokens, zoom_text};
12use crate::navigator::NavigatorTokens;
13
14/// The whole graph and the part in view, sharing the editor's
15/// [`GraphState`]. A drag of the frame pans (Escape puts the view
16/// back), a press elsewhere centres the view there, the wheel zooms, a
17/// double click fits; focused, the arrows pan, `+` and `-` zoom, `0`
18/// fits.
19#[derive(Debug)]
20pub struct GraphMinimap<'a> {
21    state: &'a mut GraphState,
22    size: Option<Vec2>,
23    label: Option<String>,
24}
25
26/// Where the minimap draws the graph: a scale and an offset.
27#[derive(Clone, Copy, Debug)]
28struct Map {
29    scale: f32,
30    origin: Pos2,
31    world: Rect,
32}
33
34impl Map {
35    fn to_screen(self, p: Pos2) -> Pos2 {
36        self.origin + (p - self.world.min) * self.scale
37    }
38
39    fn to_world(self, p: Pos2) -> Pos2 {
40        self.world.min + (p - self.origin) / self.scale
41    }
42
43    fn rect(self, r: Rect) -> Rect {
44        Rect::from_min_max(self.to_screen(r.min), self.to_screen(r.max))
45    }
46}
47
48impl<'a> GraphMinimap<'a> {
49    pub fn new(state: &'a mut GraphState) -> GraphMinimap<'a> {
50        GraphMinimap {
51            state,
52            size: None,
53            label: None,
54        }
55    }
56
57    /// The size in points (default: the available width, two thirds as
58    /// high).
59    pub fn size(mut self, size: Vec2) -> Self {
60        self.size = Some(size);
61        self
62    }
63
64    /// The accessible name (default "Graph overview").
65    pub fn label(mut self, label: impl Into<String>) -> Self {
66        self.label = Some(label.into());
67        self
68    }
69
70    /// Draws the minimap; `changed()` when it moved the view.
71    pub fn show(self, ui: &mut Ui) -> Response {
72        let GraphMinimap { state, size, label } = self;
73        let size = size.unwrap_or_else(|| {
74            let w = ui.available_width().clamp(120.0, 320.0);
75            vec2(w, (w * 2.0 / 3.0).round())
76        });
77        let (rect, mut response) = ui.allocate_exact_size(size, Sense::click_and_drag());
78        let drawn = state.drawn.clone();
79        let world = drawn.bounds.union(drawn.visible).expand(20.0);
80        let inner = rect.shrink(4.0);
81        let nav = NavigatorTokens::of(ui.ctx());
82        let g = GraphTokens::of(ui.ctx());
83        let radius = Tokens::of(ui.ctx()).radius.widget;
84        ui.painter().rect_filled(rect, radius, nav.background);
85        let mut changed = false;
86        // The view's frame, on screen: dragging is its only action.
87        let mut view_frame = None;
88        if world.is_positive() && drawn.visible.is_positive() {
89            let scale = (inner.size() / world.size()).min_elem();
90            let origin = inner.center() - world.size() * scale / 2.0;
91            let map = Map {
92                scale,
93                origin,
94                world,
95            };
96            changed = gestures(ui, &response, state, &map);
97            let painter = ui.painter_at(rect);
98            for (r, selected) in &drawn.boxes {
99                let s = map.rect(*r);
100                painter.rect_filled(s, 1.0, if *selected { g.node_selected } else { g.node });
101                painter.rect_stroke(s, 1.0, Stroke::new(1.0, g.node_border), StrokeKind::Inside);
102            }
103            let frame = map.rect(state.drawn.visible).intersect(inner);
104            view_frame = Some(frame);
105            // The veil over what is out of view.
106            let veil = nav.veil.gamma_multiply(0.55);
107            for r in [
108                Rect::from_min_max(inner.min, egui::pos2(inner.max.x, frame.min.y)),
109                Rect::from_min_max(egui::pos2(inner.min.x, frame.max.y), inner.max),
110                Rect::from_min_max(
111                    egui::pos2(inner.min.x, frame.min.y),
112                    egui::pos2(frame.min.x, frame.max.y),
113                ),
114                Rect::from_min_max(
115                    egui::pos2(frame.max.x, frame.min.y),
116                    egui::pos2(inner.max.x, frame.max.y),
117                ),
118            ] {
119                if r.is_positive() {
120                    painter.rect_filled(r, 0.0, veil);
121                }
122            }
123            painter.rect_stroke(frame, 0.0, Stroke::new(1.5, nav.frame), StrokeKind::Inside);
124        }
125        if response.has_focus() {
126            egui_pop_core::focus::own_ring(&response.ctx, response.id);
127        }
128        if egui_pop_core::focus::shows_ring(&response) {
129            ui.painter().rect_stroke(
130                rect.expand(2.0),
131                radius,
132                Stroke::new(2.0, g.focus),
133                StrokeKind::Outside,
134            );
135        }
136        if response.clicked() || response.drag_started() {
137            response.request_focus();
138        }
139        // Its frame moves the view; elsewhere a click jumps there, the
140        // arrow until the drag starts.
141        let over_frame = response
142            .hover_pos()
143            .is_some_and(|p| view_frame.is_some_and(|f: egui::Rect| f.contains(p)));
144        egui_pop_core::pointer::drag_cursor(&response, egui_pop_core::pointer::DragKind::Move)
145            .clicks(!over_frame);
146        if changed {
147            response.mark_changed();
148        }
149        let label = label.unwrap_or_else(|| strings::tr(ui.ctx(), &crate::strings::GRAPH_MINIMAP));
150        let value = strings::tr_args(
151            ui.ctx(),
152            &crate::strings::GRAPH_MINIMAP_VALUE,
153            &[("zoom", &zoom_text(ui.ctx(), drawn.zoom))],
154        );
155        let enabled = ui.is_enabled();
156        response.widget_info(|| {
157            let mut info = WidgetInfo::labeled(Role::Unknown, enabled, &label);
158            info.current_text_value = Some(value.clone());
159            info
160        });
161        ui.ctx().accesskit_node_builder(response.id, |node| {
162            node.set_role(egui::accesskit::Role::ScrollView);
163        });
164        response
165    }
166}
167
168/// The view before a drag on the minimap, per minimap.
169const VIEW_BEFORE: Slot<Rect> = Slot::new("viewport.graph.minimap_view_before");
170
171/// The minimap's pointer, wheel and keys; whether the view moved.
172fn gestures(ui: &Ui, response: &Response, state: &mut GraphState, map: &Map) -> bool {
173    let id = VIEW_BEFORE.keyed(response.id);
174    let before = state.view;
175    let pointer = response.interact_pointer_pos();
176    if response.drag_started()
177        && let Some(p) = pointer
178    {
179        let frame = map.rect(state.drawn.visible);
180        // A press outside the frame first brings it there.
181        if !frame.contains(p) {
182            state.center_on(map.to_world(p));
183        }
184        id.set(ui.ctx(), before);
185    }
186    if response.dragged() {
187        state.pan(response.drag_delta() / map.scale);
188    }
189    if response.drag_stopped()
190        && egui_pop_core::focus::cancel_pressed(ui.ctx(), Key::Escape)
191        && let Some(start) = id.get(ui.ctx())
192    {
193        state.view = start;
194    }
195    if response.clicked()
196        && let Some(p) = pointer
197    {
198        state.center_on(map.to_world(p));
199    }
200    if response.double_clicked() {
201        state.fit();
202    }
203    let visible = state.drawn.visible;
204    if response.hovered() {
205        let scroll = ui.input(|i| i.smooth_scroll_delta.y);
206        if scroll != 0.0 {
207            state.zoom_by((scroll * 0.003).exp(), visible.center());
208        }
209    }
210    if response.has_focus() {
211        crate::change::lock_arrows(ui, response.id);
212        let [x, y] = crate::change::arrows(ui);
213        if x != 0.0 || y != 0.0 {
214            state.pan(vec2(x * visible.width(), -y * visible.height()) * 0.1);
215        }
216        let (zin, zout, fit) = ui.input(|i| {
217            (
218                i.key_pressed(Key::Plus) || i.key_pressed(Key::Equals),
219                i.key_pressed(Key::Minus),
220                i.key_pressed(Key::Num0),
221            )
222        });
223        if zin {
224            state.zoom_by(1.25, visible.center());
225        }
226        if zout {
227            state.zoom_by(0.8, visible.center());
228        }
229        if fit {
230            state.fit();
231        }
232    }
233    state.view != before || state.fit
234}