Skip to main content

egui_pop_imaging/
lib.rs

1//! The image tools of `egui-pop-viewport` in an application: each
2//! finished change of a tool runs as a step (ADR 0011), so plugins may
3//! veto it, redirect it, replace it or follow it, and the journal
4//! records it.
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! The tools are egui widgets: they see their changes through a hook
10//! (`on_change`). The functions here give a hook running each finished
11//! change (`done`: a drag's release, a key, a click, a reset) as the
12//! tool's step, named after the tool in its arguments; a drag's frames
13//! go through untouched.
14//!
15//! | Step | Arguments | Default |
16//! |---|---|---|
17//! | `histogram.drag` | `histogram`, `from`, `to` (`{at, delta}`: where the drag began, 0..1 or `null` for keys, and how far it moved in widths), `cause` | writes `to` |
18//! | `curve.change` | `curve`, `from`, `to` (`[[x, y], ...]`), `cause` (`drag`, `add`, `delete`, `reset`, `key`, `pick`, `access`) | writes `to` |
19//! | `wheel.change` | `wheel`, `from`, `to` (`{hue, chroma, luminance}`), `cause` | writes `to` |
20//! | `zoom.change` | `viewport`, `from`, `to` (`{zoom: "fit" or a number, center: [x, y]}`), `cause` (`command`, `drag`, `click`, `wheel`, `key`, `reset`) | writes `to` |
21//! | `cursor.resolve` | `viewport`, `query` (`{tool, modifiers, dragging, panning, handle, over_image, brush}`), `default` (`{system}`, `{tool}`, `{image}` or `{brush}`) | gives `default` |
22//! | `graph.connect`, `graph.disconnect`, `graph.move`, `graph.delete`, `graph.add` | `graph`, the edit's fields, `cause` | hands the edit to the application ([`graph`]) |
23//!
24//! A before-hook vetoes the change (the tool keeps, or goes back to,
25//! `from`) or redirects it (another `to`); a run-hook gives the value to
26//! write (its result); an after-hook follows it. [`ImagingPlugin`]
27//! declares the steps.
28//!
29//! `cursor.resolve` is not a change: a viewport asks it which cursor to
30//! show each time the situation under the pointer changes (the tool, the
31//! keys held, a drag, a handle). A run-hook (or a redirect of `default`)
32//! gives another cursor; a veto shows the default.
33//!
34//! [`preview`] opens a preview dialog: an image viewport in a custom
35//! dialog over a clear backdrop (ADR 0013).
36//!
37//! ```
38//! use egui_pop_api::AppHandle;
39//! use egui_pop_viewport::curve::CurveEditor;
40//!
41//! fn tone(ui: &mut egui::Ui, app: &AppHandle, points: &mut Vec<[f32; 2]>) {
42//!     CurveEditor::new(points, "Tone curve")
43//!         .on_change(egui_pop_imaging::curve(app, "tone"))
44//!         .show(ui);
45//! }
46//! ```
47
48pub mod graph;
49pub mod preview;
50
51pub use graph::{GRAPHS, Graphs, show_graph};
52
53use egui_pop_api::steps::{Outcome, StepSpec};
54use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
55use egui_pop_model::ids::{PluginId, StepId};
56use egui_pop_viewport::View;
57use egui_pop_viewport::change::{Change, StepValue, Verdict};
58use egui_pop_viewport::cursor::{Cursor, CursorQuery};
59use egui_pop_viewport::histogram::Drag;
60use egui_pop_viewport::wheel::WheelValue;
61use serde_json::json;
62
63/// A histogram's drag ends (or a key moves it).
64pub const STEP_HISTOGRAM: StepId = StepId::from_static("histogram.drag");
65/// A curve's points change.
66pub const STEP_CURVE: StepId = StepId::from_static("curve.change");
67/// A colour wheel's value changes.
68pub const STEP_WHEEL: StepId = StepId::from_static("wheel.change");
69/// A zoom control or a navigator changes a viewport's view.
70pub const STEP_ZOOM: StepId = StepId::from_static("zoom.change");
71/// A viewport asks which cursor to show.
72pub const STEP_CURSOR: StepId = StepId::from_static("cursor.resolve");
73
74/// The plugin's id.
75pub const IMAGING_PLUGIN: PluginId = PluginId::from_static("egui_pop.imaging");
76
77/// The steps, as [`ImagingPlugin`] declares them.
78pub fn specs() -> Vec<StepSpec> {
79    let mut specs = tool_specs();
80    specs.extend(graph::specs());
81    specs
82}
83
84/// The image tools' steps.
85fn tool_specs() -> Vec<StepSpec> {
86    vec![
87        StepSpec::new(
88            STEP_HISTOGRAM,
89            "A histogram's drag ends, or a key moves it (`histogram`, `from`, `to`: {at, delta}, `cause`); a veto gives the gesture back, a redirect or a run-hook gives another distance.",
90        )
91        .args(json!({
92            "histogram": "main",
93            "from": { "at": 0.8, "delta": 0.0 },
94            "to": { "at": 0.8, "delta": 0.12 },
95            "cause": "drag",
96        })),
97        StepSpec::new(
98            STEP_CURVE,
99            "A curve's points change at the end of a gesture (`curve`, `from`, `to`: [[x, y], ...], `cause`); a veto keeps `from`, a redirect or a run-hook gives other points.",
100        )
101        .args(json!({
102            "curve": "tone",
103            "from": [[0.0, 0.0], [1.0, 1.0]],
104            "to": [[0.0, 0.0], [0.5, 0.6], [1.0, 1.0]],
105            "cause": "add",
106        })),
107        StepSpec::new(
108            STEP_WHEEL,
109            "A colour wheel's value changes at the end of a gesture (`wheel`, `from`, `to`: {hue, chroma, luminance}, `cause`); a veto keeps `from`, a redirect or a run-hook gives another value.",
110        )
111        .args(json!({
112            "wheel": "lift",
113            "from": { "hue": 0.0, "chroma": 0.0, "luminance": 0.0 },
114            "to": { "hue": 210.0, "chroma": 0.2, "luminance": 0.0 },
115            "cause": "drag",
116        })),
117        StepSpec::new(
118            STEP_ZOOM,
119            "A zoom control or a navigator changes a viewport's view (`viewport`, `from`, `to`: {zoom, center}, `cause`); a veto keeps `from`, a redirect or a run-hook gives another view.",
120        )
121        .args(json!({
122            "viewport": "main",
123            "from": { "zoom": "fit", "center": [0.0, 0.0] },
124            "to": { "zoom": 1.0, "center": [3000.0, 2000.0] },
125            "cause": "command",
126        })),
127        StepSpec::new(
128            STEP_CURSOR,
129            "A viewport asks which cursor to show when the situation under the pointer changes (`viewport`, `query`: {tool, modifiers, dragging, panning, handle, over_image, brush}, `default`: egui-pop's cursor); a run-hook or a redirect of `default` gives another ({system}, {tool}, {image} or {brush}), a veto shows the default.",
130        )
131        .args(json!({
132            "viewport": "main",
133            "query": CursorQuery::new(egui_pop_viewport::cursor::Tool::Zoom).to_json(),
134            "default": { "tool": "zoom-in" },
135        })),
136    ]
137}
138
139/// Declares the image tools' steps, and the node editors' steps,
140/// registry ([`GRAPHS`]) and agent commands.
141#[derive(Debug, Default)]
142pub struct ImagingPlugin;
143
144impl Plugin for ImagingPlugin {
145    fn id(&self) -> PluginId {
146        IMAGING_PLUGIN
147    }
148
149    fn title(&self) -> String {
150        "Image tools".into()
151    }
152
153    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
154        for spec in specs() {
155            ctx.step(spec)?;
156        }
157        graph::connect(ctx)?;
158        Ok(())
159    }
160}
161
162/// A hook running each finished change as `step`, the tool named
163/// `name` under `key` in its arguments.
164fn hook<'a, T: StepValue>(
165    app: &'a AppHandle,
166    step: StepId,
167    key: &'static str,
168    name: &'a str,
169) -> impl FnMut(&Change<T>) -> Verdict<T> + 'a {
170    move |c: &Change<T>| {
171        if !c.done {
172            return Verdict::Allow;
173        }
174        let mut args = json!({
175            "from": c.from.to_json(),
176            "to": c.to.to_json(),
177            "cause": c.cause.name(),
178        });
179        args[key] = json!(name);
180        match app.step(&step, args, |_, args| Ok(args["to"].clone())) {
181            Outcome::Done(Ok(v)) => match T::from_json(&v) {
182                Some(to) if to == c.to => Verdict::Allow,
183                Some(to) => Verdict::Redirect(to),
184                None => Verdict::Veto,
185            },
186            Outcome::Done(Err(_)) | Outcome::Vetoed { .. } => Verdict::Veto,
187        }
188    }
189}
190
191/// A histogram hook ([`Histogram::on_change`](egui_pop_viewport::histogram::Histogram::on_change))
192/// running each finished change as the `histogram.drag` step.
193pub fn histogram<'a>(
194    app: &'a AppHandle,
195    name: &'a str,
196) -> impl FnMut(&Change<Drag>) -> Verdict<Drag> + 'a {
197    hook(app, STEP_HISTOGRAM, "histogram", name)
198}
199
200/// A curve's points, `[x, y]` in 0..1.
201pub type Points = Vec<[f32; 2]>;
202
203/// A curve editor hook ([`CurveEditor::on_change`](egui_pop_viewport::curve::CurveEditor::on_change))
204/// running each finished change as the `curve.change` step.
205pub fn curve<'a>(
206    app: &'a AppHandle,
207    name: &'a str,
208) -> impl FnMut(&Change<Points>) -> Verdict<Points> + 'a {
209    hook(app, STEP_CURVE, "curve", name)
210}
211
212/// A colour wheel hook ([`ColorWheel::on_change`](egui_pop_viewport::wheel::ColorWheel::on_change))
213/// running each finished change as the `wheel.change` step.
214pub fn wheel<'a>(
215    app: &'a AppHandle,
216    name: &'a str,
217) -> impl FnMut(&Change<WheelValue>) -> Verdict<WheelValue> + 'a {
218    hook(app, STEP_WHEEL, "wheel", name)
219}
220
221/// A zoom control or navigator hook
222/// ([`Navigator::on_change`](egui_pop_viewport::navigator::Navigator::on_change),
223/// [`ZoomControl::on_change`](egui_pop_viewport::navigator::ZoomControl::on_change))
224/// running each finished change as the `zoom.change` step, the viewport
225/// named `name`.
226pub fn zoom<'a>(
227    app: &'a AppHandle,
228    name: &'a str,
229) -> impl FnMut(&Change<View>) -> Verdict<View> + 'a {
230    hook(app, STEP_ZOOM, "viewport", name)
231}
232
233/// A viewport's cursor hook ([`Viewport::on_cursor`](egui_pop_viewport::Viewport::on_cursor))
234/// running each new situation as the `cursor.resolve` step, the viewport
235/// named `name`: plugins give another cursor for a tool, a key held, a
236/// handle. An answer that is not a cursor keeps the default.
237pub fn cursor<'a>(
238    app: &'a AppHandle,
239    name: &'a str,
240) -> impl FnMut(&CursorQuery, Cursor) -> Cursor + 'a {
241    move |q: &CursorQuery, default: Cursor| {
242        let args = json!({
243            "viewport": name,
244            "query": q.to_json(),
245            "default": default.to_json(),
246        });
247        match app.step(&STEP_CURSOR, args, |_, args| Ok(args["default"].clone())) {
248            Outcome::Done(Ok(v)) => Cursor::from_json(&v).unwrap_or(default),
249            Outcome::Done(Err(_)) | Outcome::Vetoed { .. } => default,
250        }
251    }
252}