Skip to main content

egui_pop_imaging/
preview.rs

1//! A preview dialog: an image viewport in a custom dialog (ADR 0013),
2//! the first use of `Dialog::Custom`. An export or a crop shows its
3//! effect before it runs: the viewport draws from a tile source of its
4//! own, the interface behind stays as it is (a `Clear` backdrop) and
5//! keeps drawing, its own viewport included, while the dialog is modal.
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! The dialog keeps every dialog rule: the primary button says what it
11//! does ("Export"), Enter runs it, Escape cancels it, except during a
12//! drag of the viewport (Escape then cancels the drag: the viewport
13//! claims Escape). It is movable and comes back where it was left. The
14//! viewport draws sRGB first (decided 2026-10-14): two overlapping
15//! wide-gamut image surfaces have not been tried.
16//!
17//! ```no_run
18//! use egui_pop_api::AppHandle;
19//! use egui_pop_imaging::preview::{self, Preview};
20//! use egui_pop_model::ids::CommandId;
21//! use egui_pop_viewport::demo::Procedural;
22//!
23//! fn export(app: &AppHandle) {
24//!     let preview = Preview::new("Export preview", "Export", CommandId::from_static("doc.export"));
25//!     let opened = preview::open(app, preview, |sink| Box::new(Procedural::new(sink, [4096, 3072], 2)));
26//!     if let Err(why) = opened {
27//!         eprintln!("no preview: {why}");
28//!     }
29//! }
30//! ```
31
32use std::cell::RefCell;
33use std::rc::Rc;
34
35use egui_pop_api::AppHandle;
36use egui_pop_api::dialogs::{Backdrop, Custom, DIALOGS, DialogSpec};
37use egui_pop_model::ids::CommandId;
38use egui_pop_viewport::source::{TileSink, TileSource};
39use egui_pop_viewport::{View, Viewport, ViewportState};
40use serde_json::{Value as Json, json};
41
42/// A preview dialog, as declared.
43#[derive(Clone, Debug, PartialEq)]
44pub struct Preview {
45    pub title: String,
46    /// The primary button: what accepting does ("Export 3 images").
47    pub verb: String,
48    pub command: CommandId,
49    /// Arguments the view is merged into (`view`: the zoom and centre
50    /// the preview was left at).
51    pub args: Json,
52    /// The share of the window the viewport takes.
53    pub share: f32,
54    /// The key its place is kept under.
55    pub remember: String,
56}
57
58impl Preview {
59    /// A preview whose primary button says what it does and runs
60    /// `command`; 70 % of the window, kept under `export.preview`.
61    pub fn new(title: &str, verb: &str, command: CommandId) -> Self {
62        Self {
63            title: title.into(),
64            verb: verb.into(),
65            command,
66            args: Json::Null,
67            share: Custom::SHARE,
68            remember: "export.preview".into(),
69        }
70    }
71
72    pub fn args(mut self, args: Json) -> Self {
73        self.args = args;
74        self
75    }
76
77    /// The share of the window the viewport takes.
78    pub fn share(mut self, share: f32) -> Self {
79        self.share = share;
80        self
81    }
82
83    /// The key its place is kept under.
84    pub fn remember(mut self, key: &str) -> Self {
85        self.remember = key.into();
86        self
87    }
88}
89
90/// The preview's viewport: its view, its state, its source.
91pub struct PreviewState {
92    pub view: View,
93    pub state: ViewportState,
94    pub source: Box<dyn TileSource>,
95}
96
97impl std::fmt::Debug for PreviewState {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("PreviewState")
100            .field("view", &self.view)
101            .field("complete", &self.state.tiles_complete())
102            .finish_non_exhaustive()
103    }
104}
105
106/// Opens a preview: `source` makes the tile source from the viewport's
107/// sink. Returns the dialog's id and the viewport's state, shared with
108/// the dialog's body; an error when the dialogs plugin is missing or
109/// the viewport does not fit a custom dialog.
110pub fn open(
111    app: &AppHandle,
112    preview: Preview,
113    source: impl FnOnce(TileSink) -> Box<dyn TileSource>,
114) -> Result<(u64, Rc<RefCell<PreviewState>>), String> {
115    let dialogs = app
116        .service(&DIALOGS)
117        .ok_or("the dialogs plugin is not connected")?;
118    let state = ViewportState::new();
119    let source = source(state.sink());
120    let shared = Rc::new(RefCell::new(PreviewState {
121        view: View::fit(),
122        state,
123        source,
124    }));
125    let custom = Custom::new(&preview.title, &preview.verb, preview.command.clone())
126        .args(preview.args.clone())
127        .share(preview.share)
128        .needs(egui_pop_viewport::mounts::viewport());
129    let spec = DialogSpec::new(custom)
130        .backdrop(Backdrop::Clear)
131        .movable(true)
132        .remember_position(&preview.remember);
133    let body = shared.clone();
134    let name = format!("preview.{}", preview.remember);
135    let id = dialogs.open_custom(app, spec, move |ui, _, pass| {
136        let mut p = body.borrow_mut();
137        let PreviewState {
138            view,
139            state,
140            source,
141        } = &mut *p;
142        // A drag of the view: this Escape cancels it, not the dialog.
143        if state.in_gesture() {
144            pass.claim_escape();
145        }
146        let _ = Viewport::new(name.as_str())
147            .source(source.as_ref())
148            .show(ui, state, view);
149        let center = [view.center[0], view.center[1]];
150        pass.value("view", json!({ "center": center }));
151        pass.describe(json!({
152            "center": center,
153            "complete": state.tiles_complete(),
154            "outstanding": state.outstanding(),
155        }));
156    })?;
157    Ok((id, shared))
158}