Skip to main content

egui_pop_viewport/
widget.rs

1//! The viewport widget: draws a view of an image and turns gestures into
2//! changes of the [`View`], reported as [`Signal`]s.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! The application owns the view (per window or per document) and the
8//! [`ViewportState`] (what the widget keeps between frames, its hooks
9//! included). Every change the widget makes goes through the
10//! `before_view` hook and is reported as a signal with its phase, so an
11//! application that keeps the view in a store records a pan as one
12//! gesture, and a cancelled pan as nothing.
13
14use std::collections::VecDeque;
15use std::sync::atomic::{AtomicU64, Ordering};
16use std::time::Duration;
17
18use std::sync::Arc;
19
20use egui::{
21    Color32, Id, PointerButton, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2,
22    WidgetInfo, pos2,
23};
24use egui_pop_core::kit::{Kit, KitCx, Part, State};
25
26use crate::cursor::{self, Cursor, CursorQuery, Shown, Tool};
27use crate::debug;
28use crate::display::{self, DisplayTarget, DisplayTransform, LinearSrgb, Stage};
29use crate::gestures::{self, Gestures};
30use crate::hooks::{Cause, HandleMove, Hooks, TRACE_KEPT, TraceEntry, Verdict, ViewChange};
31use crate::loupe::{self, Loupe, LoupeFrame};
32use crate::navigation::{self, NavCommand};
33use crate::overlay::{self, Handle, HandleKind, HandleState, Overlay};
34use crate::source::{Readout, Side, Stats, TileSink, TileSource};
35use crate::tiles::{self, Texture, Tiles, Transfers, UploadBudget, UploadReport};
36use crate::tokens::ViewportTokens;
37use crate::view::{self, Mapping, View, Zoom};
38use egui_pop_core::pointer::view::{self as canvas, GestureState, ZoomPan};
39
40/// Where a change stands in its gesture (shared with every image
41/// canvas, `egui_pop_core::pointer::view`).
42pub use egui_pop_core::pointer::view::Phase;
43
44/// What the viewport tells the application.
45#[derive(Clone, Debug, PartialEq)]
46pub enum Signal {
47    /// The view changed.
48    View {
49        view: View,
50        phase: Phase,
51        cause: Cause,
52    },
53    /// The window's display target changed (another monitor, another
54    /// surface format); the viewport follows it.
55    Display { target: DisplayTarget },
56    /// A handle moved: `from` is where it was when the gesture began,
57    /// `at` where it is now (image pixels). On `Cancel`, put the shape
58    /// back as it was at `Begin`.
59    Handle {
60        overlay: String,
61        handle: u32,
62        kind: HandleKind,
63        phase: Phase,
64        from: [f64; 2],
65        at: [f64; 2],
66    },
67    /// A double click on a handle: reset what it adjusts.
68    HandleReset {
69        overlay: String,
70        handle: u32,
71        kind: HandleKind,
72    },
73    /// A click on a handle (pressed and released without moving): select
74    /// what it belongs to, toggle a point's corner.
75    HandleClick {
76        overlay: String,
77        handle: u32,
78        kind: HandleKind,
79        modifiers: egui::Modifiers,
80    },
81    /// A click on an overlay's outline away from its handles: `segment`
82    /// as `overlay::hit_edge` numbers it, `at` the nearest point of the
83    /// outline (image pixels), to add a point there.
84    EdgeClick {
85        overlay: String,
86        segment: u32,
87        at: [f64; 2],
88        modifiers: egui::Modifiers,
89    },
90    /// The wheel over a handle (points, positive up): adjust what the
91    /// handle adjusts, never the zoom.
92    HandleWheel {
93        overlay: String,
94        handle: u32,
95        kind: HandleKind,
96        delta: f32,
97    },
98    /// The comparison changed: the split moved, the "before" shown or
99    /// hidden.
100    Compare { compare: Compare, phase: Phase },
101    /// The source's values under the pointer arrived.
102    Readout(Readout),
103    /// The loupe was turned on or off with its key.
104    Loupe { on: bool },
105    /// The pointer asked to leave the view (darktable's double click on
106    /// the image, back to the lighttable): the application decides what
107    /// that means; the view does not change.
108    Leave,
109    /// Tiles moved this frame: asked for, arrived, given up. `complete`
110    /// when every tile wanted is on screen.
111    Tiles {
112        requested: u64,
113        delivered: u64,
114        cancelled: u64,
115        complete: bool,
116    },
117}
118
119/// Before and after: what the viewport shows of the "before" image.
120#[derive(Clone, Copy, Debug, Default, PartialEq)]
121pub enum Compare {
122    /// The image only.
123    #[default]
124    Off,
125    /// "Before" left of the split (a fraction of the view's width),
126    /// "after" right of it; the split is dragged with its handle.
127    Split(f32),
128    /// "Before" only (a toggle, or held with the gestures' `before`
129    /// key).
130    Before,
131}
132
133/// A handle being dragged.
134#[derive(Clone, Debug)]
135struct HandleDrag {
136    overlay: String,
137    handle: Handle,
138    /// The pointer at the start, in image pixels.
139    press: [f64; 2],
140    at: [f64; 2],
141}
142
143/// What the widget keeps between frames. One per viewport; the
144/// application owns it.
145#[derive(Debug, Default)]
146pub struct ViewportState {
147    transform: Transform,
148    transform_revision: u64,
149    target: Option<DisplayTarget>,
150    resolution: Option<display::Resolution>,
151    tiles: Tiles,
152    /// This state's GPU uniforms (0 until first drawn).
153    slot: u64,
154    last_counts: [u64; 3],
155    drag: Option<HandleDrag>,
156    split_drag: Option<f32>,
157    before_held: bool,
158    /// The `before` key as last seen down, and whether its press began
159    /// a comparison (a `Begin` signalled): the hook is asked once per
160    /// press and release, a release only after a press it let through.
161    before_key: bool,
162    before_begun: bool,
163    asked_readout: Option<(Side, [i64; 2])>,
164    signalled_readout: Option<(Side, [i64; 2])>,
165    last_complete: bool,
166    /// The canvas gestures' memory: a pan going on, the wheel held at
167    /// 100 %.
168    gesture: GestureState,
169    last_mapping: Option<Mapping>,
170    hooks: Hooks,
171    trace: VecDeque<TraceEntry>,
172    /// Signals from calls between frames, given with the next frame's.
173    pending: Vec<Signal>,
174    now: f64,
175    cursor: CursorState,
176    loupe: Loupe,
177    loupe_frame: Option<LoupeFrame>,
178    /// The last readout the loupe showed fresh: shown dimmed while the
179    /// next pixel's values are on their way.
180    loupe_readout: Option<Readout>,
181    /// The tiles drawn this frame, for the loupe.
182    tile_draws: Vec<TileDraw>,
183    /// The display stage drawn with this frame.
184    stage: Option<Stage>,
185}
186
187/// The cursor between frames: the last query and what it resolved to,
188/// what was shown, whether a bitmap was handed to the integration.
189#[derive(Debug, Default)]
190struct CursorState {
191    last: Option<(CursorQuery, Cursor)>,
192    shown: Option<Shown>,
193    image_set: bool,
194}
195
196/// A tile's texture, as the loupe draws it again.
197#[derive(Clone, Copy, Debug)]
198enum TileTexture {
199    Egui(egui::TextureId),
200    Gpu(u64),
201}
202
203/// A tile drawn this frame: its side, texture, size and where it landed
204/// (window physical pixels).
205#[derive(Clone, Copy, Debug)]
206struct TileDraw {
207    side: Side,
208    texture: TileTexture,
209    size: [u32; 2],
210    dst_px: [f64; 4],
211}
212
213/// The display transform in use (the default: [`LinearSrgb`]).
214#[derive(Clone, Debug)]
215struct Transform(Arc<dyn DisplayTransform>);
216
217impl Default for Transform {
218    fn default() -> Self {
219        Transform(Arc::new(LinearSrgb))
220    }
221}
222
223impl ViewportState {
224    /// An empty state.
225    pub fn new() -> ViewportState {
226        ViewportState::default()
227    }
228
229    /// The mapping of the last frame drawn.
230    pub fn mapping(&self) -> Option<Mapping> {
231        self.last_mapping
232    }
233
234    /// Whether a gesture is in progress.
235    pub fn in_gesture(&self) -> bool {
236        self.gesture.pan.is_some()
237    }
238
239    /// Replaces the display transform (the application's colour
240    /// management; [`LinearSrgb`] by default).
241    pub fn set_display_transform(&mut self, transform: Arc<dyn DisplayTransform>) {
242        self.transform = Transform(transform);
243    }
244
245    /// The display transform in use.
246    pub fn display_transform(&self) -> &Arc<dyn DisplayTransform> {
247        &self.transform.0
248    }
249
250    /// The display target the last frame was drawn for.
251    pub fn display_target(&self) -> Option<DisplayTarget> {
252        self.target
253    }
254
255    /// What the last frame was drawn for: the wanted target, the
256    /// surface's, the one drawn and why it carries less, if it does.
257    pub fn display_resolution(&self) -> Option<&display::Resolution> {
258        self.resolution.as_ref()
259    }
260
261    /// Where the source delivers the image's tiles (give it to the
262    /// source when making it).
263    pub fn sink(&self) -> TileSink {
264        self.tiles.sink(Side::After)
265    }
266
267    /// Where a second source delivers the "before" image of a
268    /// comparison.
269    pub fn before_sink(&self) -> TileSink {
270        self.tiles.sink(Side::Before)
271    }
272
273    /// What happened to the tiles, counted.
274    pub fn stats(&self) -> &Arc<Stats> {
275        &self.tiles.stats
276    }
277
278    /// Changes and readouts the source sent that wait for the next
279    /// draw: at most [`NOTICES`](crate::source::NOTICES), however long
280    /// the viewport is not drawn (the others are folded, counted as
281    /// `coalesced` in [`stats`](Self::stats)).
282    pub fn notices_waiting(&self) -> usize {
283        self.tiles.feed.backlog.queued()
284    }
285
286    /// No request outstanding and every wanted exact tile on screen
287    /// (after the last frame).
288    pub fn tiles_complete(&self) -> bool {
289        self.tiles.complete()
290    }
291
292    /// Requests waiting for an answer.
293    pub fn outstanding(&self) -> usize {
294        self.tiles.outstanding()
295    }
296
297    /// Tiles held.
298    pub fn tile_count(&self) -> usize {
299        self.tiles.len()
300    }
301
302    /// Bytes of tile textures held.
303    pub fn texture_bytes(&self) -> usize {
304        self.tiles.used()
305    }
306
307    /// The side of a tile wanted, in pixels (256 by default; the device's
308    /// largest texture side at most).
309    pub fn set_tile_size(&mut self, side: u32) {
310        self.tiles.wanted_size = side.max(16);
311    }
312
313    /// The texture budget, in bytes (256 MB by default). Tiles drawn in
314    /// the current frame are never evicted, so a view larger than the
315    /// budget still shows whole.
316    pub fn set_texture_budget(&mut self, bytes: usize) {
317        self.tiles.budget = bytes;
318    }
319
320    /// How much one frame uploads at most ([`UploadBudget::DEFAULT`], 8
321    /// MiB, by default). Tiles over it wait for the next frames, the
322    /// visible area's first, and are kept when the view moves.
323    /// [`UploadBudget::UNLIMITED`] opts out: every tile arrived goes up
324    /// in the frame that takes it in.
325    pub fn set_upload_budget(&mut self, budget: UploadBudget) {
326        self.tiles.upload_budget = budget;
327    }
328
329    /// The upload budget.
330    pub fn upload_budget(&self) -> UploadBudget {
331        self.tiles.upload_budget
332    }
333
334    /// Converts tiles on the thread that delivers them (the source's
335    /// worker) instead of the interface thread: the display transform
336    /// of the CPU path, the half-float texels of the GPU path. **On by
337    /// default**: the source's thread runs the display transform
338    /// ([`DisplayTransform`] is `Send + Sync`), and a tile converted
339    /// with a transform replaced meanwhile is shown, marked stale and
340    /// asked for again. `false` opts out: the interface thread converts
341    /// each tile when it takes it in, for a source whose threads must
342    /// not run the transform, or one delivering from the interface
343    /// thread anyway (the conversion then happens there either way).
344    /// See docs/threading.md for the measurements.
345    pub fn set_prepare_on_worker(&mut self, on: bool) {
346        self.tiles.prepare_on_worker = on;
347    }
348
349    /// Whether tiles are converted on the delivering thread.
350    pub fn prepare_on_worker(&self) -> bool {
351        self.tiles.prepare_on_worker
352    }
353
354    /// What the last frame uploaded, and what waits.
355    pub fn upload_report(&self) -> UploadReport {
356        self.tiles.report
357    }
358
359    /// Tile pixels copied to the GPU since the state was made, counted
360    /// where the copy happens (up to the last paint); device tiles count
361    /// as bound, with no byte.
362    pub fn transfers(&self) -> Transfers {
363        self.tiles.transfers()
364    }
365
366    /// What the last whole frame copied, its paint included: from the
367    /// start of the frame before the last one to the start of the last
368    /// one. Zero bytes on a view drawn from device tiles alone.
369    pub fn frame_transfers(&self) -> Transfers {
370        self.tiles.frame_transfers
371    }
372
373    /// The last error about tiles: one a source reported
374    /// ([`TileSink::failed`](crate::source::TileSink::failed)), or a
375    /// device tile refused and why.
376    pub fn last_error(&self) -> Option<&str> {
377        self.tiles.last_error.as_deref()
378    }
379
380    /// How long the view stays still before exact tiles are asked for,
381    /// in seconds (0.1 by default; 0 asks at once).
382    pub fn set_settle(&mut self, seconds: f64) {
383        self.tiles.settle = seconds.max(0.0);
384    }
385
386    /// The loupe's settings.
387    pub fn loupe(&self) -> &Loupe {
388        &self.loupe
389    }
390
391    /// The loupe's settings, to change (turn it on for a tool, change its
392    /// magnification).
393    pub fn loupe_mut(&mut self) -> &mut Loupe {
394        &mut self.loupe
395    }
396
397    /// What the loupe showed in the last frame, if it showed.
398    pub fn loupe_frame(&self) -> Option<&LoupeFrame> {
399        self.loupe_frame.as_ref()
400    }
401
402    /// The cursor resolved for the pointer in the last frame (after the
403    /// `on_cursor` hook), while the pointer is over the viewport.
404    pub fn cursor(&self) -> Option<&Cursor> {
405        self.cursor
406            .shown
407            .as_ref()
408            .and_then(|_| self.cursor.last.as_ref().map(|(_, c)| c))
409    }
410
411    /// What the cursor showed in the last frame, while the pointer is
412    /// over the viewport.
413    pub fn cursor_shown(&self) -> Option<&Shown> {
414        self.cursor.shown.as_ref()
415    }
416
417    /// Forgets the cursor resolved, so the next frame asks the
418    /// `on_cursor` hook again (its answer changed for the same
419    /// situation).
420    pub fn refresh_cursor(&mut self) {
421        self.cursor.last = None;
422    }
423
424    /// The hooks, to set or remove.
425    pub fn hooks_mut(&mut self) -> &mut Hooks {
426        &mut self.hooks
427    }
428
429    /// The hooks.
430    pub fn hooks(&self) -> &Hooks {
431        &self.hooks
432    }
433
434    /// What the hooks decided lately, oldest first.
435    pub fn trace(&self) -> impl Iterator<Item = &TraceEntry> {
436        self.trace.iter()
437    }
438
439    pub(crate) fn record(&mut self, hook: &'static str, verdict: &'static str, detail: String) {
440        if self.trace.len() == TRACE_KEPT {
441            self.trace.pop_front();
442        }
443        self.trace.push_back(TraceEntry {
444            time: self.now,
445            hook,
446            verdict,
447            detail,
448        });
449    }
450
451    /// Changes the view from outside the widget (a menu's "zoom in"),
452    /// through the `before_view` hook like a gesture. Returns whether the
453    /// view changed; the signal comes with the next frame's output.
454    pub fn propose(&mut self, view: &mut View, to: View) -> bool {
455        let Some(m) = self.last_mapping else {
456            *view = to;
457            return true;
458        };
459        match self.ask(view, to, Cause::Command, &m) {
460            Some(to) if to != *view => {
461                *view = to;
462                self.pending.push(Signal::View {
463                    view: to,
464                    phase: Phase::Once,
465                    cause: Cause::Command,
466                });
467                true
468            }
469            _ => false,
470        }
471    }
472
473    /// One ladder step up around the centre (a command).
474    pub fn zoom_in(&mut self, view: &mut View) -> bool {
475        self.zoom_to_with(view, view::zoom_in)
476    }
477
478    /// One ladder step down around the centre (a command).
479    pub fn zoom_out(&mut self, view: &mut View) -> bool {
480        self.zoom_to_with(view, view::zoom_out)
481    }
482
483    fn zoom_to_with(&mut self, view: &mut View, f: fn(f64) -> f64) -> bool {
484        let Some(m) = self.last_mapping else {
485            return false;
486        };
487        let to = m.zoom_around(m.rect.center(), f(m.zoom));
488        self.propose(view, to)
489    }
490
491    /// The `before_view` hook's answer for a proposed change, traced.
492    fn ask(&mut self, from: &View, to: View, cause: Cause, m: &Mapping) -> Option<View> {
493        let Some(hook) = self.hooks.before_view.as_mut() else {
494            return Some(to);
495        };
496        let change = ViewChange {
497            from: *from,
498            to,
499            cause,
500        };
501        match hook(&change, m) {
502            Verdict::Allow => Some(to),
503            Verdict::Veto => {
504                self.record("before_view", "veto", format!("{} to {to:?}", cause.name()));
505                None
506            }
507            Verdict::Redirect(v) => {
508                self.record(
509                    "before_view",
510                    "redirect",
511                    format!("{} to {to:?}, given {v:?}", cause.name()),
512                );
513                Some(v)
514            }
515        }
516    }
517}
518
519/// What a frame of the viewport gives back.
520#[derive(Debug)]
521pub struct ViewportOutput {
522    pub response: Response,
523    /// The mapping used this frame (`None` without an image size).
524    pub mapping: Option<Mapping>,
525    /// The image pixel under the pointer, by the drawing's own rule.
526    pub hover_pixel: Option<[i64; 2]>,
527    /// The source's values at that pixel, once they arrived.
528    pub readout: Option<Readout>,
529    /// What changed this frame, in order.
530    pub signals: Vec<Signal>,
531    /// While the pointer is over it: what the pointer does with the
532    /// keys held now, as the profile says (`Wheel: pan ยท Ctrl+...`
533    /// gestures with Ctrl held), for a status line; empty otherwise.
534    pub hint: String,
535    /// The canvas's id for the navigation commands
536    /// (`egui_pop_core::canvas::request_to`, a
537    /// [`CanvasZoom`](crate::navigation::CanvasZoom)): the response's.
538    pub canvas: Id,
539}
540
541/// The viewport widget, built per frame.
542///
543/// Need (image): an image viewport (pan, zoom, tiles).
544pub struct Viewport<'a> {
545    source: Option<&'a dyn TileSource>,
546    before: Option<&'a dyn TileSource>,
547    compare: Compare,
548    overlays: &'a [Overlay],
549    readout: bool,
550    id: Id,
551    name: String,
552    image_size: Option<[u32; 2]>,
553    label: Option<String>,
554    pixel_grid: bool,
555    size: Option<Vec2>,
556    tool: Tool,
557    on_cursor: Option<OnCursor<'a>>,
558    nav_hint: bool,
559}
560
561/// A cursor hook: the situation and the default, the cursor to show.
562type CursorHook<'a> = dyn FnMut(&CursorQuery, Cursor) -> Cursor + 'a;
563type OnCursor<'a> = Box<CursorHook<'a>>;
564
565impl std::fmt::Debug for Viewport<'_> {
566    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
567        f.debug_struct("Viewport")
568            .field("name", &self.name)
569            .field("source", &self.source.is_some())
570            .field("image_size", &self.image_size)
571            .finish()
572    }
573}
574
575static NEXT_SLOT: AtomicU64 = AtomicU64::new(1);
576
577/// From this zoom up, the pixel grid shows (when enabled).
578pub const GRID_FROM_ZOOM: f64 = 8.0;
579
580/// One frame's working set: the view, its mapping, what changed.
581struct Frame<'a> {
582    state: &'a mut ViewportState,
583    view: &'a mut View,
584    mapping: Mapping,
585    signals: Vec<Signal>,
586}
587
588impl Frame<'_> {
589    /// Proposes a change; applies what the hook allows and signals it.
590    fn change(&mut self, to: View, cause: Cause, phase: Phase) -> bool {
591        let to = if phase == Phase::Cancel {
592            Some(to)
593        } else {
594            self.state.ask(self.view, to, cause, &self.mapping)
595        };
596        let Some(to) = to else { return false };
597        if to == *self.view && phase != Phase::Cancel {
598            return false;
599        }
600        *self.view = to;
601        self.mapping = Mapping::new(
602            self.view,
603            self.mapping.image,
604            self.mapping.rect,
605            self.mapping.ppp,
606        );
607        self.signals.push(Signal::View {
608            view: to,
609            phase,
610            cause,
611        });
612        true
613    }
614
615    fn signal(&mut self, phase: Phase, cause: Cause) {
616        self.signals.push(Signal::View {
617            view: *self.view,
618            phase,
619            cause,
620        });
621    }
622}
623
624/// The shared canvas gestures drive the viewport through its frame: each
625/// change goes through the `before_view` hook and is signalled.
626impl ZoomPan for Frame<'_> {
627    fn view(&self) -> View {
628        *self.view
629    }
630
631    fn mapping(&self) -> Mapping {
632        self.mapping
633    }
634
635    fn gesture(&mut self) -> &mut GestureState {
636        &mut self.state.gesture
637    }
638
639    fn change(&mut self, to: View, cause: Cause, phase: Phase) -> bool {
640        Frame::change(self, to, cause, phase)
641    }
642
643    fn signal(&mut self, phase: Phase, cause: Cause) {
644        Frame::signal(self, phase, cause);
645    }
646
647    fn leave(&mut self) {
648        self.signals.push(Signal::Leave);
649    }
650
651    /// The `on_double_click` hook, when set, decides (and may run the
652    /// default).
653    fn double_click(
654        &mut self,
655        at: Pos2,
656        default: &mut dyn FnMut() -> Option<View>,
657    ) -> Option<View> {
658        let m = self.mapping;
659        let Some(run) = self.state.hooks.on_double_click.as_mut() else {
660            return default();
661        };
662        let to = run(at, &m, default);
663        self.state
664            .record("on_double_click", "run", format!("gave {to:?}"));
665        to
666    }
667}
668
669impl<'a> Viewport<'a> {
670    /// A viewport; `id_salt` tells it apart from others in the same `Ui`
671    /// and names it in the debug bridge.
672    pub fn new(id_salt: impl egui::AsIdSalt) -> Viewport<'a> {
673        Viewport {
674            source: None,
675            before: None,
676            compare: Compare::Off,
677            overlays: &[],
678            readout: false,
679            name: format!("{id_salt:?}").trim_matches('"').to_string(),
680            id: Id::unique(id_salt),
681            image_size: None,
682            label: None,
683            pixel_grid: true,
684            size: None,
685            tool: Tool::None,
686            on_cursor: None,
687            nav_hint: false,
688        }
689    }
690
691    /// Shows the navigation model's one-time hint on the first hover
692    /// (`navigation::hint`, kind `image`; default: off).
693    pub fn hint(mut self, on: bool) -> Viewport<'a> {
694        self.nav_hint = on;
695        self
696    }
697
698    /// Decides the cursor: gets the situation (the tool, the keys held, a
699    /// drag, a handle under the pointer) and egui-pop's default for it,
700    /// returns the cursor to show. Asked again only when the situation
701    /// changes (or after [`ViewportState::refresh_cursor`]);
702    /// `egui-pop-imaging`'s `cursor` runs it as the `cursor.resolve`
703    /// step.
704    pub fn on_cursor(
705        mut self,
706        hook: impl FnMut(&CursorQuery, Cursor) -> Cursor + 'a,
707    ) -> Viewport<'a> {
708        self.on_cursor = Some(Box::new(hook));
709        self
710    }
711
712    /// The tool active over the viewport, which decides the cursor
713    /// (default: none, the system's arrow).
714    pub fn tool(mut self, tool: Tool) -> Viewport<'a> {
715        self.tool = tool;
716        self
717    }
718
719    /// Where the pixels come from (its size is the image's unless
720    /// [`Viewport::image_size`] says otherwise).
721    pub fn source(mut self, source: &'a dyn TileSource) -> Viewport<'a> {
722        self.source = Some(source);
723        self
724    }
725
726    /// The "before" image of a comparison (deliver to
727    /// [`ViewportState::before_sink`]).
728    pub fn before(mut self, source: &'a dyn TileSource) -> Viewport<'a> {
729        self.before = Some(source);
730        self
731    }
732
733    /// How "before" and "after" are shown (the application keeps it and
734    /// applies the `Compare` signals).
735    pub fn compare(mut self, compare: Compare) -> Viewport<'a> {
736        self.compare = compare;
737        self
738    }
739
740    /// Overlays in image coordinates, drawn over the image, their
741    /// handles dragged through `Handle` signals.
742    pub fn overlays(mut self, overlays: &'a [Overlay]) -> Viewport<'a> {
743        self.overlays = overlays;
744        self
745    }
746
747    /// Shows the source's values under the pointer in a corner (they
748    /// are in the output and signalled either way).
749    pub fn readout(mut self, on: bool) -> Viewport<'a> {
750        self.readout = on;
751        self
752    }
753
754    /// The image's size in pixels.
755    pub fn image_size(mut self, size: [u32; 2]) -> Viewport<'a> {
756        self.image_size = Some(size);
757        self
758    }
759
760    /// The accessible name (default "Image viewport").
761    pub fn label(mut self, label: impl Into<String>) -> Viewport<'a> {
762        self.label = Some(label.into());
763        self
764    }
765
766    /// Draws the pixel grid from [`GRID_FROM_ZOOM`] up (default on).
767    pub fn pixel_grid(mut self, on: bool) -> Viewport<'a> {
768        self.pixel_grid = on;
769        self
770    }
771
772    /// The widget's size in points (default: all the space available).
773    pub fn size(mut self, size: Vec2) -> Viewport<'a> {
774        self.size = Some(size);
775        self
776    }
777
778    /// Draws the viewport and handles its gestures.
779    pub fn show(self, ui: &mut Ui, state: &mut ViewportState, view: &mut View) -> ViewportOutput {
780        let size = self.size.unwrap_or_else(|| ui.available_size());
781        let (_, rect) = ui.allocate_space(size);
782        let response = ui.interact(
783            rect,
784            ui.make_persistent_id(self.id),
785            Sense::click_and_drag(),
786        );
787        // Handed the keyboard, a panel gives it to the image, not its toolbar.
788        egui_pop_core::focus::prefer(ui.ctx(), response.id);
789        let tokens = ViewportTokens::of(ui.ctx());
790        let g = gestures::gestures(ui.ctx());
791        let ppp = ui.ctx().pixels_per_point();
792        state.now = ui.input(|i| i.time);
793        let mut signals = std::mem::take(&mut state.pending);
794        // The image's own surface, when the platform gives it one: the
795        // target below is then that surface's.
796        #[cfg(feature = "wayland")]
797        let image_route = if tiles::device(ui.ctx()).gpu {
798            crate::image_surface::frame(ui.ctx(), ui.ctx().viewport_id())
799        } else {
800            None
801        };
802        #[cfg(not(feature = "wayland"))]
803        let image_route: ImageRoute = ();
804        let surface = display::target(ui.ctx());
805        if state.target.is_some_and(|t| t != surface) {
806            signals.push(Signal::Display { target: surface });
807        }
808        state.target = Some(surface);
809        let resolved = display::resolution(ui.ctx());
810        let same = state
811            .resolution
812            .as_ref()
813            .is_some_and(|r| r.wanted == resolved.wanted && r.surface == resolved.surface);
814        let resolution = if same {
815            state.resolution.clone().unwrap_or(resolved)
816        } else {
817            resolve_hook(state, resolved)
818        };
819        let target = resolution.drawn;
820        let target_changed = state.resolution.as_ref().is_some_and(|r| r.drawn != target);
821        state.resolution = Some(resolution);
822        ui.painter().rect_filled(rect, 0.0, tokens.background);
823
824        let size = self
825            .image_size
826            .or_else(|| self.source.and_then(|s| s.size()));
827        let Some(image) = size.map(|s| [f64::from(s[0]), f64::from(s[1])]) else {
828            name(&response, self.label.as_deref(), None);
829            state.last_mapping = None;
830            return ViewportOutput {
831                canvas: response.id,
832                response,
833                mapping: None,
834                hover_pixel: None,
835                readout: None,
836                signals,
837                hint: String::new(),
838            };
839        };
840
841        let mapping = Mapping::new(view, image, rect, ppp);
842        let mut f = Frame {
843            state,
844            view,
845            mapping,
846            signals: Vec::new(),
847        };
848        for to in debug::take_commands(ui.ctx(), &self.name) {
849            f.change(to, Cause::Command, Phase::Once);
850        }
851        // The navigation model (docs/design/navigation.md): the canvas
852        // in use takes the `view.*` commands and their keys; hand mode
853        // makes a drag pan as the pan key held does.
854        let nav = navigation::commands(
855            ui.ctx(),
856            response.id,
857            response.hovered(),
858            response.has_focus(),
859        );
860        let start_view = *f.view;
861        let touching = navigation::touching(ui.ctx());
862        let pan_key = canvas::pan_key_held(ui, &response, &g)
863            || response.hovered() && navigation::hand(ui.ctx());
864        let compare = handle_compare(ui, &response, &g, self.compare, &mut f);
865        let captured = handle_overlays(ui, &response, &g, pan_key, self.overlays, compare, &mut f);
866        if !captured.drag && !touching {
867            canvas::pan(ui, &response, &g, pan_key, &mut f);
868        }
869        // Two fingers on a touch screen: the image follows them (their
870        // pinch zooms with the wheel's inputs).
871        let touch = navigation::touch_pan(ui.ctx(), rect);
872        if touch != Vec2::ZERO {
873            let to = f.mapping.panned(touch);
874            f.change(to, Cause::Pan, Phase::Once);
875        }
876        if !captured.double_click {
877            canvas::double_click(ui, &response, &g, &mut f);
878        }
879        if !captured.click && !pan_key {
880            canvas::click(ui, &response, &g, &mut f);
881        }
882        if !captured.wheel {
883            canvas::wheel(ui, &response, &g, &mut f);
884        }
885        for c in nav {
886            handle_nav(c, &mut f);
887        }
888        if response.has_focus() {
889            canvas::keys(ui, &g, true, &mut f);
890        }
891        let panned = *f.view != start_view
892            && f.signals.iter().any(|s| {
893                matches!(
894                    s,
895                    Signal::View {
896                        cause: Cause::Pan,
897                        ..
898                    }
899                )
900            });
901        if let Some(k) = f.state.loupe.key
902            && (response.hovered() || response.has_focus())
903            && ui.input(|i| i.key_pressed(k))
904        {
905            f.state.loupe.on = !f.state.loupe.on;
906            f.signals.push(Signal::Loupe {
907                on: f.state.loupe.on,
908            });
909        }
910        if response.clicked() || response.drag_started() {
911            response.request_focus();
912        }
913        let Frame {
914            state,
915            view,
916            mapping,
917            signals: frame_signals,
918        } = f;
919        signals.extend(frame_signals);
920
921        // The image.
922        let image_rect = mapping.image_rect_to_screen([0.0, 0.0, image[0], image[1]]);
923        let painter = ui.painter_at(rect);
924        painter.rect_filled(image_rect, 0.0, tokens.backdrop);
925        let split_x = split_x(&mapping, compare);
926        draw_tiles(
927            ui,
928            &painter,
929            state,
930            [self.source, self.before],
931            split_x,
932            compare == Compare::Before,
933            &mapping,
934            &target,
935            target_changed,
936            &mut signals,
937            image_route,
938            tokens.backdrop,
939        );
940        if self.pixel_grid && mapping.zoom >= GRID_FROM_ZOOM {
941            draw_grid(&painter, &mapping, tokens.grid);
942        }
943        painter.rect_stroke(
944            image_rect,
945            0.0,
946            Stroke::new(1.0 / ppp, tokens.frame),
947            StrokeKind::Outside,
948        );
949        if let Some(under) = state.hooks.under_overlays.as_mut() {
950            under(&painter, &mapping);
951        }
952        for o in self.overlays {
953            overlay::paint_shape(&painter, &mapping, o, &tokens);
954        }
955        let hovered_handle = response
956            .hover_pos()
957            .filter(|_| state.drag.is_none())
958            .and_then(|p| overlay::hit(self.overlays, &mapping, p));
959        for o in self.overlays {
960            for h in &o.handles {
961                let active = state
962                    .drag
963                    .as_ref()
964                    .is_some_and(|d| d.overlay == o.id && d.handle.index == h.index);
965                let hover = hovered_handle
966                    .as_ref()
967                    .is_some_and(|(i, hh)| self.overlays[*i].id == o.id && hh.index == h.index);
968                let st = if active {
969                    HandleState::Active
970                } else if hover {
971                    HandleState::Hover
972                } else {
973                    HandleState::Rest
974                };
975                overlay::paint_handle_styled(
976                    &painter,
977                    mapping.image_to_screen(h.at),
978                    h.kind,
979                    st,
980                    o.style.emphasis,
981                    &tokens,
982                );
983            }
984        }
985        if let Some(x) = split_x {
986            draw_divider(&painter, rect, x, state.split_drag.is_some(), &tokens);
987        }
988        if let Some(after) = state.hooks.after_paint.as_mut() {
989            after(&painter, &mapping);
990        }
991        if response.has_focus() {
992            egui_pop_core::focus::own_ring(&response.ctx, response.id);
993        }
994        if egui_pop_core::focus::shows_ring(&response) {
995            Kit::of(ui.ctx()).viewport_focus.paint(
996                &KitCx {
997                    painter: &painter,
998                    ppp: ui.ctx().pixels_per_point(),
999                },
1000                &Part {
1001                    rect,
1002                    room: rect,
1003                    state: State::FOCUS,
1004                    label: None,
1005                },
1006            );
1007        }
1008
1009        let hover_pixel = response.hover_pos().and_then(|p| mapping.pixel_at(p));
1010        let readout = handle_readout(
1011            &response,
1012            state,
1013            hover_pixel,
1014            split_x,
1015            compare,
1016            [self.source, self.before],
1017            &mut signals,
1018        );
1019        if self.readout
1020            && let Some(r) = &readout
1021        {
1022            draw_readout(ui, &painter, rect, state, r);
1023        }
1024        let pointer = (response.hovered() || response.dragged())
1025            .then(|| ui.input(|i| i.pointer.hover_pos()))
1026            .flatten();
1027        state.loupe_frame = None;
1028        if state.loupe.on
1029            && let Some(p) = pointer.filter(|p| rect.contains(*p))
1030        {
1031            let before = state.tile_draws.iter().any(|d| d.side == Side::Before)
1032                && (state.before_held || split_x.is_some_and(|x| p.x < x));
1033            let side = if before { Side::Before } else { Side::After };
1034            draw_loupe(
1035                ui,
1036                &painter,
1037                state,
1038                &mapping,
1039                p,
1040                side,
1041                readout.as_ref(),
1042                &tokens,
1043            );
1044        }
1045        let query = CursorQuery {
1046            tool: self.tool.clone(),
1047            modifiers: ui.input(|i| i.modifiers),
1048            dragging: response.dragged() || state.gesture.pan.is_some() || state.drag.is_some(),
1049            // The pan key held, a pan, or keys held that make a drag pan
1050            // (where a drag without them would not).
1051            panning: state.gesture.pan.is_some() || pan_key || {
1052                let m = ui.input(|i| i.modifiers);
1053                response.hovered()
1054                    && m.any()
1055                    && g.pointer.drag_pans(PointerButton::Primary, m)
1056                    && !g
1057                        .pointer
1058                        .drag_pans(PointerButton::Primary, egui::Modifiers::NONE)
1059            },
1060            handle: state
1061                .drag
1062                .as_ref()
1063                .map(|d| d.handle.kind)
1064                .or(hovered_handle.as_ref().map(|(_, h)| h.kind)),
1065            over_image: hover_pixel.is_some(),
1066        };
1067        let mut on_cursor = self.on_cursor;
1068        update_cursor(
1069            ui.ctx(),
1070            &painter,
1071            state,
1072            query,
1073            on_cursor.as_deref_mut(),
1074            pointer,
1075            &mapping,
1076        );
1077        name(&response, self.label.as_deref(), Some(mapping.zoom));
1078        egui_pop_core::canvas::set_zoom(
1079            ui.ctx(),
1080            response.id,
1081            (zoom_percent(view, Some(&mapping)) / 100.0) as f32,
1082        );
1083        navigation::indicator(ui, rect, &response);
1084        if self.nav_hint {
1085            navigation::hint(ui, response.id, rect, "image", &response, panned);
1086        }
1087        state.last_mapping = Some(mapping);
1088        debug::publish(ui.ctx(), &self.name, state, view, &mapping, &signals);
1089        let hint = if response.hovered() {
1090            let hint = gestures::hint(ui.ctx(), egui_pop_core::model::pointer::SCOPE_IMAGE);
1091            egui_pop_core::pointer::show_hint(ui.ctx(), &hint);
1092            hint
1093        } else {
1094            String::new()
1095        };
1096        ViewportOutput {
1097            canvas: response.id,
1098            response,
1099            mapping: Some(mapping),
1100            hover_pixel,
1101            readout,
1102            signals,
1103            hint,
1104        }
1105    }
1106}
1107
1108/// A pan by command moves the view by this part of its size.
1109const PAN_STEP: f32 = 0.1;
1110
1111/// A navigation command (`view.fit`, `view.zoom_in`...), on the image:
1112/// fit and frame the selection both fit it (the image is the
1113/// selection), the zooms go around the centre.
1114fn handle_nav(c: NavCommand, f: &mut Frame<'_>) {
1115    let m = f.mapping;
1116    let center = m.rect.center();
1117    let to = match c {
1118        NavCommand::Fit | NavCommand::FrameSelection => View::fit(),
1119        NavCommand::ZoomIn => m.zoom_around(center, view::zoom_in(m.zoom)),
1120        NavCommand::ZoomOut => m.zoom_around(center, view::zoom_out(m.zoom)),
1121        NavCommand::Zoom100 => m.zoom_around(center, 1.0),
1122        NavCommand::ZoomTo(p) => m.zoom_around(
1123            center,
1124            (f64::from(p) / 100.0).clamp(view::MIN_ZOOM, view::MAX_ZOOM),
1125        ),
1126        NavCommand::Pan(d) => m.panned(-d.vec() * m.rect.size() * PAN_STEP),
1127        NavCommand::Hand => return,
1128    };
1129    f.change(to, Cause::Command, Phase::Once);
1130}
1131
1132/// The accessible node: an image (readers say what the widget is), its
1133/// name, and the zoom as the value.
1134fn name(response: &Response, label: Option<&str>, zoom: Option<f64>) {
1135    let label = label.map_or_else(
1136        || egui_pop_core::strings::tr(&response.ctx, &crate::strings::VIEWPORT),
1137        str::to_string,
1138    );
1139    response.widget_info(move || {
1140        let mut info = WidgetInfo::labeled(Role::Image, true, &label);
1141        if let Some(z) = zoom {
1142            info.value = Some(z * 100.0);
1143            info.current_text_value = Some(format!("{:.0} %", z * 100.0));
1144        }
1145        info
1146    });
1147}
1148
1149/// Lines between image pixels, over the visible part.
1150fn draw_grid(painter: &egui::Painter, m: &Mapping, color: Color32) {
1151    let Some(v) = m.visible() else { return };
1152    let stroke = Stroke::new(1.0 / m.ppp, color);
1153    let (x0, x1) = (v[0].floor() as i64, v[2].ceil() as i64);
1154    let (y0, y1) = (v[1].floor() as i64, v[3].ceil() as i64);
1155    if (x1 - x0) > 1000 || (y1 - y0) > 1000 {
1156        return;
1157    }
1158    let top = m.image_to_screen([0.0, v[1]]).y;
1159    let bottom = m.image_to_screen([0.0, v[3]]).y;
1160    let left = m.image_to_screen([v[0], 0.0]).x;
1161    let right = m.image_to_screen([v[2], 0.0]).x;
1162    for x in x0..=x1 {
1163        let sx = m.image_to_screen([x as f64, 0.0]).x;
1164        painter.line_segment([Pos2::new(sx, top), Pos2::new(sx, bottom)], stroke);
1165    }
1166    for y in y0..=y1 {
1167        let sy = m.image_to_screen([0.0, y as f64]).y;
1168        painter.line_segment([Pos2::new(left, sy), Pos2::new(right, sy)], stroke);
1169    }
1170}
1171
1172/// The zoom of a view as shown, in percent (fit resolved by `mapping`).
1173pub fn zoom_percent(view: &View, mapping: Option<&Mapping>) -> f64 {
1174    match (view.zoom, mapping) {
1175        (Zoom::Px(z), _) => z * 100.0,
1176        (Zoom::Fit, Some(m)) => m.zoom * 100.0,
1177        (Zoom::Fit, None) => 100.0,
1178    }
1179}
1180
1181/// Where the split falls on screen (points), when splitting.
1182fn split_x(m: &Mapping, compare: Compare) -> Option<f32> {
1183    match compare {
1184        Compare::Split(t) => Some(m.rect.left() + m.rect.width() * t.clamp(0.0, 1.0)),
1185        _ => None,
1186    }
1187}
1188
1189/// The image's own surface for a frame, when it has one.
1190#[cfg(feature = "wayland")]
1191type ImageRoute = Option<(
1192    crate::image_surface::ImageSurfaces,
1193    crate::image_surface::Route,
1194)>;
1195#[cfg(not(feature = "wayland"))]
1196type ImageRoute = ();
1197
1198/// Takes in what the sources sent, asks for what is missing, draws the
1199/// tiles (proxy, then exact) of each side shown, evicts past the budget,
1200/// and signals what moved.
1201#[allow(
1202    clippy::too_many_arguments,
1203    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1204)]
1205fn draw_tiles(
1206    ui: &Ui,
1207    painter: &egui::Painter,
1208    state: &mut ViewportState,
1209    sources: [Option<&dyn TileSource>; 2],
1210    split_x: Option<f32>,
1211    before_only: bool,
1212    mapping: &Mapping,
1213    target: &DisplayTarget,
1214    target_changed: bool,
1215    signals: &mut Vec<Signal>,
1216    image: ImageRoute,
1217    backdrop: Color32,
1218) {
1219    let ctx = ui.ctx();
1220    let transform = state.transform.0.clone();
1221    if target_changed || state.transform_revision != transform.revision() {
1222        state.transform_revision = transform.revision();
1223        state.tiles.rebake();
1224    }
1225    if state.slot == 0 {
1226        // Three slots: the image, the "before" image, the loupe.
1227        state.slot = NEXT_SLOT.fetch_add(3, Ordering::Relaxed);
1228    }
1229    let device = tiles::device(ctx);
1230    state
1231        .tiles
1232        .receive(ctx, device, target, &transform, mapping);
1233    let settled = state.tiles.note_view(mapping, state.now);
1234    if let Some(left) = state.tiles.settles_in(state.now) {
1235        ctx.request_repaint_after(Duration::from_secs_f64(left));
1236    }
1237    let [after, before] = sources;
1238    let stage = transform.stage(&target.effective());
1239    state.stage = Some(stage);
1240    let mut drawn: Vec<TileDraw> = Vec::new();
1241    // "Before" alone: the application's choice, or the key held.
1242    let showing_before = before_only;
1243    let rect = mapping.rect;
1244    let mut sides: Vec<(Side, &dyn TileSource, Rect, u64)> = Vec::new();
1245    match (before, split_x, showing_before) {
1246        (Some(b), _, true) => sides.push((Side::Before, b, rect, state.slot + 1)),
1247        (Some(b), Some(x), false) => {
1248            if let Some(a) = after {
1249                sides.push((
1250                    Side::After,
1251                    a,
1252                    Rect::from_min_max(pos2(x, rect.top()), rect.max),
1253                    state.slot,
1254                ));
1255            }
1256            sides.push((
1257                Side::Before,
1258                b,
1259                Rect::from_min_max(rect.min, pos2(x, rect.bottom())),
1260                state.slot + 1,
1261            ));
1262        }
1263        _ => {
1264            if let Some(a) = after {
1265                sides.push((Side::After, a, rect, state.slot));
1266            }
1267        }
1268    }
1269    #[cfg(feature = "wgpu")]
1270    let mut paints: Vec<(crate::gpu::TilePaint, Rect)> = Vec::new();
1271    for (side, source, clip, slot) in sides {
1272        let clip = clip.intersect(painter.clip_rect());
1273        let painter = painter.with_clip_rect(clip);
1274        let mut gpu: Vec<(u64, [f32; 4], [u32; 2])> = Vec::new();
1275        let ppp = f64::from(mapping.ppp);
1276        for d in state.tiles.frame(side, source, mapping, settled) {
1277            let r = d.dst_px;
1278            drawn.push(TileDraw {
1279                side,
1280                texture: match d.texture {
1281                    Texture::Egui(handle) => TileTexture::Egui(handle.id()),
1282                    Texture::Gpu(id) => TileTexture::Gpu(*id),
1283                },
1284                size: d.size,
1285                dst_px: r,
1286            });
1287            match d.texture {
1288                Texture::Egui(handle) => {
1289                    painter.image(
1290                        handle.id(),
1291                        Rect::from_min_max(
1292                            pos2((r[0] / ppp) as f32, (r[1] / ppp) as f32),
1293                            pos2((r[2] / ppp) as f32, (r[3] / ppp) as f32),
1294                        ),
1295                        Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
1296                        Color32::WHITE,
1297                    );
1298                }
1299                Texture::Gpu(id) => {
1300                    gpu.push((
1301                        *id,
1302                        [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32],
1303                        d.size,
1304                    ));
1305                }
1306            }
1307        }
1308        #[cfg(feature = "wgpu")]
1309        if device.gpu {
1310            let paint = crate::gpu::TilePaint {
1311                slot,
1312                queue: state.tiles.gpu.clone(),
1313                draws: gpu
1314                    .into_iter()
1315                    .map(|(texture, dst, size)| crate::gpu::GpuDraw { texture, dst, size })
1316                    .collect(),
1317                stage,
1318            };
1319            paints.push((paint, clip));
1320        }
1321        #[cfg(not(feature = "wgpu"))]
1322        let _ = (gpu, slot);
1323    }
1324    // The image goes to its own surface when it has one for what is
1325    // drawn (a hook may have redirected it), else to the window.
1326    #[cfg(feature = "wayland")]
1327    let paints = match image {
1328        Some((surfaces, route)) if route.target() == Some(*target) => {
1329            let visible = mapping
1330                .image_rect_to_screen([0.0, 0.0, mapping.image[0], mapping.image[1]])
1331                .intersect(painter.clip_rect());
1332            let px = |r: Rect| {
1333                [
1334                    r.min.x * mapping.ppp,
1335                    r.min.y * mapping.ppp,
1336                    r.max.x * mapping.ppp,
1337                    r.max.y * mapping.ppp,
1338                ]
1339            };
1340            if visible.is_positive() {
1341                let paint = crate::image_surface::ImagePaint {
1342                    ctx: ctx.clone(),
1343                    surfaces,
1344                    viewport: ctx.viewport_id(),
1345                    route,
1346                    key: state.slot,
1347                    pass: ctx.cumulative_pass_nr(),
1348                    rect_px: px(visible),
1349                    scale: ctx.native_pixels_per_point().unwrap_or(mapping.ppp),
1350                    background: crate::image_surface::clear_colour(backdrop, target),
1351                    sides: paints.into_iter().map(|(p, clip)| (p, px(clip))).collect(),
1352                    shown: std::sync::atomic::AtomicBool::new(false),
1353                };
1354                painter
1355                    .with_clip_rect(visible)
1356                    .add(egui_wgpu::Callback::new_paint_callback(visible, paint));
1357            }
1358            Vec::new()
1359        }
1360        _ => paints,
1361    };
1362    #[cfg(not(feature = "wayland"))]
1363    let _ = (image, backdrop);
1364    #[cfg(feature = "wgpu")]
1365    for (paint, clip) in paints {
1366        painter
1367            .with_clip_rect(clip)
1368            .add(egui_wgpu::Callback::new_paint_callback(rect, paint));
1369    }
1370    state.tiles.evict();
1371    state.tile_draws = drawn;
1372
1373    let snap = state.tiles.stats.snapshot();
1374    let counts = [snap[0].1, snap[1].1, snap[3].1];
1375    let complete = state.tiles.complete();
1376    let any = after.is_some() || before.is_some();
1377    if any && (counts != state.last_counts || complete != state.last_complete) {
1378        signals.push(Signal::Tiles {
1379            requested: counts[0] - state.last_counts[0],
1380            delivered: counts[1] - state.last_counts[1],
1381            cancelled: counts[2] - state.last_counts[2],
1382            complete,
1383        });
1384        state.last_counts = counts;
1385        state.last_complete = complete;
1386    }
1387}
1388
1389/// What the overlays took of this frame's input.
1390#[derive(Clone, Copy, Debug, Default)]
1391struct Captured {
1392    drag: bool,
1393    /// A click on a handle or an outline.
1394    click: bool,
1395    double_click: bool,
1396    wheel: bool,
1397}
1398
1399/// The `before_handle` hook's answer for a handle move, traced.
1400fn ask_handle(state: &mut ViewportState, mv: &HandleMove, m: &Mapping) -> Option<[f64; 2]> {
1401    let Some(hook) = state.hooks.before_handle.as_mut() else {
1402        return Some(mv.to);
1403    };
1404    match hook(mv, m) {
1405        Verdict::Allow => Some(mv.to),
1406        Verdict::Veto => {
1407            state.record(
1408                "before_handle",
1409                "veto",
1410                format!("{} {} to {:?}", mv.overlay, mv.handle, mv.to),
1411            );
1412            None
1413        }
1414        Verdict::Redirect(p) => {
1415            state.record(
1416                "before_handle",
1417                "redirect",
1418                format!("{} {} to {:?}, given {p:?}", mv.overlay, mv.handle, mv.to),
1419            );
1420            Some(p)
1421        }
1422    }
1423}
1424
1425/// Handle drags (one gesture each, Escape cancels), double clicks and
1426/// the wheel over a handle.
1427fn handle_overlays(
1428    ui: &Ui,
1429    response: &Response,
1430    g: &Gestures,
1431    pan_key: bool,
1432    overlays: &[Overlay],
1433    compare: Compare,
1434    f: &mut Frame<'_>,
1435) -> Captured {
1436    let mut captured = Captured::default();
1437    let m = f.mapping;
1438    // A drag on the split moves it.
1439    if let Some(x) = split_x(&m, compare) {
1440        let near = |p: Pos2| (p.x - x).abs() <= overlay::HIT_RADIUS;
1441        if response.drag_started_by(g.pan_button)
1442            && !pan_key
1443            && ui.input(|i| i.pointer.press_origin()).is_some_and(near)
1444        {
1445            f.state.split_drag = Some(x);
1446        }
1447        if f.state.split_drag.is_some() {
1448            captured.drag = true;
1449            if let Some(p) = response.interact_pointer_pos() {
1450                let t = ((p.x - m.rect.left()) / m.rect.width()).clamp(0.0, 1.0);
1451                let phase = if response.drag_stopped() {
1452                    Phase::End
1453                } else {
1454                    Phase::Update
1455                };
1456                f.signals.push(Signal::Compare {
1457                    compare: Compare::Split(t),
1458                    phase,
1459                });
1460            }
1461            if response.drag_stopped() || !response.dragged() {
1462                f.state.split_drag = None;
1463            }
1464        }
1465    }
1466    if overlays.is_empty() && f.state.drag.is_none() {
1467        return captured;
1468    }
1469    let pointer = response.hover_pos();
1470    let under = pointer.and_then(|p| overlay::hit(overlays, &m, p));
1471    if response.drag_started_by(g.pan_button)
1472        && !pan_key
1473        && f.state.drag.is_none()
1474        && let Some(origin) = ui.input(|i| i.pointer.press_origin())
1475        && let Some((i, h)) = overlay::hit(overlays, &m, origin)
1476    {
1477        let d = HandleDrag {
1478            overlay: overlays[i].id.clone(),
1479            handle: h,
1480            press: m.screen_to_image(origin),
1481            at: h.at,
1482        };
1483        f.signals.push(Signal::Handle {
1484            overlay: d.overlay.clone(),
1485            handle: h.index,
1486            kind: h.kind,
1487            phase: Phase::Begin,
1488            from: h.at,
1489            at: h.at,
1490        });
1491        f.state.drag = Some(d);
1492    }
1493    if let Some(mut d) = f.state.drag.clone() {
1494        captured.drag = true;
1495        let signal = |phase, at| Signal::Handle {
1496            overlay: d.overlay.clone(),
1497            handle: d.handle.index,
1498            kind: d.handle.kind,
1499            phase,
1500            from: d.handle.at,
1501            at,
1502        };
1503        if egui_pop_core::focus::cancel_pressed(ui.ctx(), g.cancel) {
1504            f.signals.push(signal(Phase::Cancel, d.handle.at));
1505            f.state.drag = None;
1506            return captured;
1507        }
1508        if let Some(p) = response.interact_pointer_pos()
1509            && response.drag_delta() != Vec2::ZERO
1510        {
1511            let now = m.screen_to_image(p);
1512            let to = [
1513                d.handle.at[0] + now[0] - d.press[0],
1514                d.handle.at[1] + now[1] - d.press[1],
1515            ];
1516            let mv = HandleMove {
1517                overlay: d.overlay.clone(),
1518                handle: d.handle.index,
1519                kind: d.handle.kind,
1520                start: d.handle.at,
1521                from: d.at,
1522                to,
1523                modifiers: ui.input(|i| i.modifiers),
1524            };
1525            if let Some(at) = ask_handle(f.state, &mv, &m) {
1526                d.at = at;
1527                f.signals.push(signal(Phase::Update, at));
1528            }
1529        }
1530        if response.drag_stopped() || !response.dragged() {
1531            f.signals.push(signal(Phase::End, d.at));
1532            f.state.drag = None;
1533        } else {
1534            f.state.drag = Some(d);
1535        }
1536    }
1537    // A click (no drag) on a handle, else on an outline.
1538    if response.clicked_by(g.pan_button)
1539        && !pan_key
1540        && let Some(p) = response.interact_pointer_pos().or(pointer)
1541    {
1542        let modifiers = ui.input(|i| i.modifiers);
1543        if let Some((i, h)) = overlay::hit(overlays, &m, p) {
1544            captured.click = true;
1545            f.signals.push(Signal::HandleClick {
1546                overlay: overlays[i].id.clone(),
1547                handle: h.index,
1548                kind: h.kind,
1549                modifiers,
1550            });
1551        } else if let Some((i, segment, at)) = overlay::hit_edge(overlays, &m, p) {
1552            captured.click = true;
1553            f.signals.push(Signal::EdgeClick {
1554                overlay: overlays[i].id.clone(),
1555                segment,
1556                at,
1557                modifiers,
1558            });
1559        }
1560    }
1561    if let Some((i, h)) = under {
1562        if response.double_clicked() {
1563            captured.double_click = true;
1564            f.signals.push(Signal::HandleReset {
1565                overlay: overlays[i].id.clone(),
1566                handle: h.index,
1567                kind: h.kind,
1568            });
1569        }
1570        let scroll = ui.input(|i| i.smooth_scroll_delta.y);
1571        if response.hovered() && scroll != 0.0 {
1572            captured.wheel = true;
1573            ui.ctx().input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);
1574            f.signals.push(Signal::HandleWheel {
1575                overlay: overlays[i].id.clone(),
1576                handle: h.index,
1577                kind: h.kind,
1578                delta: scroll,
1579            });
1580        }
1581    }
1582    captured
1583}
1584
1585/// The `before` key held shows the "before" image (a quasimode); the
1586/// `before_compare` hook may veto or redirect a change. Returns the
1587/// comparison to draw this frame.
1588fn handle_compare(
1589    ui: &Ui,
1590    response: &Response,
1591    g: &Gestures,
1592    compare: Compare,
1593    f: &mut Frame<'_>,
1594) -> Compare {
1595    let held = (response.hovered() || response.has_focus()) && ui.input(|i| i.key_down(g.before));
1596    if held != f.state.before_key {
1597        f.state.before_key = held;
1598        if held || f.state.before_begun {
1599            let proposed = if held { Compare::Before } else { compare };
1600            let allowed = match f.state.hooks.before_compare.as_mut() {
1601                None => Some(proposed),
1602                Some(hook) => match hook(&compare, &proposed) {
1603                    Verdict::Allow => Some(proposed),
1604                    Verdict::Veto => {
1605                        f.state.record(
1606                            "before_compare",
1607                            "veto",
1608                            format!("{compare:?} to {proposed:?}"),
1609                        );
1610                        None
1611                    }
1612                    Verdict::Redirect(c) => {
1613                        f.state.record(
1614                            "before_compare",
1615                            "redirect",
1616                            format!("{compare:?} to {proposed:?}, given {c:?}"),
1617                        );
1618                        Some(c)
1619                    }
1620                },
1621            };
1622            f.state.before_begun = held && allowed.is_some();
1623            if let Some(c) = allowed {
1624                f.state.before_held = held && c == Compare::Before;
1625                f.signals.push(Signal::Compare {
1626                    compare: c,
1627                    phase: if held { Phase::Begin } else { Phase::End },
1628                });
1629            }
1630        }
1631    }
1632    if f.state.before_held {
1633        Compare::Before
1634    } else {
1635        compare
1636    }
1637}
1638
1639/// The `before_display` hook on a new resolution.
1640fn resolve_hook(state: &mut ViewportState, mut r: display::Resolution) -> display::Resolution {
1641    let Some(hook) = state.hooks.before_display.as_mut() else {
1642        return r;
1643    };
1644    let (verdict, to) = match hook(&r) {
1645        Verdict::Allow => return r,
1646        Verdict::Veto => (
1647            "veto",
1648            DisplayTarget {
1649                surface_format: r.surface.surface_format,
1650                source: r.surface.source,
1651                ..DisplayTarget::srgb()
1652            },
1653        ),
1654        Verdict::Redirect(t) => ("redirect", t.effective()),
1655    };
1656    let detail = format!("{} -> {}", r.drawn.describe(), to.describe());
1657    r.drawn = to;
1658    r.fallback = Some(display::Fallback::Hook);
1659    state.record("before_display", verdict, detail);
1660    r
1661}
1662
1663/// Asks the source shown under the pointer for its values when the
1664/// pointer moves to another pixel; gives back what arrived for it.
1665fn handle_readout(
1666    response: &Response,
1667    state: &mut ViewportState,
1668    pixel: Option<[i64; 2]>,
1669    split_x: Option<f32>,
1670    compare: Compare,
1671    sources: [Option<&dyn TileSource>; 2],
1672    signals: &mut Vec<Signal>,
1673) -> Option<Readout> {
1674    let pixel = pixel?;
1675    let left = split_x
1676        .zip(response.hover_pos())
1677        .is_some_and(|(x, p)| p.x < x);
1678    let side = if (compare == Compare::Before || state.before_held || left) && sources[1].is_some()
1679    {
1680        Side::Before
1681    } else {
1682        Side::After
1683    };
1684    let source = if side == Side::Before {
1685        sources[1]
1686    } else {
1687        sources[0]
1688    }?;
1689    if state.asked_readout != Some((side, pixel)) {
1690        state.asked_readout = Some((side, pixel));
1691        source.readout(pixel);
1692    }
1693    let r = state
1694        .tiles
1695        .readout
1696        .clone()
1697        .filter(|r| r.side == side && r.pixel == pixel)?;
1698    if state.signalled_readout != Some((side, pixel)) {
1699        state.signalled_readout = Some((side, pixel));
1700        signals.push(Signal::Readout(r.clone()));
1701    }
1702    Some(r)
1703}
1704
1705/// The readout's text: the `on_readout` hook's, or the pixel and its
1706/// values.
1707pub fn readout_text(r: &Readout) -> String {
1708    let mut s = format!("{}, {}", r.pixel[0], r.pixel[1]);
1709    for (name, v) in &r.values {
1710        s.push_str(&format!("  {name} {v:.3}"));
1711    }
1712    s
1713}
1714
1715fn draw_readout(
1716    ui: &Ui,
1717    painter: &egui::Painter,
1718    rect: Rect,
1719    state: &mut ViewportState,
1720    r: &Readout,
1721) {
1722    let text = match state.hooks.on_readout.as_mut() {
1723        Some(hook) => hook(r),
1724        None => readout_text(r),
1725    };
1726    let t = egui_pop_core::theme::Tokens::of(ui.ctx());
1727    let font = egui::FontId::monospace(t.font.small);
1728    let galley = painter.layout_no_wrap(text, font, Color32::PLACEHOLDER);
1729    let kit = Kit::of(ui.ctx());
1730    let size = kit.readout.measure(galley.size());
1731    let at = pos2(rect.left() + t.space.s, rect.bottom() - t.space.s - size.y);
1732    let bg = Rect::from_min_size(at, size);
1733    kit.readout.paint_part(
1734        &KitCx {
1735            painter,
1736            ppp: ui.ctx().pixels_per_point(),
1737        },
1738        &Part {
1739            rect: bg,
1740            room: bg,
1741            state: State::REST,
1742            label: Some(&galley),
1743        },
1744    );
1745}
1746
1747fn draw_divider(painter: &egui::Painter, rect: Rect, x: f32, active: bool, t: &ViewportTokens) {
1748    let top = pos2(x, rect.top());
1749    let bottom = pos2(x, rect.bottom());
1750    let w = |x: f32| egui_pop_core::scale::stroke(painter.ctx(), x);
1751    painter.line_segment(
1752        [top, bottom],
1753        Stroke::new(w(overlay::UNDER_WIDTH), t.handle_outline),
1754    );
1755    painter.line_segment([top, bottom], Stroke::new(w(overlay::LINE_WIDTH), t.guide));
1756    let st = if active {
1757        HandleState::Active
1758    } else {
1759        HandleState::Rest
1760    };
1761    overlay::paint_handle(painter, pos2(x, rect.center().y), HandleKind::Edge, st, t);
1762}
1763
1764/// Resolves the cursor when the query changed (the default, then the
1765/// `on_cursor` hook), and shows it; clears a bitmap cursor once the
1766/// pointer has left.
1767fn update_cursor(
1768    ctx: &egui::Context,
1769    painter: &egui::Painter,
1770    state: &mut ViewportState,
1771    query: CursorQuery,
1772    hook: Option<&mut CursorHook<'_>>,
1773    pointer: Option<Pos2>,
1774    mapping: &Mapping,
1775) {
1776    let Some(p) = pointer else {
1777        if state.cursor.image_set {
1778            cursor::clear_image(ctx);
1779            state.cursor.image_set = false;
1780        }
1781        state.cursor.shown = None;
1782        return;
1783    };
1784    let cached = state
1785        .cursor
1786        .last
1787        .as_ref()
1788        .filter(|(q, _)| *q == query)
1789        .map(|(_, c)| c.clone());
1790    let resolved = match cached {
1791        Some(c) => c,
1792        None => {
1793            let default = cursor::default_cursor(&query);
1794            let given = hook.map(|hook| hook(&query, default.clone()));
1795            let c = match given {
1796                Some(c) if c != default => {
1797                    state.record(
1798                        "on_cursor",
1799                        "redirect",
1800                        format!("{} {} to {}", query.tool.name(), default.name(), c.name()),
1801                    );
1802                    c
1803                }
1804                _ => default,
1805            };
1806            state.cursor.last = Some((query, c.clone()));
1807            c
1808        }
1809    };
1810    let shown = cursor::shown(ctx, &resolved, mapping.zoom, mapping.ppp);
1811    let image = cursor::apply(ctx, painter, p, &shown);
1812    if !image && state.cursor.image_set {
1813        cursor::clear_image(ctx);
1814    }
1815    state.cursor.image_set = image;
1816    state.cursor.shown = Some(shown);
1817}
1818
1819/// Draws the loupe beside the pointer: the side's tiles again through
1820/// the magnifying sampling (a second paint callback on the GPU path, the
1821/// same egui textures on the CPU path), its grid, its marker and its
1822/// readout.
1823#[allow(
1824    clippy::too_many_arguments,
1825    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1826)]
1827fn draw_loupe(
1828    ui: &Ui,
1829    painter: &egui::Painter,
1830    state: &mut ViewportState,
1831    mapping: &Mapping,
1832    pointer: Pos2,
1833    side: Side,
1834    readout: Option<&Readout>,
1835    tokens: &ViewportTokens,
1836) {
1837    let l = state.loupe;
1838    let ctx = ui.ctx();
1839    let ppp = mapping.ppp;
1840    let t = egui_pop_core::theme::Tokens::of(ctx);
1841    let tr = |k: &egui_pop_core::strings::StrKey| egui_pop_core::strings::tr(ctx, k);
1842    let labels = [
1843        tr(&crate::strings::LOUPE_DISPLAY),
1844        tr(&crate::strings::LOUPE_SCENE),
1845        tr(&crate::strings::LOUPE_NONE),
1846    ];
1847    let pixel = mapping.pixel_at(pointer);
1848    if let Some(r) = readout.filter(|r| Some(r.pixel) == pixel) {
1849        state.loupe_readout = Some(r.clone());
1850    }
1851    let shown = state.loupe_readout.as_ref();
1852    let labels: [&str; 3] = [&labels[0], &labels[1], &labels[2]];
1853    let lines = loupe::readout_lines(pixel, shown, l.values, state.stage.as_ref(), labels);
1854    let stale = lines.len() > 1 && loupe::stale(pixel, shown);
1855    let names: Vec<String> = shown
1856        .map(|r| r.values.iter().map(|(n, _)| n.clone()).collect())
1857        .unwrap_or_default();
1858    let templates = loupe::readout_templates(l.values, labels, &names);
1859    let font = egui::FontId::monospace(t.font.small);
1860    // The block is measured from the widest values, not from this
1861    // frame's: it keeps its size while the pointer moves.
1862    let block = (!templates.is_empty()).then(|| {
1863        painter
1864            .layout_no_wrap(templates.join("\n"), font.clone(), t.text.default)
1865            .size()
1866    });
1867    let galley = (!lines.is_empty()).then(|| {
1868        let mut job = egui::text::LayoutJob::default();
1869        let values = if stale { t.text.muted } else { t.text.default };
1870        for (i, line) in lines.iter().enumerate() {
1871            let (text, color) = match i {
1872                0 => (line.clone(), t.text.default),
1873                _ => (format!("\n{line}"), values),
1874            };
1875            job.append(&text, 0.0, egui::TextFormat::simple(font.clone(), color));
1876        }
1877        painter.layout_job(job)
1878    });
1879    let pad = egui_pop_core::scale::snap_size(t.space.xs, ppp);
1880    let picture = loupe::picture_size(&l, ppp);
1881    let text_h = block.map_or(0.0, |b| b.y + pad);
1882    let width = (picture.x + 2.0 * pad).max(block.map_or(0.0, |b| b.x + 2.0 * pad));
1883    let size = Vec2::new(
1884        egui_pop_core::scale::snap_size(width, ppp),
1885        egui_pop_core::scale::snap_size(picture.y + 2.0 * pad + text_h, ppp),
1886    );
1887    let placed = loupe::place(pointer, size, mapping.rect, l.offset);
1888    let snap = |v: f32| (v * ppp).round() / ppp;
1889    let rect = Rect::from_min_size(pos2(snap(placed.min.x), snap(placed.min.y)), size);
1890    let pic = Rect::from_min_size(rect.min + Vec2::splat(pad), picture);
1891    painter.rect_filled(rect, 0.0, tokens.loupe_background);
1892    painter.rect_filled(pic, 0.0, tokens.background);
1893    let s = loupe::Sampling::new(mapping, pointer, l.magnification(), pic.center());
1894    let clip = pic.intersect(painter.clip_rect());
1895    let lp = painter.with_clip_rect(clip);
1896    let a = mapping.image_to_px([0.0, 0.0]);
1897    let b = mapping.image_to_px(mapping.image);
1898    lp.rect_filled(
1899        loupe::to_points(s.map_rect([a[0], a[1], b[0], b[1]]), ppp),
1900        0.0,
1901        tokens.backdrop,
1902    );
1903    let mut gpu: Vec<(u64, [f64; 4], [u32; 2])> = Vec::new();
1904    let mut tiles = 0;
1905    let whole = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
1906    for d in state.tile_draws.iter().filter(|d| d.side == side) {
1907        tiles += 1;
1908        let dst = s.map_rect(d.dst_px);
1909        match d.texture {
1910            TileTexture::Egui(id) => {
1911                lp.image(id, loupe::to_points(dst, ppp), whole, Color32::WHITE);
1912            }
1913            TileTexture::Gpu(id) => gpu.push((id, dst, d.size)),
1914        }
1915    }
1916    let on_gpu = !gpu.is_empty();
1917    #[cfg(feature = "wgpu")]
1918    if let (true, Some(stage)) = (on_gpu, state.stage) {
1919        let paint = crate::gpu::TilePaint {
1920            slot: state.slot + 2,
1921            queue: state.tiles.gpu.clone(),
1922            draws: gpu
1923                .into_iter()
1924                .map(|(texture, dst, size)| crate::gpu::GpuDraw {
1925                    texture,
1926                    dst: dst.map(|v| v as f32),
1927                    size,
1928                })
1929                .collect(),
1930            stage,
1931        };
1932        lp.add(egui_wgpu::Callback::new_paint_callback(clip, paint));
1933    }
1934    #[cfg(not(feature = "wgpu"))]
1935    let _ = gpu;
1936    let p = f64::from(ppp);
1937    let pic_px = [
1938        f64::from(pic.left()) * p,
1939        f64::from(pic.top()) * p,
1940        f64::from(pic.right()) * p,
1941        f64::from(pic.bottom()) * p,
1942    ];
1943    if l.grid {
1944        // Hairlines centred on the physical pixel past each edge.
1945        let stroke = Stroke::new(1.0 / ppp, tokens.loupe_grid.gamma_multiply(0.8));
1946        let half = 0.5 / ppp;
1947        let (xs, ys) = s.grid_lines(pic_px);
1948        for x in xs {
1949            let x = (x / p) as f32 + half;
1950            lp.line_segment([pos2(x, pic.top()), pos2(x, pic.bottom())], stroke);
1951        }
1952        for y in ys {
1953            let y = (y / p) as f32 + half;
1954            lp.line_segment([pos2(pic.left(), y), pos2(pic.right(), y)], stroke);
1955        }
1956    }
1957    let w = |x: f32| egui_pop_core::scale::stroke(ctx, x);
1958    if l.marker {
1959        let r = loupe::to_points(s.center_block(), ppp);
1960        lp.rect_stroke(
1961            r,
1962            0.0,
1963            Stroke::new(w(3.0), tokens.cursor_outline),
1964            StrokeKind::Outside,
1965        );
1966        lp.rect_stroke(
1967            r,
1968            0.0,
1969            Stroke::new(w(1.0), tokens.loupe_marker),
1970            StrokeKind::Outside,
1971        );
1972    }
1973    painter.rect_stroke(
1974        rect,
1975        0.0,
1976        Stroke::new(w(1.0), tokens.loupe_frame),
1977        StrokeKind::Inside,
1978    );
1979    if let Some(g) = galley {
1980        painter.galley(pos2(pic.left(), pic.bottom() + pad), g, t.text.default);
1981    }
1982    state.loupe_frame = Some(LoupeFrame {
1983        rect,
1984        picture: pic,
1985        sampling: s,
1986        tiles,
1987        gpu: on_gpu,
1988        lines,
1989        stale,
1990    });
1991}