From bd5c5aa139fda4c0d9669689df8d3cc6be5909ba Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:30:11 +0700 Subject: [PATCH] color-w18: net change of 1 commits - color-w18: written by an agent --- crates/ui-egui/src/dialogs/color_balance.rs | 287 +++++--- crates/ui-egui/src/dialogs/gradient_stop.rs | 721 ++++++++++++-------- crates/ui-egui/src/dialogs/saturate.rs | 63 +- 3 files changed, 673 insertions(+), 398 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 65ca83056f..f80f505530 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -1,28 +1,35 @@ //! Edit → Edit Colors → Adjust Color Balance: the colour mode (Gray, RGB, CMYK or Global), a slider -//! per channel (−100..100 %; Global has one, Tint, for the tints of global and spot colours), +//! per channel (−100..100 %; Global has one, Tint, for the tints of global and spot colors), //! Convert, Fill and Stroke, previewed live on the canvas; OK keeps the preview as one undo step //! (`edit.colors.adjustBalance`). //! +//! The dialog lives on the dialog host as a `HostedParamDialog`; [`Adjust`] is the one mechanism it +//! shares with Saturate: it opens the dialog, runs the live preview from the dialog's values each +//! frame (`pump`) and commits the preview at OK. +//! //! Fields: `mode` (`gray`, `rgb`, `cmyk` or `global`), the channels `r`, `g`, `b`, `c`, `m`, `y`, -//! `k`, `gray`, `tint`, then `convert`, `fill`, `stroke` and `preview`. +//! `k`, `gray`, `tint`, then `convert`, `fill` and `stroke`. The preview check box is the host's. +use craft::color_ui::ui::{ChannelRow, ChannelRule, ChannelUnit}; +use craft::theme::Srgba; +use craft::ui::contract::Bind; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::{CustomContext, DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::runtime::env::Label; use serde_json::{Value, json}; use vectorcraft_color::Color; -use super::{DialogSpec, form}; +use super::color_picker::ColorDialogs; +use super::host; +use super::preview::LivePreview; use crate::VectorcraftApp; use crate::panels::c32; -use crate::state::Dialog; -use crate::widgets; /// The dialog kind of Adjust Color Balance. pub const KIND: &str = "colorBalance"; const CMD: &str = "edit.colors.adjustBalance"; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Adjust Colors").into(), body, confirm, preview: true, min_width: 340.0, ..DialogSpec::FORM }; - /// A colour mode: its `mode` id, label and channels as (field, label). struct Mode { id: &'static str, @@ -40,32 +47,142 @@ const MODES: [Mode; 4] = [ /// Global mode: it shifts the tints of linked colours, which keep their model (no Convert). const GLOBAL: &str = "global"; -/// Open the dialog with every channel at 0, adjusting fills and strokes. -pub fn open(app: &mut VectorcraftApp) { - let fields = json!({ - "mode": "rgb", "r": 0, "g": 0, "b": 0, "c": 0, "m": 0, "y": 0, "k": 0, "gray": 0, "tint": 0, - "convert": false, "fill": true, "stroke": true, "preview": true, - }); - app.ui.dialog = Some(Dialog::new(KIND, fields)); +/// The record of an open Edit Colors dialog: its id on the host and the live preview it shows on the canvas. +pub(crate) struct Open { + /// The dialog's id on the host. + pub id: DialogId, + /// The preview the dialog's values run as one interaction. + pub preview: LivePreview, } -fn mode(d: &Dialog) -> &'static Mode { - let id = d.str("mode"); +/// What an Edit Colors dialog is: how it opens, previews and commits. Balance and Saturate differ only in these values. +#[derive(Clone, Copy)] +pub(super) struct Adjust { + /// The dialog's key on the host. + pub(super) kind: &'static str, + /// The command the dialog previews and commits. + pub(super) cmd: &'static str, + /// The title and the name of the preview's undo step. + pub(super) label: &'static str, + /// Where the open dialog's record is kept. + pub(super) slot: fn(&mut ColorDialogs) -> &mut Option, + /// The values the dialog opens with. + pub(super) initial: fn() -> DialogFields, + /// The dialog's rows. + pub(super) rows: fn() -> Vec, + /// The command's parameters for the dialog's values. + pub(super) params: fn(&DialogFields) -> Value, +} + +impl Adjust { + /// Opens the dialog with its initial values; one still open is replaced and its preview rolled back. + pub(super) fn open(self, app: &mut VectorcraftApp) { + if let Err(reason) = self.try_open(app) { + app.status(reason); + } + } + + fn try_open(self, app: &mut VectorcraftApp) -> Result<(), String> { + const NO_WINDOW: &str = "no window to open the dialog in"; + let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; + if let Some(old) = (self.slot)(&mut app.color_dialogs).take() { + old.preview.cancel(app); + } + let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| { + ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true) + }); + let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?; + *(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview: LivePreview::default() }); + Ok(()) + } + + /// OK: keeps the preview as one undo step; an `Err` keeps the dialog open with the reason. + fn commit(self, app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { + let live = (self.slot)(&mut app.color_dialogs).as_ref().map(|open| open.preview.clone()).unwrap_or_default(); + // PLAN: assumed `LivePreview::commit(self, ..)` as the contract row says; the clone keeps the record when it fails. + live.commit(app, self.cmd, (self.params)(&answer.fields))?; + *(self.slot)(&mut app.color_dialogs) = None; + Ok(()) + } + + /// Once per frame: previews the dialog's values while its Preview box is on, and rolls the preview back once the + /// dialog is gone without OK. + pub(super) fn pump(self, app: &mut VectorcraftApp) { + let Some(Open { id, mut preview }) = (self.slot)(&mut app.color_dialogs).take() else { return }; + let shown = app.dialogs().and_then(|dialogs| { + dialogs.with(|host| host.get_mut_by_id::(id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields())))) + }); + match shown { + Some((on, params)) => { + // `run` reports a failed preview to the status line itself. + let _ = preview.run(app, on, self.label, self.cmd, ¶ms); + *(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview }); + } + None => preview.cancel(app), + } + } +} + +/// A channel row over the percent value `key` of `fields` (−100..100 %), its rail the colours `track` gives from the +/// rail's start to its end. +pub(super) fn percent_row(ui: &mut egui::Ui, fields: &mut DialogFields, key: &str, label: &'static str, track: impl Fn(f32) -> Srgba) { + const RAIL_STOPS: usize = 5; + let rail = (0..RAIL_STOPS).map(|i| track(i as f32 / (RAIL_STOPS - 1) as f32)).collect(); + let rule = ChannelRule { range: -100.0..=100.0, step: 1.0, decimals: 0 }; + let value = fields.number(key).unwrap_or(0.0); + let edit = ChannelRow::new(label, Bind::given(value), rule).unit(ChannelUnit::Percent).track(rail).show(ui); + if let Some(value) = edit.as_ref().and_then(|edit| edit.value()) { + fields.set(key, *value); + } +} + +const ADJUST: Adjust = Adjust { kind: KIND, cmd: CMD, label: "Adjust Colors", slot, initial, rows, params }; + +fn slot(dialogs: &mut ColorDialogs) -> &mut Option { + &mut dialogs.balance +} + +/// Open the dialog with every channel at 0, adjusting fills and strokes. +pub fn open(app: &mut VectorcraftApp) { + ADJUST.open(app); +} + +/// Previews the open dialog; one line of `dialogs::host::pump`. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + ADJUST.pump(app); +} + +/// Every channel field of every mode. +fn channel_keys() -> impl Iterator { + MODES.iter().flat_map(|m| m.channels.iter()).map(|(key, _)| *key) +} + +fn initial() -> DialogFields { + let mut fields = DialogFields::new(); + for key in channel_keys() { + fields.set(key, 0.0); + } + fields +} + +fn mode(fields: &DialogFields) -> &'static Mode { + let id = fields.text("mode").unwrap_or_default(); MODES.iter().find(|m| m.id == id).unwrap_or(&MODES[1]) } /// `edit.colors.adjustBalance` parameters: the mode, its channels and the options. -fn params(d: &Dialog) -> Value { - let m = mode(d); - let mut p = json!({"mode": m.id, "convert": d.bool("convert"), "fill": d.bool("fill"), "stroke": d.bool("stroke")}); +fn params(fields: &DialogFields) -> Value { + let m = mode(fields); + let flag = |key: &str| fields.bool(key).unwrap_or_default(); + let mut p = json!({"mode": m.id, "convert": flag("convert"), "fill": flag("fill"), "stroke": flag("stroke")}); for (k, _) in m.channels { - p[*k] = json!(d.f64(k, 0.0)); + p[*k] = json!(fields.number(k).unwrap_or(0.0)); } p } /// The rail of channel `key`: the channel from −100 % to +100 % over a mid colour. -fn track(key: &str, x: f32) -> egui::Color32 { +fn track(key: &str, x: f32) -> Srgba { let v = x.clamp(0.0, 1.0); let c = match key { "r" => Color::rgb(v, 0.5, 0.5), @@ -77,93 +194,91 @@ fn track(key: &str, x: f32) -> egui::Color32 { "k" => Color::cmyk(0.0, 0.0, 0.0, v), _ => Color::gray(v), }; - c32(&c) + Srgba::from(c32(&c)) } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let m = mode(d); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Color Mode:")); - let labels: Vec<&str> = MODES.iter().map(|m| m.label).collect(); - if let Some(i) = widgets::dropdown(ui, "balance-mode", m.label, &labels, 120.0) { - d.fields.insert("mode".into(), json!(MODES[i].id)); +/// The channel rows of the current mode. +fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response { + ui.vertical(|ui| { + for (key, label) in mode(fields).channels { + percent_row(ui, fields, key, *label, |x| track(key, x)); } - ui.add_space(12.0); - if widgets::check(ui, tl!("Convert"), d.bool("convert"), m.id != GLOBAL) { - d.fields.insert("convert".into(), json!(!d.bool("convert"))); - } - }); - ui.add_space(8.0); - let m = mode(d); - if m.id == GLOBAL { - widgets::dim_label(ui, tl!("Shifts the tints of global and spot colors; other colors stay.")); - } - for (k, label) in m.channels { - form::slider(ui, d, k, label, -100.0..=100.0, "%", &|x| track(k, x)); - } - ui.add_space(8.0); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Adjust Options:")); - for (k, label) in [("fill", tl!("Fill")), ("stroke", tl!("Stroke"))] { - if widgets::check(ui, label, d.bool(k), true) { - d.fields.insert(k.into(), json!(!d.bool(k))); - } - } - }); - let p = params(d); - form::preview(app, ui, d, "Adjust Colors", CMD, p); - false + }) + .response } -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - form::commit_preview(app, CMD, params(d)) +fn rows() -> Vec { + let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(m.label))).collect(); + let with_model = MODES.iter().map(|m| m.id).filter(|id| *id != GLOBAL); + vec![ + Param::new("mode", "Color Mode", ParamKind::choice(modes, Some("rgb".to_owned()))), + Param::new("convert", "Convert", ParamKind::bool(false)).enabled_when_in("mode", with_model), + Param::read_only_text("note", "", "Shifts the tints of global and spot colors; other colors stay.").visible_when("mode", GLOBAL), + Param::custom("channels", "Channels", channels).companions(channel_keys()), + Param::section("Adjust Options"), + Param::new("fill", "Fill", ParamKind::bool(true)), + Param::new("stroke", "Stroke", ParamKind::bool(true)), + ] } #[cfg(test)] mod tests { - use super::*; + use craft::ui::dialog::dialog_id; use vectorcraft_engine::Session; + use super::*; + fn fill_hex(app: &VectorcraftApp, id: u64) -> String { let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); n.appearance.fill_paint().color().unwrap().to_hex() } - fn frame(app: &mut VectorcraftApp) { + /// An app with the window context that hosts the dialog. + fn app() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); + app.ui_ctx = Some(ctx.clone()); + (app, ctx) + } + + fn set(app: &VectorcraftApp, ctx: &egui::Context, field: &str, value: Value) { + app.dialogs().unwrap().with(|host| host.set_json_field(ctx, dialog_id(KIND), field, value)).unwrap(); + } + + /// OK as the button files it, then the frame that drains it. + fn confirm(app: &mut VectorcraftApp, ctx: &egui::Context) { + app.dialogs().unwrap().with(|host| host.confirm_by_id(ctx, dialog_id(KIND))); + host::pump(app, ctx); } #[test] fn previews_live_and_commits_one_undo_step() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (mut app, ctx) = app(); app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); app.run("paint.setFill", json!({"color": "#808080"})).unwrap(); let undo = app.session.doc().unwrap().history.undo.len(); - app.run("ui.colorBalanceDialog", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); - app.ui.dialog.as_mut().unwrap().fields.insert("r".into(), json!(20)); - frame(&mut app); + open(&mut app); + assert!(app.dialogs().unwrap().with(|host| host.is_open::())); + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); assert!(app.session.in_interaction(), "the preview runs"); assert_eq!(fill_hex(&app, id), "#b38080", "previewed on the canvas"); - // A field set from outside (`ui.dialog.set`) previews on the next frame. - app.ui.dialog.as_mut().unwrap().fields.insert("r".into(), json!(40)); - frame(&mut app); + // A field set from outside previews on the next frame. + set(&app, &ctx, "r", json!(40)); + host::pump(&mut app, &ctx); assert_eq!(fill_hex(&app, id), "#e68080"); // Cancel rolls the preview back. - super::super::cancel(&mut app); + app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog_id(KIND))); + host::pump(&mut app, &ctx); assert_eq!(fill_hex(&app, id), "#808080"); // OK keeps it as one undo step. - app.run("ui.colorBalanceDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("mode".into(), json!("cmyk")); - d.fields.insert("k".into(), json!(-50)); - frame(&mut app); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + open(&mut app); + set(&app, &ctx, "mode", json!("cmyk")); + set(&app, &ctx, "k", json!(-50)); + host::pump(&mut app, &ctx); + confirm(&mut app, &ctx); + assert!(!app.session.in_interaction()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); let lighter = vectorcraft_color::Color::from_hex(&fill_hex(&app, id)).unwrap().to_rgb()[0]; assert!(lighter > 0.6, "{lighter}"); @@ -171,18 +286,18 @@ mod tests { #[test] fn global_mode_shifts_the_tints_of_global_colours() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (mut app, ctx) = app(); app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 1, "y": 0, "k": 0}, "spot": true})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); app.run("paint.setFill", json!({"swatch": "Ink", "tint": 50})).unwrap(); - app.run("ui.colorBalanceDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("mode".into(), json!("global")); - d.fields.insert("tint".into(), json!(-20)); - frame(&mut app); - assert_eq!(params(app.ui.dialog.as_ref().unwrap())["tint"], json!(-20.0)); - super::super::confirm(&mut app).unwrap(); + open(&mut app); + set(&app, &ctx, "mode", json!("global")); + set(&app, &ctx, "tint", json!(-20)); + host::pump(&mut app, &ctx); + let tint = app.dialogs().unwrap().with(|host| host.get_by_id::(dialog_id(KIND)).map(|d| params(d.fields())["tint"].clone())); + assert_eq!(tint, Some(json!(-20.0))); + confirm(&mut app, &ctx); let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); let vectorcraft_color::Paint::Solid { swatch, tint, .. } = n.appearance.fill_paint() else { panic!() }; assert_eq!(swatch.as_deref(), Some("Ink"), "the colour stays linked"); diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 63dcfa916b..6bc5baffab 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -2,35 +2,54 @@ //! Gradient panel's slider) edits it next to its chip — its colour (the Color panel's controls, //! or a document swatch, which stays linked when it is a global or spot colour), opacity and //! location. It edits the selected stop (`gradient.selectStop`) through `paint.editGradient`, and -//! closes on Escape or a click elsewhere. On a freeform gradient it edits the selected point +//! closes on Escape or a press elsewhere. On a freeform gradient it edits the selected point //! (`paint.freeform.selectPoint`) instead: its colour, opacity and spread, through //! `paint.freeform.setPoint`. //! -//! Fields: `index`, `x`, `y` (the chip, document coordinates) or `screen` ([x, y], screen points, -//! from the panel), and `tab` (`color` or `swatches`). -//! Agents can set `color` (hex), `opacity` and `location` (a point: `spread`) as percentages, -//! and confirm. +//! The popover is a `StackDialog` on the dialog host. It holds plain data that `pump` pushes each +//! frame (the target's values, the swatches, what the Color panel shows, where it goes) and files what +//! the user did for `pump` to apply, since `show` has no app. +//! +//! Fields: `tab` (`color` or `swatches`). Agents can set `color` (hex), `opacity` and `location` (a +//! point: `spread`) as percentages, and confirm; confirming reports no stop index. -use egui::{Sense, vec2}; +use craft::behavior::IconId; +use craft::color_ui::ui::{ColorPanel, ColorPanelLayout, ColorPanelOutput, ColorPanelShown, ColorPanelState, DropperButton, SwatchPalette}; +use craft::theme::Srgba; +use craft::theme::variant::Tone; +use craft::ui::choice::Segmented; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::form::Field; +use craft::ui::layout_components::Stack; +use craft::ui::notices::Notice; +use craft::ui::popover::Popover; +use craft::ui::runtime::env::{Label, UnitKind}; +use craft::ui::runtime::overlay::CloseReason; +use craft::ui::text::NumberField; +use egui::{Pos2, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::gradient::move_stop; use vectorcraft_color::{Color, FreeformPoint, GradientKind, GradientStop, Paint}; -use vectorcraft_geom::Point; +use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; -use super::{DialogResult, DialogSpec}; use crate::VectorcraftApp; -use crate::canvas::Xf; -use crate::panels::active_paint; -use crate::panels::gradient::{edit_point, set_stops, shown_points}; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::widgets::{self, Live}; +use crate::panels::gradient::{edit_point, set_stops, set_stops_keeping_models, shown_points}; +use crate::panels::{Live, active_paint, c32}; -pub(super) const SPEC: DialogSpec = DialogSpec { inputs: |_| &["color", "opacity", "location", "spread"], ..DialogSpec::window(show, confirm) }; +/// The dialog kind of the gradient stop popover. +pub const KIND: &str = "gradientStop"; -/// The field holding the frame the popover was first drawn in. -const OPENED: &str = "__opened"; +/// Where the popover opens: at a screen point (from the Gradient panel's chip) or beside the art, from the +/// chip of a stop on the canvas (a document point). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Anchor { + /// A screen point. + Screen(Pos2), + /// A stop's or point's chip on the canvas, in document coordinates. + Chip(Point), +} /// What the popover edits: the selected stop of the gradient behind the active proxy (with all /// its stops), or the selected point of a freeform gradient. @@ -42,16 +61,23 @@ enum Target { impl Target { fn color(&self) -> Color { match self { - Target::Stop(stops, i) => stops[*i].color, + Target::Stop(stops, i) => stops.get(*i).map_or(Color::BLACK, |s| s.color), Target::Point(p, _) => p.color, } } fn opacity(&self) -> f32 { match self { - Target::Stop(stops, i) => stops[*i].opacity, + Target::Stop(stops, i) => stops.get(*i).map_or(1.0, |s| s.opacity), Target::Point(p, _) => p.opacity, } } + /// The location of a stop or the spread of a point, 0 to 1. + fn amount(&self) -> f32 { + match self { + Target::Stop(stops, i) => stops.get(*i).map_or(0.0, |s| s.offset), + Target::Point(p, _) => p.spread, + } + } } fn selected(app: &VectorcraftApp) -> Option { @@ -78,104 +104,217 @@ fn swatch_colors(app: &VectorcraftApp) -> Vec<(String, Color)> { d.swatches.iter().chain(d.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter_map(|s| Some((s.name.clone(), s.paint.color()?))).collect() } -fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { - let Some(d) = app.ui.dialog.clone() else { return }; - // The stop or point went away (undo, another object selected): nothing left to edit. - let Some(target) = selected(app) else { - app.ui.dialog = None; - return; - }; - let t = Tokens::get(ctx); - // Opened from the Gradient panel: at `screen`; from the annotator: beside the chip. - let screen = - d.fields.get("screen").and_then(Value::as_array).and_then(|a| Some(egui::pos2(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32))); - let chip = Point::new(d.f64("x", 0.0), d.f64("y", 0.0)); - let area = egui::Id::unique("gradient-stop-popover"); - let size = ctx.memory(|m| m.area_rect(area)).map_or(POPOVER_SIZE, |r| r.size()); - let pos = screen.unwrap_or_else(|| match app.canvas_rect.zip(app.canvas_xf()) { - Some((canvas, xf)) => { - let at = xf.to_screen(chip); - selection_on_screen(app, &xf).map_or(at + vec2(14.0, 14.0), |art| beside_art(at, art, size, canvas)) +/// The popover's two views. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Tab { + /// The Color panel's controls. + #[default] + Color, + /// The document's swatches. + Swatches, +} + +impl Tab { + /// The tab's name in the `tab` field. + fn id(self) -> &'static str { + match self { + Tab::Color => "color", + Tab::Swatches => "swatches", } - None => ctx.content_rect().center(), - }); - let swatches = d.str("tab") == "swatches"; - let mut tab = None; - let mut eyedropper = false; - let resp = egui::Area::new(area) - .order(egui::Order::Foreground) - .fixed_pos(pos) - .constrain(true) - .show(ctx, |ui| { - egui::Frame::popup(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(10)).show(ui, |ui| { - ui.set_width(250.0); - ui.horizontal(|ui| { - for (icon, tip, on) in [("palette", tl!("Color"), !swatches), ("swatch-book", tl!("Swatches"), swatches)] { - if widgets::icon_button(ui, icon, tip, on, 24.0).clicked() { - tab = Some(if icon == "palette" { "color" } else { "swatches" }); - } - } - // A stop's colour can come from the art, as from the Gradient panel's eyedropper. - if matches!(target, Target::Stop(..)) - && widgets::icon_button(ui, "pipette", tl!("Eyedropper: click the art to sample the stop's colour"), false, 24.0).clicked() - { - eyedropper = true; - } - }); - ui.add_space(6.0); - if swatches { - swatch_grid(app, ui, &target); - } else { - // The Color panel edits the selected stop (or point) of the active gradient. - crate::panels::color::show(app, ui); - } - ui.add_space(6.0); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Opacity:")); - if let Some(v) = widgets::plain_field(ui, "stop-pop-op", target.opacity() as f64 * 100.0, "%", 0, 54.0) { - apply(app, &target, &json!({ "opacity": v })); - } - let (label, key, value) = match &target { - Target::Stop(stops, i) => (tl!("Location:"), "location", stops[*i].offset), - Target::Point(p, _) => (tl!("Spread:"), "spread", p.spread), - }; - widgets::dim_label(ui, label); - if let Some(v) = widgets::plain_field(ui, ("stop-pop", key), value as f64 * 100.0, "%", 1, 54.0) { - apply(app, &target, &json!({ key: v })); - } - }); - }); - }) - .response; - if eyedropper { - app.ui.dialog = None; - crate::panels::gradient::stop_eyedropper(app); - return; - } - // The frame it opened in (its first drawn). - let frame = ctx.cumulative_frame_nr(); - let opened = d.fields.get(OPENED).and_then(Value::as_u64).unwrap_or(frame); - if let Some(d) = app.ui.dialog.as_mut() { - if let Some(tab) = tab { - d.fields.insert("tab".into(), json!(tab)); - } - d.fields.insert(OPENED.into(), json!(opened)); - } - // The click that opened the popover (the Gradient panel's colour chip) or the double-click - // (a stop's chip) lands outside it: only a later click elsewhere closes it (#577). - if frame > opened && resp.clicked_elsewhere() && !ctx.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)) { - app.ui.dialog = None; } } -/// The popover's size before it has been drawn. +/// The fields set from outside the popover or edited in it, as percentages where the field is one; each `None` is +/// a field left alone. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct PopoverFields { + color: Option, + opacity: Option, + location: Option, + spread: Option, +} + +/// The target's values and what the Color panel shows, as `pump` last pushed them. +#[derive(Clone)] +struct Feed { + /// A freeform point (spread) rather than a stop (location). + point: bool, + color: Color, + /// The colour as the panel and the swatches show it. + current: Srgba, + /// Percent. + opacity: f64, + /// Percent: the stop's location or the point's spread. + amount: f64, + swatches: Vec<(String, Color)>, + /// `swatches` as the palette draws them, in the same order. + tiles: Vec<(Label, Srgba)>, + shown: ColorPanelShown, +} + +/// What the user did in the popover since `pump` last took it. +#[derive(Default)] +struct Filed { + fields: PopoverFields, + swatch: Option<(String, Color)>, + eyedropper: bool, + panels: Vec, +} + +/// The gradient stop popover. +pub(crate) struct GradientStopPopover { + /// Where it opened. + pub(crate) anchor: Anchor, + /// The view it shows. + pub(crate) tab: Tab, + /// The screen point it hangs from, as `pump` last placed it. + at: Pos2, + panel: ColorPanelState, + feed: Option, + /// The fields set from outside, applied at confirm. + set: PopoverFields, + filed: Filed, +} + +impl GradientStopPopover { + fn new(anchor: Anchor) -> Self { + Self { + anchor, + tab: Tab::default(), + at: Pos2::ZERO, + panel: ColorPanelState::default(), + feed: None, + set: PopoverFields::default(), + filed: Filed::default(), + } + } + + fn take_filed(&mut self) -> Filed { + std::mem::take(&mut self.filed) + } +} + +fn rejects(field: &str, value: &Value) -> String { + FieldRefusal::Rejects(value).message(field) +} + +impl StackDialog for GradientStopPopover { + type Result = PopoverFields; + + fn id(&self) -> DialogId { + dialog_id(KIND) + } + + fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option> { + let Self { feed: Some(feed), tab, panel, filed, at, set, .. } = self else { return None }; + let mut open = true; + let shown = Popover::new("Gradient stop", Bind::bound(&mut open)).at_point(*at).close_on_enter(true).show(ui, |ui, _| body(ui, feed, tab, panel, filed)); + match shown.output.closed { + Some(CloseReason::Enter) => Some(DialogResult::Ok(set.clone())), + Some(_) => Some(DialogResult::Cancel), + None => None, + } + } + + fn json_fields(&self) -> Option { + let mut fields = json!({ "tab": self.tab.id() }); + if let Some(feed) = &self.feed { + let (key, set) = if feed.point { ("spread", self.set.spread) } else { ("location", self.set.location) }; + fields["color"] = json!(self.set.color.unwrap_or(feed.color).to_hex()); + fields["opacity"] = json!(self.set.opacity.unwrap_or(feed.opacity)); + fields[key] = json!(set.unwrap_or(feed.amount)); + } + Some(fields) + } + + fn set_json_field(&mut self, _ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { + let number = || value.as_f64().ok_or_else(|| rejects(field, &value)); + match field { + "tab" => { + self.tab = match value.as_str() { + Some("color") => Tab::Color, + Some("swatches") => Tab::Swatches, + _ => return Err(rejects(field, &value)), + } + } + "color" => { + let hex = value.as_str().ok_or_else(|| rejects(field, &value))?; + self.set.color = Some(Color::from_hex(hex).ok_or_else(|| format!("bad colour `{hex}` (#rrggbb)"))?); + } + "opacity" => self.set.opacity = Some(number()?), + "location" => self.set.location = Some(number()?), + "spread" => self.set.spread = Some(number()?), + _ => return Err(FieldRefusal::Unknown.message(field)), + } + Ok(()) + } + + /// OK (agents): the fields that were set, which `pump` applies; an untouched popover confirms to no change. + fn confirm(&mut self, _ctx: &egui::Context) -> Option { + Some(self.set.clone()) + } +} + +/// The popover's body: the tabs and the eyedropper, the Color panel or the swatches, then opacity and location (a +/// point: spread). What the user edits is filed in `filed`. +fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) { + Stack::new().show(ui, |ui, _| { + ui.horizontal(|ui| { + let tabs = [ + Entry::new(Tab::Color, tl!("Color").to_owned()).icon(IconId::new("palette")), + Entry::new(Tab::Swatches, tl!("Swatches").to_owned()).icon(IconId::new("swatch-book")), + ]; + Segmented::new("View", Bind::bound(&mut *tab), &tabs).show(ui); + // A stop's colour can come from the art, as from the Gradient panel's eyedropper. + if !feed.point { + let tip = tl!("Eyedropper: click the art to sample the stop's colour").to_owned(); + filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true); + } + }); + match *tab { + // The Color panel edits the selected stop (or point) of the active gradient. + Tab::Color => { + filed.panels.push(ColorPanel::new(Bind::bound(&mut *panel), [feed.current; 2]).layout(ColorPanelLayout::FillStroke).shown(feed.shown.clone()).show(ui)); + } + Tab::Swatches => swatches(ui, feed, filed), + } + ui.horizontal(|ui| { + filed.fields.opacity = percent_field(ui, tl!("Opacity").to_owned(), feed.opacity).or(filed.fields.opacity); + let (label, amount) = if feed.point { (tl!("Spread"), &mut filed.fields.spread) } else { (tl!("Location"), &mut filed.fields.location) }; + *amount = percent_field(ui, label.to_owned(), feed.amount).or(*amount); + }); + }); +} + +/// Document swatches as tiles: a pick gives the stop (or point) that colour. +fn swatches(ui: &mut Ui, feed: &Feed, filed: &mut Filed) { + if feed.tiles.is_empty() { + Notice::new(Tone::Info, tl!("The document has no colour swatches.").to_owned()).show(ui); + return; + } + let shown = SwatchPalette::new("Swatches", Bind::given(feed.current), &feed.tiles).show(ui); + let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()) else { return }; + // The first swatch of that colour: the palette reports colours, not cells. + let at = feed.tiles.iter().position(|(_, c)| c.to_rgba() == picked.to_rgba()); + filed.swatch = at.and_then(|i| feed.swatches.get(i)).cloned(); +} + +/// A percent field named `label` over `value`; the number the user entered in this pass. +fn percent_field(ui: &mut Ui, label: String, value: f64) -> Option { + let field = Field::new(label.clone()).show(ui, |ui, _| { + NumberField::new(label.clone(), Bind::given(Some(value))).unit_kind(UnitKind::Percent).range(0.0..=100.0).step(1.0).show(ui) + }); + field.inner?.value().copied().flatten() +} + +/// The popover's size before it has been drawn, for placing it. const POPOVER_SIZE: egui::Vec2 = vec2(272.0, 360.0); -/// The selected art's box on the screen. -fn selection_on_screen(app: &VectorcraftApp, xf: &Xf) -> Option { +/// The selected art's box on the screen, `quad` taking a document box to its corners on the screen. +fn selection_on_screen(app: &VectorcraftApp, quad: impl Fn(Rect) -> [Pos2; 4]) -> Option { let st = app.session.active()?; let b = st.doc.bounds_of(&st.selection.objects, false)?; - Some(egui::Rect::from_points(&xf.quad(b))) + Some(egui::Rect::from_points(&quad(b))) } /// Where the popover opened from a stop's chip at `chip` goes: beside the selected `art` on the @@ -196,96 +335,171 @@ fn beside_art(chip: egui::Pos2, art: egui::Rect, size: egui::Vec2, room: egui::R .unwrap_or(chip + vec2(14.0, 14.0)) } -/// Document swatches as tiles: a click gives the stop (or point) that colour. -fn swatch_grid(app: &mut VectorcraftApp, ui: &mut egui::Ui, target: &Target) { - let colors = swatch_colors(app); - if colors.is_empty() { - widgets::dim_label(ui, tl!("The document has no colour swatches.")); - return; - } - let current = target.color(); - let mut pick = None; - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(2.0, 2.0); - for (name, c) in &colors { - let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click()); - widgets::swatch_tile(ui, r, &Paint::solid(*c), current == *c, resp.hovered()); - if resp.on_hover_text(name).clicked() { - pick = Some((name.clone(), *c)); +/// The screen point the popover hangs from. +fn place(app: &VectorcraftApp, ctx: &egui::Context, anchor: Anchor) -> Pos2 { + match anchor { + Anchor::Screen(at) => at, + // PLAN: assumed `CanvasView::{to_screen(Point) -> Pos2, quad(Rect) -> [Pos2; 4]}` and its `rect` field (cv.S4 gives names only). + Anchor::Chip(chip) => match app.canvas_view() { + Some(view) => { + let at = view.to_screen(chip); + selection_on_screen(app, |b| view.quad(b)).map_or(at + vec2(14.0, 14.0), |art| beside_art(at, art, POPOVER_SIZE, view.rect)) } - } - }); - let Some((name, c)) = pick else { return }; - match target { - // A global or spot color (or a tint of one) stays linked, and the swatch's color keeps - // its model. - Target::Stop(stops, i) => { - let link = crate::panels::gradient::dropped_link(app, &json!({ "swatch": name })); - crate::panels::gradient::set_stops_keeping_models(app, &recolor(stops.clone(), *i, c, link), Some(*i), Live::Released); - } - Target::Point(_, i) => edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&c), "keepModel": true })), + None => ctx.content_rect().center(), + }, } } -/// Apply the `color` (hex), `opacity` and `location` or `spread` (percentages) set in `f` to the -/// target as one edit; returns the stop's (or point's) index after it. -fn apply(app: &mut VectorcraftApp, target: &Target, f: &Value) -> usize { - let pct = |k: &str| f.get(k).and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0)); - let color = f.get("color").and_then(Value::as_str).and_then(crate::panels::color::parse_hex); +/// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`. +fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(anchor) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.anchor)) else { return }; + // PLAN: co.A1 gives no signatures; assumed `panels::color::target(app) -> Target` and `shown(app, &Target) -> ColorPanelShown`. + let shown = crate::panels::color::shown(app, &crate::panels::color::target(app)); + let swatches = swatch_colors(app); + let feed = Feed { + point: matches!(target, Target::Point(..)), + color: target.color(), + current: Srgba::from(c32(&target.color())), + opacity: f64::from(target.opacity()) * 100.0, + amount: f64::from(target.amount()) * 100.0, + tiles: swatches.iter().map(|(name, c)| (Label::from(name.clone()), Srgba::from(c32(c)))).collect(), + swatches, + shown, + }; + let at = place(app, ctx, anchor); + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(id) { + (popover.at, popover.feed) = (at, Some(feed)); + } + }); +} + +/// Opens the popover on the selected stop (a freeform gradient's selected point) of the active gradient, the stop +/// at `index` when it is not the selected one. Nothing opens without a window or a stop to edit. +pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + let Some(dialogs) = app.dialogs() else { return }; + if let Paint::Gradient(g) = active_paint(app) + && g.gradient.kind != GradientKind::Freeform + && app.session.selected_stop() != Some(index) + { + // An index past the last stop selects nothing, and `selected` then finds nothing to edit. + app.run("gradient.selectStop", json!({ "index": index })).ok(); + } + let Some(target) = selected(app) else { return }; + dialogs.with(|host| { + host.open(GradientStopPopover::new(anchor)); + }); + refresh(app, &ctx, dialog_id(KIND), &target); +} + +/// Once per frame: applies what the user did in the popover and its confirmed answer, closes it when its stop or +/// point goes away, and pushes the target's values for the next frame. One line of `dialogs::host::pump`. +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + let id = dialog_id(KIND); + match dialogs.with(|host| host.take_by_id::(id)) { + Some(DialogResult::Ok(fields)) => { + if fields != PopoverFields::default() + && let Some(target) = selected(app) + { + apply(app, &target, &fields); + } + return; + } + Some(_) => return, + None => {} + } + if !dialogs.with(|host| host.is_open::()) { + return; + } + let Some(target) = selected(app) else { + // The stop or point went away (undo, another object selected): nothing left to edit. + dialogs.with(|host| host.cancel_by_id(ctx, id)); + return; + }; + let filed = dialogs.with(|host| host.get_mut_by_id::(id).map(GradientStopPopover::take_filed)).unwrap_or_default(); + if filed.fields != PopoverFields::default() { + apply(app, &target, &filed.fields); + } + if let Some((name, color)) = filed.swatch + && let Some(target) = selected(app) + { + pick_swatch(app, &target, &name, color); + } + for output in &filed.panels { + // PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision). + crate::panels::color::apply_output(app, output); + } + if filed.eyedropper { + dialogs.with(|host| host.cancel_by_id(ctx, id)); + crate::panels::gradient::stop_eyedropper(app); + return; + } + if let Some(target) = selected(app) { + refresh(app, ctx, id, &target); + } +} + +/// Gives the target the swatch `name`'s colour. A global or spot color (or a tint of one) stays linked, and the +/// swatch's color keeps its model. +fn pick_swatch(app: &mut VectorcraftApp, target: &Target, name: &str, color: Color) { + match target { + Target::Stop(stops, i) => { + let link = crate::panels::gradient::dropped_link(app, &json!({ "swatch": name })); + set_stops_keeping_models(app, &recolor(stops.clone(), *i, color, link), Some(*i), Live::Released); + } + Target::Point(_, i) => edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&color), "keepModel": true })), + } +} + +/// Apply the `color`, `opacity` and `location` or `spread` (percentages) set in `f` to the target as one edit. +fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { + let pct = |v: Option| v.map(|v| (v / 100.0).clamp(0.0, 1.0)); match target { Target::Stop(stops, i) => { let (mut stops, mut i) = (stops.clone(), *i); - if let Some(c) = color { + if let Some(c) = f.color { stops = recolor(stops, i, c, None); } - if let Some(o) = pct("opacity") { - stops[i].opacity = o as f32; + if let Some(o) = pct(f.opacity) + && let Some(stop) = stops.get_mut(i) + { + stop.opacity = o as f32; } - if let Some(l) = f.get("location").and_then(Value::as_f64) { + if let Some(l) = f.location { (stops, i) = move_stop(&stops, i, (l / 100.0) as f32); } set_stops(app, &stops, Some(i), Live::Released); - i } Target::Point(_, i) => { let mut p = json!({ "index": i }); - if let Some(c) = color { + if let Some(c) = f.color { p["color"] = color_json(&c); } - for k in ["opacity", "spread"] { - if let Some(v) = pct(k) { + for (k, v) in [("opacity", pct(f.opacity)), ("spread", pct(f.spread))] { + if let Some(v) = v { p[k] = json!(v); } } edit_point(app, "paint.freeform.setPoint", p); - *i } } } -/// OK (agents): apply the `color`, `opacity` and `location` (a point: `spread`) fields that are -/// set, then close. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - let target = selected(app).ok_or("no gradient stop or freeform point is selected")?; - if let Some(hex) = d.fields.get("color").and_then(Value::as_str) { - crate::panels::color::parse_hex(hex).ok_or_else(|| format!("bad colour `{hex}` (#rrggbb)"))?; - } - let i = apply(app, &target, &Value::Object(d.fields.clone())); - app.ui.dialog = None; - Ok(json!({ "index": i })) -} - #[cfg(test)] mod tests { use vectorcraft_engine::Session; - use vectorcraft_tools::{PointerEvent, PointerKind}; use super::*; + use crate::dialogs::host; /// A rectangle with a three-stop gradient from (100, 150) to (200, 150), the Gradient tool - /// and stop 1 selected. + /// and stop 1 selected, in an app with the window context that hosts the popover. fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(egui::Context::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 1, "color": "#000000"}]); @@ -295,6 +509,30 @@ mod tests { app } + fn ctx(app: &VectorcraftApp) -> egui::Context { + app.ui_ctx.clone().unwrap() + } + + fn open_popover(app: &mut VectorcraftApp) { + open_at(app, 1, Anchor::Screen(egui::pos2(200.0, 200.0))); + assert!(is_open(app), "the popover opened"); + } + + fn is_open(app: &VectorcraftApp) -> bool { + app.dialogs().unwrap().with(|host| host.is_open::()) + } + + fn set(app: &VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + app.dialogs().unwrap().with(|host| host.set_json_field(&ctx(app), dialog_id(KIND), field, value)) + } + + /// OK, then the frame that applies the answer. + fn confirm(app: &mut VectorcraftApp) { + let ctx = ctx(app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KIND))); + host::pump(app, &ctx); + } + /// #862: the popover goes beside the art, on the first side with room, not over it. #[test] fn the_popover_goes_beside_the_art_it_edits() { @@ -324,124 +562,25 @@ mod tests { } } - thread_local! { - // One context per test, so frames follow one another as in the app. - static CTX: egui::Context = { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - ctx - }; - } - - /// One headless frame of the dialog layer and the shortcuts. - fn frame(app: &mut VectorcraftApp, events: Vec) { - let ctx = CTX.with(Clone::clone); - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { - crate::shortcuts::handle(app, ui.ctx()); - super::super::show(app, ui.ctx()); - }); - out.textures_delta.clear(); - } - - fn key(k: egui::Key) -> egui::Event { - egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } - } - - #[test] - fn double_clicking_a_stop_opens_the_popover_which_draws_both_tabs() { - let mut app = app(); - let view = app.view_info(); - let chip = Point::new(150.0, 150.0 + 10.0 / view.zoom); - crate::canvas::dispatch( - &mut app, - &PointerEvent { kind: PointerKind::DoubleClick, pos: chip, mods: Default::default(), backquote: false, pressure: 1.0, pen: None }, - view, - ); - let d = app.ui.dialog.clone().expect("the popover opened"); - assert_eq!((d.kind.as_str(), d.fields["index"].clone(), d.str("tab")), ("gradientStop", json!(1), "color".into())); - assert_eq!(app.session.selected_stop(), Some(1)); - frame(&mut app, vec![]); - app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("swatches")); - frame(&mut app, vec![]); - assert!(app.ui.dialog.is_some(), "still open"); - // Escape closes it. - frame(&mut app, vec![key(egui::Key::Escape)]); - assert!(app.ui.dialog.is_none()); - } - #[test] fn confirm_applies_colour_opacity_and_location() { let mut app = app(); - app.ui.dialog = Some(Dialog::new("gradientStop", json!({"index": 1, "x": 150, "y": 160, "color": "#ff0000", "opacity": 40, "location": 80}))); - assert_eq!(super::super::confirm(&mut app).unwrap(), json!({"index": 1})); + open_popover(&mut app); + for (field, value) in [("color", json!("#ff0000")), ("opacity", json!(40)), ("location", json!(80))] { + set(&app, field, value).unwrap(); + } + confirm(&mut app); let s = stops(&app); assert_eq!((s[1].color.to_hex(), s[1].opacity, (s[1].offset * 100.0).round()), ("#ff0000".to_string(), 0.4, 80.0)); - assert!(app.ui.dialog.is_none()); + assert!(!is_open(&app)); // Moving it past the last stop keeps it selected at its new index. - app.ui.dialog = Some(Dialog::new("gradientStop", json!({"location": 100}))); - super::super::confirm(&mut app).unwrap(); + open_popover(&mut app); + set(&app, "location", json!(100)).unwrap(); + confirm(&mut app); assert_eq!((app.session.selected_stop(), stops(&app)[2].color.to_hex()), (Some(2), "#ff0000".to_string())); - app.ui.dialog = Some(Dialog::new("gradientStop", json!({"color": "red"}))); - assert!(super::super::confirm(&mut app).is_err()); - } - - fn click(at: egui::Pos2, pressed: bool) -> egui::Event { - egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } - } - - #[test] - fn the_opening_double_click_keeps_it_open_and_a_later_click_elsewhere_closes_it() { - let mut app = app(); - app.ui.dialog = Some(Dialog::new("gradientStop", json!({"index": 1, "x": 150, "y": 160}))); - // The frame the double-click lands in (the popover opens beside the pointer, not under it). - let at = egui::pos2(5.0, 5.0); - let double = vec![egui::Event::PointerMoved(at), click(at, true), click(at, false), click(at, true), click(at, false)]; - frame(&mut app, double); - assert!(app.ui.dialog.is_some(), "the opening double-click must not close it"); - frame(&mut app, vec![egui::Event::PointerMoved(at), click(at, true), click(at, false)]); - assert!(app.ui.dialog.is_none(), "a click elsewhere closes it"); - } - - /// #577: the Gradient panel's colour chip opens it with a click whose release lands in the - /// frame it opens in, outside it: that click doesn't close it. - #[test] - fn the_click_that_opens_it_from_the_panel_keeps_it_open() { - let mut app = app(); - let at = egui::pos2(5.0, 5.0); - frame(&mut app, vec![egui::Event::PointerMoved(at), click(at, true)]); - // The panel opens it while the click is released. - app.ui.dialog = Some(Dialog::new("gradientStop", json!({"index": 1, "screen": [200.0, 200.0], "tab": "color"}))); - frame(&mut app, vec![click(at, false)]); - for _ in 0..3 { - frame(&mut app, vec![]); - } - assert!(app.ui.dialog.is_some(), "the opening click must not close it"); - let away = egui::pos2(5.0, 600.0); - frame(&mut app, vec![egui::Event::PointerMoved(away), click(away, true), click(away, false)]); - assert!(app.ui.dialog.is_none(), "a later click elsewhere closes it"); - } - - #[test] - fn the_popover_closes_when_its_stop_goes_away() { - let mut app = app(); - app.ui.dialog = Some(Dialog::new("gradientStop", json!({"index": 1, "x": 150, "y": 160}))); - app.run("gradient.selectStop", json!({"index": null})).unwrap(); - frame(&mut app, vec![]); - assert!(app.ui.dialog.is_none()); - } - - #[test] - fn delete_removes_the_selected_stop_instead_of_the_object() { - let mut app = app(); - frame(&mut app, vec![key(egui::Key::Delete)]); - assert_eq!(stops(&app).len(), 2); - frame(&mut app, vec![key(egui::Key::Backspace)]); - assert_eq!(stops(&app).len(), 2, "never below two stops"); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1, "the rectangle stays"); - // The arrows nudge it. - let before = stops(&app)[1].offset; - frame(&mut app, vec![key(egui::Key::ArrowLeft)]); - assert!((stops(&app)[1].offset - (before - 0.01)).abs() < 1e-6); + // A colour that is not `#rrggbb` is refused when it is set. + open_at(&mut app, 2, Anchor::Screen(egui::pos2(200.0, 200.0))); + assert!(set(&app, "color", json!("red")).is_err()); } #[test] @@ -454,26 +593,24 @@ mod tests { _ => panic!("no point selected"), }; let (p, i) = point(&app); - // Double-clicking the point opens the popover beside it. - let view = app.view_info(); - crate::canvas::dispatch( - &mut app, - &PointerEvent { kind: PointerKind::DoubleClick, pos: p.at, mods: Default::default(), backquote: false, pressure: 1.0, pen: None }, - view, - ); - let d = app.ui.dialog.clone().expect("the popover opened"); - assert_eq!((d.kind.as_str(), d.fields["index"].clone()), ("gradientStop", json!(i))); - frame(&mut app, vec![]); - app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("swatches")); - frame(&mut app, vec![]); - assert!(app.ui.dialog.is_some(), "both tabs draw"); + open_at(&mut app, i, Anchor::Chip(p.at)); + assert!(is_open(&app), "the popover opened"); // Agents set its colour, opacity and spread. - for (k, v) in [("color", json!("#ff0000")), ("opacity", json!(40)), ("spread", json!(25))] { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + for (field, value) in [("color", json!("#ff0000")), ("opacity", json!(40)), ("spread", json!(25))] { + set(&app, field, value).unwrap(); } - assert_eq!(super::super::confirm(&mut app).unwrap(), json!({"index": i})); + confirm(&mut app); let (p, _) = point(&app); assert_eq!((p.color.to_hex(), p.opacity, p.spread), ("#ff0000".to_string(), 0.4, 0.25)); - assert!(app.ui.dialog.is_none()); + assert!(!is_open(&app)); + } + + #[test] + fn the_popover_closes_when_its_stop_goes_away() { + let mut app = app(); + open_popover(&mut app); + app.run("gradient.selectStop", json!({"index": null})).unwrap(); + host::pump(&mut app, &ctx(&app)); + assert!(!is_open(&app)); } } diff --git a/crates/ui-egui/src/dialogs/saturate.rs b/crates/ui-egui/src/dialogs/saturate.rs index 2492c2e85d..f9d80aebd4 100644 --- a/crates/ui-egui/src/dialogs/saturate.rs +++ b/crates/ui-egui/src/dialogs/saturate.rs @@ -1,58 +1,81 @@ //! Edit → Edit Colors → Saturate: an intensity slider (−100..100 %) previewed live on the canvas; -//! OK keeps the preview as one undo step (`edit.colors.saturate`). +//! OK keeps the preview as one undo step (`edit.colors.saturate`). Hosted like Adjust Color Balance +//! (`color_balance::Adjust`). //! -//! Fields: `intensity` and `preview`. +//! Fields: `intensity`. The preview check box is the host's. +use craft::theme::Srgba; +use craft::ui::patterns::{DialogFields, Param}; use serde_json::{Value, json}; use vectorcraft_color::Color; -use super::{DialogSpec, form}; +use super::color_balance::{Adjust, percent_row}; +use super::color_picker::ColorDialogs; use crate::VectorcraftApp; use crate::panels::c32; -use crate::state::Dialog; + +pub(crate) use super::color_balance::Open; /// The dialog kind of Saturate. pub const KIND: &str = "saturate"; const CMD: &str = "edit.colors.saturate"; -pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Saturate").into(), body, confirm, preview: true, ..DialogSpec::FORM }; +const ADJUST: Adjust = Adjust { kind: KIND, cmd: CMD, label: "Saturate", slot, initial, rows, params }; +fn slot(dialogs: &mut ColorDialogs) -> &mut Option { + &mut dialogs.saturate +} + +/// Opens the dialog at intensity 0. pub fn open(app: &mut VectorcraftApp) { - app.ui.dialog = Some(Dialog::new(KIND, json!({"intensity": 0, "preview": true}))); + ADJUST.open(app); } -fn params(d: &Dialog) -> Value { - json!({"intensity": d.f64("intensity", 0.0)}) +/// Previews the open dialog; one line of `dialogs::host::pump`. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + ADJUST.pump(app); } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - // The rail runs from grey to a fully saturated colour. - form::slider(ui, d, "intensity", tl!("Intensity:"), -100.0..=100.0, "%", &|x| c32(&Color::from_hsb(12.0, x, 0.85))); - let p = params(d); - form::preview(app, ui, d, "Saturate", CMD, p); - false +fn initial() -> DialogFields { + DialogFields::from_pairs([("intensity", 0.0)]) } -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - form::commit_preview(app, CMD, params(d)) +fn params(fields: &DialogFields) -> Value { + json!({"intensity": fields.number("intensity").unwrap_or(0.0)}) +} + +fn rows() -> Vec { + vec![Param::custom("intensity", "Intensity", |ui, fields, _cx| { + // The rail runs from grey to a fully saturated colour. + percent_row(ui, fields, "intensity", "Intensity", |x| Srgba::from(c32(&Color::from_hsb(12.0, x, 0.85)))); + ui.response() + })] } #[cfg(test)] mod tests { - use super::*; + use craft::ui::dialog::dialog_id; use vectorcraft_engine::Session; + use super::*; + use crate::dialogs::host; + #[test] fn commits_without_a_drawn_frame_as_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); app.run("paint.setFill", json!({"color": "#cc6666"})).unwrap(); let undo = app.session.doc().unwrap().history.undo.len(); - app.run("ui.saturateDialog", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("intensity".into(), json!(-100)); - super::super::confirm(&mut app).unwrap(); + open(&mut app); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.set_json_field(&ctx, dialog_id(KIND), "intensity", json!(-100))).unwrap(); + // OK in the frame the value was set, with no drawn pass of the dialog: still one undo step. + dialogs.with(|host| host.confirm_by_id(&ctx, dialog_id(KIND))); + host::pump(&mut app, &ctx); let st = app.session.doc().unwrap(); assert_eq!(st.history.undo.len(), undo + 1); let c = st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint().color().unwrap();