Skip to main content

egui_pop_views/library/
compare.rs

1//! One surface for one to many images: one image is a loupe (the whole
2//! surface), several are a survey, side by side in a grid that grows with
3//! their count (four in a square, six in three columns), with their zoom
4//! and pan synced (an option), an active image and a "best" marker.
5//!
6//! Each pane is an image canvas with the image viewport's own gestures,
7//! implemented once (`egui_pop_core::pointer::view`) and read from the
8//! pointer profile in force: the wheel, a scroll and a pinch zoom around
9//! the pointer or pan (the wheel alone zooms with darktable's profile,
10//! Alt and the wheel with Photoshop's, where Ctrl and the wheel pan
11//! sideways, Ctrl and the wheel with the default one), a drag pans (any
12//! drag with Space held), a click and a double click run the profile's
13//! view action (darktable's middle click cycles 100 %, 200 % and fit;
14//! its double click asks to leave, [`Intent::Leave`]), and with the
15//! keyboard `+` and `-` step the zoom, `0` fits, `1` shows 100 % and `2`
16//! 200 % in the active pane. The zoom counts physical pixels per image
17//! pixel as in the viewport ([`View`]): it goes below fit and the wheel
18//! stops at 100 %. Synced, every pane shows the same [`View`], its centre
19//! taken to the same place of each photo, whatever its size.
20//!
21//! The application owns the list of images: the surface says what the
22//! user asked for, as [`Intent`]s in [`CompareOutput::intents`]: a pane
23//! made active (a click, the arrow keys, the keyboard focus), images
24//! dropped on the surface to add at a place, a pane taken out (its close
25//! button, Delete or Backspace on the active pane, a pane dragged out and
26//! let go over nothing), a pane dragged to another place. Drops go
27//! through the application's drag session (`egui_pop_api::bus::drag`,
28//! feature `api`), across windows too, with the payload the application
29//! names ([`CompareView::carry`]). The images come from the library's
30//! [`ThumbSource`]; the application says which one is the best and hears
31//! when the user marks another ([`CompareOutput::best`]).
32//!
33//! ```
34//! use egui_pop_views::library::compare::{CompareState, CompareView, Intent, Pane};
35//! use egui_pop_views::library::grid::{Thumb, ThumbSource};
36//!
37//! struct Thumbs;
38//!
39//! impl ThumbSource<u64> for Thumbs {
40//!     fn thumb(&self, _: &u64, _: u32) -> Thumb {
41//!         Thumb::Pending { average: None }
42//!     }
43//! }
44//!
45//! struct Compared {
46//!     keys: Vec<u64>,
47//!     active: Option<u64>,
48//!     best: Option<u64>,
49//! }
50//!
51//! fn ui(ui: &mut egui::Ui, state: &mut CompareState, c: &mut Compared) {
52//!     let panes: Vec<Pane<u64>> = c
53//!         .keys
54//!         .iter()
55//!         .map(|k| Pane::new(*k, format!("IMG_{k:04}")))
56//!         .collect();
57//!     let out = CompareView::new("compare")
58//!         .best(c.best)
59//!         .active(c.active)
60//!         .removable(true)
61//!         .show(ui, state, &panes, &Thumbs);
62//!     if let Some(key) = out.best {
63//!         c.best = Some(key);
64//!     }
65//!     for intent in out.intents {
66//!         match intent {
67//!             Intent::Active { key } => c.active = Some(key),
68//!             Intent::Remove { key } => {
69//!                 if let Some(i) = c.keys.iter().position(|k| *k == key) {
70//!                     c.keys.remove(i);
71//!                     state.removed(i);
72//!                 }
73//!             }
74//!             _ => {}
75//!         }
76//!     }
77//! }
78//! ```
79
80use egui::{
81    Align2, Color32, EventFilter, Id, Key as EKey, Rect, Response, Role, Sense, Stroke, StrokeKind,
82    TextStyle, Ui, Vec2, WidgetInfo, pos2, vec2,
83};
84use egui_pop_core::icon::Icon;
85use egui_pop_core::kit::{self, Corners, Kit, KitCx, Part, State};
86use egui_pop_core::placeholder::SkeletonTokens;
87use egui_pop_core::pointer::view::{
88    self as canvas, Cause, GestureState, Mapping, Phase, View, Zoom, ZoomPan,
89};
90use egui_pop_core::pointer::{DragKind, drag_cursor};
91use egui_pop_core::strings::{tr, tr_args};
92use egui_pop_core::theme::Tokens;
93
94use super::grid::{Thumb, ThumbSource};
95use super::paint::{self, LibraryTokens};
96use crate::select::Key;
97use crate::strings as s;
98
99/// How many panes a comparison shows unless [`CompareView::max_panes`]
100/// says otherwise: four, in a square.
101pub const MAX_PANES: usize = 4;
102/// The most panes a comparison can show ([`CompareView::max_panes`]).
103pub const PANE_LIMIT: usize = 16;
104/// One image to compare.
105#[derive(Clone, Debug, PartialEq)]
106pub struct Pane<K> {
107    pub key: K,
108    pub label: String,
109    /// The image's size in pixels, what 100 % shows one screen pixel per
110    /// pixel of ([`Pane::size`]); unknown, the thumbnail's.
111    pub size: Option<[u32; 2]>,
112}
113
114impl<K> Pane<K> {
115    pub fn new(key: K, label: impl Into<String>) -> Pane<K> {
116        Pane {
117            key,
118            label: label.into(),
119            size: None,
120        }
121    }
122
123    /// The image's size in pixels (its zoom is counted against it; by
124    /// default the thumbnail's).
125    pub fn size(mut self, size: [u32; 2]) -> Pane<K> {
126        self.size = Some(size);
127        self
128    }
129}
130
131/// The view all panes share when synced, and the size of the image it
132/// was set on (its centre goes to the same place of each photo).
133#[derive(Clone, Copy, Debug, Default, PartialEq)]
134struct Shared {
135    view: View,
136    size: Option<[f64; 2]>,
137}
138
139/// The comparison's state: one view shared by every pane when synced,
140/// else one per pane, by the pane's place; and each pane's gestures.
141#[derive(Clone, Debug, Default)]
142pub struct CompareState {
143    shared: Shared,
144    panes: Vec<View>,
145    gestures: Vec<GestureState>,
146}
147
148impl CompareState {
149    pub fn new() -> Self {
150        Self::default()
151    }
152
153    /// Pane `i`'s view (the shared one when synced, on the image it was
154    /// last changed on).
155    pub fn view(&self, i: usize, synced: bool) -> View {
156        if synced {
157            self.shared.view
158        } else {
159            self.panes.get(i).copied().unwrap_or_default()
160        }
161    }
162
163    /// Sets pane `i`'s view (the shared one when synced: every pane then
164    /// shows it as it is).
165    pub fn set_view(&mut self, i: usize, synced: bool, view: View) {
166        if synced {
167            self.shared = Shared { view, size: None };
168        } else {
169            *self.view_mut(i) = view;
170        }
171    }
172
173    /// Pane `i`'s view on its image of `size` pixels: the shared one
174    /// with its centre at the same place of this photo.
175    fn view_on(&self, i: usize, synced: bool, size: [f64; 2]) -> View {
176        if !synced {
177            return self.view(i, false);
178        }
179        let Shared { view, size: from } = self.shared;
180        match (view.zoom, from) {
181            (Zoom::Px(_), Some(from)) if from != size && from[0] > 0.0 && from[1] > 0.0 => View {
182                zoom: view.zoom,
183                center: [
184                    view.center[0] / from[0] * size[0],
185                    view.center[1] / from[1] * size[1],
186                ],
187            },
188            _ => view,
189        }
190    }
191
192    /// Pane `i` changed its view, on its image of `size` pixels.
193    fn store(&mut self, i: usize, synced: bool, view: View, size: [f64; 2]) {
194        if synced {
195            self.shared = Shared {
196                view,
197                size: Some(size),
198            };
199        } else {
200            *self.view_mut(i) = view;
201        }
202    }
203
204    fn gesture_mut(&mut self, i: usize) -> &mut GestureState {
205        let i = i.min(PANE_LIMIT - 1);
206        if self.gestures.len() <= i {
207            self.gestures.resize(i + 1, GestureState::default());
208        }
209        &mut self.gestures[i]
210    }
211
212    /// Every pane back to fit.
213    pub fn reset(&mut self) {
214        *self = Self::default();
215    }
216
217    /// Pane `i` was taken out of the list: the views of those after it
218    /// follow their panes.
219    pub fn removed(&mut self, i: usize) {
220        if i < self.panes.len() {
221            self.panes.remove(i);
222        }
223        if i < self.gestures.len() {
224            self.gestures.remove(i);
225        }
226    }
227
228    /// A pane was put in the list at `i`, at fit: the views of those
229    /// from there on follow their panes.
230    pub fn inserted(&mut self, i: usize) {
231        if i < self.panes.len() {
232            self.panes.insert(i, View::default());
233        }
234        if i < self.gestures.len() {
235            self.gestures.insert(i, GestureState::default());
236        }
237    }
238
239    /// The pane at `from` moved to `to` (its place once moved).
240    pub fn moved(&mut self, from: usize, to: usize) {
241        let view = self.view(from, false);
242        self.removed(from);
243        self.inserted(to);
244        if view != View::default() {
245            *self.view_mut(to) = view;
246        }
247    }
248
249    fn view_mut(&mut self, i: usize) -> &mut View {
250        let i = i.min(PANE_LIMIT - 1);
251        if self.panes.len() <= i {
252            self.panes.resize(i + 1, View::default());
253        }
254        &mut self.panes[i]
255    }
256}
257
258/// What the user asked of the comparison's list, which the application
259/// owns: it edits its list (or refuses), and shows it again.
260#[derive(Clone, Debug, PartialEq)]
261#[non_exhaustive]
262pub enum Intent<K> {
263    /// This image becomes the active one: a click on its pane, the arrow
264    /// keys, the keyboard focus on its pane.
265    Active { key: K },
266    /// These images, dropped on the surface, go in before the pane at
267    /// `at` (the count of panes: after the last one). Images already
268    /// compared are left out.
269    Add { keys: Vec<K>, at: usize },
270    /// The pointer profile's "leave the view" on this image's pane
271    /// (darktable's double click): the application may leave the
272    /// comparison, as it leaves the image viewport.
273    Leave { key: K },
274    /// This image goes out of the comparison: its pane's close button,
275    /// Delete or Backspace on the active pane, its pane dragged out and
276    /// let go over nothing.
277    Remove { key: K },
278    /// This image's pane, dragged and let go on the surface, goes to
279    /// `to` (its place once moved).
280    Move { key: K, to: usize },
281}
282
283/// What [`CompareView::show`] returns.
284#[derive(Debug)]
285#[non_exhaustive]
286pub struct CompareOutput<K> {
287    pub response: Response,
288    /// The image the user marked as the best this pass.
289    pub best: Option<K>,
290    /// What the user asked of the list this pass, in order.
291    pub intents: Vec<Intent<K>>,
292    /// Where each pane was drawn, in the order of the panes shown.
293    pub panes: Vec<Rect>,
294}
295
296/// The comparison view.
297#[must_use = "show it with `show`"]
298pub struct CompareView<K> {
299    id: String,
300    synced: bool,
301    best: Option<K>,
302    active: Option<K>,
303    height: Option<f32>,
304    max_panes: usize,
305    removable: bool,
306    #[cfg(feature = "api")]
307    carry: Option<carry::Carry<K>>,
308}
309
310impl<K: std::fmt::Debug> std::fmt::Debug for CompareView<K> {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        let mut d = f.debug_struct("CompareView");
313        d.field("id", &self.id)
314            .field("synced", &self.synced)
315            .field("best", &self.best)
316            .field("active", &self.active)
317            .field("height", &self.height)
318            .field("max_panes", &self.max_panes)
319            .field("removable", &self.removable);
320        #[cfg(feature = "api")]
321        d.field("carry", &self.carry.as_ref().map(|c| c.kind));
322        d.finish()
323    }
324}
325
326/// The panes' places for `n` panes in `rect`, `gap` apart, row by row:
327/// one fills it, two and three side by side, four in a square, more in
328/// the grid that shows a 3:2 image the largest.
329pub fn layout(n: usize, rect: Rect, gap: f32) -> Vec<Rect> {
330    let (cols, rows) = grid(n, rect.size(), gap);
331    let pw = ((rect.width() - gap * (cols as f32 - 1.0)) / cols as f32).max(0.0);
332    let ph = ((rect.height() - gap * (rows as f32 - 1.0)) / rows as f32).max(0.0);
333    (0..n)
334        .map(|i| {
335            let (c, r) = (i % cols, i / cols);
336            Rect::from_min_size(
337                rect.min + vec2(c as f32 * (pw + gap), r as f32 * (ph + gap)),
338                vec2(pw, ph),
339            )
340        })
341        .collect()
342}
343
344/// The grid's columns and rows for `n` panes.
345fn grid(n: usize, size: Vec2, gap: f32) -> (usize, usize) {
346    match n {
347        0 | 1 => (1, 1),
348        2 => (2, 1),
349        3 => (3, 1),
350        4 => (2, 2),
351        _ => {
352            let shown = |cols: usize| {
353                let rows = n.div_ceil(cols);
354                let w = (size.x - gap * (cols as f32 - 1.0)) / cols as f32;
355                let h = (size.y - gap * (rows as f32 - 1.0)) / rows as f32;
356                // A 3:2 image fitted in the pane.
357                let (iw, ih) = (w.min(h * 1.5), h.min(w / 1.5));
358                iw.max(0.0) * ih.max(0.0)
359            };
360            let mut best = 2;
361            for cols in 3..=n {
362                if shown(cols) > shown(best) {
363                    best = cols;
364                }
365            }
366            (best, n.div_ceil(best))
367        }
368    }
369}
370
371impl<K: Key> CompareView<K> {
372    pub fn new(id: impl Into<String>) -> Self {
373        Self {
374            id: id.into(),
375            synced: true,
376            best: None,
377            active: None,
378            height: None,
379            max_panes: MAX_PANES,
380            removable: false,
381            #[cfg(feature = "api")]
382            carry: None,
383        }
384    }
385
386    /// Zoom and pan synced across the panes (on by default).
387    pub fn synced(mut self, on: bool) -> Self {
388        self.synced = on;
389        self
390    }
391
392    /// The image marked as the best.
393    pub fn best(mut self, key: Option<K>) -> Self {
394        self.best = key;
395        self
396    }
397
398    /// The active image, outlined; the arrow keys move from it, Delete
399    /// takes it out ([`CompareView::removable`]).
400    pub fn active(mut self, key: Option<K>) -> Self {
401        self.active = key;
402        self
403    }
404
405    /// Its height (default: what is available).
406    pub fn height(mut self, height: f32) -> Self {
407        self.height = Some(height);
408        self
409    }
410
411    /// How many panes it shows at most ([`MAX_PANES`] by default, at
412    /// most [`PANE_LIMIT`]); a drop that would go past it is refused.
413    pub fn max_panes(mut self, n: usize) -> Self {
414        self.max_panes = n.clamp(1, PANE_LIMIT);
415        self
416    }
417
418    /// Panes the user can take out (off by default): a close button on
419    /// each, Delete and Backspace on the active one, each an
420    /// [`Intent::Remove`].
421    pub fn removable(mut self, on: bool) -> Self {
422        self.removable = on;
423        self
424    }
425
426    /// Images carried in and out by the application's drag session
427    /// (`egui_pop_api::bus::drag`), across its windows too: a drag of a
428    /// `T` let go on the surface adds the images `unpack` finds in it
429    /// ([`Intent::Add`], none: refused), a pane's caption drags its image
430    /// out as `pack` makes it, under `kind` (`photos`), and a pane let go
431    /// over nothing goes out ([`Intent::Remove`]), let go on the surface
432    /// moves ([`Intent::Move`]).
433    #[cfg(feature = "api")]
434    pub fn carry<T: std::any::Any + Send + Sync>(
435        mut self,
436        kind: &'static str,
437        pack: fn(Vec<K>) -> T,
438        unpack: fn(&T) -> Option<Vec<K>>,
439    ) -> Self {
440        self.carry = Some(carry::Carry::new(kind, pack, unpack));
441        self
442    }
443
444    pub fn show(
445        self,
446        ui: &mut Ui,
447        state: &mut CompareState,
448        panes: &[Pane<K>],
449        source: &dyn ThumbSource<K>,
450    ) -> CompareOutput<K> {
451        let t = Tokens::of(ui.ctx());
452        let lt = LibraryTokens::of(ui.ctx());
453        let kit = Kit::of(ui.ctx());
454        let id = Id::unique(("egui_pop_views::compare", &self.id));
455        let panes = &panes[..panes.len().min(self.max_panes)];
456        let height = self
457            .height
458            .unwrap_or_else(|| ui.available_height())
459            .max(80.0);
460        let (rect, response) =
461            ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
462        // The surface takes the keyboard: the arrows move the active
463        // pane, Delete takes it out.
464        let surface = ui.interact(rect, id, Sense::focusable_noninteractive());
465        let name = tr(ui.ctx(), &s::COMPARE);
466        egui_pop_core::a11y::name(&surface, Role::List, &name);
467        let gap = t.space.s;
468        let areas = layout(panes.len(), rect, gap);
469        let active = self
470            .active
471            .as_ref()
472            .and_then(|a| panes.iter().position(|p| p.key == *a));
473        let small = TextStyle::Small.resolve(ui.style());
474        // The image canvas's gestures, the image viewport's own.
475        let gestures = canvas::canvas_gestures(ui.ctx());
476        let ppp = ui.ctx().pixels_per_point();
477        // Each pane's image size and room, for the keys after the panes.
478        let mut rooms: Vec<([f64; 2], Rect)> = Vec::with_capacity(panes.len());
479        let mut best = None;
480        let mut intents = Vec::new();
481        let mut focus_within = surface.has_focus();
482        #[cfg(feature = "api")]
483        let carrying: Option<K> = ui
484            .data(|d| d.get_temp::<String>(id.with("carrying")))
485            .and_then(|k| serde_json::from_str(&k).ok());
486        if panes.is_empty() {
487            ui.painter().text(
488                rect.center(),
489                Align2::CENTER_CENTER,
490                tr(ui.ctx(), &s::COMPARE_EMPTY),
491                TextStyle::Body.resolve(ui.style()),
492                t.text.muted,
493            );
494        }
495        for (i, (pane, &area)) in panes.iter().zip(&areas).enumerate() {
496            let painter = ui.painter_at(area);
497            let is_best = self.best.as_ref() == Some(&pane.key);
498            let is_active = active == Some(i);
499            let cx = KitCx {
500                painter: &painter,
501                ppp: ui.ctx().pixels_per_point(),
502            };
503            let pane_state = State::REST.with(State::SELECTED, is_best);
504            kit.compare_pane.paint(
505                &cx,
506                &Part {
507                    rect: area,
508                    room: area,
509                    state: pane_state,
510                    label: None,
511                },
512            );
513            let pane_box = *kit.compare_pane.style(pane_state);
514            let px = (area.width().max(area.height()) * ppp) as u32;
515            let thumb = source.thumb(&pane.key, px);
516            let room = area.shrink(t.space.xs);
517            // The image's size: given, else the thumbnail's; unknown (on
518            // its way), a 3:2 placeholder's fitted in the pane, so the
519            // gestures already work.
520            let known = pane.size.or(match thumb {
521                Thumb::Ready { size, .. } => Some(size),
522                _ => None,
523            });
524            let image = match known {
525                Some(s) => [f64::from(s[0]), f64::from(s[1])],
526                None => {
527                    let fit = crate::library::fitted(room, [3, 2]).size() * ppp;
528                    [f64::from(fit.x.max(1.0)), f64::from(fit.y.max(1.0))]
529                }
530            };
531            // A pane is an image canvas: the image viewport's gestures,
532            // on its view.
533            let pr = ui.interact(area, id.with(("pane", i)), Sense::click_and_drag());
534            drag_cursor(&pr, DragKind::Pan);
535            let pane_name = pane.label.clone();
536            pr.widget_info(move || {
537                WidgetInfo::selected(Role::ListItem, true, is_active, &pane_name)
538            });
539            focus_within |= pr.has_focus();
540            if (pr.clicked() || pr.gained_focus()) && !is_active {
541                intents.push(Intent::Active {
542                    key: pane.key.clone(),
543                });
544            }
545            if pr.clicked() {
546                surface.request_focus();
547            }
548            rooms.push((image, room));
549            let mut target = PaneCanvas::new(state, i, self.synced, image, room, ppp);
550            let pan_key = canvas::pan_key_held(ui, &pr, &gestures);
551            canvas::pan(ui, &pr, &gestures, pan_key, &mut target);
552            canvas::double_click(ui, &pr, &gestures, &mut target);
553            if !pan_key {
554                canvas::click(ui, &pr, &gestures, &mut target);
555            }
556            canvas::wheel(ui, &pr, &gestures, &mut target);
557            let (m, leave) = target.finish();
558            if leave {
559                intents.push(Intent::Leave {
560                    key: pane.key.clone(),
561                });
562            }
563            let drawn = m.image_rect_to_screen([0.0, 0.0, image[0], image[1]]);
564            match thumb {
565                Thumb::Ready { texture, .. } => {
566                    painter.image(
567                        texture,
568                        drawn,
569                        Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
570                        Color32::WHITE,
571                    );
572                }
573                Thumb::Pending { average } => {
574                    let fill = average.unwrap_or_else(|| SkeletonTokens::of(ui.ctx()).fill);
575                    painter.rect_filled(drawn, 0.0, fill);
576                }
577                Thumb::Failed => {
578                    let side = t.size.icon_panel;
579                    Icon::Warning.paint(
580                        &painter,
581                        Rect::from_center_size(area.center(), vec2(side, side)),
582                        t.text.muted,
583                    );
584                }
585            }
586            // The caption: the image's name, and the handle a pane is
587            // carried out by (with a drag session).
588            let caption = Rect::from_min_max(
589                pos2(area.left(), area.bottom() - small.size - 2.0 * t.space.s),
590                area.right_bottom(),
591            );
592            painter.text(
593                area.left_bottom() + vec2(t.space.s, -t.space.s),
594                Align2::LEFT_BOTTOM,
595                &pane.label,
596                small.clone(),
597                pane_box.text,
598            );
599            #[cfg(feature = "api")]
600            if let Some(c) = &self.carry {
601                let hr = ui.interact(caption, id.with(("carry", i)), Sense::drag());
602                drag_cursor(&hr, DragKind::Carry);
603                let hname = tr_args(ui.ctx(), &s::ITEM_MOVE, &[("name", &pane.label)]);
604                hr.widget_info(move || WidgetInfo::labeled(Role::Button, true, &hname));
605                if hr.drag_started() {
606                    (c.start)(ui.ctx(), vec![pane.key.clone()]);
607                    let key = serde_json::to_string(&pane.key).unwrap_or_default();
608                    ui.data_mut(|d| d.insert_temp(id.with("carrying"), key));
609                }
610                if hr.dragged() {
611                    egui_pop_core::pointer::hold_drag_cursor(ui.ctx(), DragKind::Carry);
612                }
613                if carrying.as_ref() == Some(&pane.key) {
614                    // The pane being carried, dimmed.
615                    painter.rect_filled(area, 0.0, t.surface.canvas.gamma_multiply(0.6));
616                }
617            }
618            #[cfg(not(feature = "api"))]
619            let _ = caption;
620            // The best marker (with two panes or more): a button in the
621            // corner, the outline when set.
622            let side = 28.0;
623            let mut corner = area.right_top() + vec2(-side - t.space.xs, t.space.xs);
624            if panes.len() > 1 {
625                let b = Rect::from_min_size(corner, vec2(side, side));
626                corner.x -= side + t.space.xs;
627                let br = ui.interact(b, id.with(("best", i)), Sense::click());
628                let badge = &kit.thumb_overlay_badge;
629                badge.paint(
630                    &cx,
631                    &Part {
632                        rect: b,
633                        room: b,
634                        state: State::REST,
635                        label: None,
636                    },
637                );
638                // The best image's star is its pane's ring colour.
639                let best_color = kit.compare_pane.style(State::SELECTED).ring_color;
640                paint::star(
641                    &painter,
642                    b.center(),
643                    9.0,
644                    is_best.then_some(best_color),
645                    if br.hovered() {
646                        badge.style(State::REST).text
647                    } else {
648                        lt.star_empty
649                    },
650                );
651                let bname = tr(ui.ctx(), &s::MARK_BEST);
652                br.widget_info(move || WidgetInfo::selected(Role::CheckBox, true, is_best, &bname));
653                if br.clicked() && !is_best {
654                    best = Some(pane.key.clone());
655                }
656            }
657            if self.removable {
658                let x = Rect::from_min_size(corner, vec2(side, side));
659                let xr = ui.interact(x, id.with(("remove", i)), Sense::click());
660                let badge = &kit.thumb_overlay_badge;
661                badge.paint(
662                    &cx,
663                    &Part {
664                        rect: x,
665                        room: x,
666                        state: State::REST,
667                        label: None,
668                    },
669                );
670                Icon::Close.paint(
671                    &painter,
672                    Rect::from_center_size(x.center(), vec2(14.0, 14.0)),
673                    if xr.hovered() {
674                        badge.style(State::REST).text
675                    } else {
676                        lt.star_empty
677                    },
678                );
679                let xname = tr_args(ui.ctx(), &s::COMPARE_REMOVE, &[("name", &pane.label)]);
680                xr.widget_info(move || WidgetInfo::labeled(Role::Button, true, &xname));
681                if xr.clicked() {
682                    intents.push(Intent::Remove {
683                        key: pane.key.clone(),
684                    });
685                }
686            }
687            // The ring again, over the image.
688            kit::paint_ring(&cx, area, &pane_box, Corners::All);
689            if is_active && panes.len() > 1 {
690                painter.rect_stroke(
691                    area.shrink(1.0),
692                    0.0,
693                    Stroke::new(2.0, t.focus_ring),
694                    StrokeKind::Inside,
695                );
696            }
697        }
698        if focus_within {
699            // The zoom keys, on the active pane (the first without one).
700            let at = active.unwrap_or(0);
701            if let Some((image, room)) = rooms.get(at) {
702                let mut target = PaneCanvas::new(state, at, self.synced, *image, *room, ppp);
703                canvas::keys(ui, &gestures, false, &mut target);
704                let _ = target.finish();
705            }
706            keys(ui, id, panes, &areas, active, self.removable, &mut intents);
707        }
708        #[cfg(feature = "api")]
709        if let Some(c) = &self.carry {
710            carry::surface(
711                ui,
712                c,
713                &self.id,
714                id,
715                rect,
716                &areas,
717                panes,
718                self.max_panes,
719                carrying,
720                &mut intents,
721            );
722        }
723        if !intents.is_empty() {
724            ui.ctx().request_repaint();
725        }
726        CompareOutput {
727            response,
728            best,
729            intents,
730            panes: areas,
731        }
732    }
733}
734
735/// The surface's keys, while it or one of its panes has the keyboard:
736/// the arrows, Home and End move the active pane; Delete and Backspace
737/// take it out.
738fn keys<K: Key>(
739    ui: &Ui,
740    id: Id,
741    panes: &[Pane<K>],
742    areas: &[Rect],
743    active: Option<usize>,
744    removable: bool,
745    intents: &mut Vec<Intent<K>>,
746) {
747    if panes.is_empty() {
748        return;
749    }
750    // The arrows are the surface's, whether it or a pane has the focus.
751    ui.memory_mut(|m| {
752        m.set_focus_lock_filter(
753            m.focused().unwrap_or(id),
754            EventFilter {
755                horizontal_arrows: true,
756                vertical_arrows: true,
757                ..Default::default()
758            },
759        )
760    });
761    let n = panes.len();
762    let at = active.unwrap_or(0);
763    let cols = areas
764        .iter()
765        .take_while(|r| r.top() == areas[0].top())
766        .count()
767        .max(1);
768    let moved = ui.input_mut(|i| {
769        let none = egui::Modifiers::NONE;
770        if i.consume_key(none, EKey::ArrowLeft) {
771            Some(at.saturating_sub(1))
772        } else if i.consume_key(none, EKey::ArrowRight) {
773            Some((at + 1).min(n - 1))
774        } else if i.consume_key(none, EKey::ArrowUp) {
775            Some(at.saturating_sub(cols))
776        } else if i.consume_key(none, EKey::ArrowDown) {
777            Some((at + cols).min(n - 1))
778        } else if i.consume_key(none, EKey::Home) {
779            Some(0)
780        } else if i.consume_key(none, EKey::End) {
781            Some(n - 1)
782        } else {
783            None
784        }
785    });
786    if let Some(to) = moved
787        && (active != Some(to))
788    {
789        intents.push(Intent::Active {
790            key: panes[to].key.clone(),
791        });
792    }
793    if removable
794        && let Some(a) = active
795        && ui.input_mut(|i| {
796            i.consume_key(egui::Modifiers::NONE, EKey::Delete)
797                | i.consume_key(egui::Modifiers::NONE, EKey::Backspace)
798        })
799    {
800        intents.push(Intent::Remove {
801            key: panes[a].key.clone(),
802        });
803    }
804}
805
806/// Images carried in and out of the surface by the application's drag
807/// session.
808#[cfg(feature = "api")]
809mod carry {
810    use std::any::Any;
811
812    use egui::{Context, Id, Pos2, Rect, Stroke, StrokeKind, Ui};
813    use egui_pop_api::bus::drag::{self, End, Seen};
814    use egui_pop_core::strings::tr;
815    use egui_pop_core::theme::Tokens;
816
817    use super::{Intent, Pane};
818    use crate::select::Key;
819    use crate::strings as s;
820
821    /// Where images let go at `at` go in among `panes`: before the pane under
822    /// the pointer when on its left half, else after it; off every pane, by
823    /// the nearest one.
824    fn insertion(panes: &[Rect], at: Pos2) -> usize {
825        let Some((i, r)) = panes.iter().enumerate().min_by(|(_, a), (_, b)| {
826            a.distance_sq_to_pos(at)
827                .total_cmp(&b.distance_sq_to_pos(at))
828        }) else {
829            return 0;
830        };
831        if at.x < r.center().x { i } else { i + 1 }
832    }
833
834    /// What a target sees of a drag of images, whatever the payload.
835    pub(super) enum Over<K> {
836        Nothing,
837        At { at: Pos2 },
838        Unknown,
839        Dropped(Vec<K>),
840    }
841
842    type Target<K> = Box<dyn Fn(&Context, &str, Rect, bool) -> Over<K>>;
843    type Start<K> = Box<dyn Fn(&Context, Vec<K>)>;
844    type Ended = Box<dyn Fn(&Context) -> Option<End>>;
845
846    /// The application's payload, behind closures.
847    pub(super) struct Carry<K> {
848        pub(super) kind: &'static str,
849        pub(super) start: Start<K>,
850        target: Target<K>,
851        ended: Ended,
852    }
853
854    impl<K: Key> Carry<K> {
855        pub(super) fn new<T: Any + Send + Sync>(
856            kind: &'static str,
857            pack: fn(Vec<K>) -> T,
858            unpack: fn(&T) -> Option<Vec<K>>,
859        ) -> Self {
860            Carry {
861                kind,
862                start: Box::new(move |ctx, keys| drag::start(ctx, kind, pack(keys))),
863                target: Box::new(move |ctx, id, rect, full| {
864                    let refusal = |p: &T| match unpack(p) {
865                        None => Some(tr(ctx, &s::COMPARE_NOT_IMAGES)),
866                        Some(_) if full => Some(tr(ctx, &s::COMPARE_FULL)),
867                        Some(_) => None,
868                    };
869                    match drag::target::<T>(ctx, id, rect, refusal) {
870                        Seen::Over { at, .. } => Over::At { at },
871                        Seen::Unknown(_) => Over::Unknown,
872                        Seen::Dropped(p) => unpack(&p).map_or(Over::Nothing, Over::Dropped),
873                        _ => Over::Nothing,
874                    }
875                }),
876                ended: Box::new(|ctx| drag::take_ended::<T>(ctx).map(|(_, end)| end)),
877            }
878        }
879    }
880
881    /// The surface as a drop target, and the end of a pane carried out.
882    #[allow(
883        clippy::too_many_arguments,
884        reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
885    )]
886    pub(super) fn surface<K: Key>(
887        ui: &Ui,
888        c: &Carry<K>,
889        name: &str,
890        id: Id,
891        rect: Rect,
892        areas: &[Rect],
893        panes: &[Pane<K>],
894        max: usize,
895        carrying: Option<K>,
896        intents: &mut Vec<Intent<K>>,
897    ) {
898        let ctx = ui.ctx();
899        let t = Tokens::of(ctx);
900        let full = carrying.is_none() && panes.len() >= max;
901        let at_id = id.with("over_at");
902        match (c.target)(ctx, name, rect, full) {
903            Over::At { at } => {
904                ui.data_mut(|d| d.insert_temp(at_id, at));
905                let painter = ui.painter();
906                painter.rect_stroke(
907                    rect,
908                    0.0,
909                    Stroke::new(2.0, t.focus_ring),
910                    StrokeKind::Inside,
911                );
912                // Where the images would go: a bar between the panes.
913                let i = insertion(areas, at);
914                let x = match areas.get(i) {
915                    // At a row's start: left of its first pane.
916                    Some(r) if i == 0 || areas[i - 1].top() != r.top() => {
917                        Some((r.left() - t.space.s / 2.0, r.y_range()))
918                    }
919                    _ => areas
920                        .get(i.wrapping_sub(1))
921                        .map(|l| (l.right() + t.space.s / 2.0, l.y_range())),
922                };
923                if let Some((x, y)) = x {
924                    painter.vline(
925                        x.clamp(rect.left() + 2.0, rect.right() - 2.0),
926                        y,
927                        Stroke::new(3.0, t.focus_ring),
928                    );
929                }
930            }
931            Over::Unknown => {
932                ui.painter().rect_stroke(
933                    rect,
934                    0.0,
935                    Stroke::new(1.0, t.focus_ring),
936                    StrokeKind::Inside,
937                );
938            }
939            Over::Dropped(keys) => {
940                let at = ui
941                    .data_mut(|d| d.remove_temp::<Pos2>(at_id))
942                    .map_or(panes.len(), |p| insertion(areas, p));
943                match &carrying {
944                    // A pane carried and let go on its own surface: moved.
945                    Some(k) if keys == [k.clone()] => {
946                        if let Some(from) = panes.iter().position(|p| p.key == *k) {
947                            let to = if at > from { at - 1 } else { at };
948                            if to != from {
949                                intents.push(Intent::Move { key: k.clone(), to });
950                            }
951                        }
952                    }
953                    _ => {
954                        let keys: Vec<K> = keys
955                            .into_iter()
956                            .filter(|k| !panes.iter().any(|p| p.key == *k))
957                            .collect();
958                        if !keys.is_empty() {
959                            intents.push(Intent::Add { keys, at });
960                        }
961                    }
962                }
963            }
964            Over::Nothing => {}
965        }
966        // A pane carried out: let go over nothing, it goes out; dropped on
967        // a target, that target has it.
968        if let Some(k) = carrying
969            && !drag::active(ctx)
970        {
971            ui.data_mut(|d| d.remove::<String>(id.with("carrying")));
972            if let Some(End::Left { .. }) = (c.ended)(ctx) {
973                drag::claim(ctx, "compare.remove");
974                intents.push(Intent::Remove { key: k });
975            }
976        }
977    }
978}
979/// One pane as an image canvas for the shared gestures: its view on its
980/// image, written back to the comparison's state when it changes.
981struct PaneCanvas<'a> {
982    state: &'a mut CompareState,
983    i: usize,
984    synced: bool,
985    view: View,
986    mapping: Mapping,
987    gesture: GestureState,
988    changed: bool,
989    leave: bool,
990}
991
992impl<'a> PaneCanvas<'a> {
993    fn new(
994        state: &'a mut CompareState,
995        i: usize,
996        synced: bool,
997        image: [f64; 2],
998        room: Rect,
999        ppp: f32,
1000    ) -> Self {
1001        let view = state.view_on(i, synced, image);
1002        let gesture = *state.gesture_mut(i);
1003        PaneCanvas {
1004            state,
1005            i,
1006            synced,
1007            view,
1008            mapping: Mapping::new(&view, image, room, ppp),
1009            gesture,
1010            changed: false,
1011            leave: false,
1012        }
1013    }
1014
1015    /// Writes the view back; the mapping it is drawn with, and whether
1016    /// the profile asked to leave.
1017    fn finish(self) -> (Mapping, bool) {
1018        *self.state.gesture_mut(self.i) = self.gesture;
1019        if self.changed {
1020            self.state
1021                .store(self.i, self.synced, self.view, self.mapping.image);
1022        }
1023        (self.mapping, self.leave)
1024    }
1025}
1026
1027impl ZoomPan for PaneCanvas<'_> {
1028    fn view(&self) -> View {
1029        self.view
1030    }
1031
1032    fn mapping(&self) -> Mapping {
1033        self.mapping
1034    }
1035
1036    fn gesture(&mut self) -> &mut GestureState {
1037        &mut self.gesture
1038    }
1039
1040    fn change(&mut self, to: View, _: Cause, phase: Phase) -> bool {
1041        if to == self.view && phase != Phase::Cancel {
1042            return false;
1043        }
1044        self.view = to;
1045        let m = self.mapping;
1046        self.mapping = Mapping::new(&to, m.image, m.rect, m.ppp);
1047        self.changed = true;
1048        true
1049    }
1050
1051    fn leave(&mut self) {
1052        self.leave = true;
1053    }
1054}