Skip to main content

egui_pop_viewport/
navigator.rs

1//! The zoom control and the navigator (a minimap): two views of a
2//! viewport's [`View`], sharing its [`ViewportState`]. What they change
3//! goes through the viewport's `before_view` hook, like the viewport's
4//! own gestures ([`ViewportState::propose`]), and comes out as the
5//! viewport's [`Signal::View`](crate::Signal) with the next frame.
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! - [`ZoomControl`]: zoom out, the zoom in percent, zoom in, fit and
11//!   100 %, one step of the zoom ladder at a time.
12//! - [`Navigator`]: the whole image (a texture the application gives,
13//!   its proxy) and a frame around the part in view. A drag of the frame
14//!   pans (Ctrl finer, Shift coarser; Escape puts the view back), a
15//!   press outside it centres the view there, the wheel zooms, a double
16//!   click fits. Focused, the arrows pan, `+` and `-` zoom, `0` fits.
17//!
18//! Each has an [`on_change`](Navigator::on_change) hook, before the
19//! viewport's: a [`Change`] of the [`View`], a drag's frames with
20//! `done: false` and its end once more from the view before it.
21//! `egui-pop-imaging` runs the finished ones as the `zoom.change` step
22//! of an application.
23//!
24//! ```
25//! use egui_pop_viewport::navigator::{Navigator, ZoomControl};
26//! use egui_pop_viewport::{View, ViewportState};
27//!
28//! fn side_panel(ui: &mut egui::Ui, state: &mut ViewportState, view: &mut View, proxy: egui::TextureId) {
29//!     ZoomControl::new(state, view).show(ui);
30//!     Navigator::new(state, view).texture(proxy).show(ui);
31//! }
32//! ```
33
34use egui::{
35    Color32, Key, Pos2, Rect, Response, Role, Sense, Shape, Stroke, StrokeKind, TextureId, Ui,
36    Vec2, WidgetInfo, pos2, vec2,
37};
38use egui_pop_core::icon::{Icon, Size};
39use egui_pop_core::state::Slot;
40use egui_pop_core::strings;
41
42/// A drag under way on a navigator, per navigator.
43const GRAB: Slot<Grab> = Slot::new("viewport.navigator.grab");
44use egui_pop_core::theme::Tokens;
45use egui_pop_core::ui::{Stock, Tone, UiPop as _};
46
47use crate::change::{self, Cause, Change, Gesture, Hook, Verdict};
48use crate::thumbnail::fitted;
49use crate::view::{self, Mapping, View, Zoom};
50use crate::widget::{ViewportState, zoom_percent};
51
52/// The navigator's colours, from the theme (`navigator.*`).
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct NavigatorTokens {
55    pub background: Color32,
56    pub frame: Color32,
57    pub veil: Color32,
58}
59
60impl NavigatorTokens {
61    pub fn of(ctx: &egui::Context) -> NavigatorTokens {
62        let t = Tokens::of(ctx);
63        let c = |path: &str, fallback: Color32| t.color(path).unwrap_or(fallback);
64        NavigatorTokens {
65            background: c("navigator.background", t.surface.sunken),
66            frame: c("navigator.frame", t.accent.default),
67            veil: c("navigator.veil", t.surface.canvas),
68        }
69    }
70}
71
72/// What a zoom control or a navigator did in a frame.
73#[derive(Debug)]
74pub struct ViewOutput {
75    /// The navigator, or the zoom control's row; `changed()` when the
76    /// view changed.
77    pub response: Response,
78    /// The changes written this frame, after the hooks.
79    pub changes: Vec<Change<View>>,
80}
81
82/// Proposes a view: the tool's hook, then the viewport's `before_view`
83/// hook. Whether the view changed.
84fn apply(
85    state: &mut ViewportState,
86    view: &mut View,
87    to: View,
88    cause: Cause,
89    done: bool,
90    hook: &mut Option<Hook<'_, View>>,
91    changes: &mut Vec<Change<View>>,
92) -> bool {
93    if to == *view {
94        return false;
95    }
96    let proposed = Change {
97        from: *view,
98        to,
99        cause,
100        done,
101    };
102    let Some(c) = change::decide(hook, proposed) else {
103        return false;
104    };
105    if state.propose(view, c.to) {
106        changes.push(Change { to: *view, ..c });
107        true
108    } else {
109        false
110    }
111}
112
113/// A view at another zoom around the view's centre (the image's centre
114/// before the viewport has drawn).
115fn zoomed(m: Option<Mapping>, f: impl Fn(f64) -> f64) -> Option<View> {
116    let m = m?;
117    Some(m.zoom_around(m.rect.center(), f(m.zoom)))
118}
119
120/// The zoom control: zoom out, the zoom, zoom in, fit, 100 %.
121///
122/// Need (image): a zoom control.
123#[derive(Debug)]
124pub struct ZoomControl<'a> {
125    state: &'a mut ViewportState,
126    view: &'a mut View,
127    hook: Option<Hook<'a, View>>,
128}
129
130impl<'a> ZoomControl<'a> {
131    pub fn new(state: &'a mut ViewportState, view: &'a mut View) -> ZoomControl<'a> {
132        ZoomControl {
133            state,
134            view,
135            hook: None,
136        }
137    }
138
139    /// Sees each change before the viewport's hook: allow, veto or
140    /// redirect (another view).
141    pub fn on_change(mut self, hook: impl FnMut(&Change<View>) -> Verdict<View> + 'a) -> Self {
142        self.hook = Some(Hook::new(hook));
143        self
144    }
145
146    /// Draws the row; says what changed.
147    pub fn show(self, ui: &mut Ui) -> ViewOutput {
148        let ZoomControl {
149            state,
150            view,
151            mut hook,
152        } = self;
153        let mut changes = Vec::new();
154        let ctx = ui.ctx().clone();
155        let tr = |k: &strings::StrKey| strings::tr(&ctx, k);
156        let inner = ui.horizontal(|ui| {
157            let m = state.mapping();
158            let out = ui.add(
159                Icon::Minus
160                    .size(Size::Toolbar)
161                    .label(&tr(&crate::strings::ZOOM_OUT))
162                    .sense_click(),
163            );
164            if out.clicked()
165                && let Some(to) = zoomed(m, view::zoom_out)
166            {
167                apply(
168                    state,
169                    view,
170                    to,
171                    Cause::Command,
172                    true,
173                    &mut hook,
174                    &mut changes,
175                );
176            }
177            let percent = zoom_percent(view, state.mapping().as_ref());
178            let text = format!("{} %", percent_text(&ctx, percent));
179            ui.add(egui::Label::new(text).selectable(false));
180            let into = ui.add(
181                Icon::Plus
182                    .size(Size::Toolbar)
183                    .label(&tr(&crate::strings::ZOOM_IN))
184                    .sense_click(),
185            );
186            if into.clicked()
187                && let Some(to) = zoomed(m, view::zoom_in)
188            {
189                apply(
190                    state,
191                    view,
192                    to,
193                    Cause::Command,
194                    true,
195                    &mut hook,
196                    &mut changes,
197                );
198            }
199            // Shown on or off: the kit's `toggle-button` in a scope.
200            let (fit, actual) = ui
201                .scoped(Stock::ToggleButton, Tone::Neutral, |ui| {
202                    let fit = ui.add(
203                        egui::Button::new(tr(&crate::strings::ZOOM_FIT)).selected(view.is_fit()),
204                    );
205                    let actual = ui.add(
206                        egui::Button::new(tr(&crate::strings::ZOOM_ACTUAL))
207                            .selected(view.zoom == Zoom::Px(1.0)),
208                    );
209                    (fit, actual)
210                })
211                .inner;
212            if fit.clicked() {
213                apply(
214                    state,
215                    view,
216                    View::fit(),
217                    Cause::Command,
218                    true,
219                    &mut hook,
220                    &mut changes,
221                );
222            }
223            if actual.clicked() {
224                let center = m.map_or(view.center, |m| m.center);
225                apply(
226                    state,
227                    view,
228                    View::actual(center),
229                    Cause::Command,
230                    true,
231                    &mut hook,
232                    &mut changes,
233                );
234            }
235        });
236        let mut response = inner.response;
237        if !changes.is_empty() {
238            response.mark_changed();
239        }
240        ViewOutput { response, changes }
241    }
242}
243
244/// A zoom in percent, as the interface writes numbers: whole above 10 %,
245/// one decimal below.
246pub fn percent_text(ctx: &egui::Context, percent: f64) -> String {
247    let decimals = if percent >= 10.0 || percent.fract() == 0.0 {
248        0
249    } else {
250        1
251    };
252    strings::number(ctx, percent, decimals)
253}
254
255/// The navigator: the whole image and the part in view.
256///
257/// Need (image): an image navigator (overview with the visible area).
258#[derive(Debug)]
259pub struct Navigator<'a> {
260    state: &'a mut ViewportState,
261    view: &'a mut View,
262    texture: Option<TextureId>,
263    image_size: Option<[u32; 2]>,
264    size: Option<Vec2>,
265    label: Option<String>,
266    hook: Option<Hook<'a, View>>,
267}
268
269/// A drag under way: the view before it, and the centre the pointer
270/// took it to (image pixels).
271#[derive(Clone, Copy, Debug)]
272struct Grab {
273    start: View,
274    center: [f64; 2],
275    cause: Cause,
276}
277
278impl<'a> Navigator<'a> {
279    pub fn new(state: &'a mut ViewportState, view: &'a mut View) -> Navigator<'a> {
280        Navigator {
281            state,
282            view,
283            texture: None,
284            image_size: None,
285            size: None,
286            label: None,
287            hook: None,
288        }
289    }
290
291    /// The whole image, small (the application's proxy).
292    pub fn texture(mut self, texture: TextureId) -> Self {
293        self.texture = Some(texture);
294        self
295    }
296
297    /// The image's size in pixels (by default, the size the viewport
298    /// drew last).
299    pub fn image_size(mut self, size: [u32; 2]) -> Self {
300        self.image_size = Some(size);
301        self
302    }
303
304    /// The size in points (default: the available width, two thirds as
305    /// high).
306    pub fn size(mut self, size: Vec2) -> Self {
307        self.size = Some(size);
308        self
309    }
310
311    /// The accessible name (default "Navigator").
312    pub fn label(mut self, label: impl Into<String>) -> Self {
313        self.label = Some(label.into());
314        self
315    }
316
317    /// Sees each change before the viewport's hook: allow, veto or
318    /// redirect (another view).
319    pub fn on_change(mut self, hook: impl FnMut(&Change<View>) -> Verdict<View> + 'a) -> Self {
320        self.hook = Some(Hook::new(hook));
321        self
322    }
323
324    /// Draws the navigator; says what changed.
325    pub fn show(self, ui: &mut Ui) -> ViewOutput {
326        let Navigator {
327            state,
328            view,
329            texture,
330            image_size,
331            size,
332            label,
333            mut hook,
334        } = self;
335        let size = size.unwrap_or_else(|| {
336            let w = ui.available_width().clamp(120.0, 320.0);
337            vec2(w, (w * 2.0 / 3.0).round())
338        });
339        let (rect, mut response) =
340            change::allocate(ui, size, Sense::click_and_drag(), ("navigator", &label));
341        let m = state.mapping();
342        let image = image_size
343            .map(|s| [f64::from(s[0]), f64::from(s[1])])
344            .or(m.map(|m| m.image))
345            .filter(|i| i[0] > 0.0 && i[1] > 0.0);
346        let mut changes = Vec::new();
347        // The view's frame, on screen: dragging is its only action.
348        let mut frame = None;
349        if let Some(image) = image {
350            let fit = fitted(rect.shrink(2.0), [image[0] as u32, image[1] as u32]);
351            let scale = f64::from(fit.width()) / image[0];
352            let to_image = |p: Pos2| {
353                [
354                    f64::from(p.x - fit.left()) / scale,
355                    f64::from(p.y - fit.top()) / scale,
356                ]
357            };
358            gestures(
359                ui,
360                &response,
361                state,
362                view,
363                m,
364                image,
365                scale,
366                &to_image,
367                &mut hook,
368                &mut changes,
369            );
370            frame = state
371                .mapping()
372                .or(m)
373                .and_then(|m| m.visible())
374                .map(|v| frame_rect(fit, v, scale));
375            paint(
376                ui,
377                rect,
378                fit,
379                &response,
380                texture,
381                state.mapping().or(m),
382                scale,
383            );
384        } else {
385            let t = NavigatorTokens::of(ui.ctx());
386            ui.painter()
387                .rect_filled(rect, Tokens::of(ui.ctx()).radius.widget, t.background);
388        }
389        if response.clicked() || response.drag_started() {
390            response.request_focus();
391        }
392        // Its frame moves the view; elsewhere a click jumps there, the
393        // arrow until the drag starts.
394        let over_frame = response
395            .hover_pos()
396            .is_some_and(|p| frame.is_some_and(|f: Rect| f.contains(p)));
397        egui_pop_core::pointer::drag_cursor(&response, egui_pop_core::pointer::DragKind::Move)
398            .clicks(!over_frame);
399        if !changes.is_empty() {
400            response.mark_changed();
401        }
402        let label = label.unwrap_or_else(|| strings::tr(ui.ctx(), &crate::strings::NAVIGATOR));
403        let percent = zoom_percent(view, state.mapping().as_ref());
404        let center = match view.zoom {
405            Zoom::Fit => image.map_or([0.0, 0.0], |i| [i[0] / 2.0, i[1] / 2.0]),
406            Zoom::Px(_) => view.center,
407        };
408        let value = strings::tr_args(
409            ui.ctx(),
410            &crate::strings::NAVIGATOR_VALUE,
411            &[
412                ("zoom", &percent_text(ui.ctx(), percent)),
413                ("x", &strings::number(ui.ctx(), center[0], 0)),
414                ("y", &strings::number(ui.ctx(), center[1], 0)),
415            ],
416        );
417        let enabled = ui.is_enabled();
418        response.widget_info(|| {
419            let mut info = WidgetInfo::labeled(Role::Unknown, enabled, &label);
420            info.current_text_value = Some(value.clone());
421            info
422        });
423        ui.ctx().accesskit_node_builder(response.id, |node| {
424            node.set_role(egui::accesskit::Role::ScrollView);
425        });
426        ViewOutput { response, changes }
427    }
428}
429
430/// The navigator's pointer, wheel and keys.
431#[allow(
432    clippy::too_many_arguments,
433    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
434)]
435fn gestures(
436    ui: &mut Ui,
437    response: &Response,
438    state: &mut ViewportState,
439    view: &mut View,
440    m: Option<Mapping>,
441    image: [f64; 2],
442    scale: f64,
443    to_image: &dyn Fn(Pos2) -> [f64; 2],
444    hook: &mut Option<Hook<'_, View>>,
445    changes: &mut Vec<Change<View>>,
446) {
447    let Some(m) = m else {
448        return;
449    };
450    let grab_id = GRAB.keyed(response.id);
451    let mut grab = grab_id.get(ui.ctx());
452    let at_center = |c: [f64; 2]| View::at(m.zoom, c);
453    let visible = m.visible();
454    let pressed = ui.input(|i| i.pointer.primary_pressed()) && response.is_pointer_button_down_on();
455    if pressed && let Some(pos) = response.interact_pointer_pos() {
456        let p = to_image(pos);
457        let inside =
458            visible.is_some_and(|v| p[0] >= v[0] && p[0] <= v[2] && p[1] >= v[1] && p[1] <= v[3]);
459        let mut g = Grab {
460            start: *view,
461            center: m.center,
462            cause: Cause::Drag,
463        };
464        if !inside {
465            g.center = [p[0].clamp(0.0, image[0]), p[1].clamp(0.0, image[1])];
466            g.cause = Cause::Click;
467            apply(
468                state,
469                view,
470                at_center(g.center),
471                Cause::Click,
472                false,
473                hook,
474                changes,
475            );
476        }
477        grab = Some(g);
478    }
479    match change::gesture(ui, response) {
480        Gesture::None => {}
481        Gesture::Moved(d) => {
482            if let Some(g) = grab.as_mut() {
483                g.center = [
484                    g.center[0] + f64::from(d.x) / scale,
485                    g.center[1] + f64::from(d.y) / scale,
486                ];
487                g.cause = Cause::Drag;
488                apply(
489                    state,
490                    view,
491                    at_center(g.center),
492                    Cause::Drag,
493                    false,
494                    hook,
495                    changes,
496                );
497            }
498        }
499        Gesture::Ended => {
500            if let Some(g) = grab.take() {
501                finish(state, view, g, hook, changes);
502            }
503        }
504        Gesture::Cancelled => {
505            if let Some(g) = grab.take() {
506                *view = g.start;
507            }
508        }
509    }
510    if response.clicked()
511        && let Some(g) = grab.take()
512    {
513        finish(state, view, g, hook, changes);
514    }
515    if response.double_clicked() {
516        grab = None;
517        apply(state, view, View::fit(), Cause::Reset, true, hook, changes);
518    }
519    // The wheel zooms around the view's centre, a ladder step a notch.
520    if response.hovered() {
521        let wheel: f32 = ui.input(|i| {
522            i.events
523                .iter()
524                .filter_map(|e| match e {
525                    egui::Event::MouseWheel { delta, .. } => Some(delta.y),
526                    _ => None,
527                })
528                .sum()
529        });
530        if wheel != 0.0 {
531            let f: fn(f64) -> f64 = if wheel > 0.0 {
532                view::zoom_in
533            } else {
534                view::zoom_out
535            };
536            if let Some(to) = zoomed(Some(m), f) {
537                apply(state, view, to, Cause::Wheel, true, hook, changes);
538            }
539            ui.input_mut(|i| {
540                i.smooth_scroll_delta = Vec2::ZERO;
541                i.events
542                    .retain(|e| !matches!(e, egui::Event::MouseWheel { .. }));
543            });
544        }
545    }
546    if response.has_focus() {
547        change::lock_arrows(ui, response.id);
548        let [x, y] = change::arrows(ui);
549        if x != 0.0 || y != 0.0 {
550            // A tenth of the part in view per press (Shift: all of it).
551            let span = visible.map_or([image[0], image[1]], |v| [v[2] - v[0], v[3] - v[1]]);
552            let s = f64::from(change::scale(ui)) / 10.0;
553            let c = [
554                m.center[0] + f64::from(x) * span[0] * s,
555                m.center[1] - f64::from(y) * span[1] * s,
556            ];
557            apply(state, view, at_center(c), Cause::Key, true, hook, changes);
558        }
559        let key = |k: Key| ui.input(|i| i.key_pressed(k));
560        let to = if key(Key::Plus) || key(Key::Equals) {
561            zoomed(Some(m), view::zoom_in)
562        } else if key(Key::Minus) {
563            zoomed(Some(m), view::zoom_out)
564        } else if key(Key::Num0) {
565            Some(View::fit())
566        } else {
567            None
568        };
569        if let Some(to) = to {
570            apply(state, view, to, Cause::Key, true, hook, changes);
571        }
572    }
573    match grab {
574        Some(g) => grab_id.set(ui.ctx(), g),
575        None => {
576            grab_id.remove(ui.ctx());
577        }
578    }
579}
580
581/// A drag's end: one done change from the view before it; a veto puts
582/// it back.
583fn finish(
584    state: &mut ViewportState,
585    view: &mut View,
586    g: Grab,
587    hook: &mut Option<Hook<'_, View>>,
588    changes: &mut Vec<Change<View>>,
589) {
590    if g.start == *view {
591        return;
592    }
593    let proposed = Change {
594        from: g.start,
595        to: *view,
596        cause: g.cause,
597        done: true,
598    };
599    match change::decide(hook, proposed) {
600        Some(c) => {
601            if c.to != *view {
602                state.propose(view, c.to);
603            }
604            changes.push(Change { to: *view, ..c });
605        }
606        None => *view = g.start,
607    }
608}
609
610/// The frame of the part in view (`visible`, in image pixels) on screen.
611fn frame_rect(fit: Rect, v: [f64; 4], scale: f64) -> Rect {
612    let s = scale as f32;
613    Rect::from_min_max(
614        pos2(fit.left() + v[0] as f32 * s, fit.top() + v[1] as f32 * s),
615        pos2(fit.left() + v[2] as f32 * s, fit.top() + v[3] as f32 * s),
616    )
617}
618
619/// The image, the veil over what is out of view, the frame.
620fn paint(
621    ui: &Ui,
622    rect: Rect,
623    fit: Rect,
624    response: &Response,
625    texture: Option<TextureId>,
626    m: Option<Mapping>,
627    scale: f64,
628) {
629    if !ui.is_rect_visible(rect) {
630        return;
631    }
632    let t = NavigatorTokens::of(ui.ctx());
633    let tokens = Tokens::of(ui.ctx());
634    let painter = ui.painter_at(rect);
635    painter.rect_filled(rect, tokens.radius.widget, t.background);
636    if let Some(tex) = texture {
637        painter.image(
638            tex,
639            fit,
640            Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
641            Color32::WHITE,
642        );
643    }
644    if let Some(v) = m.and_then(|m| m.visible()) {
645        let frame = frame_rect(fit, v, scale);
646        // The veil: four bands around the frame.
647        let veil = t.veil.gamma_multiply(0.6);
648        for band in [
649            Rect::from_min_max(fit.min, pos2(fit.right(), frame.top())),
650            Rect::from_min_max(pos2(fit.left(), frame.bottom()), fit.max),
651            Rect::from_min_max(
652                pos2(fit.left(), frame.top()),
653                pos2(frame.left(), frame.bottom()),
654            ),
655            Rect::from_min_max(
656                pos2(frame.right(), frame.top()),
657                pos2(fit.right(), frame.bottom()),
658            ),
659        ] {
660            if band.is_positive() {
661                painter.add(Shape::rect_filled(band, 0.0, veil));
662            }
663        }
664        painter.rect_stroke(frame, 0.0, Stroke::new(1.5, t.frame), StrokeKind::Inside);
665    }
666    if response.has_focus() {
667        egui_pop_core::focus::own_ring(&response.ctx, response.id);
668    }
669    if egui_pop_core::focus::shows_ring(response) {
670        painter.rect_stroke(
671            rect,
672            tokens.radius.widget,
673            Stroke::new(2.0, tokens.focus_ring),
674            StrokeKind::Inside,
675        );
676    }
677}
678
679#[cfg(test)]
680mod tests {
681    use super::*;
682
683    #[test]
684    fn a_percent_has_a_decimal_only_when_small_and_not_whole() {
685        let ctx = egui::Context::default();
686        assert_eq!(percent_text(&ctx, 100.0), "100");
687        assert_eq!(percent_text(&ctx, 100.0 / 3.0), "33");
688        assert_eq!(percent_text(&ctx, 100.0 / 12.0), "8.3");
689        assert_eq!(percent_text(&ctx, 5.0), "5");
690    }
691}