From b4a8a2b09d48d4ccdc59d2fcd2b388e5aa18a789 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:30:16 +0700 Subject: [PATCH] color-w19: net change of 1 commits - color-w19: written by an agent --- crates/ui-egui/src/dialogs/recolor.rs | 4636 ++++++++--------- crates/ui-egui/src/dialogs/recolor/fixture.rs | 199 + 2 files changed, 2322 insertions(+), 2513 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/recolor/fixture.rs diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1b80ce5e35..fcda02bee8 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -14,9 +14,10 @@ //! Separate, Randomize order or //! saturation and brightness, Find (with it on, the art of the selected rows shows as the preview //! shows it, their current colors with Preview off, and the rest of the selected art shows its -//! current colors dimmed; a second click shows the art as before), Reset, the Method and Limit to Library (its folder button imports a +//! current colors dimmed; a second click shows the art as before), Reset, the Method and Limit to Library (Other Library… imports a //! library file and limits to it; a library's colours apply as its swatches: a spot colour stays a -//! spot colour, and joins the document's swatches). Edit tab: a hue and +//! spot colour, and joins the document's swatches). A row's right-click menu has Pick from Swatches +//! and Limit to Library. The Edit tab is [`edit_tab`]'s: a hue and //! saturation wheel with a marker per new colour (drag one; with linked handles they all turn and //! scale together), a brightness slider, the harmony rules, and the color sliders with their mode //! menu, whose Global Adjust shows Saturation, Brightness, Temperature and Luminosity (-100% to @@ -53,7 +54,7 @@ //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new //! colours as a colour group named `groupName`. //! -//! The Color Groups list on the right (under the tabs in a window too narrow for both; the Show +//! The Color Groups list beside the tabs (under them in a window too narrow for both; the Show //! Color Groups button beside the tabs shows or hides it, and it opens shown) lists the document's color groups with their colors. A click on one makes it //! the group being edited, as opening on it would: with art the art is reduced to as many rows as //! it has colors, which become their new colors, and without art the rows are its colors. Save @@ -78,10 +79,13 @@ //! them; OK keeps them as one undo step. A new count of Colors keeps the picks: the new rows take them again. //! //! Undo Changes and Redo Changes beside the Color Theme Picker (`ui.recolorUndo`, `ui.recolorRedo`) -//! step back and forward through the dialog's own color edits ([`History`]), not the document's -//! undo history; Cancel discards them and OK still records one undo step. Each opening starts -//! with nothing to undo, and selecting another color group or Save Changes leaves nothing to undo -//! or redo. +//! step back and forward through the dialog's own color edits, not the document's undo history; +//! Cancel discards them and OK still records one undo step. Each opening starts with nothing to +//! undo, and selecting another color group or Save Changes leaves nothing to undo or redo. +//! +//! The dialog sits on the window's dialog host ([`RecolorDialog`]); [`pump`] feeds it what it reads of +//! the app, runs what it asked for and previews its recolour, and OK is held until the recolour is +//! committed, which can fail and keep the dialog open. //! //! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot //! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true` @@ -104,44 +108,64 @@ //! Color Groups list is shown), `groupAction` (`save`, `new` or `delete`: the list's buttons, //! checked as the field is set and run by the next frame, or by OK first). Setting `group` to a color group's name selects it in the list, and null //! selects none. Changing `colors`, a preserve flag or `limitTo` reduces the rows again (and drops -//! `weights`). +//! `weights`). The controls `__sel` (the selected rows), `__seed` (Randomize's seed) and +//! `__saveGroup` (the New Color Group menu's `all` or `prominent`) can be set too. -use egui::{Rect, Sense, Ui, pos2, vec2}; +pub(crate) mod edit_tab; +#[cfg(test)] +pub(crate) mod fixture; +mod prominent; + +use std::borrow::Cow; +use std::cell::RefCell; +use std::sync::Arc; + +use craft::behavior::edit_history::{EditHistory, Step}; +use craft::behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed}; +use craft::color_ui::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorPanelMode, DiscRadius, patch_at}; +use craft::host::PickRequest; +use craft::theme::variant::Tone; +use craft::theme::{ModelValues, Rgba, Srgba}; +use craft::ui::buttons::{IconButton, ToggleButton}; +use craft::ui::choice::{Checkbox, Swatch}; +use craft::ui::contract::overlay::Anchor; +use craft::ui::contract::{Bind, CollectionEvent, ColumnSpec, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Trigger}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; +use craft::ui::display::{Shade, Text}; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize}; +use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::notices::{Notice, NoticeLayout}; +use craft::ui::patterns::form_dialogs::{FormDialog, ResetFooter, ResetPick}; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::overlay::CloseReason; +use craft::ui::sections::{FooterAction, FooterBar}; +use craft::ui::table::Table; +use craft::ui::tabs::{Tab, TabKind, TabStrip}; +use craft::ui::text::{HexField, TextField}; +use egui::Ui; use serde_json::{Value, json}; use vectorcraft_color::harmony::{Harmony, move_on_wheel}; use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method}; use vectorcraft_color::{Color, keep_model}; use vectorcraft_engine::cmd::color_value; +use vectorcraft_engine::cmd::fileio::builtin_open_filters; use vectorcraft_engine::cmd::swatchlib; -use super::{DialogSpec, form}; +use super::host::{HeldOptions, open_held_with}; +use super::preview::LivePreview; +use crate::VectorcraftApp; use crate::panels::c32; -use crate::panels::color::{Mode, components, from_components, track_color}; +use crate::panels::color::{color_of_values, working_rgb}; use crate::panels::swatches::{DOCUMENT_SWATCHES, colour_libraries, limit_key}; -use crate::state::Dialog; -use crate::theme::{self, Tokens}; -use crate::{VectorcraftApp, widgets}; /// The dialog kind of Recolor Artwork. pub const KIND: &str = "recolor"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Recolor Artwork").into(), - body, - confirm, - preview: true, - min_width: 540.0, - max_width: Some(MAIN_W + STORAGE_GAP + STORAGE_W), - inputs: |_| &[GROUP_ACTION], - ..DialogSpec::FORM -}; +/// The dialog's title, and the name of the undo step its recolour makes. +const TITLE: &str = "Recolor Artwork"; -/// Widths of the dialog's main part (the tabs), of the Color Groups list and of the gap between -/// them; the height of a group's row in the list. -const MAIN_W: f32 = 560.0; -const STORAGE_W: f32 = 170.0; -const STORAGE_GAP: f32 = 12.0; -const GROUP_ROW_H: f32 = 34.0; /// The fields of the Color Groups list: whether it is shown, a request from its buttons, and the /// group whose colors the rows were last given. const GROUP_STORAGE: &str = "groupStorage"; @@ -149,41 +173,86 @@ const GROUP_ACTION: &str = "groupAction"; const GROUP_LOADED: &str = "__groupLoaded"; /// The `recolor.reduce` parameters the art's rows were last reduced with. const REDUCED: &str = "__reduced"; +/// Set by a change that leaves Undo Changes and Redo Changes no step ([`restart_history`]); the dialog's history +/// takes it. +const RESTART: &str = "__restartHistory"; const CMD: &str = "recolor.apply"; -/// Width of the current colours of a row. -const CURRENT_W: f32 = 250.0; -/// Diameter of the Edit tab's colour wheel. -const WHEEL: f32 = 220.0; -/// Height of the Edit tab's color bars area (the wheel with its Brightness slider), and of a bar. -const BARS_H: f32 = WHEEL + 31.0; -const BAR_H: f32 = 22.0; -/// Without the Prominent Colors bar, the Edit tab's gaps above the wheel and above the sliders. -const WHEEL_GAP: f32 = 8.0; -const SLIDERS_GAP: f32 = 6.0; -/// Height of the rows table, and of either tab (so switching tabs doesn't resize the dialog). -const TABLE_H: f32 = 182.0; -const TAB_H: f32 = 400.0; const PRESETS: [&str; 5] = ["Custom", "1 Color Job", "2 Color Job", "3 Color Job", "Color Library"]; -/// The id of row `i`'s new colour chip, with `i`. -const NEW_CHIP: &str = "recolor-new"; /// The color modes of the sliders under the rows; a row whose new color is a spot color of the /// library also has Tint. -const SLIDER_MODES: [Mode; 4] = [Mode::Hsb, Mode::Rgb, Mode::Cmyk, Mode::Lab]; -/// Widths of a color slider's label, of the slider and of its number field. -const SLIDER_LABEL_W: f32 = 12.0; -const SLIDER_W: f32 = 170.0; -const SLIDER_FIELD_W: f32 = 48.0; +const SLIDER_MODES: [ColorPanelMode; 4] = [ColorPanelMode::HsbSliders, ColorPanelMode::RgbSliders, ColorPanelMode::CmykSliders, ColorPanelMode::LabSliders]; +/// Colours a slider's track shows from its start to its end. +const TRACK_STOPS: usize = 7; /// The `sliderMode` of the Edit tab's Global Adjust sliders, and the menu's name for it. const GLOBAL: &str = "global"; const GLOBAL_ADJUST: &str = "Global Adjust"; /// The `globalAdjust` field's keys (and `recolor.apply`'s), in the order of the sliders. const ADJUSTS: [&str; 4] = ["saturation", "brightness", "temperature", "luminosity"]; -/// Widths of a Global Adjust slider's label and of the slider. -const GLOBAL_LABEL_W: f32 = 76.0; -const GLOBAL_SLIDER_W: f32 = 110.0; /// The slider values last shown: `{row, key, mode, v}` (HSB keeps its hue at no saturation). const COMPS: &str = "__comps"; +/// The `__` controls `ui.dialog.set` can set: the selected rows, Randomize's seed and the New Color Group menu's +/// request. +const SETTABLE: [&str; 3] = ["__sel", "__seed", SAVE_GROUP]; + +/// The columns of the Assign tab's rows: the current colors, the arrow that excludes the row, the +/// new color and its hex. +const CURRENT: ColumnKey = ColumnKey::new("current"); +const ARROW: ColumnKey = ColumnKey::new("arrow"); +const NEW: ColumnKey = ColumnKey::new("new"); +const HEX: ColumnKey = ColumnKey::new("hex"); +/// The arrow of a row that is recolored, and of one that is excluded (a dashed line without a head). +// PLAN: assumed icons `dc-recolor-arrow` and `dc-recolor-arrow-off` (VectorCraft's own solid and dashed arrows); +// the assets owner draws them and adds them to `assets/icons`, `icon_data.rs` and `ASSETS.md`. +const ARROW_ON: &str = "dc-recolor-arrow"; +const ARROW_OFF: &str = "dc-recolor-arrow-off"; + +/// The dialog's values: the JSON map automation lists and sets, and the rows and marks the model +/// functions read and write. `__` names are the dialog's own marks. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Fields { + /// The values by name. + pub fields: serde_json::Map, +} + +impl Fields { + /// The fields of the object `fields` (none when it is not an object). + pub(crate) fn new(fields: Value) -> Self { + Self { fields: fields.as_object().cloned().unwrap_or_default() } + } + + /// Field `k` as a number: a number as it is, a string as a length in points; `d` otherwise. + pub(crate) fn f64(&self, k: &str, d: f64) -> f64 { + match self.fields.get(k) { + Some(Value::Number(n)) => n.as_f64().unwrap_or(d), + Some(Value::String(s)) => vectorcraft_doc::Unit::Points.parse(s).unwrap_or(d), + _ => d, + } + } + + /// Field `k` as text: a string as it is, another value as JSON, empty when missing. + pub(crate) fn str(&self, k: &str) -> String { + match self.fields.get(k) { + Some(Value::String(s)) => s.clone(), + Some(v) => v.to_string(), + None => String::new(), + } + } + + /// Field `k` as a bool; `false` when it is missing or not a bool. + pub(crate) fn bool(&self, k: &str) -> bool { + self.fields.get(k).and_then(Value::as_bool).unwrap_or(false) + } +} + +/// The open Recolor Artwork dialog's record on the app (`app.color_dialogs.recolor`): its id and the +/// live preview of its recolour, which outlive a pass of the dialog. +pub(crate) struct Open { + /// The dialog on the window's host. + pub id: DialogId, + /// The preview the pump runs and OK commits. + pub preview: LivePreview, +} /// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?}`) on the selected art and, /// with `group`, on that colour group: art is reduced to as many rows as the group has colours, @@ -232,20 +301,36 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { "preserveWhite": kept("preserveWhite", true), "preserveBlack": kept("preserveBlack", true), "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, - "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, "__assign": assign, "__newGroup": new_group, - GROUP_STORAGE: true, GROUP_LOADED: group, + "preview": true, "globalAdjust": zero_adjust(), THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, + "__assign": assign, "__newGroup": new_group, GROUP_STORAGE: true, GROUP_LOADED: group, }); - let mut d = Dialog::new(KIND, fields); + let mut d = Fields::new(fields); // Without art the rows are there from the start: limit them now (art's rows snap as they reduce). let mut rs = rows(&d); snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); - // Undo Changes has nothing to undo on a new opening. - app.ui.recolor_history = History { opened: Some(snapshot(&d)), ..History::default() }; - app.ui.dialog = Some(d); + // A Recolor Artwork still open is replaced: its preview goes before this one's starts. + if let Some(old) = app.color_dialogs.recolor.take() { + old.preview.cancel(app); + } + let dialog = RecolorDialog::new(app, d); + let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() }; + let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?; + app.color_dialogs.recolor = Some(Open { id, preview: LivePreview::default() }); Ok(Value::Null) } +/// Recolor Artwork closed with Cancel: its preview goes and its record with it, unless a Recolor +/// Artwork opened over it holds the record now. +fn cancelled(app: &mut VectorcraftApp) { + if app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.is_open::())) { + return; + } + if let Some(open) = app.color_dialogs.recolor.take() { + open.preview.cancel(app); + } +} + fn key(c: &Color) -> Value { json!(ColorKey::of(c).to_string()) } @@ -258,7 +343,7 @@ fn first_library(app: &VectorcraftApp) -> Option { } /// `recolor.reduce` parameters (Method only picks each row's colour, so changing it keeps the rows). -fn reduce_params(d: &Dialog) -> Value { +fn reduce_params(d: &Fields) -> Value { json!({ "colors": d.fields.get("colors").cloned().unwrap_or(Value::Null), "preserve": {"white": d.bool("preserveWhite"), "black": d.bool("preserveBlack"), "grays": d.bool("preserveGrays")}, @@ -268,16 +353,14 @@ fn reduce_params(d: &Dialog) -> Value { /// Reduce the art's colours into rows again when the count, preserve flags or library changed /// (assigning a group's colours or the opener's colours as the new colours). -fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { +fn sync(app: &mut VectorcraftApp, d: &mut Fields) { const DONE: &str = REDUCED; let sig = reduce_params(d); if !d.bool("__art") || d.fields.get(DONE) == Some(&sig) { return; } // The art's own colors are reduced, not those of the preview, which runs again afterwards. - if d.fields.remove(super::form::PREVIEWED).is_some() { - let _ = app.session.cancel_interaction(); - } + cancel_preview(app); let mut p = sig.clone(); p["method"] = json!(d.str("method")); match app.session.execute("recolor.reduce", &p) { @@ -302,40 +385,32 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { // New rows take the colors picked with the Color Theme Picker again. d.fields.remove(THEME_DONE); // Weights given for the old rows don't apply to the new ones. - d.fields.remove(WEIGHTS); + d.fields.insert(WEIGHTS.into(), Value::Null); d.fields.remove(WEIGHED); } /// The fields of Prominent Colors: the weights the rows are to take (`recolor.weigh`'s `weights`, /// one per row; a new list moves the rows' current colors), the weights they last took, each row's /// share of the art's uses (`recolor.weigh`'s `shares`) and the rows' current colors, exclusions -/// and whether each has a new color, which those were read for; a drag of a part's edge (each part's share of the bar while it lasts); and a request -/// from the New Color Group menu (`all` or `prominent`). +/// and whether each has a new color, which those were read for; and a request from the New Color +/// Group menu (`all` or `prominent`). const WEIGHTS: &str = "weights"; const WEIGHED: &str = "__weighed"; const SHARES: &str = "__shares"; const SHARES_OF: &str = "__sharesOf"; -const BAR_DRAG: &str = "__barDrag"; const SAVE_GROUP: &str = "__saveGroup"; -/// Height of the Prominent Colors bar, and the smallest share of it a drag leaves a part. With the -/// bar the Edit tab leaves out [`WHEEL_GAP`] and [`SLIDERS_GAP`], which keeps the tab's height. -const PROMINENT_H: f32 = 10.0; -const MIN_PART: f64 = 0.01; -/// The ids of the bar's part `n` and of the edge after part `k`, with `n` or `k`. -const PROMINENT_PART: &str = "recolor-prominent-part"; -const PROMINENT_EDGE: &str = "recolor-prominent-edge"; -/// Cancel the preview, so commands read the art's own colors; it runs again afterwards. -fn cancel_preview(app: &mut VectorcraftApp, d: &mut Dialog) { - if d.fields.remove(super::form::PREVIEWED).is_some() { - let _ = app.session.cancel_interaction(); +/// Cancel the preview, so commands read the art's own colors; the pump runs it again afterwards. +fn cancel_preview(app: &mut VectorcraftApp) { + if let Some(preview) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) { + preview.cancel(app); } } /// With art: when `weights` changed, move the rows' current colors toward them /// (`recolor.weigh`); when the rows' current colors changed, read each row's share of the art's /// uses again. -fn sync_weights(app: &mut VectorcraftApp, d: &mut Dialog) { +fn sync_weights(app: &mut VectorcraftApp, d: &mut Fields) { if !d.bool("__art") { return; } @@ -343,7 +418,7 @@ fn sync_weights(app: &mut VectorcraftApp, d: &mut Dialog) { && d.fields.get(WEIGHED) != Some(&w) { d.fields.insert(WEIGHED.into(), w.clone()); - cancel_preview(app, d); + cancel_preview(app); match app.session.execute("recolor.weigh", &json!({"map": rows(d), "weights": w})) { Ok(r) => { if let Some(m) = r["map"].as_array() { @@ -361,7 +436,7 @@ fn sync_weights(app: &mut VectorcraftApp, d: &mut Dialog) { if d.fields.get(SHARES_OF) == Some(&of) { return; } - cancel_preview(app, d); + cancel_preview(app); let shares = match app.session.execute("recolor.weigh", &json!({"map": rs})) { Ok(r) => r["shares"].clone(), Err(e) => { @@ -375,7 +450,7 @@ fn sync_weights(app: &mut VectorcraftApp, d: &mut Dialog) { /// The parts of the Prominent Colors bar: each row that isn't excluded and has a share of the /// art's uses, with that share in percent, the largest share first (on a tie, the first row). -fn prominent_parts(d: &Dialog, rows: &[Value]) -> Vec<(usize, f64)> { +fn prominent_parts(d: &Fields, rows: &[Value]) -> Vec<(usize, f64)> { let shares = d.fields.get(SHARES).and_then(Value::as_array).cloned().unwrap_or_default(); let mut parts: Vec<(usize, f64)> = shares .iter() @@ -387,69 +462,10 @@ fn prominent_parts(d: &Dialog, rows: &[Value]) -> Vec<(usize, f64)> { parts } -/// The Prominent Colors bar: a part per row of [`prominent_parts`] with the row's new color, as wide -/// as its share of the art's uses. A drag of the edge between two parts moves width from one to -/// the other (each keeps at least [`MIN_PART`] of the bar); when it ends, the parts' widths become -/// the rows' `weights`. -fn prominent_bar(ui: &mut Ui, d: &mut Dialog, rows: &[Value]) { - let t = Tokens::get(ui.ctx()); - let parts = prominent_parts(d, rows); - let (bar, resp) = ui.allocate_exact_size(vec2(ui.available_width(), PROMINENT_H), Sense::hover()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, ui.is_enabled(), tl!("Prominent Colors"))); - if parts.is_empty() { - ui.painter().rect_stroke(bar, 1.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - return; - } - let total: f64 = parts.iter().map(|p| p.1).sum(); - let mut widths: Vec = match d.fields.get(BAR_DRAG).and_then(Value::as_array) { - Some(w) if w.len() == parts.len() => w.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(), - _ => parts.iter().map(|p| p.1 / total).collect(), - }; - let w = f64::from(bar.width()); - let edge = |k: usize, widths: &[f64]| bar.left() + (widths[..=k].iter().sum::() * w) as f32; - let mut left = bar.left(); - for (n, (i, _)) in parts.iter().enumerate() { - let right = if n + 1 == parts.len() { bar.right() } else { edge(n, &widths) }; - let r = Rect::from_min_max(pos2(left, bar.top()), pos2(right, bar.bottom())); - let c = to_color(&rows[*i]).or_else(|| from_colors(&rows[*i]).first().copied()).unwrap_or_default(); - chip(ui, r, c, false); - let share = (widths[n] * 100.0).round(); - ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()) - .on_hover_text(format!("{} {share}%", crate::i18n::colon(&format!("{} {}", tl!("Color"), i + 1)))); - left = right; - } - let mut ended = false; - for k in 0..parts.len() - 1 { - let x = edge(k, &widths); - let handle = Rect::from_center_size(pos2(x, bar.center().y), vec2(8.0, PROMINENT_H)); - let h = ui.interact(handle, egui::Id::unique((PROMINENT_EDGE, k)), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); - if h.dragged() && w > 0.0 { - // Each part keeps MIN_PART, or half of the two parts' width when they are narrower. - let pair = widths[k] + widths[k + 1]; - let least = MIN_PART.min(pair / 2.0); - let moved = (widths[k] + f64::from(h.drag_delta().x) / w).clamp(least, pair - least); - widths[k] = moved; - widths[k + 1] = pair - moved; - d.fields.insert(BAR_DRAG.into(), json!(widths)); - } - if h.hovered() || h.dragged() { - ui.painter().vline(x, bar.y_range(), egui::Stroke::new(2.0, t.accent)); - } - ended |= h.drag_stopped(); - } - if ended && d.fields.remove(BAR_DRAG).is_some() { - let mut weights = vec![0.0; rows.len()]; - for ((i, _), x) in parts.iter().zip(&widths) { - weights[*i] = (x * 10_000.0).round() / 100.0; - } - d.fields.insert(WEIGHTS.into(), json!(weights)); - } -} - /// The colors a new color group takes from rows `rs`: each row's new color with the Global Adjust, /// snapped to Limit to Library, as `recolor.apply` gives them to a group; a row without a new color /// gives its first current color, which the art keeps. -fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator) -> Vec { +fn group_colors<'a>(app: &VectorcraftApp, d: &Fields, rs: impl Iterator) -> Vec { let adjust = global_adjust(adjust_values(d)); let limit = d.str("limitTo"); let palette = Some(limit).filter(|l| !l.is_empty()).and_then(|l| swatchlib::limit_palette(&app.session, &l)); @@ -468,7 +484,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator Result<(), String> { +fn save_group(app: &mut VectorcraftApp, d: &mut Fields, which: &str) -> Result<(), String> { let rs = rows(d); let order: Vec = match which { "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).filter(|&i| to_color(&rs[i]).is_some()).collect(), @@ -479,7 +495,7 @@ fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) -> Result<( return Ok(()); } // The group is added to the document itself, not to the preview, which runs again afterwards. - cancel_preview(app, d); + cancel_preview(app); app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})).map(|_| ()) } @@ -489,11 +505,23 @@ fn doc_groups(app: &VectorcraftApp) -> Vec<(String, Vec)> { st.doc.swatch_groups.iter().map(|g| (g.name.clone(), g.swatches.iter().filter_map(|w| w.paint.color()).collect())).collect() } +/// Refuse a `group` that names no color group (`has` says which names one does) or isn't a name +/// or null. +fn check_group(want: &Value, has: impl Fn(&str) -> bool) -> Result<(), String> { + match want { + Value::Null => Ok(()), + Value::String(n) if has(n) => Ok(()), + Value::String(n) => Err(format!("no colour group `{n}`")), + v => Err(format!("`group` must be a color group name, not {v}")), + } +} + /// Make the `group` field's color group (none when it is null) the group being edited, when its /// colors aren't the rows' yet: with art the art is reduced again to as many rows as the group has /// colors, which become their new colors (as [`open`] does); without art the rows are its colors. -/// A name no color group has is refused, and the field goes back to the group being edited. -fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { +/// A name no color group has is refused ([`check_group`]), and the field goes back to the group +/// being edited. +fn select_group(app: &mut VectorcraftApp, d: &mut Fields) -> Result<(), String> { let want = d.fields.get("group").cloned().unwrap_or(Value::Null); let loaded = d.fields.get(GROUP_LOADED).cloned().unwrap_or(Value::Null); if want == loaded { @@ -504,39 +532,35 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> if let Value::String(n) = &want && loaded.is_string() && *n == d.str("groupName") - && d.fields.contains_key(super::form::PREVIEWED) + && app.session.in_interaction() { - cancel_preview(app, d); + cancel_preview(app); if !doc_groups(app).iter().any(|(g, _)| g == n) { d.fields.insert("group".into(), loaded); return Ok(()); } } - let art = d.bool("__art"); - let name = match &want { - Value::Null => { - // No group: without art OK saves the rows as a new color group. - d.fields.insert(GROUP_LOADED.into(), Value::Null); - if !art { - d.fields.insert("__newGroup".into(), json!(true)); - d.fields.insert("groupName".into(), json!(NEW_GROUP)); - } - restart_history(app, d); - return Ok(()); - } - Value::String(n) => n.clone(), - v => { - d.fields.insert("group".into(), loaded); - return Err(format!("`group` must be a color group name, not {v}")); - } - }; // The group's own colors, not those the preview (which rewrites the group being edited) shows. - if doc_groups(app).iter().any(|(n, _)| *n == name) { - cancel_preview(app, d); + if let Value::String(n) = &want + && doc_groups(app).iter().any(|(g, _)| g == n) + { + cancel_preview(app); } - let Some((_, colors)) = doc_groups(app).into_iter().find(|(n, _)| *n == name) else { + let groups = doc_groups(app); + if let Err(e) = check_group(&want, |n| groups.iter().any(|(g, _)| g == n)) { d.fields.insert("group".into(), loaded); - return Err(format!("no colour group `{name}`")); + return Err(e); + } + let art = d.bool("__art"); + let Some((name, colors)) = want.as_str().and_then(|n| groups.into_iter().find(|(g, _)| g == n)) else { + // No group: without art OK saves the rows as a new color group. + d.fields.insert(GROUP_LOADED.into(), Value::Null); + if !art { + d.fields.insert("__newGroup".into(), json!(true)); + d.fields.insert("groupName".into(), json!(NEW_GROUP)); + } + restart_history(d); + return Ok(()); }; let assign: Vec = colors.iter().map(key).collect(); d.fields.insert(GROUP_LOADED.into(), json!(name)); @@ -562,7 +586,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.remove(COMPS); } d.fields.insert("__assign".into(), Value::Array(assign)); - restart_history(app, d); + restart_history(d); Ok(()) } @@ -571,8 +595,8 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> /// name in `groupName`; `new` saves the new colors of the rows that aren't excluded as a new group; /// `delete` removes the selected group and its swatches. Each is an undo step of its own on the /// document, not on the preview, which runs again afterwards. -fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Result<(), String> { - check_group_action(app, d, action)?; +fn group_action(app: &mut VectorcraftApp, d: &mut Fields, action: &Value) -> Result<(), String> { + check_group_action(d, action, |g| holds_other_paints(app, g))?; let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); // The rows as OK reads them (a group just selected reduces the art again). sync(app, d); @@ -584,10 +608,10 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // Nothing changed since the last save but perhaps the name. let name = d.str("groupName"); if name.trim().is_empty() || group.as_deref() == Some(name.as_str()) { - restart_history(app, d); + restart_history(d); return Ok(()); } - cancel_preview(app, d); + cancel_preview(app); let colors: Vec = doc_groups(app) .into_iter() .find(|(n, _)| group.as_deref() == Some(n.as_str())) @@ -598,7 +622,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res d.fields.insert("group".into(), name.clone()); d.fields.insert(GROUP_LOADED.into(), name.clone()); d.fields.insert("groupName".into(), name); - restart_history(app, d); + restart_history(d); Ok(()) } Some("save") => { @@ -607,7 +631,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, // then the colors added on the Edit tab; a row made with New Row that holds no current // colors gives the group no color. - cancel_preview(app, d); + cancel_preview(app); let own: Vec = doc_groups(app) .into_iter() .find(|(n, _)| group.as_deref() == Some(n.as_str())) @@ -705,11 +729,11 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res reread_rows(app, d, &rs, &before, &gone); } } - restart_history(app, d); + restart_history(d); Ok(()) } Some("delete") => { - cancel_preview(app, d); + cancel_preview(app); app.run("swatch.delete", json!({"names": [group]}))?; d.fields.insert("group".into(), Value::Null); select_group(app, d) @@ -720,7 +744,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res /// The color Save Changes gives the group's swatch for `row`: `null` when the row's color was /// removed, which removes the swatch as OK does, otherwise its new color as OK gives it. -fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { +fn saved_color(app: &VectorcraftApp, d: &Fields, row: &Value) -> Option { if color_removed(row) { Some(Value::Null) } else { group_colors(app, d, std::iter::once(row)).into_iter().next() } } @@ -732,7 +756,7 @@ fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { /// that row's new color and exclusion (art the save left as it was keeps its recolor); the rest /// are excluded too. A row that lists only `gone` colors (those of swatches the save removed) is /// left out: its art keeps its colors, and the row gives the group no color. -fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec], gone: &[Value]) { +fn reread_rows(app: &mut VectorcraftApp, d: &mut Fields, old: &[Value], before: &[Vec], gone: &[Value]) { let given: Vec = art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); // A swatch whose color the save gave the art is found by that color again: the row its old @@ -770,9 +794,14 @@ fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: mark_saved(app, d); } +/// The Global Adjust at 0%: every amount, none changing a color. +fn zero_adjust() -> Value { + Value::Object(ADJUSTS.iter().map(|k| (k.to_string(), json!(0.0))).collect()) +} + /// Give each row's new color the Global Adjust (and Limit to Library) as OK would, and set the /// Global Adjust back to 0%; nothing changes when it is 0%. -fn bake_adjust(app: &VectorcraftApp, d: &mut Dialog) { +fn bake_adjust(app: &VectorcraftApp, d: &mut Fields) { if global_adjust(adjust_values(d)).is_identity() { return; } @@ -785,12 +814,12 @@ fn bake_adjust(app: &VectorcraftApp, d: &mut Dialog) { } } d.fields.insert("rows".into(), Value::Array(rs)); - d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().map(|k| (k.to_string(), json!(0.0))).collect())); + d.fields.insert("globalAdjust".into(), zero_adjust()); } /// After Save Changes with art: until the rows or the Global Adjust change, OK and the preview /// leave the selected group's colors as they were saved. -fn mark_saved(app: &VectorcraftApp, d: &mut Dialog) { +fn mark_saved(app: &VectorcraftApp, d: &mut Fields) { let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); let saved: Vec = doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); @@ -800,7 +829,7 @@ fn mark_saved(app: &VectorcraftApp, d: &mut Dialog) { } /// Whether the rows and the Global Adjust are as [`mark_saved`] recorded them. -fn unchanged_since_save(d: &Dialog) -> bool { +fn unchanged_since_save(d: &Fields) -> bool { d.fields.get(SAVED_ROWS).and_then(Value::as_array).is_some_and(|s| *s == rows(d)) && d.fields.get(SAVED_ADJUST).is_some_and(|a| *a == json!(adjust_values(d))) } @@ -840,7 +869,7 @@ const SWATCH_ROWS: &str = "__swatchRows"; /// The row that gives the swatch at place `i` of `own` (the group's colors) its new color, with the /// color that finds it: the row listing the color [`SWATCH_ROWS`] holds for that swatch, else the /// first row listing the swatch's own color. -fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Option<(Value, &'a Value)> { +fn swatch_row<'a>(d: &Fields, rs: &'a [Value], own: &[Value], i: usize) -> Option<(Value, &'a Value)> { let links = d.fields.get(SWATCH_ROWS).and_then(Value::as_array).filter(|l| l.len() == own.len()); let link = links.and_then(|l| l.get(i)).filter(|l| !l.is_null()); link.and_then(|l| row_listing(rs, l).map(|r| (l.clone(), r))).or_else(|| own.get(i).and_then(|k| row_listing(rs, k).map(|r| (k.clone(), r)))) @@ -855,113 +884,40 @@ fn kept_color(assign: &[Value], i: usize) -> Value { /// Refuse a `groupAction` other than `save`, `new` or `delete`, `save` or `delete` with no group /// selected, and `save` on a group with a swatch that is not a color (a gradient, pattern or None -/// swatch): the rows hold only the group's colors, so the save would replace or remove it. -fn check_group_action(app: &VectorcraftApp, d: &Dialog, action: &Value) -> Result<(), String> { +/// swatch; `other_paints` says which groups have one): the rows hold only the group's colors, so the +/// save would replace or remove it. +fn check_group_action(d: &Fields, action: &Value, other_paints: impl Fn(&str) -> bool) -> Result<(), String> { let group = d.fields.get("group").and_then(Value::as_str); match (action.as_str(), group) { (Some("new"), _) => Ok(()), - (Some("save"), Some(g)) if holds_other_paints(app, g) => { - Err(format!("color group `{g}` holds swatches that are not colors, which Save Changes can't keep")) - } + (Some("save"), Some(g)) if other_paints(g) => Err(format!("color group `{g}` holds swatches that are not colors, which Save Changes can't keep")), (Some("save" | "delete"), Some(_)) => Ok(()), (Some("save" | "delete"), None) => Err("missing `group`".into()), _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), } } -/// Whether color group `group` has a swatch that is not a color, in the document as it is without -/// the preview (which can rewrite or rename the group). -fn holds_other_paints(app: &VectorcraftApp, group: &str) -> bool { - let Some(st) = app.session.active() else { return false }; +/// The color groups with a swatch that is not a color, in the document as it is without the +/// preview (which can rewrite or rename the group being edited). +fn other_paint_groups(app: &VectorcraftApp) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); - doc.swatch_groups.iter().any(|g| g.name == group && g.swatches.iter().any(|w| w.paint.color().is_none())) + doc.swatch_groups.iter().filter(|g| g.swatches.iter().any(|w| w.paint.color().is_none())).map(|g| g.name.clone()).collect() +} + +/// Whether color group `group` has a swatch that is not a color ([`other_paint_groups`]). +fn holds_other_paints(app: &VectorcraftApp, group: &str) -> bool { + other_paint_groups(app).iter().any(|g| g == group) } /// Run the button of the Color Groups list that `groupAction` holds, if any. -fn run_group_action(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { +fn run_group_action(app: &mut VectorcraftApp, d: &mut Fields) -> Result<(), String> { match d.fields.remove(GROUP_ACTION) { Some(a) => group_action(app, d, &a), None => Ok(()), } } -/// `ui.dialog.set` of `group`, `groupStorage` or `groupAction`: select the group, or check the -/// button, which the next frame (or OK) runs. -pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), String> { - let Some(mut d) = app.ui.dialog.take() else { return Ok(()) }; - let r = match field { - "group" => select_group(app, &mut d), - GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { - Some(a) => check_group_action(app, &d, &a), - None => Ok(()), - }, - GROUP_STORAGE if !d.fields.get(GROUP_STORAGE).is_some_and(Value::is_boolean) => Err(format!("`{GROUP_STORAGE}` must be true or false")), - _ => Ok(()), - }; - app.ui.dialog = Some(d); - r -} - -/// The Color Groups list: a row per color group of the document with its name and colors (a click -/// selects it), and the Save Changes, New Color Group and Delete buttons under it. -fn group_storage(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, max_h: f32) { - let t = Tokens::get(ui.ctx()); - let groups = doc_groups(app); - let mut current = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); - // While the art previews, the group being edited shows under its new name. - if current.is_some() && d.fields.contains_key(super::form::PREVIEWED) && !groups.iter().any(|(n, _)| Some(n) == current.as_ref()) { - current = Some(d.str("groupName")); - } - let mut picked = None; - egui::ScrollArea::vertical().id_salt("recolor-groups").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { - for (name, colors) in &groups { - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_ROW_H), Sense::click()); - let on = current.as_deref() == Some(name.as_str()); - if on { - ui.painter().rect_filled(r, 2.0, t.row_selected); - } else if resp.hovered() { - ui.painter().rect_filled(r, 2.0, t.hover); - } - let inner = r.shrink2(vec2(4.0, 3.0)); - ui.painter().text(inner.left_top(), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(12.0), t.text); - let fit = ((inner.width() + 2.0) / 12.0).floor().max(0.0) as usize; - for (n, c) in colors.iter().take(fit).enumerate() { - let x = inner.left() + n as f32 * 12.0; - chip(ui, Rect::from_min_size(pos2(x, inner.bottom() - 10.0), vec2(10.0, 10.0)), *c, false); - } - let resp = resp.on_hover_text(name); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), on, name)); - if resp.clicked() { - picked = Some(name.clone()); - } - } - }); - if let Some(name) = picked { - d.fields.insert("group".into(), json!(name)); - if let Err(e) = select_group(app, d) { - app.status(e); - } - } - ui.add_space(4.0); - let selected = current.is_some(); - let any = rows(d).iter().any(|r| !excluded(r)); - let mut action = None; - ui.horizontal(|ui| { - if widgets::icon_button_enabled(ui, "save", tl!("Save Changes"), false, selected, 24.0).clicked() { - action = Some("save"); - } - if widgets::icon_button_enabled(ui, "dc-folder", tl!("New Color Group"), false, any, 24.0).clicked() { - action = Some("new"); - } - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete"), false, selected, 24.0).clicked() { - action = Some("delete"); - } - }); - if let Some(a) = action { - d.fields.insert(GROUP_ACTION.into(), json!(a)); - } -} - /// The fields of the Color Theme Picker: whether a click or drag on the canvas picks colors, and /// the picks so far (`recolor.pickTheme`'s `picks`); the picks the rows last took them from. const THEME_PICKER: &str = "themePicker"; @@ -972,7 +928,7 @@ const THEME_DONE: &str = "__themePicked"; /// current colors or were added on the Edit tab the palette of the art picked (`recolor.pickTheme`, as many colors as those /// rows), in row order; with fewer colors than rows, the colors repeat. Picks that touch no art /// leave the rows as they are. -fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) { +fn sync_theme(app: &mut VectorcraftApp, d: &mut Fields) { let picks = d.fields.get(THEME_PICKS).cloned().unwrap_or(Value::Null); if !picks.as_array().is_some_and(|a| !a.is_empty()) || d.fields.get(THEME_DONE) == Some(&picks) { return; @@ -984,9 +940,7 @@ fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) { return; } // The art as it is, not as the preview shows it; the preview runs again afterwards. - if d.fields.remove(super::form::PREVIEWED).is_some() { - let _ = app.session.cancel_interaction(); - } + cancel_preview(app); let colors = match app.session.execute("recolor.pickTheme", &json!({"picks": picks, "colors": active.len().min(64)})) { Ok(r) => r["colors"].as_array().map(|a| a.iter().filter_map(color_value).collect::>()).unwrap_or_default(), Err(e) => return app.status(e.to_string()), @@ -1006,55 +960,8 @@ fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) { /// The picks recolor.pickTheme takes at most; the oldest go first. const MAX_PICKS: usize = 256; -/// While the Color Theme Picker is on: a layer over the canvas, under the dialog, takes the clicks -/// and drags there as picks (with Shift they add to the picks so far, else they replace them) and -/// draws a drag's marquee, whose sides follow the document's axes. -fn theme_overlay(app: &VectorcraftApp, ctx: &egui::Context, d: &mut Dialog) { - let (Some(rect), Some(view)) = (app.canvas_rect, app.view()) else { return }; - let xf = crate::canvas::Xf::at(rect, view, app.canvas_ui_zoom); - let accent = Tokens::get(ctx).accent; - let id = egui::Id::unique("recolor-theme-picker"); - let shown = egui::Area::new(id).order(egui::Order::Middle).fixed_pos(rect.min).movable(false).show(ctx, |ui| { - let resp = ui.allocate_rect(rect, Sense::click_and_drag()).on_hover_cursor(egui::CursorIcon::Crosshair); - let shift = ui.input(|i| i.modifiers.shift); - // Where a press on the canvas began, kept from the first frame that sees it for the frame - // that releases it (the pointer forgets it then). - let from = egui::Id::unique("recolor-theme-drag"); - if let Some(o) = ui.input(|i| i.pointer.press_origin()).filter(|o| rect.contains(*o)) { - ui.data_mut(|m| m.insert_temp(from, o)); - } - if resp.clicked() { - ui.data_mut(|m| m.remove::(from)); - let p = xf.to_doc(resp.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos()))?); - return Some((json!({"at": [p.x, p.y]}), shift)); - } - if !(resp.dragged() || resp.drag_stopped()) { - return None; - } - let a = ui.data(|m| m.get_temp::(from))?; - let b = ui.input(|i| i.pointer.latest_pos()); - let (a, b) = (xf.to_doc(a), xf.to_doc(b?)); - if resp.drag_stopped() { - ui.data_mut(|m| m.remove::(from)); - return Some((json!({"rect": [a.x, a.y, b.x, b.y]}), shift)); - } - let corners = [(a.x, a.y), (b.x, a.y), (b.x, b.y), (a.x, b.y), (a.x, a.y)]; - let pts: Vec = corners.iter().map(|&(x, y)| xf.to_screen(vectorcraft_geom::Point::new(x, y))).collect(); - ui.painter().with_clip_rect(rect).extend(egui::Shape::dashed_line(&pts, egui::Stroke::new(1.0, accent), 4.0, 3.0)); - None - }); - // Above the backdrop of the dialog (which a click elsewhere raises), still under its window. - ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); - let Some((pick, add)) = shown.inner else { return }; - let mut picks = if add { d.fields.get(THEME_PICKS).and_then(Value::as_array).cloned().unwrap_or_default() } else { vec![] }; - picks.push(pick); - let extra = picks.len().saturating_sub(MAX_PICKS); - picks.drain(..extra); - d.fields.insert(THEME_PICKS.into(), Value::Array(picks)); -} - /// With Limit to Library, the rows' new colours snap to the library's nearest colours. -fn snap(app: &VectorcraftApp, d: &Dialog, rows: &mut [Value]) { +fn snap(app: &VectorcraftApp, d: &Fields, rows: &mut [Value]) { let Some(palette) = Some(d.str("limitTo")).filter(|l| !l.is_empty()).and_then(|l| swatchlib::limit_palette(&app.session, &l)) else { return }; for r in rows { if let Some(c) = to_color(r) { @@ -1063,7 +970,7 @@ fn snap(app: &VectorcraftApp, d: &Dialog, rows: &mut [Value]) { } } -fn rows(d: &Dialog) -> Vec { +fn rows(d: &Fields) -> Vec { d.fields.get("rows").and_then(Value::as_array).cloned().unwrap_or_default() } @@ -1085,9 +992,6 @@ fn set_to(row: &mut Value, c: &Color) { } } -/// Set for the frame in which Randomly change color order shuffled the rows' new colors. -const SHUFFLED: &str = "__shuffled"; - /// Give each row of `rows` whose current colors and new color are those of the same row of /// `before` that row's tint and model again, when it has none: a change that snaps back to the /// same new color keeps the tint of it and the model a slider edit gave it. @@ -1140,11 +1044,11 @@ fn in_group(row: &Value) -> bool { } /// The seed for the next Randomize: one past the last, held at `u64::MAX`. -fn next_seed(d: &Dialog) -> u64 { +fn next_seed(d: &Fields) -> u64 { (d.f64("__seed", 0.0) as u64).saturating_add(1) } -fn selection(d: &Dialog) -> Vec { +fn selection(d: &Fields) -> Vec { d.fields.get("__sel").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(|i| i as usize).collect()).unwrap_or_default() } @@ -1155,7 +1059,7 @@ fn selection(d: &Dialog) -> Vec { /// colors added on the Edit tab. With art in a color of the group, each swatch whose row /// ([`swatch_row`]) is found takes that row's new color instead, and every other swatch keeps its /// color, as Save Changes gives them. -fn apply_params(d: &Dialog) -> Value { +fn apply_params(d: &Fields) -> Value { let rs = rows(d); // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. let saved = unchanged_since_save(d); @@ -1257,7 +1161,7 @@ fn row_listing<'a>(rows: &'a [Value], k: &Value) -> Option<&'a Value> { /// with Preview on, a second recolors the selected rows as [`apply_params`] would (the other rows /// excluded, no color group rewritten). None otherwise, and when there is nothing to dim with /// Preview off. OK still applies [`apply_params`]. -fn find_params(d: &Dialog) -> Option { +fn find_params(d: &Fields) -> Option { if !d.bool(FIND) || !d.bool("__art") || d.str("tab") == "edit" { return None; } @@ -1323,220 +1227,42 @@ fn find_params(d: &Dialog) -> Option { (!commands.is_empty()).then(|| json!({"commands": commands})) } -/// The tabs, and the Color Groups list on their right while it is shown. -fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { - if let Err(e) = select_group(app, d) { - app.status(e); - } - let room = ui.available_width(); - // Without the room for both side by side (a narrow window), the list goes under the tabs. - let beside = room >= SPEC.min_width + STORAGE_GAP + STORAGE_W; - // The Color Picker that a double-click on a new color or Pick from Swatches asks for opens over - // the dialog after the list is drawn, so the window keeps its size while the picker is open. - let mut picker = None; - if !d.bool(GROUP_STORAGE) || !beside { - ui.vertical(|ui| { - ui.set_width(room.min(MAIN_W)); - picker = main(app, ui, d); - if d.bool(GROUP_STORAGE) { - ui.add_space(6.0); - group_storage(app, ui, d, 3.0 * GROUP_ROW_H); - } - }); - } else { - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); - picker = main(app, ui, d); - }); - ui.add_space(STORAGE_GAP); - ui.vertical(|ui| { - ui.set_width(STORAGE_W); - group_storage(app, ui, d, TAB_H - 30.0); - }); - }); - } - if let Some((i, swatches)) = picker - && let Some(row) = rows(d).get(i) - { - let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); - *d = super::color_picker::over_recolor(d, c, i, swatches); - } - false -} - -/// The tabs and the controls under them. Returns the row whose new color a double-click or Pick -/// from Swatches asked to pick in the Color Picker, with `true` for Pick from Swatches. -fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, bool)> { - seed(app, d); - sync(app, d); - sync_theme(app, d); - sync_weights(app, d); - // The fields as the dialog read the art are where Undo Changes starts, also when the pointer is - // down on the first frame and the first step is recorded only on release. - app.ui.recolor_history.start(d); - if let Err(e) = run_group_action(app, d) { - app.status(e); - } - let t = Tokens::get(ui.ctx()); - let picking = d.bool(THEME_PICKER); - let mut stepped = None; - ui.horizontal(|ui| { - let tab = d.str("tab"); - for (id, label) in [("assign", tl!("Assign")), ("edit", tl!("Edit"))] { - if ui.selectable_label(tab == id || (id == "assign" && tab != "edit"), egui::RichText::new(label).font(theme::semibold(12.5))).clicked() { - d.fields.insert("tab".into(), json!(id)); - } - } - ui.add_space(8.0); - if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { - d.fields.insert(THEME_PICKER.into(), json!(!picking)); - } - let h = &app.ui.recolor_history; - for (back, icon, tip) in [(true, "undo-2", tl!("Undo Changes")), (false, "redo-2", tl!("Redo Changes"))] { - if widgets::icon_button_enabled(ui, icon, tip, false, h.can(d, back), 24.0).clicked() { - stepped = Some(back); - } - } - let storage = d.bool(GROUP_STORAGE); - if widgets::icon_button(ui, "library", tl!("Show Color Groups"), storage, 24.0).clicked() { - d.fields.insert(GROUP_STORAGE.into(), json!(!storage)); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. - if let Some(i) = widgets::dropdown_named(ui, "recolor-preset", Some(tl!("Preset:")), PRESETS[preset_of(d)], &PRESETS, 130.0) { - set_preset(app, d, i); - } - ui.label(egui::RichText::new(tl!("Preset:")).color(t.text_dim)); - }); - }); - if let Some(back) = stepped { - app.ui.recolor_history.step(d, back); - } - widgets::divider(ui); - ui.add_space(4.0); - if d.bool(THEME_PICKER) { - widgets::dim_label(ui, tl!("Click or drag across the art to pick its colors; Shift adds more")); - ui.add_space(4.0); - theme_overlay(app, ui.ctx(), d); - sync_theme(app, d); - } - let mut rs = rows(d); - let top = ui.cursor().top(); - let (changed, pick) = if d.str("tab") == "edit" { edit_tab(app, ui, d, &mut rs) } else { assign_tab(app, ui, d, &mut rs) }; - if d.str("tab") != "edit" { - ui.add_space((TAB_H - (ui.cursor().top() - top)).max(0.0)); - } - if changed { - snap(app, d, &mut rs); - // A shuffle by `recolor.randomize` has already moved each tint with its color. - if d.fields.remove(SHUFFLED).is_none() { - keep_tints(&rows(d), &mut rs); - } - d.fields.insert("rows".into(), Value::Array(rs)); - } - sync_weights(app, d); - if let Some(which) = d.fields.remove(SAVE_GROUP) - && let Err(e) = save_group(app, d, which.as_str().unwrap_or_default()) - { - app.status(e); - } - if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { - ui.add_space(6.0); - ui.horizontal(|ui| { - widgets::dim_label(ui, tl!("Color Group:")); - form::text(ui, d, "groupName", 200.0); - }); - } - sync(app, d); - // New rows take the picks now, so that a new count of Colors is one step. - sync_theme(app, d); - // A change is a step once the pointer is up: a drag is one step from press to release. - if !ui.input(|i| i.pointer.any_down()) { - app.ui.recolor_history.note(d); - } - if d.bool("__art") { - match find_params(d) { - // Find shows the art so with Preview off too. - Some(p) => { - ui.add_space(8.0); - form::preview_check(ui, d); - form::preview_now(app, d, "Recolor Artwork", "command.batch", p); - } - None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), - } - } - pick -} - -/// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. -pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: Color) -> Dialog { - let mut rs = rows(&d); - if let Some(r) = rs.get_mut(i) { - set_to(r, &c); - snap(app, &d, &mut rs); - keep_tints(&rows(&d), &mut rs); - d.fields.insert("rows".into(), Value::Array(rs)); - } - d -} - /// The fields a step of Undo Changes and Redo Changes restores: what the art is recolored with. const STEP_FIELDS: [&str; 11] = ["rows", "colors", "method", "preserveWhite", "preserveBlack", "preserveGrays", "limitTo", "rule", "globalAdjust", THEME_PICKS, WEIGHTS]; /// The fields that record which reduction, picks and weights the rows already took, restored with /// [`STEP_FIELDS`] so that the restored rows are not reduced, picked or weighed again. -const STEP_MARKS: [&str; 4] = ["__reduced", THEME_DONE, WEIGHED, PRESERVED]; -/// VectorCraft's own limits on the steps Undo Changes keeps: at most this many, and at most this -/// many bytes of them as JSON; the oldest go first. -const MAX_STEPS: usize = 64; +const STEP_MARKS: [&str; 4] = [REDUCED, THEME_DONE, WEIGHED, PRESERVED]; +/// VectorCraft's own limit on the bytes of JSON the steps of Undo Changes keep; the oldest go first. const MAX_STEP_BYTES: usize = 4 << 20; type Snapshot = serde_json::Map; -/// The open dialog's own history of color edits: Undo Changes goes back one edit and Redo Changes -/// forward one, without touching the document's undo history. A change of [`STEP_FIELDS`] is one -/// step once the pointer is up, so a drag is one step; a new edit after Undo Changes ends what Redo -/// Changes could restore. -#[derive(Clone, Debug, Default)] -pub struct History { - /// The fields the dialog opened with (or had when its steps were dropped), before it read the - /// art, until its first frame or command. - opened: Option, - /// The fields after the last step (none before the dialog's first frame). - base: Option, - undo: Vec, - redo: Vec, -} - -/// Drop the dialog's steps, after another color group is selected or Save Changes rewrites the -/// group: Undo Changes and Redo Changes then have no step to go to. The fields of `d` are where -/// Undo Changes starts again, as on a new opening, so fields set before the next frame or step -/// (with `ui.dialog.set`) are a step back to them. -fn restart_history(app: &mut VectorcraftApp, d: &Dialog) { - app.ui.recolor_history = History { opened: Some(snapshot(d)), ..History::default() }; -} - /// The size of `s` as JSON, which [`MAX_STEP_BYTES`] limits. fn snapshot_size(s: &Snapshot) -> usize { serde_json::to_vec(s).map_or(0, |b| b.len()) } /// The fields of `d` a step restores ([`STEP_FIELDS`] and [`STEP_MARKS`]). -fn snapshot(d: &Dialog) -> Snapshot { +fn snapshot(d: &Fields) -> Snapshot { STEP_FIELDS.iter().chain(&STEP_MARKS).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect() } -/// Before the first step is recorded: when fields were set after the dialog opened (with -/// `ui.dialog.set`, before a frame drew it), the fields it opened with, as they read the art, are -/// the step Undo Changes goes back to. -fn seed(app: &mut VectorcraftApp, d: &Dialog) { - let Some(opened) = app.ui.recolor_history.opened.take() else { return }; - if app.ui.recolor_history.base.is_some() || snapshot(d) == opened { - return; +/// Leave Undo Changes and Redo Changes no step to go to, after another color group is selected or +/// Save Changes rewrites the group: the dialog's steps start again from the fields `d` has then, as on +/// a new opening, so fields set before the next frame or step are a step back to them. +fn restart_history(d: &mut Fields) { + d.fields.insert(RESTART.into(), json!(true)); +} + +/// Before the first step: when fields were set after the dialog opened (with `ui.dialog.set`, before +/// a frame read the art), the fields it `opened` with, as they read the art, are the step Undo +/// Changes goes back to. `None` when nothing was set. +fn seed(app: &mut VectorcraftApp, d: &Fields, opened: &Snapshot) -> Option { + if snapshot(d) == *opened { + return None; } let mut first = d.clone(); - first.fields.remove(super::form::PREVIEWED); for k in STEP_FIELDS.iter().chain(&STEP_MARKS) { match opened.get(*k) { Some(v) => first.fields.insert(k.to_string(), v.clone()), @@ -1545,127 +1271,381 @@ fn seed(app: &mut VectorcraftApp, d: &Dialog) { } sync(app, &mut first); sync_theme(app, &mut first); - app.ui.recolor_history.base = Some(snapshot(&first)); + Some(snapshot(&first)) } -impl History { - /// Take the fields of `d` as those after the last step when no step has them yet. - fn start(&mut self, d: &Dialog) { - if self.base.is_none() { - self.base = Some(snapshot(d)); +/// The open dialog's own history of color edits: Undo Changes goes back one edit and Redo Changes +/// forward one, without touching the document's undo history. A change of [`STEP_FIELDS`] is one +/// step once the gesture that makes it has ended, so a drag is one step; a new edit after Undo +/// Changes ends what Redo Changes could restore. +struct Steps { + history: EditHistory, + /// The fields after the latest step, which a change is told from. + settled: Snapshot, + /// The fields the dialog opened with (or had when its steps were dropped), until the pump has + /// read the art and the history starts ([`Work::begin`]). + opened: Option, +} + +impl Steps { + /// Steps of a dialog that opened with the fields `opened` and has not read the art yet. + fn opened(opened: Snapshot) -> Self { + Steps { history: EditHistory::new(&opened), settled: opened.clone(), opened: Some(opened) } + } + + /// The history from `base` on, with nothing to undo or redo. + fn start(&mut self, base: Snapshot) { + self.history = EditHistory::new(&base).with_budget(MAX_STEP_BYTES, snapshot_size); + self.settled = base; + } + + /// Takes `d`'s mark from [`restart_history`]: the steps start again from its fields. + fn take_restart(&mut self, d: &mut Fields) { + if d.fields.remove(RESTART).is_some() { + self.opened = Some(snapshot(d)); } } - /// Whether the fields of `d` differ from those after the last step. - fn pending(&self, d: &Dialog) -> bool { - self.base.as_ref().is_some_and(|b| STEP_FIELDS.iter().any(|k| d.fields.get(*k) != b.get(*k))) - } - - /// Record a change of `d`'s fields since the last step as a step. - fn note(&mut self, d: &Dialog) { - if self.base.is_some() && !self.pending(d) { + /// Records a change of `d`'s fields since the latest step as a step. + fn note(&mut self, d: &Fields) { + let now = snapshot(d); + if now == self.settled { return; } - if let Some(before) = self.base.replace(snapshot(d)) { - self.undo.push(before); - self.redo.clear(); - self.trim(); - } + let before = std::mem::replace(&mut self.settled, now.clone()); + self.history.record(&EditEvent::set(Mixed::Same(before), now, Arc::from(TITLE), None)); } - /// Drop the oldest steps past [`MAX_STEPS`] and [`MAX_STEP_BYTES`], keeping the newest step - /// even when it and the current fields alone pass the byte limit. - fn trim(&mut self) { - let extra = self.undo.len().saturating_sub(MAX_STEPS); - self.undo.drain(..extra); - let mut total: usize = self.base.iter().chain(&self.undo).map(snapshot_size).sum(); - let mut gone = 0; - while total > MAX_STEP_BYTES && gone + 1 < self.undo.len() { - total -= snapshot_size(&self.undo[gone]); - gone += 1; - } - self.undo.drain(..gone); + /// Whether `d`'s fields differ from those after the latest step. + fn pending(&self, d: &Fields) -> bool { + STEP_FIELDS.iter().any(|k| d.fields.get(*k) != self.settled.get(*k)) } - fn can(&self, d: &Dialog, back: bool) -> bool { - // Before the first frame or command, fields set since the dialog opened are a step back, - // except rows and weights that the art's reduction is about to replace or drop ([`sync`]). - if self.base.is_none() - && let Some(opened) = &self.opened - { - let reduces = d.bool("__art") && d.fields.get("__reduced") != Some(&reduce_params(d)); + /// Whether Undo Changes (`back`) or Redo Changes has a step to go to. + fn can(&self, d: &Fields, back: bool) -> bool { + // Before the art is read, fields set since the dialog opened are a step back, except rows + // and weights that the art's reduction is about to replace or drop ([`sync`]). + if let Some(opened) = &self.opened { + let reduces = d.bool("__art") && d.fields.get(REDUCED) != Some(&reduce_params(d)); let kept = |k: &&&str| !(reduces && (**k == "rows" || **k == WEIGHTS)); return back && STEP_FIELDS.iter().filter(kept).any(|k| d.fields.get(*k) != opened.get(*k)); } - if back { !self.undo.is_empty() || self.pending(d) } else { !self.redo.is_empty() && !self.pending(d) } + if back { self.history.can_undo() || self.pending(d) } else { self.history.can_redo() && !self.pending(d) } } /// Undo Changes (`back`) or Redo Changes on `d`: give it the fields of the step before or after. /// Returns false when there is none. - fn step(&mut self, d: &mut Dialog, back: bool) -> bool { + fn step(&mut self, d: &mut Fields, back: bool) -> bool { + if self.opened.is_some() { + return false; + } self.note(d); - let (from, to) = if back { (&mut self.undo, &mut self.redo) } else { (&mut self.redo, &mut self.undo) }; - let Some(s) = from.pop() else { return false }; - to.extend(self.base.take()); + let mut now = snapshot(d); + if !self.history.step(&mut now, if back { Step::Undo } else { Step::Redo }) { + return false; + } for k in STEP_FIELDS.iter().chain(&STEP_MARKS) { - match s.get(*k) { + match now.get(*k) { Some(v) => d.fields.insert(k.to_string(), v.clone()), None => d.fields.remove(*k), }; } // The rows hold no slider edit or drag, and the selection keeps to them. - for k in [COMPS, DRAG, BAR_DRAG, SHUFFLED] { + for k in [COMPS, DRAG] { d.fields.remove(k); } let n = rows(d).len(); d.fields.insert("__sel".into(), json!(selection(d).into_iter().filter(|i| *i < n).collect::>())); - self.base = Some(s); + self.settled = now; true } } +/// What `show` asked for in the passes since the pump last ran, which needs the app. +#[derive(Default)] +struct Filed { + /// Undo Changes (`true`) or Redo Changes. + step: Option, + /// Randomize: saturation and brightness (`true`) or color order. + randomize: Option, + /// Other Library…: a library file to import and limit to. + library: bool, + /// The row whose new color the Color Picker edits, with `true` from Pick from Swatches. + picker: Option<(usize, bool)>, + /// The rows before the passes edited them, which the edit snaps to the library from. + edited: Option>, + /// A gesture in the dialog was running after the latest pass: its change is no step yet. + running: bool, +} + +/// One row as the dialog shows it: the color its new color chip shows, the color its Tint rail runs +/// to, and the name of the library's spot color its new color is. +struct RowFeed { + shown: Color, + linked: Color, + spot: Option, +} + +impl RowFeed { + fn of(app: &VectorcraftApp, d: &Fields, row: &Value) -> RowFeed { + let to = to_color(row); + let spot = to.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c)); + RowFeed { shown: new_shown(app, d, row), linked: linked(app, to.unwrap_or_default()), spot } + } +} + +/// What the dialog shows of the app, which the pump feeds it each frame: the dialog has no app of +/// its own. +struct Feed { + /// Limit to Library's choices: the key `limitTo` takes and the name the menu shows. + libraries: Vec<(String, String)>, + /// The first colour library, which the Color Library preset limits to. + first_library: Option, + /// The document's color groups with their colors, in the Swatches panel's order. + groups: Vec<(String, Vec)>, + /// The groups with a swatch that is not a color ([`other_paint_groups`]). + other_paints: Vec, + /// The art previews the dialog's recolour. + previewing: bool, + /// Each row as the dialog shows it. + rows: Vec, + /// What the Edit tab reads of the app. + edit: edit_tab::EditData, +} + +impl Feed { + fn of(app: &VectorcraftApp, d: &Fields) -> Feed { + // None, the document's swatches, then the colour libraries: the built-in ones (at the top + // level of the library menu) translated, those the user saved or loaded by their names. + let libs = colour_libraries(app); + let keys: Vec<&str> = ["", swatchlib::DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.id.as_str())).collect(); + let names: Vec<&str> = ["None", DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.name.as_str())).collect(); + let builtin = |k: usize| k.checked_sub(2).is_none_or(|i| libs.get(i).is_some_and(|l| l.submenu.is_none())); + let shown = super::shown_names(crate::i18n::current(), &names, builtin); + let libraries = keys.iter().zip(&shown).map(|(k, n)| ((*k).to_owned(), (*n).to_owned())).collect(); + let rs = rows(d); + Feed { + libraries, + first_library: libs.first().map(|l| l.id.clone()), + groups: doc_groups(app), + other_paints: other_paint_groups(app), + previewing: app.session.in_interaction(), + rows: rs.iter().map(|r| RowFeed::of(app, d, r)).collect(), + edit: edit_tab::EditData::of(app, d, &rs), + } + } +} + +/// What the pump works on with the app, out of the host: the values, their steps and what `show` +/// asked for. +struct Work { + fields: Fields, + steps: Steps, + filed: Filed, +} + +impl Work { + /// Reads the art for fields set since the last frame, as the next frame would; the first time, + /// the steps start ([`seed`]). + fn begin(&mut self, app: &mut VectorcraftApp) { + let baseline = self.steps.opened.take().map(|opened| seed(app, &self.fields, &opened)); + sync(app, &mut self.fields); + sync_theme(app, &mut self.fields); + sync_weights(app, &mut self.fields); + if let Some(base) = baseline { + self.steps.start(base.unwrap_or_else(|| snapshot(&self.fields))); + } + } + + /// One frame of the dialog's work: the group picked, the art read again, what the last passes + /// asked for, and the change as a step once no gesture runs. Returns the Color Picker asked for. + fn run(&mut self, app: &mut VectorcraftApp) -> Option<(usize, bool)> { + let d = &mut self.fields; + if let Err(e) = select_group(app, d) { + app.status(e); + } + self.steps.take_restart(&mut self.fields); + self.begin(app); + let filed = std::mem::take(&mut self.filed); + if let Err(e) = run_group_action(app, &mut self.fields) { + app.status(e); + } + self.steps.take_restart(&mut self.fields); + if let Some(back) = filed.step { + self.steps.step(&mut self.fields, back); + } + if let Some(sb) = filed.randomize { + randomize(app, &mut self.fields, sb); + } + if filed.library { + pick_library(app); + } + let d = &mut self.fields; + if let Some(before) = filed.edited { + let mut rs = rows(d); + snap(app, d, &mut rs); + keep_tints(&before, &mut rs); + d.fields.insert("rows".into(), Value::Array(rs)); + } + sync_weights(app, d); + if let Some(which) = d.fields.remove(SAVE_GROUP) + && let Err(e) = save_group(app, d, which.as_str().unwrap_or_default()) + { + app.status(e); + } + sync(app, d); + // New rows take the picks now, so that a new count of Colors is one step. + sync_theme(app, d); + // A change is a step once the gesture that makes it has ended: a drag is one step from press + // to release, and a change `ui.dialog.set` made is one at once. + if self.steps.opened.is_none() && !filed.running { + self.steps.note(&self.fields); + } + filed.picker + } +} + +/// Randomly change the rows' color order, or (`sb`) their saturation and brightness +/// (`recolor.randomize`), from the next seed. A shuffle moves each tint with its color. +fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) { + let seed = next_seed(d); + d.fields.insert("__seed".into(), json!(seed)); + let rs = rows(d); + let p = json!({"map": rs, "order": !sb, "saturationBrightness": sb, "seed": seed}); + match app.session.execute("recolor.randomize", &p) { + Ok(r) => { + let mut shuffled = r["map"].as_array().cloned().unwrap_or_default(); + keep_marks(&rs, &mut shuffled); + snap(app, d, &mut shuffled); + d.fields.insert("rows".into(), Value::Array(shuffled)); + } + Err(e) => app.status(e.to_string()), + } +} + +/// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and +/// limit to it. +fn pick_library(app: &mut VectorcraftApp) { + let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts)); + // PLAN: assumed `file_asks::Owner::Free` (fl.A3's owner of a continuation no document holds), as appearance-w19 codes it. + crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, |app, picked| { + let Some(path) = picked.first_path() else { return Ok(Value::Null) }; + let r = app.run("swatch.library.load", json!({ "path": path }))?; + let library = r["library"].clone(); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| { + if let Some(d) = host.get_mut::() { + d.fields.fields.insert("limitTo".into(), library); + } + }); + } + Ok(r) + }); +} + +/// What the art previews of `d`, with art: Find's `command.batch` while Find shows the art so +/// (with Preview off too), else `recolor.apply` while Preview is on. +fn preview_params(d: &Fields) -> Option<(bool, &'static str, Value)> { + if !d.bool("__art") { + return None; + } + Some(match find_params(d) { + Some(p) => (true, "command.batch", p), + None => (d.bool("preview"), CMD, apply_params(d)), + }) +} + +/// Runs the open dialog's live preview with `(on, command, params)`. +fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) { + let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return }; + // `run` reports a preview that fails on the status line itself. + let _ = live.run(app, on, TITLE, cmd, ¶ms); + if let Some(open) = app.color_dialogs.recolor.as_mut() { + open.preview = live; + } +} + +/// Feeds the open Recolor Artwork what it shows of the app, runs what its passes asked for, opens +/// the Color Picker it asked for over it and previews its recolour: once a frame, after the window's +/// dialog host ran. +// PLAN: hub-w2 adds the line `recolor::pump(app, ctx)` to `dialogs::host::pump` (co.A6 names this pump). +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(id) = app.color_dialogs.recolor.as_ref().map(|open| open.id) else { return }; + let Some(dialogs) = app.dialogs() else { return }; + let Some(mut work) = dialogs.with(|host| host.get_mut_by_id::(id).map(RecolorDialog::take_work)) else { return }; + let picker = work.run(app); + let picker = picker.and_then(|(row, swatches)| { + let r = rows(&work.fields).into_iter().nth(row)?; + Some((row, to_color(&r).or_else(|| from_colors(&r).first().copied()).unwrap_or_default(), swatches)) + }); + let previewing = preview_params(&work.fields); + let feed = Feed::of(app, &work.fields); + dialogs.with(|host| { + if let Some(d) = host.get_mut_by_id::(id) { + d.put_work(work, feed); + } + }); + if let Some((row, color, swatches)) = picker { + // PLAN: assumed `color_picker::open_over(app, parent, color, row, swatches) -> Result<(), String>` (color-w8's request row). + if let Err(e) = super::color_picker::open_over(app, id, color, row, swatches) { + app.status(e); + } + } + if let Some(p) = previewing { + run_preview(app, p); + } +} + /// Undo Changes (`ui.recolorUndo`, `back`) or Redo Changes (`ui.recolorRedo`) in the open Recolor /// Artwork dialog → {changed, canUndo, canRedo}. pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result { - if app.ui.dialog.as_ref().is_none_or(|d| d.kind != KIND) { - return Err("Recolor Artwork is not open".into()); - } - let Some(mut d) = app.ui.dialog.take() else { return Err("Recolor Artwork is not open".into()) }; + const NOT_OPEN: &str = "Recolor Artwork is not open"; + let id = app.color_dialogs.recolor.as_ref().map(|open| open.id).ok_or(NOT_OPEN)?; + let dialogs = app.dialogs().ok_or(NOT_OPEN)?; + let mut work = dialogs.with(|host| host.get_mut_by_id::(id).map(RecolorDialog::take_work)).ok_or(NOT_OPEN)?; // Fields set since the last frame take effect first, as the next frame would give them. - seed(app, &d); - sync(app, &mut d); - sync_theme(app, &mut d); - sync_weights(app, &mut d); - let mut h = std::mem::take(&mut app.ui.recolor_history); - let changed = h.step(&mut d, back); - let r = json!({"changed": changed, "canUndo": h.can(&d, true), "canRedo": h.can(&d, false)}); - app.ui.recolor_history = h; - // The art previews the step at once, as the frame after a button would preview it. - if changed && d.bool("__art") { - sync_weights(app, &mut d); - match find_params(&d) { - Some(p) => { - let _ = form::preview_now(app, &mut d, "Recolor Artwork", "command.batch", p); - } - None => { - let p = apply_params(&d); - form::preview_without_check(app, &mut d, "Recolor Artwork", CMD, p); - } - } + work.begin(app); + let changed = work.steps.step(&mut work.fields, back); + if changed { + sync_weights(app, &mut work.fields); } - app.ui.dialog = Some(d); - Ok(r) + let answer = json!({"changed": changed, "canUndo": work.steps.can(&work.fields, true), "canRedo": work.steps.can(&work.fields, false)}); + let previewing = preview_params(&work.fields).filter(|_| changed); + let feed = Feed::of(app, &work.fields); + dialogs.with(|host| { + if let Some(d) = host.get_mut_by_id::(id) { + d.put_work(work, feed); + } + }); + // The art previews the step at once, as the frame after a button would preview it. + if let Some(p) = previewing { + run_preview(app, p); + } + Ok(answer) } /// Whether Undo Changes (`back`) or Redo Changes can run: Recolor Artwork is open with a step to go to. pub(crate) fn can_step(app: &VectorcraftApp, back: bool) -> bool { - app.ui.dialog.as_ref().filter(|d| d.kind == KIND).is_some_and(|d| app.ui.recolor_history.can(d, back)) + app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some_and(|d| d.steps.can(&d.fields, back)))) +} + +/// Row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. +pub(super) fn with_new_color(app: &VectorcraftApp, d: &mut RecolorDialog, i: usize, c: Color) { + let before = rows(&d.fields); + let mut rs = before.clone(); + if let Some(r) = rs.get_mut(i) { + set_to(r, &c); + snap(app, &d.fields, &mut rs); + keep_tints(&before, &mut rs); + d.fields.fields.insert("rows".into(), Value::Array(rs)); + } } /// OK: keep the previewed recolour as one undo step (or apply it, e.g. to a colour group only; or -/// save colours opened alone as a new colour group). -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mut d = d.clone(); +/// save colours opened alone as a new colour group). The dialog closes once this answers `Ok`; an +/// `Err` keeps it open with the reason. +fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { + let mut d = fields.clone(); select_group(app, &mut d)?; sync(app, &mut d); sync_theme(app, &mut d); @@ -1674,29 +1654,316 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // its result, so an OK that fails afterwards does not run it again. if d.fields.contains_key(GROUP_ACTION) { let r = run_group_action(app, &mut d); - if let Some(live) = app.ui.dialog.as_mut().filter(|x| x.kind == KIND) { - *live = d.clone(); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| { + if let Some(live) = host.get_mut::() { + live.take_fields(d.clone()); + } + }); } r?; } - if d.bool("__newGroup") { + let preview = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)).unwrap_or_default(); + let committed = if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r) && to_color(r).is_some())); - let r = form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}))?; - app.ui.recolor_history = History::default(); - return Ok(r); - } - let r = form::commit_preview(app, CMD, apply_params(&d))?; - app.ui.recolor_history = History::default(); + preview.commit(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})) + } else { + preview.commit(app, CMD, apply_params(&d)) + }; + committed?; + app.color_dialogs.recolor = None; // The Preserve checkboxes (shown with art) open as confirmed here next time (#2960). if d.bool("__art") { app.ui.recolor_preserve = json!({"preserveWhite": d.bool("preserveWhite"), "preserveBlack": d.bool("preserveBlack"), "preserveGrays": d.bool("preserveGrays")}); } - Ok(r) + Ok(()) +} + +/// The Recolor Artwork dialog on the window's dialog host: the toolbar, the Assign or Edit tab, the +/// Color Groups list, the group's name, Preview and OK and Cancel. It edits its [`Fields`]; what needs +/// the app it files for [`pump`], which feeds it the app's state. Its OK is held until [`confirm`] +/// commits the recolour. +pub(crate) struct RecolorDialog { + id: DialogId, + fields: Fields, + steps: Steps, + held: HeldAnswer, + feed: Feed, + filed: Filed, + /// The lead and anchor of the rows table's selection, whose items are `__sel`: a Shift-click + /// range runs from the anchor. + ends: (Option, Option), + /// The row whose right-click menu is open, and where it opened. + row_menu: Option<(usize, egui::Pos2)>, +} + +impl RecolorDialog { + fn new(app: &VectorcraftApp, fields: Fields) -> Self { + RecolorDialog { + id: dialog_id(KIND), + feed: Feed::of(app, &fields), + steps: Steps::opened(snapshot(&fields)), + fields, + held: HeldAnswer::new(), + filed: Filed::default(), + ends: (None, None), + row_menu: None, + } + } + + /// The values, steps and requests, for the pump to work on with the app. + fn take_work(&mut self) -> Work { + Work { + fields: std::mem::take(&mut self.fields), + steps: std::mem::replace(&mut self.steps, Steps::opened(Snapshot::new())), + filed: std::mem::take(&mut self.filed), + } + } + + /// The pump's work back, with what the dialog shows of the app now. + fn put_work(&mut self, work: Work, feed: Feed) { + self.fields = work.fields; + self.steps = work.steps; + self.filed = work.filed; + self.feed = feed; + } + + /// Fields that OK's Color Groups button left, which the dialog keeps. + fn take_fields(&mut self, fields: Fields) { + self.fields = fields; + self.steps.take_restart(&mut self.fields); + } + + /// `ui.dialog.set`: a field the dialog holds, `preview`, `groupAction` or one of the + /// [`SETTABLE`] controls, as the dialog's own control sets it. A name no color group has, a + /// Color Groups button that can't run ([`check_group_action`]) and a `groupStorage` that is not a + /// bool are refused, and the dialog stays as it was. + fn set_field(&mut self, field: &str, value: Value) -> Result<(), String> { + let known = if field.starts_with("__") { + SETTABLE.contains(&field) + } else { + self.fields.fields.contains_key(field) || field == "preview" || field == GROUP_ACTION + }; + if !known { + return Err(FieldRefusal::Unknown.message(field)); + } + match field { + "group" => check_group(&value, |g| self.feed.groups.iter().any(|(n, _)| n == g))?, + GROUP_ACTION => check_group_action(&self.fields, &value, |g| self.feed.other_paints.iter().any(|n| n == g))?, + GROUP_STORAGE if !value.is_boolean() => return Err(format!("`{GROUP_STORAGE}` must be true or false")), + _ => {} + } + self.fields.fields.insert(field.to_owned(), value); + Ok(()) + } + + fn shown(&mut self, ui: &mut Ui) -> Option> { + let measuring = craft::ui::runtime::measure::active(ui.ctx()); + let finish = self.held.is_accepted(); + // The refusal of OK shows until a value changes. + if self.held.refusal().is_some_and(|(_, refused)| *refused != self.fields) { + self.held.clear_refusal(); + } + let refusal = self.held.refusal().map(|(reason, _)| reason.clone()); + let waiting = self.held.is_waiting(); + let can = (self.steps.can(&self.fields, true), self.steps.can(&self.fields, false)); + let art = self.fields.bool("__art"); + let mut preview = self.fields.bool("preview"); + let footer = ResetFooter::new(ui, None, true); + let RecolorDialog { fields, feed, filed, ends, row_menu, .. } = self; + // PLAN: Enter is not OK here: a form whose OK stays open closes on Enter without reporting it as its OK + // (form_dialogs/form.rs:429, :534), which would close a held dialog unanswered; the forms owner makes + // `FormDialog` report Enter as the pick of OK when `accept_stays_open` is on. + let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).enter_confirms(false).ok_enabled(!waiting); + if art { + form = form.preview(Some(Bind::bound(&mut preview))); + } + let mut running = false; + let out = form.show(ui, |ui, cx, d| { + // A measuring run closes nothing: the real run of the same pass makes the close. + if finish && !measuring { + cx.request_close_as(CloseReason::Activated); + } + let ctx = ui.ctx().clone(); + let ((), gesture) = craft::ui::runtime::edit::watch_gestures(&ctx, || body(ui, d, feed, filed, ends, row_menu, can)); + if !measuring { + running = gesture; + } + if let Some(reason) = &refusal { + Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui); + } + true + }); + if !measuring { + self.filed.running = running; + } + if art && preview != self.fields.bool("preview") { + self.fields.fields.insert("preview".into(), json!(preview)); + } + match out.closed { + Some(CloseReason::Activated) if finish => Some(self.held.finish().map_or(DialogResult::Cancel, DialogResult::Ok)), + Some(_) => Some(DialogResult::Cancel), + None => { + // OK files the fields for the app, which commits the recolour before the dialog closes. + if footer.pick(out.picked) == Some(ResetPick::Accept) && !self.held.is_waiting() { + self.held.file(self.fields.clone()); + } + None + } + } + } +} + +impl StackDialog for RecolorDialog { + type Result = Fields; + + fn id(&self) -> DialogId { + self.id + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + self.shown(ui) + } + + /// OK as its button gives it: the fields are filed for the app, which answers none until it has + /// committed the recolour; then the accepted fields. + fn confirm(&mut self, _: &egui::Context) -> Option { + if self.held.is_accepted() { + return self.held.finish(); + } + if !self.held.is_waiting() { + self.held.file(self.fields.clone()); + } + None + } + + fn held_state(&self) -> Option { + self.held.state() + } + + // PLAN: color-w20 asked for `canvas()` to return the main canvas while the Color Theme Picker is on; no main + // canvas id exists in the app to return (canvas-w20 owns the tool hook, `edit_tab::with_theme_pick`). + + /// The fields without the dialog's own `__` marks. + fn json_fields(&self) -> Option { + Some(Value::Object(self.fields.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect())) + } + + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { + self.set_field(field, value) + } +} + +impl HoldsOk for RecolorDialog { + type Answer = Fields; + + /// Recolor Artwork always holds its OK. + fn held_ok(self) -> Self { + self + } + + fn take_ok(&mut self) -> Option { + self.held.take() + } + + fn answer_ok(&mut self, answer: Result<(), Label>) { + self.held.answer(answer); + } +} + +/// The dialog's body: the toolbar, the tab shown with the Color Groups list beside it (under it +/// when the room is too narrow for both), and the group's name. +fn body( + ui: &mut Ui, + d: &mut Fields, + feed: &Feed, + filed: &mut Filed, + ends: &mut (Option, Option), + row_menu: &mut Option<(usize, egui::Pos2)>, + can: (bool, bool), +) { + toolbar(ui, d, feed, filed, can); + if d.bool(THEME_PICKER) { + Text::new(tl!("Click or drag across the art to pick its colors; Shift adds more")).shade(Shade::Muted).show(ui); + } + let before = rows(d); + let mut rs = before.clone(); + let mut changed = false; + Row::new().wrap(true).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + if d.str("tab") == "edit" { + let (edited, pick) = edit_tab::show(ui, d, &feed.edit, &mut rs); + changed = edited; + if pick.is_some() { + filed.picker = pick; + } + } else { + changed = assign_tab(ui, d, feed, filed, ends, row_menu, &mut rs); + } + }); + if d.bool(GROUP_STORAGE) { + group_list(ui, d, feed); + } + }); + if changed { + d.fields.insert("rows".into(), Value::Array(rs)); + filed.edited.get_or_insert(before); + } + if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { + let mut name = d.str("groupName"); + TextField::new(tl!("Color Group:"), Bind::bound(&mut name)).show(ui); + if name != d.str("groupName") { + d.fields.insert("groupName".into(), json!(name)); + } + } +} + +/// An icon-only toggle named `label` over the bool field `key` of `d`. +fn toggle_field(ui: &mut Ui, d: &mut Fields, key: &str, label: &'static str, icon: &'static str, enabled: bool) { + let mut on = d.bool(key); + ToggleButton::new(label, Bind::bound(&mut on)).icon(IconId::new(icon)).icon_only().enabled(enabled).show(ui); + if on != d.bool(key) { + d.fields.insert(key.into(), json!(on)); + } +} + +/// The toolbar: the Assign and Edit tabs, the Color Theme Picker, Undo Changes and Redo Changes +/// (`can` says whether each has a step), Show Color Groups and the preset menu. +fn toolbar(ui: &mut Ui, d: &mut Fields, feed: &Feed, filed: &mut Filed, (can_undo, can_redo): (bool, bool)) { + Row::new().show(ui, |ui, _| { + let titles = [tl!("Assign").to_owned(), tl!("Edit").to_owned()]; + let tabs = [0usize, 1]; + let source = keyed(&tabs, |k| *k).with_text(|k| Cow::Owned(titles.get(*k).cloned().unwrap_or_default())); + let shown = usize::from(d.str("tab") == "edit"); + let strip = TabStrip::new(tl!(TITLE)) + .kind(TabKind::Text) + .shown(shown) + .show_items(ui, &source, &mut |key, _| Tab::new(titles.get(*key).cloned().unwrap_or_default())); + for event in strip.response.events { + if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event + && let Some(&k) = keys.last() + { + d.fields.insert("tab".into(), json!(if k == 1 { "edit" } else { "assign" })); + } + } + toggle_field(ui, d, THEME_PICKER, tl!("Color Theme Picker"), "pipette", true); + if IconButton::new(IconId::new("undo-2")).label(tl!("Undo Changes")).enabled(can_undo).show(ui).clicks == 1 { + filed.step = Some(true); + } + if IconButton::new(IconId::new("redo-2")).label(tl!("Redo Changes")).enabled(can_redo).show(ui).clicks == 1 { + filed.step = Some(false); + } + toggle_field(ui, d, GROUP_STORAGE, tl!("Show Color Groups"), "library", true); + let presets: Vec> = PRESETS.iter().enumerate().map(|(i, p)| Entry::new(i, Label::from(*p))).collect(); + if let Some(&i) = Select::new(tl!("Preset:"), Bind::given(preset_of(d)), &presets).show(ui).value() { + set_preset(d, i, feed.first_library.as_deref()); + } + }); } /// The preset the fields match: an n-colour job (n rows, Scale Tints), a library, or Custom. -fn preset_of(d: &Dialog) -> usize { +fn preset_of(d: &Fields) -> usize { match d.fields.get("colors").and_then(Value::as_u64) { Some(n @ 1..=3) if d.str("method") == Method::ScaleTints.id() => n as usize, _ if !d.str("limitTo").is_empty() => 4, @@ -1704,312 +1971,319 @@ fn preset_of(d: &Dialog) -> usize { } } -fn set_preset(app: &VectorcraftApp, d: &mut Dialog, i: usize) { +/// Set up preset `i`: an n-colour job, or (without a library yet) `first_library`. +fn set_preset(d: &mut Fields, i: usize, first_library: Option<&str>) { match i { 1..=3 => { d.fields.insert("colors".into(), json!(i)); d.fields.insert("method".into(), json!(Method::ScaleTints.id())); } 4 if d.str("limitTo").is_empty() => { - d.fields.insert("limitTo".into(), json!(first_library(app).unwrap_or_default())); + d.fields.insert("limitTo".into(), json!(first_library.unwrap_or_default())); } _ => {} } } -/// A colour chip with a hairline frame. -fn chip(ui: &Ui, r: Rect, c: Color, dim: bool) { - let t = Tokens::get(ui.ctx()); - let fill = c32(&c); - ui.painter().rect_filled(r, 1.0, if dim { fill.gamma_multiply(0.35) } else { fill }); - ui.painter().rect_stroke(r, 1.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); +/// `c` as the framework's encoded sRGB, as the canvas shows it. +fn srgba(c: &Color) -> Srgba { + Srgba::from(c32(c)) } -/// The Assign tab. Returns true when the rows changed, and the row whose new colour was -/// double-clicked or chosen via "Pick from Swatches" (with `true` for swatches view). -fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec) -> (bool, Option<(usize, bool)>) { - let t = Tokens::get(ui.ctx()); +/// `c` as the hex field's value. +fn hex_rgba(c: &Color) -> Rgba { + Rgba::from_hex(&c.to_hex()).unwrap_or(Rgba::rgb(0, 0, 0)) +} + +/// The colors side by side across `rect`, each an equal part of it. +fn chips(rect: egui::Rect, colors: &[egui::Color32]) -> Vec { + let w = rect.width() / colors.len().max(1) as f32; + colors + .iter() + .enumerate() + .map(|(i, c)| egui::Shape::rect_filled(egui::Rect::from_min_size(rect.min + egui::vec2(i as f32 * w, 0.0), egui::vec2(w, rect.height())), 0.0, *c)) + .collect() +} + +/// An edit a row of the Assign tab's table made. +enum RowEdit { + /// The arrow: excluded (`true`) or recolored. + Exclude(usize, bool), + /// The hex field's new color. + Hex(usize, Rgba), + /// A double-click on the new color: the Color Picker. + Pick(usize), +} + +/// The Assign tab. Returns true when the rows changed; the Color Picker a double-click or Pick from +/// Swatches asks for, Randomize and Other Library… are filed for the pump. +fn assign_tab( + ui: &mut Ui, + d: &mut Fields, + feed: &Feed, + filed: &mut Filed, + ends: &mut (Option, Option), + row_menu: &mut Option<(usize, egui::Pos2)>, + rows: &mut Vec, +) -> bool { let mut changed = false; + let art = d.bool("__art"); let total: usize = rows.iter().map(|r| r["from"].as_array().map_or(0, Vec::len)).sum(); // Reduction and the preserve rules apply to art (a colour group alone has a row per colour). - if d.bool("__art") { - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Colors:")).color(t.text_dim)); - let labels: Vec = std::iter::once(tl!("Auto").to_string()).chain((1..=total).map(|n| n.to_string())).collect(); - let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); - let cur = d.fields.get("colors").and_then(Value::as_u64).map_or(tl!("Auto").to_string(), |n| n.to_string()); - if let Some(i) = widgets::dropdown_named(ui, "recolor-count", Some(tl!("Colors:")), &cur, &refs, 70.0) { - d.fields.insert("colors".into(), if i == 0 { Value::Null } else { json!(i) }); + if art { + Row::new().show(ui, |ui, _| { + let counts: Vec> = + std::iter::once(Entry::new(0, Label::from(tl!("Auto")))).chain((1..=total).map(|n| Entry::new(n, Label::from(n.to_string())))).collect(); + let current = d.fields.get("colors").and_then(Value::as_u64).map_or(0, |n| n as usize); + if let Some(&n) = Select::new(tl!("Colors:"), Bind::given(current), &counts).show(ui).value() { + d.fields.insert("colors".into(), if n == 0 { Value::Null } else { json!(n) }); } - ui.add_space(18.0); - ui.label(egui::RichText::new(tl!("Preserve:")).color(t.text_dim)); + Text::new(tl!("Preserve:")).shade(Shade::Muted).show(ui); for (k, label) in [("preserveWhite", tl!("White")), ("preserveBlack", tl!("Black")), ("preserveGrays", tl!("Grays"))] { - let on = d.bool(k); - if widgets::check(ui, label, on, true) { - d.fields.insert(k.into(), json!(!on)); + let mut on = d.bool(k); + Checkbox::new(Bind::bound(&mut on)).label(label).show(ui); + if on != d.bool(k) { + d.fields.insert(k.into(), json!(on)); } } }); - ui.add_space(6.0); } - ui.horizontal(|ui| { - ui.add_space(6.0); - ui.add_sized( - [CURRENT_W, 16.0], - egui::Label::new( - egui::RichText::new(crate::i18n::fmt(tl!("Current Colors ({total})"), &[("total", &total.to_string())])).color(t.text_dim), - ), - ); - ui.add_space(60.0); - ui.label(egui::RichText::new(tl!("New")).color(t.text_dim)); - }); - let mut sel = selection(d); - let mut clicked: Option = None; - let mut pick: Option<(usize, bool)> = None; - let mut limit_to: Option = None; - let shown: Vec = rows.iter().map(|r| new_shown(app, d, r)).collect(); - widgets::list_box(ui, |ui| { - egui::ScrollArea::vertical().id_salt("recolor-rows").max_height(TABLE_H).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.set_min_height(TABLE_H); - if rows.is_empty() { - ui.add_space(8.0); - widgets::dim_label(ui, tl!("No colors to recolor (preserved colors are left out).")); - } - for (i, row) in rows.iter_mut().enumerate() { - let bg = ui.painter().add(egui::Shape::Noop); - let off = excluded(row); - let r = ui.horizontal(|ui| { - ui.add_space(4.0); - let from = from_colors(row); - let (cur, cr) = ui.allocate_exact_size(vec2(CURRENT_W, 20.0), Sense::click()); - let w = CURRENT_W / from.len().max(1) as f32; - for (j, c) in from.iter().enumerate() { - let x = cur.left() + j as f32 * w; - chip(ui, Rect::from_min_max(pos2(x, cur.top()), pos2(x + w - if w > 4.0 { 2.0 } else { 0.0 }, cur.bottom())), *c, false); + if rows.is_empty() { + Text::new(tl!("No colors to recolor (preserved colors are left out).")).shade(Shade::Muted).show(ui); + } + let columns = vec![ + ColumnSpec::new(CURRENT, Label::from(crate::i18n::fmt(tl!("Current Colors ({total})"), &[("total", &total.to_string())])), ColumnWidth::fill(1.0)), + ColumnSpec::new(ARROW, Label::from(""), ColumnWidth::Content), + ColumnSpec::new(NEW, Label::from(tl!("New")), ColumnWidth::Content), + ColumnSpec::new(HEX, Label::from(tl!("Hex")), ColumnWidth::Content), + ]; + // A row is named by its current colors. + let names: Vec = rows + .iter() + .map(|r| { + let hex: Vec = from_colors(r).iter().map(Color::to_hex).collect(); + if hex.is_empty() { tl!("New Row").to_owned() } else { hex.join(", ") } + }) + .collect(); + // The table's selection is the rows' `__sel`; its lead and anchor stay with the dialog, so a + // Shift-click range runs from the anchor. An end that is no longer selected goes. + let items = selection(d); + let end = |e: Option| e.filter(|i| items.contains(i)); + let mut sel = Selection::new(items.clone(), end(ends.0), end(ends.1)); + let keys: Vec = (0..rows.len()).collect(); + let source = keyed(&keys, |k| *k).with_text(|k| Cow::Owned(names.get(*k).cloned().unwrap_or_default())); + let edits: RefCell> = RefCell::new(Vec::new()); + let shown_rows: &[Value] = rows; + let out = Table::::new(tl!("Colors"), columns).min_rows(5).max_rows(8).selection(Bind::bound(&mut sel)).show_items( + ui, + &source, + &mut |key, icx| { + let i = *key; + let edits = &edits; + let row = shown_rows.get(i).cloned().unwrap_or_default(); + let off = excluded(&row); + let from: Vec = from_colors(&row) + .iter() + .map(|c| if off { c32(c).gamma_multiply(0.35) } else { c32(c) }) + .collect(); + let to = to_color(&row); + let fill = to.map(|c| srgba(&feed.rows.get(i).map_or(c, |f| f.shown))); + let arrow = ToggleButton::new(tl!("Recolor this row"), Bind::given(!off)).icon(IconId::new(ARROW_OFF)).on_icon(IconId::new(ARROW_ON)).icon_only(); + let swatch = Swatch::new(format!("{} {}", tl!("New"), i + 1), fill.map_or(Mixed::Mixed, Mixed::Same)).enabled(!off); + let hex = HexField::hex(format!("{} {}", tl!("Color"), i + 1), Bind::given(to.map_or(Rgba::rgb(0, 0, 0), |c| hex_rgba(&c)))).enabled(to.is_some()); + // PLAN: the current colors are the row's thumbnail strip, not a `SwatchTable` cell: a cell field takes its + // own presses, so a click on them would not select the row as it does in production. + ListRow::new(names.get(i).cloned().unwrap_or_default()) + .cells(icx.cells()) + .thumb_aspect(ThumbSize::Small, ThumbAspect::new(6, 1), move |cx, rect| cx.data_shapes(chips(rect, &from))) + .cell_field(ARROW, arrow, move |out| { + if let Some(&on) = out.value() { + edits.borrow_mut().push(RowEdit::Exclude(i, !on)); } - // A row made with New Row shows an empty slot until colors are merged into it. - if from.is_empty() { - ui.painter().rect_stroke(cur, 1.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + }) + .cell_field(NEW, swatch, move |out| { + // A double-click is the first pass's input: a second pass of the frame reports none. + if out.response.double_clicked() && to.is_some() { + edits.borrow_mut().push(RowEdit::Pick(i)); } - if cr.clicked() { - clicked = Some(i); + }) + .cell_field(HEX, hex, move |out| { + if let Some(c) = out.events.committed() { + edits.borrow_mut().push(RowEdit::Hex(i, *c)); } - let (ar, aresp) = ui.allocate_exact_size(vec2(44.0, 20.0), Sense::click()); - arrow(ui, ar, !off, aresp.hovered()); - if aresp.on_hover_text(if off { tl!("Recolor this row") } else { tl!("Keep this row's colors (exclude)") }).clicked() { - row["exclude"] = json!(!off); - changed = true; - } - let (nr, _) = ui.allocate_exact_size(vec2(46.0, 20.0), Sense::hover()); - let nresp = ui.interact(nr, egui::Id::unique((NEW_CHIP, i)), Sense::click()); - let to = to_color(row).unwrap_or_default(); - // A row whose new color was removed shows an empty frame and an empty hex field. - let has_new = to_color(row).is_some(); - if has_new { - chip(ui, nr, shown.get(i).copied().unwrap_or_default(), off); - } else { - ui.painter().rect_stroke(nr, 1.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - } - if nresp.clicked() { - clicked = Some(i); - } - if nresp.double_clicked() && has_new { - pick = Some((i, false)); - } - ui.add_space(6.0); - let hex = if has_new { crate::panels::color::hex_digits(&to) } else { String::new() }; - let hex_name = format!("{} {}", tl!("Color"), i + 1); - if let Some(h) = widgets::hex_field_named(ui, ("recolor-hex", i), Some(&hex_name), &hex) - && let Some(c) = crate::panels::color::parse_hex(&h) - { - set_to(row, &keep_model(to, c)); - changed = true; - } - let mut row_menu = |ui: &mut Ui| { - if widgets::menu_item(ui, tl!("Pick from Swatches"), true, false) { - pick = Some((i, true)); - ui.close(); - } - ui.menu_button(tl!("Limit to Library"), |ui| { - let cur = d.str("limitTo"); - if widgets::menu_item(ui, tl!("None"), true, cur.is_empty()) { - limit_to = Some("".to_string()); - ui.close(); - } - ui.separator(); - if let Some(k) = crate::panels::swatches::library_list(app, ui, &cur) { - limit_to = Some(k); - ui.close(); - } - }); - }; - if (cr.secondary_clicked() || nresp.secondary_clicked()) && !sel.contains(&i) { - clicked = Some(i); - } - cr.context_menu(&mut row_menu); - nresp.context_menu(&mut row_menu); - let empty_w = ui.available_width(); - if empty_w > 0.0 { - let (_, empty_resp) = ui.allocate_exact_size(vec2(empty_w, 20.0), Sense::click()); - if empty_resp.clicked() { - clicked = Some(i); - } - if empty_resp.secondary_clicked() && !sel.contains(&i) { - clicked = Some(i); - } - empty_resp.context_menu(&mut row_menu); - } - }); - if sel.contains(&i) { - ui.painter().set(bg, egui::Shape::rect_filled(r.response.rect.expand2(vec2(2.0, 1.0)), 2.0, t.row_selected)); + }) + }, + ); + let mut items = sel.items.clone(); + items.sort_unstable(); + items.dedup(); + let end = |e: Option| e.filter(|i| items.contains(i)); + *ends = (end(sel.lead), end(sel.anchor)); + if items != selection(d) { + d.fields.insert("__sel".into(), json!(items)); + } + for edit in edits.into_inner() { + match edit { + RowEdit::Exclude(i, off) => { + if let Some(r) = rows.get_mut(i) { + r["exclude"] = json!(off); + changed = true; } } - }); - }); - if let Some(k) = limit_to { - d.fields.insert("limitTo".into(), json!(k)); - changed = true; - } - if let Some(i) = clicked { - let m = ui.input(|i| i.modifiers); - match sel.iter().position(|s| *s == i) { - Some(p) if m.shift || m.command => { - sel.remove(p); + RowEdit::Hex(i, c) => { + if let (Some(r), Some(new)) = (rows.get_mut(i), Color::from_hex(&c.to_hex())) { + let to = to_color(r).unwrap_or_default(); + set_to(r, &keep_model(to, new)); + changed = true; + } } - None if m.shift || m.command => sel.push(i), - _ => sel = vec![i], + RowEdit::Pick(i) => filed.picker = Some((i, false)), } - d.fields.insert("__sel".into(), json!(sel)); } - ui.add_space(4.0); - ui.horizontal(|ui| { + for event in out.events { + if let CollectionEvent::ContextMenu(request) = event { + *row_menu = Some((request.key, request.at)); + } + } + // A row's right-click menu: Pick from Swatches, and Limit to Library's choices. + if let Some((i, at)) = *row_menu { + let mut open = true; + let mut limit_to = None; + let current = d.str("limitTo"); + let menu = Menu::new(tl!("Colors")).opened_by(&out.response, Trigger::Manual).anchor(Anchor::Point(at)).open(Bind::bound(&mut open)).show(ui, |ui, _| { + if MenuItem::new(tl!("Pick from Swatches")).show(ui).ran { + filed.picker = Some((i, true)); + } + Menu::submenu_row(ui, tl!("Limit to Library"), |ui, _| { + for (key, name) in &feed.libraries { + if MenuItem::new(name.clone()).check(*key == current).show(ui).ran { + limit_to = Some(key.clone()); + } + } + }); + }); + if menu.output.closed.is_some() || !open { + *row_menu = None; + } + if let Some(k) = limit_to { + d.fields.insert("limitTo".into(), json!(k)); + changed = true; + } + } + let sel = selection(d); + Row::new().show(ui, |ui, _| { // New Row is available only with art. - if widgets::icon_button_enabled(ui, "plus", tl!("New Row"), false, d.bool("__art"), 24.0).clicked() { + if IconButton::new(IconId::new("plus")).label(tl!("New Row")).enabled(art).show(ui).clicks == 1 { let at = new_row(rows, &sel); d.fields.insert("__sel".into(), json!([at])); // The slider edit was kept for a row index that now names another row. d.fields.remove(COMPS); changed = true; } - let can_merge = sel.len() > 1; - if widgets::icon_button_enabled(ui, "combine", tl!("Merge colors into one row"), false, can_merge, 24.0).clicked() { + if IconButton::new(IconId::new("combine")).label(tl!("Merge colors into one row")).enabled(sel.len() > 1).show(ui).clicks == 1 { merge(rows, &sel); d.fields.insert("__sel".into(), json!([sel.iter().min()])); changed = true; } let can_split = sel.iter().any(|i| rows.get(*i).is_some_and(|r| r["from"].as_array().is_some_and(|a| a.len() > 1))); - if widgets::icon_button_enabled(ui, "ungroup", tl!("Separate colors into rows"), false, can_split, 24.0).clicked() { + if IconButton::new(IconId::new("ungroup")).label(tl!("Separate colors into rows")).enabled(can_split).show(ui).clicks == 1 { separate(rows, &sel); d.fields.insert("__sel".into(), json!([])); changed = true; } - ui.add_space(12.0); - for (icon, tip, sb) in + for (icon, label, sb) in [("arrow-left-right", tl!("Randomly change color order"), false), ("sparkles", tl!("Randomly change saturation and brightness"), true)] { - if widgets::icon_button_enabled(ui, icon, tip, false, rows.len() > 1 || sb, 24.0).clicked() { - let seed = next_seed(d); - d.fields.insert("__seed".into(), json!(seed)); - let p = json!({"map": rows, "order": !sb, "saturationBrightness": sb, "seed": seed}); - match app.session.execute("recolor.randomize", &p) { - Ok(r) => { - let mut shuffled = r["map"].as_array().cloned().unwrap_or_default(); - keep_marks(rows, &mut shuffled); - *rows = shuffled; - if !sb { - d.fields.insert(SHUFFLED.into(), json!(true)); - } - changed = true; - } - Err(e) => app.status(e.to_string()), - } + if IconButton::new(IconId::new(icon)).label(label).enabled(rows.len() > 1 || sb).show(ui).clicks == 1 { + filed.randomize = Some(sb); } } - let finding = d.bool(FIND); - if widgets::icon_button_enabled(ui, "search", tl!("Find the selected colors in the artwork"), finding, d.bool("__art"), 24.0).clicked() { - d.fields.insert(FIND.into(), json!(!finding)); - } - if widgets::icon_button(ui, "rotate-ccw", tl!("Reset the rows to the artwork's colors"), false, 24.0).clicked() { - d.fields.remove("__reduced"); + toggle_field(ui, d, FIND, tl!("Find the selected colors in the artwork"), "search", art); + if IconButton::new(IconId::new("rotate-ccw")).label(tl!("Reset the rows to the artwork's colors")).show(ui).clicks == 1 { + d.fields.remove(REDUCED); d.fields.remove(COMPS); // The rows keep no slider edit, also when they cannot be reduced again. - let saved = d.fields.get_mut("rows").and_then(Value::as_array_mut).into_iter().flatten(); - for r in rows.iter_mut().chain(saved).filter_map(Value::as_object_mut) { + for r in rows.iter_mut().filter_map(Value::as_object_mut) { r.remove("model"); } + d.fields.insert("rows".into(), Value::Array(rows.clone())); } - let target = SliderTarget::of(app, d, rows); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target, false)); + let target = SliderTarget::at(feed, d, rows, first_selected(d, rows)); + mode_menu(ui, d, &target, false); }); - ui.add_space(6.0); let row = first_selected(d, rows); - changed |= sliders(app, ui, d, rows, row); - ui.add_space(8.0); - egui::Grid::new("recolor-options").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { - ui.label(egui::RichText::new(tl!("Method:")).color(t.text_dim)); - let m = Method::parse(&d.str("method")).unwrap_or_default(); - let labels: Vec<&str> = Method::ALL.iter().map(|m| m.label()).collect(); - let chosen = ui.name_inputs(tl!("Method:"), |ui| widgets::dropdown(ui, "recolor-method", m.label(), &labels, 180.0)); - if let Some(i) = chosen { - d.fields.insert("method".into(), json!(Method::ALL[i].id())); + changed |= sliders(ui, feed, d, rows, row); + Row::new().show(ui, |ui, _| { + let methods: Vec> = Method::ALL.iter().enumerate().map(|(i, m)| Entry::new(i, Label::from(m.label()))).collect(); + let method = Method::parse(&d.str("method")).unwrap_or_default(); + let at = Method::ALL.iter().position(|m| m.id() == method.id()).unwrap_or(0); + if let Some(&i) = Select::new(tl!("Method:"), Bind::given(at), &methods).show(ui).value() + && let Some(m) = Method::ALL.get(i) + { + d.fields.insert("method".into(), json!(m.id())); } - ui.end_row(); - ui.label(egui::RichText::new(tl!("Limit to Library:")).color(t.text_dim)); - // None, the document's swatches, then the colour libraries: the built-in ones (at the top - // level of the library menu) translated, those the user saved or loaded by their names. - let libs = colour_libraries(app); - let keys: Vec<&str> = ["", swatchlib::DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.id.as_str())).collect(); - let names: Vec<&str> = ["None", DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.name.as_str())).collect(); - let builtin = |k: usize| k.checked_sub(2).is_none_or(|i| libs.get(i).is_some_and(|l| l.submenu.is_none())); - let shown = super::shown_names(crate::i18n::current(), &names, builtin); - let cur = d.str("limitTo"); - let at = keys.iter().position(|k| *k == cur).unwrap_or(0); - let current = shown.get(at).copied().unwrap_or_default(); - ui.horizontal(|ui| { - let library = ui.name_inputs(tl!("Limit to Library:"), |ui| widgets::dropdown_names(ui, "recolor-library", current, &shown, 180.0)); - if let Some(k) = library.and_then(|i| keys.get(i)) { - d.fields.insert("limitTo".into(), json!(k)); - } - // Import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and limit to it. - if app.services.pick_open.is_some() && widgets::icon_button(ui, "folder-open", tl!("Other Library…"), false, 24.0).clicked() { - let r = crate::picks::in_dialog(app, d, |app, d| { - let filters = crate::FilePick::filters(vectorcraft_engine::cmd::fileio::builtin_open_filters()); - let pick = crate::FilePick { filters, ..Default::default() }; - let Some(path) = crate::picks::open(app, &pick) else { return Ok(()) }; - let r = app.run("swatch.library.load", json!({ "path": path }))?; - d.fields.insert("limitTo".into(), r["library"].clone()); - Ok(()) - }); - if let Err(e) = r { - app.status(e); - } - } - }); - ui.end_row(); }); - (changed, pick) + Row::new().show(ui, |ui, _| { + let libraries: Vec> = feed.libraries.iter().enumerate().map(|(i, (_, name))| Entry::new(i, Label::from(name.clone()))).collect(); + let current = d.str("limitTo"); + let at = feed.libraries.iter().position(|(k, _)| *k == current).unwrap_or(0); + if let Some(&i) = Select::new(tl!("Limit to Library:"), Bind::given(at), &libraries).show(ui).value() + && let Some((k, _)) = feed.libraries.get(i) + { + d.fields.insert("limitTo".into(), json!(k)); + } + if IconButton::new(IconId::new("folder-open")).label(tl!("Other Library…")).show(ui).clicks == 1 { + filed.library = true; + } + }); + changed } -/// The arrow between a row's current and new colours: solid when the row is recoloured, a dashed -/// line without a head when it is excluded. -fn arrow(ui: &Ui, r: Rect, on: bool, hovered: bool) { - let t = Tokens::get(ui.ctx()); - let c = if hovered { - t.text_strong - } else if on { - t.text - } else { - t.text_disabled - }; - let (a, b) = (pos2(r.left() + 6.0, r.center().y), pos2(r.right() - 6.0, r.center().y)); - let stroke = egui::Stroke::new(1.2, c); - if on { - ui.painter().line_segment([a, b], stroke); - ui.painter().line_segment([b, b + vec2(-5.0, -4.0)], stroke); - ui.painter().line_segment([b, b + vec2(-5.0, 4.0)], stroke); - } else { - ui.painter().extend(egui::Shape::dashed_line(&[a, b], stroke, 3.0, 3.0)); +/// The Color Groups list: a row per color group of the document with its name and colors (a click +/// selects it, as the `group` field does), and Save Changes, New Color Group and Delete under it, +/// which set `groupAction`. +fn group_list(ui: &mut Ui, d: &mut Fields, feed: &Feed) { + let names: Vec = feed.groups.iter().map(|(n, _)| n.clone()).collect(); + let mut current = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // While the art previews, the group being edited shows under its new name. + if current.as_ref().is_some_and(|c| feed.previewing && !names.contains(c)) { + current = Some(d.str("groupName")); + } + let mut chosen = current.as_ref().and_then(|c| names.iter().position(|n| n == c)).map_or_else(Selection::default, Selection::single); + let keys: Vec = (0..names.len()).collect(); + let mut picked: Option = None; + Stack::new().show(ui, |ui, _| { + let source = keyed(&keys, |k| *k).with_text(|k| Cow::Owned(names.get(*k).cloned().unwrap_or_default())); + let out = List::new(tl!("Color Groups")).select(SelectMode::Single).selection(Bind::bound(&mut chosen)).show_items(ui, &source, &mut |key, _| { + let colors: Vec = feed.groups.get(*key).map(|(_, cs)| cs.iter().map(c32).collect()).unwrap_or_default(); + ListRow::new(names.get(*key).cloned().unwrap_or_default()) + .thumb_aspect(ThumbSize::Small, ThumbAspect::new(4, 1), move |cx, rect| cx.data_shapes(chips(rect, &colors))) + }); + for event in out.events { + if let CollectionEvent::Selection { change, .. } = event { + picked = match change { + SelectionChange::Set(keys) => keys.last().and_then(|k| names.get(*k)).map(|n| json!(n)), + SelectionChange::Toggle(k) => names.get(k).map(|n| json!(n)), + SelectionChange::Clear => Some(Value::Null), + _ => picked.take(), + }; + } + } + let selected = current.is_some(); + let any = rows(d).iter().any(|r| !excluded(r)); + // From the end edge: Delete, New Color Group, Save Changes. + let actions = [ + FooterAction::new(IconId::new("trash-2"), tl!("Delete")).enabled(selected), + FooterAction::new(IconId::new("dc-folder"), tl!("New Color Group")).enabled(any), + FooterAction::new(IconId::new("save"), tl!("Save Changes")).enabled(selected), + ]; + let footer = FooterBar::actions(actions).show_footer(ui); + if let Some(action) = footer.picked.and_then(|i| ["delete", "new", "save"].get(i)) { + d.fields.insert(GROUP_ACTION.into(), json!(action)); + } + }); + if let Some(group) = picked { + d.fields.insert("group".into(), group); } } @@ -2018,16 +2292,21 @@ fn row_tint(row: &Value) -> f32 { row["tint"].as_f64().map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32) } -/// Tint `t` (0..1) of spot color `c` as art linked to it shows it: a Lab spot color is the active -/// document's working-CMYK equivalent while the Spot Colors options use CMYK values -/// ([`vectorcraft_doc::Document::linked_color`]), and its inks scale. +/// Spot color `c` as art linked to it shows it: a Lab spot color is the active document's +/// working-CMYK equivalent while the Spot Colors options use CMYK values +/// ([`vectorcraft_doc::Document::linked_color`]). +fn linked(app: &VectorcraftApp, c: Color) -> Color { + app.session.active().map_or(c, |st| st.doc.linked_color(c, true)) +} + +/// Tint `t` (0..1) of spot color `c` as art linked to it shows it ([`linked`]): its inks scale. fn spot_tinted(app: &VectorcraftApp, c: Color, t: f32) -> Color { - app.session.active().map_or(c, |st| st.doc.linked_color(c, true)).tinted(t) + linked(app, c).tinted(t) } /// The color row `row`'s new color chip shows: what the art takes, at the row's tint (a spot color /// of the library as [`spot_tinted`] shows it). -fn new_shown(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Color { +fn new_shown(app: &VectorcraftApp, d: &Fields, row: &Value) -> Color { let to = to_color(row).unwrap_or_default(); // Only a Lab spot color can show another color; the library lookup is skipped for the rest. if matches!(to, Color::Lab { .. }) && d.bool("__art") && spot_of(app, d, &to).is_some() { @@ -2037,14 +2316,83 @@ fn new_shown(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Color { } } -/// The `sliderMode` id of `m` (`hsb`, `rgb`, `cmyk`, `lab`). -fn mode_id(m: Mode) -> String { - serde_json::to_value(m).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() +/// The `sliderMode` id of `m` (`hsb`, `rgb`, `cmyk`, `lab`), which is also its values' model id. +fn mode_id(m: ColorPanelMode) -> &'static str { + match m { + ColorPanelMode::RgbSliders => "rgb", + ColorPanelMode::CmykSliders => "cmyk", + ColorPanelMode::LabSliders => "lab", + _ => "hsb", + } +} + +/// The color mode menu's name for `m`. +fn mode_label(m: ColorPanelMode) -> &'static str { + match m { + ColorPanelMode::RgbSliders => "RGB", + ColorPanelMode::CmykSliders => "CMYK", + ColorPanelMode::LabSliders => "Lab", + _ => "HSB", + } +} + +/// The channels the sliders show in `mode`: label, least and greatest value, unit. +fn channels(mode: ColorPanelMode) -> &'static [(&'static str, f64, f64, ChannelUnit)] { + match mode { + ColorPanelMode::RgbSliders => &[("R", 0.0, 255.0, ChannelUnit::None), ("G", 0.0, 255.0, ChannelUnit::None), ("B", 0.0, 255.0, ChannelUnit::None)], + ColorPanelMode::CmykSliders => &[ + ("C", 0.0, 100.0, ChannelUnit::Percent), + ("M", 0.0, 100.0, ChannelUnit::Percent), + ("Y", 0.0, 100.0, ChannelUnit::Percent), + ("K", 0.0, 100.0, ChannelUnit::Percent), + ], + ColorPanelMode::LabSliders => &[("L", 0.0, 100.0, ChannelUnit::None), ("a", -128.0, 127.0, ChannelUnit::None), ("b", -128.0, 127.0, ChannelUnit::None)], + _ => &[("H", 0.0, 360.0, ChannelUnit::Degrees), ("S", 0.0, 100.0, ChannelUnit::Percent), ("B", 0.0, 100.0, ChannelUnit::Percent)], + } +} + +/// A slider's rule: whole steps from `lo` to `hi`. +fn rule(lo: f64, hi: f64) -> ChannelRule { + ChannelRule { range: lo..=hi, step: 1.0, decimals: 0 } +} + +/// `c`'s values in `mode` (HSB °/%/% and RGB 0 to 255 of the working RGB, CMYK %, Lab L*a*b*). +fn values_in(mode: ColorPanelMode, c: &Color) -> Vec { + match mode { + ColorPanelMode::RgbSliders => working_rgb(c).iter().map(|v| (v * 255.0).clamp(0.0, 255.0)).collect(), + ColorPanelMode::CmykSliders => c.to_cmyk().iter().map(|v| v * 100.0).collect(), + ColorPanelMode::LabSliders => { + let l = c.to_lab(); + vec![l.l, l.a, l.b] + } + _ => { + let hsb = egui::ecolor::Hsva::from_rgb(working_rgb(c)); + vec![hsb.h * 360.0, hsb.s * 100.0, hsb.v * 100.0] + } + } +} + +/// The color `values` give in `mode`. +fn color_in(mode: ColorPanelMode, values: &[f32]) -> Color { + color_of_values(&ModelValues::new(mode_id(mode), values)) +} + +/// The track of channel `n` (from `lo` to `hi`) of `mode` with the other values `comps`. +fn track(mode: ColorPanelMode, comps: &[f32], n: usize, lo: f64, hi: f64) -> Vec { + (0..TRACK_STOPS) + .map(|k| { + let mut v = comps.to_vec(); + if let Some(x) = v.get_mut(n) { + *x = (lo + (hi - lo) * k as f64 / (TRACK_STOPS - 1) as f64) as f32; + } + srgba(&color_in(mode, &v)) + }) + .collect() } /// The name of the library swatch (Limit to Library) that `recolor.apply` gives new color `c`, when /// it is a spot color: the first swatch of the library color nearest `c`. -fn spot_of(app: &VectorcraftApp, d: &Dialog, c: &Color) -> Option { +fn spot_of(app: &VectorcraftApp, d: &Fields, c: &Color) -> Option { let lib = d.str("limitTo"); if lib.is_empty() { return None; @@ -2055,92 +2403,83 @@ fn spot_of(app: &VectorcraftApp, d: &Dialog, c: &Color) -> Option { /// The mode the sliders show new color `c` in, `None` for Tint: the mode picked in the menu, else /// `c`'s own model (HSB for a gray), or Tint for a spot color (`spot`). -fn slider_mode(d: &Dialog, c: &Color, spot: bool) -> Option { +fn slider_mode(d: &Fields, c: &Color, spot: bool) -> Option { let picked = d.str("sliderMode"); match SLIDER_MODES.into_iter().find(|m| mode_id(*m) == picked) { Some(m) => Some(m), None if spot => None, - None => Some(match Mode::of(c) { - Mode::Grayscale => Mode::Hsb, - m => m, + None => Some(match c { + Color::Rgb { .. } => ColorPanelMode::RgbSliders, + Color::Cmyk { .. } => ColorPanelMode::CmykSliders, + Color::Lab { .. } => ColorPanelMode::LabSliders, + Color::Gray { .. } => ColorPanelMode::HsbSliders, }), } } /// The values the sliders show for row `i`'s new color `c` in `mode`: those they set last while /// the color is the one they set, else `c`'s. -fn slider_values(d: &Dialog, rows: &[Value], i: usize, c: &Color, mode: Mode) -> Vec { - let held = d.fields.get(COMPS).filter(|s| s["row"] == json!(i) && s["key"] == rows[i]["to"] && s["mode"] == json!(mode_id(mode))); +fn slider_values(d: &Fields, rows: &[Value], i: usize, c: &Color, mode: ColorPanelMode) -> Vec { + let to = rows.get(i).map(|r| r["to"].clone()).unwrap_or_default(); + let held = d.fields.get(COMPS).filter(|s| s["row"] == json!(i) && s["key"] == to && s["mode"] == json!(mode_id(mode))); let v: Option> = held.and_then(|s| s["v"].as_array()).map(|a| a.iter().filter_map(Value::as_f64).map(|x| x as f32).collect()); - v.filter(|v| v.len() == mode.labels().len()).unwrap_or_else(|| components(mode, c)) + v.filter(|v| v.len() == channels(mode).len()).unwrap_or_else(|| values_in(mode, c)) } /// The first selected row of `rows`. -fn first_selected(d: &Dialog, rows: &[Value]) -> Option { +fn first_selected(d: &Fields, rows: &[Value]) -> Option { selection(d).into_iter().filter(|i| *i < rows.len()).min() } /// What the color sliders edit: a row (the first selected row on the Assign tab, the base color's -/// row on the Edit tab), its new color, and the name of the library's spot color that color is. +/// row on the Edit tab), its new color, the name of the library's spot color that color is, and the +/// color art linked to it shows. struct SliderTarget { row: Option, color: Option, spot: Option, + linked: Color, } impl SliderTarget { - fn of(app: &VectorcraftApp, d: &Dialog, rows: &[Value]) -> Self { - Self::at(app, d, rows, first_selected(d, rows)) - } - /// What the color sliders edit when they edit row `row`. - fn at(app: &VectorcraftApp, d: &Dialog, rows: &[Value], row: Option) -> Self { + fn at(feed: &Feed, d: &Fields, rows: &[Value], row: Option) -> Self { let row = row.filter(|i| *i < rows.len()); - let color = row.and_then(|i| to_color(&rows[i])); + let color = row.and_then(|i| rows.get(i)).and_then(to_color); + let fed = row.and_then(|i| feed.rows.get(i)); // A row tint acts only on art, so without art a spot color shows the process modes. - let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c)); - Self { row, color, spot } + let spot = fed.and_then(|f| f.spot.clone()).filter(|_| d.bool("__art") && color.is_some()); + Self { row, color, spot, linked: fed.map_or(color.unwrap_or_default(), |f| f.linked) } } /// The mode the sliders show (`None`: Tint). - fn mode(&self, d: &Dialog) -> Option { + fn mode(&self, d: &Fields) -> Option { slider_mode(d, &self.color.unwrap_or_default(), self.spot.is_some()) } } /// The color mode menu of the sliders (HSB, RGB, CMYK, Lab, Tint for a spot color, and with -/// `global` Global Adjust), drawn right to left: the menu, then its label. -fn mode_menu(ui: &mut Ui, d: &mut Dialog, target: &SliderTarget, global: bool) { - let t = Tokens::get(ui.ctx()); - let mut labels: Vec<&str> = SLIDER_MODES.iter().map(|m| m.label()).collect(); +/// `global` Global Adjust). +fn mode_menu(ui: &mut Ui, d: &mut Fields, target: &SliderTarget, global: bool) { + let mut modes: Vec<(&'static str, &'static str)> = SLIDER_MODES.iter().map(|m| (mode_id(*m), mode_label(*m))).collect(); if target.spot.is_some() { - labels.push("Tint"); + modes.push(("tint", "Tint")); } if global { - labels.push(GLOBAL_ADJUST); + modes.push((GLOBAL, GLOBAL_ADJUST)); } - let adjusting = global && d.str("sliderMode") == GLOBAL; - let current = if adjusting { GLOBAL_ADJUST } else { target.mode(d).map_or("Tint", Mode::label) }; - // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. - let chosen = ui - .add_enabled_ui(target.color.is_some() || global, |ui| { - widgets::dropdown_named(ui, "recolor-slider-mode", Some(tl!("Color Mode:")), current, &labels, if global { 110.0 } else { 90.0 }) - }) - .inner; - if let Some(i) = chosen { - let id = match SLIDER_MODES.get(i) { - Some(m) => mode_id(*m), - None if labels.get(i) == Some(&GLOBAL_ADJUST) => GLOBAL.to_string(), - None => "tint".to_string(), - }; + let current = if global && d.str("sliderMode") == GLOBAL { GLOBAL } else { target.mode(d).map_or("tint", mode_id) }; + let at = modes.iter().position(|(id, _)| *id == current).unwrap_or(0); + let entries: Vec> = modes.iter().enumerate().map(|(i, (_, label))| Entry::new(i, Label::from(*label))).collect(); + let chosen = Select::new(tl!("Color Mode:"), Bind::given(at), &entries).enabled(target.color.is_some() || global).show(ui); + if let Some((id, _)) = chosen.value().and_then(|i| modes.get(*i)) { d.fields.insert("sliderMode".into(), json!(id)); } - ui.label(egui::RichText::new(tl!("Color Mode:")).color(t.text_dim)); } /// The Global Adjust amounts, in percent from -100 to 100, of `ADJUSTS`' keys in the /// `globalAdjust` field (0 for one it lacks). -fn adjust_values(d: &Dialog) -> [f64; 4] { +fn adjust_values(d: &Fields) -> [f64; 4] { let given = d.fields.get("globalAdjust"); ADJUSTS.map(|k| given.and_then(|g| g.get(k)).and_then(Value::as_f64).unwrap_or(0.0).clamp(-100.0, 100.0)) } @@ -2154,122 +2493,110 @@ fn global_adjust(values: [f64; 4]) -> GlobalAdjust { /// The Global Adjust sliders, two to a line: Saturation, Brightness, Temperature and Luminosity, /// each from -100% to 100% (0% changes nothing). They change every new color at once, so they /// edit no row; each rail shows its amounts on `sample`. -fn global_sliders(ui: &mut Ui, d: &mut Dialog, sample: Color) { +fn global_sliders(ui: &mut Ui, d: &mut Fields, sample: Color) { let labels = [tl!("Saturation"), tl!("Brightness"), tl!("Temperature"), tl!("Luminosity")]; let values = adjust_values(d); let mut set: Option<(usize, f64)> = None; - egui::Grid::new("recolor-global-adjust").num_columns(6).spacing([6.0, 4.0]).show(ui, |ui| { - for (n, lbl) in labels.iter().enumerate() { - let shown = widgets::SliderValue::field(values[n], -100.0..=100.0, "%", 0); - // The rail: `sample` with this slider's amount alone. - let track = |x: f32| { - let mut one = [0.0; 4]; - one[n] = f64::from(x) * 200.0 - 100.0; - c32(&global_adjust(one).apply(sample)) - }; - if let Some(v) = slider_cell(ui, ("global", n), lbl, shown, "%", &track, GLOBAL_LABEL_W, GLOBAL_SLIDER_W) { - set = Some((n, v)); + for (line, pair) in labels.chunks(2).enumerate() { + Row::new().show(ui, |ui, _| { + for (k, label) in pair.iter().enumerate() { + let n = line * 2 + k; + // The rail: `sample` with this slider's amount alone. + let stops = (0..TRACK_STOPS) + .map(|s| { + let mut one = [0.0; 4]; + if let Some(x) = one.get_mut(n) { + *x = -100.0 + 200.0 * s as f64 / (TRACK_STOPS - 1) as f64; + } + srgba(&global_adjust(one).apply(sample)) + }) + .collect(); + let value = values.get(n).copied().unwrap_or(0.0); + let Some(out) = ChannelRow::new(*label, Bind::given(value), rule(-100.0, 100.0)).unit(ChannelUnit::Percent).track(stops).show(ui) else { + continue; + }; + if let Some(&v) = out.events.value().filter(|v| v.is_finite()) { + set = Some((n, v.round())); + } } - if n % 2 == 1 { - ui.end_row(); - } - } - }); + }); + } if let Some((n, v)) = set { let mut values = values; - values[n] = v; + if let Some(x) = values.get_mut(n) { + *x = v; + } d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().zip(values).map(|(k, v)| (k.to_string(), json!(v))).collect())); } } -/// One color slider in the grid: its label `label_w` wide, its rail with `track` `slider_w` wide -/// and its number field, showing `shown` with `suffix`. Returns the whole number in `shown`'s -/// range that a drag, a key or the field sets. -#[allow(clippy::too_many_arguments)] -pub(crate) fn slider_cell( - ui: &mut Ui, - id: impl std::hash::Hash + Copy, - label: &str, - shown: widgets::SliderValue, - suffix: &str, - track: &dyn Fn(f32) -> egui::Color32, - label_w: f32, - slider_w: f32, -) -> Option { - let t = Tokens::get(ui.ctx()); - let (lo, hi) = (*shown.range.start(), *shown.range.end()); - let value = shown.value; - ui.add_sized(vec2(label_w, 22.0), egui::Label::new(egui::RichText::new(label).size(12.5).color(t.text))); - let unit = ((value - lo) / (hi - lo)) as f32; - let (dragged, _, keyed) = widgets::color_slider_stepped(ui, ("recolor-slider", id), label, Some(shown), unit, slider_w, track); - let typed = widgets::plain_field_named(ui, ("recolor-slider-field", id), Some(label), value, suffix, 0, SLIDER_FIELD_W); - dragged.map(|x| (lo + f64::from(x) * (hi - lo)).round()).or(keyed).or(typed).map(|v| v.clamp(lo, hi)).filter(|v| (v - value).abs() > 1e-6) -} - /// The color sliders, two to a line: they edit row `row`'s new color (the others keep theirs) in /// the mode of [`mode_menu`], or its tint of a spot color of the library. Without a row they are /// disabled. Returns true when they changed a row. -fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], row: Option) -> bool { - let target = SliderTarget::at(app, d, rows, row); - let mode = target.mode(d); +// PLAN: `edit_tab::show` gets only `&EditData` (co.A6), so the Edit tab reaches these sliders only if `EditData` +// carries what `Feed` gives them (each row's spot and linked color); color-w20 settles which. +fn sliders(ui: &mut Ui, feed: &Feed, d: &mut Fields, rows: &mut [Value], row: Option) -> bool { + let target = SliderTarget::at(feed, d, rows, row); let mut changed = false; - let top = ui.cursor().top(); - let lines = mode.map_or(1, |m| m.labels().len().div_ceil(2)); - ui.add_enabled_ui(target.color.is_some(), |ui| { - egui::Grid::new("recolor-sliders").num_columns(6).spacing([6.0, 4.0]).show(ui, |ui| { - let (Some(i), Some(c)) = (target.row, target.color) else { - // Nothing to edit: the mode's sliders, disabled. - let mode = mode.unwrap_or(Mode::Hsb); - let input = Tokens::get(ui.ctx()).input; - let gray = move |_: f32| input; - for (n, lbl) in mode.labels().iter().enumerate() { - let shown = widgets::SliderValue::field(0.0, f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); - slider_cell(ui, n, lbl, shown, mode.suffix(n), &gray, SLIDER_LABEL_W, SLIDER_W); - if n % 2 == 1 { - ui.end_row(); + Stack::new().enabled(target.color.is_some()).show(ui, |ui, _| { + let (Some(i), Some(c)) = (target.row, target.color) else { + // Nothing to edit: the mode's sliders, disabled. + let mode = target.mode(d).unwrap_or(ColorPanelMode::HsbSliders); + for pair in channels(mode).chunks(2) { + Row::new().show(ui, |ui, _| { + for &(name, lo, hi, unit) in pair { + // A disabled row edits nothing: its output has no edit to read. + let _ = ChannelRow::new(name, Bind::given(lo), rule(lo, hi)).short(name).unit(unit).show(ui); } - } - return; - }; - let Some(mode) = mode else { - // Tint of the spot color, and its name. - let tint = f64::from(row_tint(&rows[i])) * 100.0; - let shown = widgets::SliderValue::field(tint, 0.0..=100.0, "%", 0); - if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&spot_tinted(app, c, x)), SLIDER_LABEL_W, SLIDER_W) { - rows[i]["tint"] = json!(v); + }); + } + return; + }; + let Some(mode) = target.mode(d) else { + // Tint of the spot color, and its name. + let tint = f64::from(row_tint(&rows[i])) * 100.0; + let stops: Vec = (0..TRACK_STOPS).map(|k| srgba(&target.linked.tinted(k as f32 / (TRACK_STOPS - 1) as f32))).collect(); + Row::new().show(ui, |ui, _| { + if let Some(out) = ChannelRow::new(tl!("Tint"), Bind::given(tint), rule(0.0, 100.0)).short("T").unit(ChannelUnit::Percent).track(stops.clone()).show(ui) + && let Some(&v) = out.events.value().filter(|v| v.is_finite()) + { + rows[i]["tint"] = json!(v.round()); changed = true; } - ui.label(egui::RichText::new(target.spot.as_deref().unwrap_or_default()).color(Tokens::get(ui.ctx()).text)); - return; - }; - let comps = slider_values(d, rows, i, &c, mode); - let mut set: Option> = None; - for (n, lbl) in mode.labels().iter().enumerate() { - let v = comps.get(n).copied().unwrap_or(0.0); - let shown = widgets::SliderValue::field(f64::from(v), f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); - if let Some(nv) = slider_cell(ui, n, lbl, shown, mode.suffix(n), &|x| c32(&track_color(mode, &comps, n, x)), SLIDER_LABEL_W, SLIDER_W) - { - let mut c2 = comps.clone(); - c2[n] = nv as f32; - set = Some(c2); + Text::new(Label::from(target.spot.clone().unwrap_or_default())).show(ui); + }); + return; + }; + let comps = slider_values(d, rows, i, &c, mode); + let mut set: Option> = None; + for (line, pair) in channels(mode).chunks(2).enumerate() { + Row::new().show(ui, |ui, _| { + for (k, &(name, lo, hi, unit)) in pair.iter().enumerate() { + let n = line * 2 + k; + let value = f64::from(comps.get(n).copied().unwrap_or(0.0)); + let Some(out) = ChannelRow::new(name, Bind::given(value), rule(lo, hi)).short(name).unit(unit).track(track(mode, &comps, n, lo, hi)).show(ui) + else { + continue; + }; + if let Some(&v) = out.events.value().filter(|v| v.is_finite()) { + let mut next = set.take().unwrap_or_else(|| comps.clone()); + if let Some(x) = next.get_mut(n) { + *x = v.clamp(lo, hi) as f32; + } + set = Some(next); + } } - if n % 2 == 1 { - ui.end_row(); - } - } - if let Some(c2) = set { - // The mode stays as the edit changes the color's model (a gray edited in HSB is RGB). - d.fields.insert("sliderMode".into(), json!(mode_id(mode))); - set_to(&mut rows[i], &from_components(mode, &c2)); - d.fields.insert(COMPS.into(), json!({"row": i, "key": rows[i]["to"], "mode": mode_id(mode), "v": c2})); - rows[i]["model"] = json!("new"); - changed = true; - } - }); + }); + } + if let Some(v) = set { + // The mode stays as the edit changes the color's model (a gray edited in HSB is RGB). + d.fields.insert("sliderMode".into(), json!(mode_id(mode))); + set_to(&mut rows[i], &color_in(mode, &v)); + d.fields.insert(COMPS.into(), json!({"row": i, "key": rows[i]["to"], "mode": mode_id(mode), "v": v})); + rows[i]["model"] = json!("new"); + changed = true; + } }); - // Room for two lines of sliders whatever the mode, so the dialog keeps its height. - let per = (ui.cursor().top() - top) / lines as f32; - ui.add_space(per * (2 - lines.min(2)) as f32); changed } @@ -2345,7 +2672,7 @@ fn active_rows(rows: &[Value]) -> Vec { /// The row the Edit tab's color sliders edit: the first selected row when the tab shows it (one of /// `active`), else the base color's row `base`. A selected row the tab does not show (excluded, or /// empty) is left as it is. -fn edit_slider_row(d: &Dialog, rows: &[Value], active: &[usize], base: Option) -> Option { +fn edit_slider_row(d: &Fields, rows: &[Value], active: &[usize], base: Option) -> Option { first_selected(d, rows).filter(|i| active.contains(i)).or(base) } @@ -2390,22 +2717,21 @@ const WHEEL_TOOL: &str = "wheelTool"; /// else (hue and saturation). const WHEEL_AXES: &str = "wheelAxes"; -/// What the Edit tab's wheels show, from [`WHEEL_AXES`]. -fn wheel_axes(d: &Dialog) -> widgets::WheelAxes { - if d.str(WHEEL_AXES) == "hueBrightness" { widgets::WheelAxes::HueBrightness } else { widgets::WheelAxes::HueSaturation } +/// The channel the radius of the Edit tab's wheels shows, from [`WHEEL_AXES`]. +fn wheel_axes(d: &Fields) -> DiscRadius { + if d.str(WHEEL_AXES) == "hueBrightness" { DiscRadius::Brightness } else { DiscRadius::Saturation } } -/// The new color the Add Color tool gives a click at hue `h` (degrees) and `t`, the saturation (or -/// with [`widgets::WheelAxes::HueBrightness`] the brightness) clicked: with the other component of -/// `base` (the selected color, whose other component the wheel shows; full without one), the segmented -/// wheel's patch color with `segmented`, in `base`'s model. -fn added_color(base: Option, h: f32, t: f32, segmented: bool, axes: widgets::WheelAxes) -> Color { - let o = base.map_or(1.0, |b| b.to_hsb()[axes.other()]); - let c = if segmented { - widgets::segment_color_on(axes, h, t, o) - } else { - let [h, s, v] = axes.hsb(h, t, o); - Color::from_hsb(h, s, v) +/// The new color the Add Color tool gives a click at hue `h` (degrees) and `t`, the channel the +/// wheel's `radius` shows (saturation, or brightness) at the click: with the other channel of +/// `base` (the selected color, whose other channel the wheel shows; full without one), the centre of +/// the segmented wheel's patch there with `segmented` ([`patch_at`]), in `base`'s model. +fn added_color(base: Option, h: f32, t: f32, segmented: bool, radius: DiscRadius) -> Color { + let [_, s, v] = base.map_or([0.0, 1.0, 1.0], |b| b.to_hsb()); + let (h, t) = if segmented { patch_at(h, t) } else { (h, t) }; + let c = match radius { + DiscRadius::Brightness => Color::from_hsb(h, s, t), + _ => Color::from_hsb(h, t, v), }; base.map_or(c, |b| keep_model(b, c)) } @@ -2440,13 +2766,13 @@ fn remove_color(rows: &mut Vec, i: usize, base: Option, keep: bool /// Whether Remove Color keeps a row with current colors (see [`remove_color`]): with art, or with a /// color group. -fn keeps_rows(d: &Dialog) -> bool { +fn keeps_rows(d: &Fields) -> bool { d.bool("__art") || d.fields.get("group").is_some_and(Value::is_string) } /// After Remove Color: select the base row at `base`; the slider values held were for a row index /// that may now hold another row. -fn removed(d: &mut Dialog, base: usize) { +fn removed(d: &mut Fields, base: usize) { d.fields.insert("__sel".into(), json!([base])); d.fields.remove(COMPS); } @@ -2478,13 +2804,9 @@ fn by_place(rs: &[Value]) -> Vec<&Value> { filled } -/// The target of the wheel's right-click menu: `{marker, line, hs}` (row indexes and the hue and -/// saturation clicked). -const MENU_AT: &str = "__wheelMenu"; /// Select Shade's grid: saturations across, from 0% to 100%, and brightnesses down, from 100%. const SHADE_COLS: usize = 7; const SHADE_ROWS: usize = 7; -const SHADE_CELL: f32 = 16.0; /// The base color's row: the row of `active` (the rows the Edit tab shows) marked `base`, else /// the first of them. @@ -2562,35 +2884,6 @@ fn shade_at(col: usize, row: usize) -> [f32; 2] { [col as f32 / (SHADE_COLS - 1) as f32, 1.0 - row as f32 / SHADE_ROWS as f32] } -/// Select Shade's grid of `c`'s hue, the cell nearest `c` framed. Returns the saturation and -/// brightness of the cell clicked. -fn shade_grid(ui: &mut Ui, c: &Color) -> Option<[f32; 2]> { - let t = Tokens::get(ui.ctx()); - let [h, s0, v0] = c.to_hsb(); - let near = ((s0 * (SHADE_COLS - 1) as f32).round() as usize, (((1.0 - v0) * SHADE_ROWS as f32).round() as usize).min(SHADE_ROWS - 1)); - let mut out = None; - egui::Grid::new("recolor-shades").spacing([2.0, 2.0]).show(ui, |ui| { - for row in 0..SHADE_ROWS { - for col in 0..SHADE_COLS { - let [s, v] = shade_at(col, row); - let (r, resp) = ui.allocate_exact_size(vec2(SHADE_CELL, SHADE_CELL), Sense::click()); - ui.painter().rect_filled(r, 1.0, c32(&Color::from_hsb(h, s, v))); - if (col, row) == near { - ui.painter().rect_stroke(r, 1.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Outside); - } - let name = format!("{} {}%, {} {}%", tl!("Saturation"), (s * 100.0).round(), tl!("Brightness"), (v * 100.0).round()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); - if resp.clicked() { - out = Some([s, v]); - ui.close(); - } - } - ui.end_row(); - } - }); - out -} - /// What a marker's or a color bar's right-click menu, or the wheel's, chose. enum MenuChoice { /// Set As Base Color for the row. @@ -2606,41 +2899,18 @@ enum MenuChoice { Add([f32; 2], Option), } -/// A marker's or a color bar's right-click menu for row `i`: Set As Base Color and Remove Color -/// (neither for the base color `base`), Select Shade and Color Picker. -fn color_menu(ui: &mut Ui, rows: &[Value], i: usize, base: Option) -> Option { - let mut choice = None; - if widgets::menu_item_name(ui, tl!("Set As Base Color"), can_set_base(rows, i), false) { - choice = Some(MenuChoice::Base(i)); - } - if let Some(c) = rows.get(i).and_then(to_color) { - // Indented like the items beside it (their check column). - ui.menu_button(format!(" {}", tl!("Select Shade")), |ui| { - if let Some(sv) = shade_grid(ui, &c) { - choice = Some(MenuChoice::Shade(i, sv)); - } - }); - } - if widgets::menu_item_name(ui, tl!("Color Picker"), true, false) { - choice = Some(MenuChoice::Picker(i)); - } - if widgets::menu_item_name(ui, tl!("Remove Color"), Some(i) != base, false) { - choice = Some(MenuChoice::Remove(i)); - } - choice -} - /// Carry out a right-click menu's `choice` on the rows (`base`: the base color's row; `shown`: the -/// color whose brightness the wheel shows; `segmented`: the menu was on the segmented wheel). -/// Returns whether the rows changed and the row whose new color the Color Picker is to edit. +/// color whose other channel the wheel shows; `segmented`: the menu was on the segmented wheel; +/// `radius`: what the wheel's radius shows). Returns whether the rows changed and the row whose new +/// color the Color Picker is to edit. fn choose( - d: &mut Dialog, + d: &mut Fields, rows: &mut Vec, choice: MenuChoice, base: Option, shown: Option, segmented: bool, - axes: widgets::WheelAxes, + radius: DiscRadius, ) -> (bool, Option) { match choice { MenuChoice::Base(i) => (set_base(rows, i), None), @@ -2664,7 +2934,7 @@ fn choose( None => (false, None), }, MenuChoice::Add([h, s], line) => { - let i = add_color(rows, &added_color(shown, h, s, segmented, axes)); + let i = add_color(rows, &added_color(shown, h, s, segmented, radius)); if let Some(l) = line { tie_to(rows, l, i); } @@ -2675,308 +2945,6 @@ fn choose( } } -/// The Edit tab. Returns whether the rows changed and the row whose new color a right-click menu's -/// Color Picker is to edit. -fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec) -> (bool, Option<(usize, bool)>) { - let top = ui.cursor().top(); - let t = Tokens::get(ui.ctx()); - let mut changed = false; - let mut pick = None; - let linked = d.bool("linked"); - let active = active_rows(rows); - // The harmony rules build from the base color; the sliders and the Brightness slider edit the - // selected color (the base color when the tab does not show the first selected row). - let base = base_row(rows, &active); - let sel = edit_slider_row(d, rows, &active, base); - let target = SliderTarget::at(app, d, rows, sel); - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Harmony Rules:")).color(t.text_dim)); - let rule = Harmony::parse(&d.str("rule")).unwrap_or(Harmony::Complementary); - let labels: Vec<&str> = Harmony::ALL.iter().map(|h| h.label()).collect(); - // Choosing a rule gives the new colours its colours, from the base colour. The heading is - // not a field label widget, so the menu carries its own accessible name. - if let Some(i) = widgets::dropdown_named(ui, "recolor-rule", Some(tl!("Harmony Rules:")), rule.label(), &labels, 170.0) { - d.fields.insert("rule".into(), json!(Harmony::ALL[i].id())); - if let Some((b, c)) = base.and_then(|b| Some((b, to_color(&rows[b])?))) { - apply_rule(rows, Harmony::ALL[i], b, c, &active); - changed = true; - } - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let tip = if linked { tl!("Unlink harmony colors") } else { tl!("Link harmony colors") }; - if widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tip, linked, 24.0).clicked() { - d.fields.insert("linked".into(), json!(!linked)); - } - // New Color Group: save the wheel's colors or the Prominent Colors as a color group. - let button = widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0); - let prominent = d.bool("__art") && prominent_parts(d, rows).iter().any(|p| rows.get(p.0).and_then(to_color).is_some()); - let saved = egui::Popup::menu(&button).show(|ui| { - if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(|r| in_group(r) && to_color(r).is_some()), false) { - return Some("all"); - } - widgets::menu_item_name(ui, tl!("Save Prominent Colors"), prominent, false).then_some("prominent") - }); - if let Some(which) = saved.and_then(|r| r.inner) { - d.fields.insert(SAVE_GROUP.into(), json!(which)); - } - ui.add_space(8.0); - // The mode of the color sliders under the wheel: the selected new color in a color - // mode, or Global Adjust for all of them. - mode_menu(ui, d, &target, true); - }); - }); - // With art the Prominent Colors bar has the room of the two gaps, so the tab is no taller with - // it: on a short screen all of the tab but the chips has to fit. - let art = d.bool("__art"); - if !art { - ui.add_space(WHEEL_GAP); - } - let colors: Vec = active.iter().filter_map(|&i| to_color(&rows[i])).collect(); - let marked = base.and_then(|b| active.iter().position(|&i| i == b)); - let selected = sel.and_then(|s| active.iter().position(|&i| i == s)); - let shown = sel.and_then(|s| to_color(&rows[s])); - let mut choice = None; - let display = d.str("display"); - let tool = d.str(WHEEL_TOOL); - let axes = wheel_axes(d); - // The tools act on either wheel, not on the color bars. - let on_wheel = display != "bars"; - let mut w = widgets::WheelResponse::default(); - ui.horizontal(|ui| { - // The display buttons, beside the wheel so the tab keeps its height. - ui.vertical(|ui| { - for (id, icon, tip) in [ - ("smooth", "circle", tl!("Show smooth color wheel")), - ("segmented", "dc-polar-grid", tl!("Show segmented color wheel")), - ("bars", "dc-list-view", tl!("Show color bars")), - ] { - let on = display == id || (id == "smooth" && !matches!(display.as_str(), "segmented" | "bars")); - if widgets::icon_button(ui, icon, tip, on, 24.0).clicked() { - d.fields.insert("display".into(), json!(id)); - } - } - // The wheel tools: a click on the button turns its tool on, or off again. - ui.add_space(8.0); - for (id, icon, tip) in [("add", "plus", tl!("Add Color Tool")), ("remove", "minus", tl!("Remove Color Tool"))] { - let on = tool == id; - if widgets::icon_button_enabled(ui, icon, tip, on && on_wheel, on_wheel, 24.0).clicked() { - d.fields.insert(WHEEL_TOOL.into(), if on { Value::Null } else { json!(id) }); - } - } - // What the wheels show: a click switches between hue and saturation, and hue and - // brightness. It changes no color. - ui.add_space(8.0); - let bright = axes == widgets::WheelAxes::HueBrightness; - let tip = if bright { tl!("Show saturation and hue on wheel") } else { tl!("Show brightness and hue on wheel") }; - if widgets::icon_button_enabled(ui, "sun", tip, bright && on_wheel, on_wheel, 24.0).clicked() { - d.fields.insert(WHEEL_AXES.into(), json!(if bright { "hueSaturation" } else { "hueBrightness" })); - } - }); - ui.vertical(|ui| match display.as_str() { - "bars" => { - let (moved, chosen) = color_bars(ui, d, rows, &active, base); - changed |= moved; - choice = chosen; - } - _ => w = widgets::recolor_wheel(ui, "recolor-wheel", WHEEL, &colors, marked, selected, display == "segmented", axes), - }); - }); - // A right-click on the wheel: a marker's menu, or Add New Color elsewhere. Its target is kept - // while the menu stays open. - if let Some((hit, line, hs)) = w.secondary { - d.fields.insert(MENU_AT.into(), json!({"marker": hit.map(|k| active[k]), "line": line.map(|k| active[k]), "hs": hs})); - } else if w.response.as_ref().is_some_and(egui::Response::secondary_clicked) { - // A right-click off the wheel (in a corner of its square) targets nothing: its menu's Add - // New Color is off, and no earlier marker is changed. - d.fields.remove(MENU_AT); - } - if let Some(resp) = &w.response { - let at = d.fields.get(MENU_AT).cloned().unwrap_or_default(); - let row = |k: &str| at[k].as_u64().map(|i| i as usize).filter(|i| active.contains(i)); - let hs = at["hs"].as_array().and_then(|a| Some([a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32])); - resp.context_menu(|ui| match row("marker") { - Some(i) => choice = color_menu(ui, rows, i, base), - None => { - if widgets::menu_item_name(ui, tl!("Add New Color"), hs.is_some(), false) - && let Some(hs) = hs - { - choice = Some(MenuChoice::Add(hs, row("line"))); - } - } - }); - } - // A menu's choice changes the rows the wheel's indexes were for, so the wheel's own clicks and - // drags of this frame are left alone. - let chosen = choice.is_some(); - if let Some(c) = choice { - let (did, picked) = choose(d, rows, c, base, shown, display == "segmented", axes); - changed |= did; - pick = picked.map(|i| (i, false)); - } - if chosen { - w.pressed = None; - w.moved = None; - w.clicked = None; - } - // A click with a wheel tool adds a color there, or removes the color of the marker clicked. - let clicked = w.clicked.filter(|_| on_wheel && matches!(tool.as_str(), "add" | "remove")); - if let Some((hit, [h, out])) = clicked { - if tool == "add" { - let c = added_color(shown, h, out, display == "segmented", axes); - let i = add_color(rows, &c); - d.fields.insert("__sel".into(), json!([i])); - d.fields.remove(COMPS); - changed = true; - } else if let Some(b) = hit.and_then(|k| remove_color(rows, active[k], base, keeps_rows(d))) { - removed(d, b); - changed = true; - } - } - // Prominent Colors: the art's new colors, each as wide as its share of the art. - if art { - prominent_bar(ui, d, rows); - } - // A tool's click selects no marker: Add Color selects the new row, and Remove Color keeps the - // base color. - if let Some(k) = w.pressed.filter(|_| clicked.is_none()) { - d.fields.insert("__sel".into(), json!([active[k]])); - } - // A drag (of a marker or the brightness slider) moves the rows as they were when it started: - // a new colour read back from its model (CMYK through the colour profile) isn't exactly the - // colour written, so building on last frame's rows drifted the linked colours (#1733). - if let Some((k, set)) = w.moved.filter(|_| clicked.is_none()) { - let start = match d.fields.get(DRAG).and_then(Value::as_array) { - Some(s) if s.len() == rows.len() => s.clone(), - _ => rows.to_vec(), - }; - // What the control didn't set comes from the start too, not from last frame's colour. - if let Some(old) = start.get(active[k]).and_then(to_color).map(|c| c.to_hsb()) { - let hsb = [0, 1, 2].map(|n| set[n].unwrap_or(old[n])); - rows.clone_from_slice(&start); - move_color(rows, active[k], hsb, linked); - changed = true; - } - d.fields.insert(DRAG.into(), Value::Array(start)); - } - if !ui.input(|i| i.pointer.any_down()) { - d.fields.remove(DRAG); - } - if !art { - ui.add_space(SLIDERS_GAP); - } - // A color added or removed above changed the rows, so the sliders and chips read them afresh. - let active = active_rows(rows); - let base = base_row(rows, &active); - let sel = edit_slider_row(d, rows, &active, base); - if d.str("sliderMode") == GLOBAL { - let sample = sel.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25)); - global_sliders(ui, d, sample); - } else { - changed |= sliders(app, ui, d, rows, sel); - } - // The new colours: click one to select it; Set Current Color As Base Color, before them, makes - // the selected one the base color, which carries a double ring as its marker does. - let min_height = (TAB_H - (ui.cursor().top() - top)).max(0.0); - let mut make_base = None; - super::modal::scrolled_rows(ui, "recolor-edit-colors", |ui| { - // Keep the usual tab height when it fits; the empty space scrolls with the chips. - ui.set_min_height(min_height); - ui.horizontal_wrapped(|ui| { - let can = sel.is_some_and(|s| can_set_base(rows, s)); - if widgets::icon_button_enabled(ui, "circle-dot", tl!("Set Current Color As Base Color"), false, can, 20.0).clicked() { - make_base = sel; - } - for &i in &active { - let (r, resp) = ui.allocate_exact_size(vec2(28.0, 20.0), Sense::click()); - chip(ui, r, to_color(&rows[i]).unwrap_or_default(), false); - if Some(i) == sel { - ui.painter().rect_stroke(r.expand(1.5), 2.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Outside); - } - if Some(i) == base { - ui.painter().circle_stroke(r.center(), 4.0, egui::Stroke::new(1.5, egui::Color32::WHITE)); - ui.painter().circle_stroke(r.center(), 5.5, egui::Stroke::new(1.0, egui::Color32::BLACK)); - } - if resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default()).clicked() { - d.fields.insert("__sel".into(), json!([i])); - } - } - }); - }); - if let Some(i) = make_base { - changed |= set_base(rows, i); - } - (changed, pick) -} - -/// The Edit tab's color bars: a solid bar per row of `active` with its new color, in row order, the -/// base row's framed, scrolling past the wheel's height. A click on a bar selects its row (the -/// sliders under it edit that row's new color); a drag moves the bar's row to where the line under -/// the pointer shows, keeping every new color. A bar's right-click menu is a marker's -/// ([`color_menu`]). Returns true when the rows moved, and the menu's choice. -fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize], base: Option) -> (bool, Option) { - let t = Tokens::get(ui.ctx()); - let mut rects: Vec = Vec::with_capacity(active.len()); - let (mut dragging, mut released, mut dropped, mut choice) = (None, None, None, None); - // The area is given its full height first: in the row beside the display buttons a scroll area - // alone is only as tall as the room the row has. - let area = vec2(ui.available_width(), BARS_H); - ui.allocate_ui_with_layout(area, egui::Layout::top_down(egui::Align::Min), |ui| { - ui.set_min_size(area); - egui::ScrollArea::vertical().id_salt("recolor-bars").max_height(BARS_H).show(ui, |ui| { - ui.set_min_height(BARS_H); - ui.set_width(ui.available_width()); - if active.is_empty() { - ui.add_space(8.0); - widgets::dim_label(ui, tl!("No colors to recolor (preserved colors are left out).")); - } - for (n, &i) in active.iter().enumerate() { - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width() - 4.0, BAR_H), Sense::click_and_drag()); - chip(ui, r, to_color(&rows[i]).unwrap_or_default(), false); - if Some(i) == base { - ui.painter().rect_stroke(r, 2.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); - } - let name = format!("{} {}", tl!("Color"), i + 1); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &name)); - if resp.clicked() || resp.drag_started() { - d.fields.insert("__sel".into(), json!([i])); - } - if resp.dragged() { - dragging = Some(n); - } - if resp.drag_stopped() { - released = Some(n); - } - rects.push(r); - let resp = resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default()); - resp.context_menu(|ui| { - if let Some(c) = color_menu(ui, rows, i, base) { - choice = Some(c); - } - }); - } - // The place a dragged bar goes: before the first bar whose middle is below the pointer. - let at = ui.input(|i| i.pointer.latest_pos()).map(|p| rects.iter().filter(|r| r.center().y < p.y).count()); - if let (Some(n), Some(to)) = (dragging, at) - && to != n - && to != n + 1 - { - let y = rects.get(to).map_or_else(|| rects.last().map_or(0.0, |r| r.bottom() + 1.5), |r| r.top() - 1.5); - let x = rects.first().map_or(ui.max_rect().x_range(), |r| r.x_range()); - ui.painter().hline(x, y, egui::Stroke::new(2.0, t.accent)); - } - dropped = released.zip(at); - }); - }); - if choice.is_some() { - return (false, choice); - } - let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return (false, None) }; - d.fields.insert("__sel".into(), json!([moved])); - // The slider values held are those of a row index that may now hold another row. - d.fields.remove(COMPS); - (true, None) -} - /// Move the row of the `from`th active row (of `active`, ascending row indexes) to before the /// `to`th, or after the last for `active.len()`; the rows between shift by one. Returns the row's /// new index, or `None` when it stays where it is. @@ -3013,7 +2981,9 @@ fn apply_rule(rows: &mut [Value], rule: Harmony, base: usize, b: Color, active: #[cfg(test)] mod tests { + use super::fixture::Recolor; use super::*; + use vectorcraft_engine::Session; fn rows() -> Vec { vec![ @@ -3023,38 +2993,48 @@ mod tests { ] } + /// An app with a new `width` by 100 document. + fn app(width: u32) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": width, "height": 100})).unwrap(); + app + } + + /// Recolor Artwork opened on `app` with `params`. + fn opened(app: VectorcraftApp, params: Value) -> Recolor { + let rc = Recolor::new(app); + rc.app().run("ui.recolorDialog", params).unwrap(); + rc + } + #[test] fn recolor_dialog_keeps_the_default_model_without_an_extra_dropdown() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("ui.recolorDialog", json!({"colors": ["#ff8000"]})).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); + let rc = opened(app(100), json!({"colors": ["#ff8000"]})); + let d = rc.fields(); assert!(!d.fields.contains_key("model")); - assert!(apply_params(d).get("model").is_none()); + assert!(apply_params(&d).get("model").is_none()); } /// `recolor.apply` gets the Global Adjust amounts only when one of them is not 0%, whatever /// mode the sliders show. #[test] fn apply_params_send_global_adjust_only_when_it_changes_colors() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("ui.recolorDialog", json!({"colors": ["#ff8000"]})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - assert!(apply_params(d).get("globalAdjust").is_none(), "no field"); + let mut rc = opened(app(100), json!({"colors": ["#ff8000"]})); + let mut d = rc.fields(); + assert!(apply_params(&d).get("globalAdjust").is_none(), "0% as the dialog opens"); d.fields.insert("globalAdjust".into(), json!({"saturation": 0, "brightness": 0})); - assert!(apply_params(d).get("globalAdjust").is_none(), "all 0%"); + assert!(apply_params(&d).get("globalAdjust").is_none(), "all 0%"); d.fields.insert("globalAdjust".into(), json!({"temperature": 25, "luminosity": 500})); d.fields.insert("sliderMode".into(), json!("hsb")); assert_eq!( - apply_params(d)["globalAdjust"], + apply_params(&d)["globalAdjust"], json!({"saturation": 0.0, "brightness": 0.0, "temperature": 25.0, "luminosity": 100.0}), "every amount, clamped to 100%" ); // Colors opened alone become a new color group with the adjustment. - d.fields.insert("globalAdjust".into(), json!({"saturation": -100})); - let d = d.clone(); - confirm(&mut app, &d).unwrap(); + rc.set("globalAdjust", json!({"saturation": -100})).unwrap(); + rc.confirm().unwrap(); + let app = rc.app(); let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); let c = g.swatches[0].paint.color().unwrap(); assert!(c.to_hsb()[1] < 1e-3, "{c:?}"); @@ -3087,7 +3067,7 @@ mod tests { #[test] fn an_added_color_takes_the_base_colors_brightness_and_model() { let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3); - let sat = widgets::WheelAxes::HueSaturation; + let sat = DiscRadius::Saturation; let base = Color::from_hsb(10.0, 0.8, 0.6); assert!(near(added_color(Some(base), 120.0, 0.5, false, sat).to_hsb(), [120.0, 0.5, 0.6])); assert!(near(added_color(None, 200.0, 0.25, false, sat).to_hsb(), [200.0, 0.25, 1.0])); @@ -3103,7 +3083,7 @@ mod tests { #[test] fn an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation() { let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3); - let bright = widgets::WheelAxes::HueBrightness; + let bright = DiscRadius::Brightness; let base = Color::from_hsb(10.0, 0.8, 0.6); assert!(near(added_color(Some(base), 120.0, 0.5, false, bright).to_hsb(), [120.0, 0.8, 0.5])); assert!(near(added_color(None, 200.0, 0.25, false, bright).to_hsb(), [200.0, 1.0, 0.25])); @@ -3123,7 +3103,7 @@ mod tests { /// new color after them; a row made with New Row, which holds no current colors, adds none. #[test] fn apply_params_give_the_group_added_colors_and_keep_its_other_colors() { - let mut d = Dialog::new(KIND, json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]})); + let mut d = Fields::new(json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]})); let mut rs = vec![json!({"from": ["rgb 255 0 0"], "to": "rgb 1 1 1"}), json!({"from": ["rgb 0 0 255"], "to": null})]; new_row(&mut rs, &[]); add_color(&mut rs, &Color::rgb(9.0 / 255.0, 9.0 / 255.0, 9.0 / 255.0)); @@ -3139,7 +3119,7 @@ mod tests { /// after its new color was edited or removed, and with Global Adjust on. #[test] fn an_excluded_row_keeps_its_group_swatch() { - let mut d = Dialog::new(KIND, json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]})); + let mut d = Fields::new(json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]})); let rs = json!([ {"from": ["rgb 255 0 0"], "to": "rgb 7 7 7", "exclude": true}, {"from": ["rgb 0 0 255"], "to": null, "exclude": true}, @@ -3148,18 +3128,17 @@ mod tests { d.fields.insert("rows".into(), rs); assert_eq!(apply_params(&d)["groupColors"], json!(["keep", "keep", "rgb 8 8 8"])); // Without art the rows are the group's colors. - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let mut app = app(100); app.run("swatch.newGroup", json!({"name": "G", "colors": ["#2878f0", "#ff0000"]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "G"})).unwrap(); - let mut d = app.ui.dialog.clone().unwrap(); - let mut rs = super::rows(&d); + let mut rc = opened(app, json!({"group": "G"})); + let mut rs = rc.rows(); rs[0]["to"] = json!("#00ff00"); rs[0]["exclude"] = json!(true); rs[1]["to"] = json!("#0000ff"); - d.fields.insert("rows".into(), json!(rs)); - d.fields.insert("globalAdjust".into(), json!({"brightness": -50})); - confirm(&mut app, &d).unwrap(); + rc.set("rows", json!(rs)).unwrap(); + rc.set("globalAdjust", json!({"brightness": -50})).unwrap(); + rc.confirm().unwrap(); + let app = rc.app(); let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "G").unwrap(); let hex: Vec = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); assert_eq!(hex[0], "#2878f0", "{hex:?}"); @@ -3170,22 +3149,21 @@ mod tests { /// an excluded row's swatch stays as it is and the other swatches keep their places. #[test] fn a_moved_row_keeps_its_group_swatch() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let mut app = app(100); app.run("swatch.newGroup", json!({"name": "G", "colors": ["#ff0000", "#0000ff", "#00ff00"]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "G"})).unwrap(); - let mut d = app.ui.dialog.clone().unwrap(); - let mut rs = super::rows(&d); + let mut rc = opened(app, json!({"group": "G"})); + let mut rs = rc.rows(); rs[1]["exclude"] = json!(true); rs[2]["to"] = json!("#ffff00"); let active = active_rows(&rs); assert_eq!(active, [0, 2]); // Drag the last bar (green, now yellow) above the first (red). assert_eq!(move_bar(&mut rs, &active, 1, 0), Some(0)); - d.fields.insert("rows".into(), json!(rs)); - let colors = &apply_params(&d)["groupColors"]; + rc.set("rows", json!(rs)).unwrap(); + let colors = &apply_params(&rc.fields())["groupColors"]; assert_eq!(colors[1], json!("keep"), "{colors}"); - confirm(&mut app, &d).unwrap(); + rc.confirm().unwrap(); + let app = rc.app(); let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "G").unwrap(); let hex: Vec = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); assert_eq!(hex, ["#ff0000", "#0000ff", "#ffff00"]); @@ -3245,7 +3223,7 @@ mod tests { let mut r = rows(); new_row(&mut r, &[]); let fields = json!({"rows": r, "group": "Trio", "__art": true, "__assign": ["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"]}); - let p = apply_params(&Dialog::new("recolor", fields)); + let p = apply_params(&Fields::new(fields)); assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "keep"])); } @@ -3253,24 +3231,20 @@ mod tests { /// new color group, in row order: an empty row gives it no color. #[test] fn an_empty_row_gives_a_new_group_no_color() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("ui.recolorDialog", json!({"colors": ["#ff8000", "#0080ff"]})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(app(100), json!({"colors": ["#ff8000", "#0080ff"]})); + let mut rs = rc.rows(); let at = new_row(&mut rs, &[1]); rs[at]["to"] = json!("rgb 255 0 255"); - d.fields.insert("rows".into(), Value::Array(rs)); - let d = d.clone(); - let groups = app.session.doc().unwrap().doc.swatch_groups.len(); - confirm(&mut app, &d).unwrap(); + rc.set("rows", Value::Array(rs)).unwrap(); + let groups = rc.app().session.doc().unwrap().doc.swatch_groups.len(); + rc.confirm().unwrap(); + let app = rc.app(); let doc = &app.session.doc().unwrap().doc; assert_eq!(doc.swatch_groups.len(), groups + 1, "a new color group"); let colors: Vec = doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); assert_eq!(colors, ["#ff8000", "#0080ff"]); } - /// Randomize after a seed past `u64::MAX` keeps the largest seed. /// A row that lists a color exactly comes before an earlier row whose "#rrggbb" entry matches /// it, as `recolor.apply` reads them; a hex entry matches a key of the same hex. #[test] @@ -3302,13 +3276,6 @@ mod tests { assert_eq!(row_listing(&rs, &json!("rgb 255 255 0")), Some(&rs[4])); } - #[test] - fn next_seed_holds_at_the_largest() { - assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); - assert_eq!(next_seed(&Dialog::new("recolor", json!({"__seed": 4}))), 5); - assert_eq!(next_seed(&Dialog::new("recolor", json!({"__seed": 1e30}))), u64::MAX); - } - #[test] fn linked_handles_move_together() { let mut r = rows(); @@ -3389,7 +3356,7 @@ mod tests { let mut fewer = vec![json!({"from": [], "to": "rgb 1 1 1"})]; keep_marks(&before, &mut fewer); assert!(fewer[0].get(BASE).is_none(), "rows of another count take no marks"); - let mut d = Dialog::new(KIND, json!({})); + let mut d = Fields::new(json!({})); d.fields.insert("rows".into(), json!(before)); assert!(apply_params(&d)["map"].as_array().unwrap().iter().all(|x| x.get(BASE).is_none())); } @@ -3435,15 +3402,6 @@ mod tests { assert!((hue(&r, chained) - 250.0).abs() < 0.5, "{r:?}"); } - /// Select Shade's grid runs from 0% to 100% saturation across and from 100% brightness down. - #[test] - fn the_shade_grid_spans_saturation_and_brightness() { - assert_eq!(shade_at(0, 0), [0.0, 1.0]); - assert_eq!(shade_at(SHADE_COLS - 1, 0)[0], 1.0); - let last = shade_at(0, SHADE_ROWS - 1)[1]; - assert!(last > 0.0 && last < 0.2, "{last}"); - } - /// A row made with New Row is not on the Edit tab while it is empty: a harmony rule gives it /// no color and a linked move leaves its new color as it is. #[test] @@ -3459,7 +3417,7 @@ mod tests { assert_eq!(r[1]["to"], "rgb 0 255 0"); assert_eq!(r[0]["to"], "rgb 255 0 0", "the empty row keeps its new color"); // With the empty row selected, the sliders edit the base color's row instead. - let sel = |s: Value| Dialog::new("recolor", json!({"__sel": s})); + let sel = |s: Value| Fields::new(json!({"__sel": s})); assert_eq!(edit_slider_row(&sel(json!([0])), &r, &active, Some(1)), Some(1)); assert_eq!(edit_slider_row(&sel(json!([3, 2])), &r, &active, Some(3)), Some(2), "a shown row: the first selected"); assert_eq!(edit_slider_row(&sel(json!([0])), &r, &[], None), None, "no row to edit"); @@ -3500,23 +3458,19 @@ mod tests { /// The Color Picker's OK keeps a row's tint when the row's new color stays, and drops it otherwise. #[test] fn a_picked_color_keeps_the_tint_only_of_the_same_color() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("ui.recolorDialog", json!({"colors": ["#ff0000"]})).unwrap(); - let mut d = app.ui.dialog.clone().unwrap(); - d.fields.insert("rows".into(), json!([{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0", "tint": 40.0}])); - let same = with_new_color(&app, d.clone(), 0, Color::rgb(1.0, 0.0, 0.0)); - assert_eq!(super::rows(&same)[0]["tint"], json!(40.0)); - let other = with_new_color(&app, d, 0, Color::rgb(0.0, 1.0, 0.0)); - assert!(super::rows(&other)[0].get("tint").is_none(), "{:?}", super::rows(&other)); + let mut rc = opened(app(100), json!({"colors": ["#ff0000"]})); + rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0", "tint": 40.0}])).unwrap(); + rc.with_dialog(|app, d| with_new_color(app, d, 0, Color::rgb(1.0, 0.0, 0.0))).unwrap(); + assert_eq!(rc.rows()[0]["tint"], json!(40.0)); + rc.with_dialog(|app, d| with_new_color(app, d, 0, Color::rgb(0.0, 1.0, 0.0))).unwrap(); + assert!(rc.rows()[0].get("tint").is_none(), "{:?}", rc.rows()); } /// With the Spot Colors options on CMYK values, a row whose new color is a Lab spot color of the /// library shows the art's color at its tint: the working-CMYK equivalent with its inks scaled. #[test] fn a_tinted_lab_spot_row_shows_the_cmyk_color_the_art_takes() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let mut app = app(100); let lab = json!({"l": 50, "a": 60, "b": -20}); app.run("swatch.new", json!({"name": "Lab Ink", "color": lab, "spot": true})).unwrap(); let data = app.run("swatch.library.save", json!({"names": ["Lab Ink"], "name": "Inks"})).unwrap()["data"].as_str().unwrap().to_string(); @@ -3527,59 +3481,39 @@ mod tests { app.run("paint.setFill", json!({"ids": [id], "color": lab})).unwrap(); app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap(); app.run("select.all", json!({})).unwrap(); - app.run("ui.recolorDialog", json!({"library": lib})).unwrap(); - let mut d = app.ui.dialog.clone().unwrap(); - sync(&mut app, &mut d); + let rc = opened(app, json!({"library": lib})); + let mut d = rc.fields(); + sync(&mut rc.app(), &mut d); let mut rs = super::rows(&d); rs[0]["tint"] = json!(50.0); let c = to_color(&rs[0]).unwrap(); assert!(matches!(c, Color::Lab { .. }), "{c:?}"); + let app = rc.app(); let cmyk = app.session.doc().unwrap().doc.linked_color(c, true); assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); assert_eq!(new_shown(&app, &d, &rs[0]), cmyk.tinted(0.5)); } - /// Runs one frame of the open dialog at `time` and returns row `i`'s new color chip, when the - /// Recolor Artwork dialog drew it. - fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec, i: usize) -> Option { - let input = egui::RawInput { time: Some(time), events, ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); - ctx.read_response(egui::Id::unique((NEW_CHIP, i))).map(|r| r.rect) + /// The new colors of the rows. + fn new_colors(rc: &Recolor) -> Vec { + rc.rows().iter().map(|r| r["to"].clone()).collect() } - /// Runs frames from `time` until the dialog stops moving (it centres itself as it measures its - /// size) and returns row `i`'s new color chip. - fn settled(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, i: usize) -> Option { - let mut last = None; - for n in 0..10 { - let r = frame(app, ctx, time + f64::from(n) * 0.001, vec![], i); - if r.is_some() && r == last { - return r; - } - last = r; - } - last - } - - /// Double-clicks row `i`'s new color chip, as drawn by the last frame at `rect`. - fn double_click(app: &mut VectorcraftApp, ctx: &egui::Context, rect: Rect, time: f64, i: usize) { - let pos = rect.center(); - let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - frame(app, ctx, time, vec![egui::Event::PointerMoved(pos), button(true)], i); - frame(app, ctx, time + 0.05, vec![button(false)], i); - frame(app, ctx, time + 0.1, vec![button(true)], i); - frame(app, ctx, time + 0.15, vec![button(false)], i); + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() } /// Double-clicking a row's new color opens the Color Picker on that new color, over the dialog. - /// OK sets that row's new color, and only that row's, in the model it was picked in (a CMYK mix - /// stays that mix, not a hex value converted back), and the art previews it; a color picked as - /// RGB is CMYK in a CMYK document. Cancel leaves the rows and the preview as they were, and - /// nothing is committed until Recolor Artwork's own OK. + /// Cancel leaves the rows and the preview as they were; OK sets that row's new color, and only + /// that row's, in the document's model (a color picked as RGB is CMYK in a CMYK document), and + /// the art previews it; nothing is committed until Recolor Artwork's own OK. + // PLAN: assumed color-w8's `open_over` opens the framework's `ColorPickerDialog` as a child of Recolor Artwork. Its + // `ui.dialog.set` takes only `#rrggbb`, so the trial picks in RGB; a CMYK mix and a Lab color kept in their model + // are color-w8's picker trials (`in_document_model`). #[test] fn double_clicking_a_new_color_picks_it_in_its_own_model() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + use craft::color_ui::ui::ColorPickerDialog; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 100, "height": 100, "colorMode": "cmyk"})).unwrap(); let mut ids = vec![]; for (n, c) in [json!({"c": 0, "m": 100, "y": 100, "k": 0}), json!({"c": 100, "m": 0, "y": 0, "k": 0})].into_iter().enumerate() { @@ -3591,73 +3525,51 @@ mod tests { app.run("select.all", json!({})).unwrap(); // New colors other than the current ones, so the picker can only start from the new one. let assign = json!([{"c": 0, "m": 0, "y": 100, "k": 0}, {"c": 0, "m": 100, "y": 0, "k": 0}]); - app.run("ui.recolorDialog", json!({"colors": assign})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let mut rc = opened(app, json!({"colors": assign})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + let before = undo_len(&rc.app()); // The previewed fill of the rectangle whose color row `row` recolors. - let fill = |app: &VectorcraftApp, row: &Value| { + let fill = |rc: &Recolor, row: &Value| { let from = from_colors(row); + let app = rc.app(); let doc = &app.session.doc().unwrap().doc; let original = |id: u64| if id == ids[0] { Color::cmyk(0.0, 1.0, 1.0, 0.0) } else { Color::cmyk(1.0, 0.0, 0.0, 0.0) }; let id = *ids.iter().find(|id| from.contains(&original(**id))).expect("a rectangle for the row"); doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill().and_then(|f| f.paint.color()) }; - let before = undo(&app); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let all = super::rows(app.ui.dialog.as_ref().unwrap()); + rc.settled(); + let all = rc.rows(); assert_eq!(all.len(), 2); let i = 1; assert_ne!(all[i]["from"][0], all[i]["to"], "the row's new color isn't its current color"); - let rect = settled(&mut app, &ctx, 0.01, i).expect("the row's new color is drawn"); let previewed = to_color(&all[i]); - assert_eq!(fill(&app, &all[i]), previewed, "the art previews the row's new color"); + assert_eq!(fill(&rc, &all[i]), previewed, "the art previews the row's new color"); + let new = format!("{} {}", tl!("New"), i + 1); + let picker = |rc: &Recolor| rc.host(|host, _| host.get::().map(StackDialog::id)).flatten(); - double_click(&mut app, &ctx, rect, 0.1, i); - frame(&mut app, &ctx, 0.3, vec![], i); - assert_eq!(fill(&app, &all[0]), to_color(&all[0]), "the picker previews nothing itself"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.kind, "colorPicker", "a double-click opens the Color Picker"); - assert_eq!(d.fields.get("color").and_then(color_value), previewed, "on the row's new color"); - crate::dialogs::cancel(&mut app); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "Cancel comes back to Recolor Artwork"); - assert_eq!(super::rows(app.ui.dialog.as_ref().unwrap()), all, "with the rows as they were"); - frame(&mut app, &ctx, 0.5, vec![], i); - assert_eq!(fill(&app, &all[i]), previewed, "and the art previews them again"); + rc.double_click(&new).frame(); + let id = picker(&rc).expect("a double-click opens the Color Picker"); + let color = rc.host(|host, _| host.get::().and_then(StackDialog::json_fields)).flatten().unwrap_or_default(); + assert_eq!(color["color"].as_str(), previewed.map(|c| c.to_hex()).as_deref(), "on the row's new color"); + assert_eq!(fill(&rc, &all[0]), to_color(&all[0]), "the picker previews nothing itself"); + rc.host(|host, ctx| host.cancel_by_id(ctx, id)); + rc.frame().frame(); + assert!(rc.is_open() && picker(&rc).is_none(), "Cancel comes back to Recolor Artwork"); + assert_eq!(rc.rows(), all, "with the rows as they were"); + assert_eq!(fill(&rc, &all[i]), previewed, "and the art previews them again"); - let rect = settled(&mut app, &ctx, 1.0, i).unwrap(); - double_click(&mut app, &ctx, rect, 1.1, i); - let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!(d.kind, "colorPicker"); - // 100 50 0 0 is a mix the round trip through sRGB changes. - d.fields.insert("color".into(), json!({"c": 100, "m": 50, "y": 0, "k": 0})); - crate::dialogs::confirm(&mut app).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.kind, KIND, "OK comes back to Recolor Artwork"); - let rows = super::rows(d); - assert_eq!(rows[i]["to"], "cmyk 100 50 0 0", "the row keeps the CMYK mix picked"); - assert_eq!(rows[0], all[0], "the other row stays"); - assert!(app.session.in_interaction(), "the dialog still previews"); - assert_eq!(undo(&app), before, "nothing is committed before Recolor Artwork's OK"); - frame(&mut app, &ctx, 1.5, vec![], i); - assert_eq!(fill(&app, &rows[i]), Some(Color::cmyk(1.0, 0.5, 0.0, 0.0)), "the art previews the picked color"); - - let rect = settled(&mut app, &ctx, 2.0, i).unwrap(); - double_click(&mut app, &ctx, rect, 2.1, i); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("color".into(), json!([1.0, 0.0, 0.0])); - crate::dialogs::confirm(&mut app).unwrap(); - let to = super::rows(app.ui.dialog.as_ref().unwrap())[i]["to"].clone(); + rc.settled().double_click(&new).frame(); + let id = picker(&rc).expect("the Color Picker opens again"); + rc.host(|host, ctx| host.set_json_field(ctx, id, "color", json!("#ff0000"))).unwrap().unwrap(); + rc.host(|host, ctx| host.confirm_by_id(ctx, id)); + rc.frame().frame(); + let rows = rc.rows(); + let to = rows[i]["to"].clone(); assert!(to.as_str().is_some_and(|k| k.starts_with("cmyk ")), "a color picked as RGB is CMYK in a CMYK document: {to}"); - - let rect = settled(&mut app, &ctx, 3.0, i).unwrap(); - double_click(&mut app, &ctx, rect, 3.1, i); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("color".into(), json!({"l": 55.0, "a": 20.0, "b": -30.0})); - crate::dialogs::confirm(&mut app).unwrap(); - let to = super::rows(app.ui.dialog.as_ref().unwrap())[i]["to"].clone(); - assert_eq!(to, "lab 55 20 -30", "a Lab color picked in the picker is kept as Lab: {to}"); + assert_eq!(rows[0], all[0], "the other row stays"); + assert!(rc.app().session.in_interaction(), "the dialog still previews"); + assert_eq!(undo_len(&rc.app()), before, "nothing is committed before Recolor Artwork's OK"); + assert_eq!(fill(&rc, &rows[i]), to_color(&rows[i]), "the art previews the picked color"); } /// A 15 pt square at (`x`, 10) filled with `fill`, without a stroke. @@ -3668,28 +3580,25 @@ mod tests { id } - fn fill_hex(app: &VectorcraftApp, id: u64) -> String { + /// The fill of object `id`, as hex. + fn fill_hex(rc: &Recolor, id: u64) -> String { + let app = rc.app(); let doc = &app.session.doc().unwrap().doc; doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill().and_then(|f| f.paint.color()).unwrap().to_hex() } /// Red and blue squares selected, and green and yellow squares beside them; Recolor Artwork /// open on the selection with the Exact method, one frame drawn. - fn theme_setup(app: &mut VectorcraftApp, ctx: &egui::Context) -> [u64; 2] { - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - let art = [square(app, 10.0, "#ff0000"), square(app, 40.0, "#0000ff")]; - square(app, 100.0, "#00ff00"); - square(app, 130.0, "#ffff00"); + fn theme_setup() -> (Recolor, [u64; 2]) { + let mut app = app(300); + let art = [square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")]; + square(&mut app, 100.0, "#00ff00"); + square(&mut app, 130.0, "#ffff00"); app.run("select.set", json!({"ids": art})).unwrap(); - app.run("ui.recolorDialog", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(ctx); - frame(app, ctx, 0.0, vec![], 0); - art - } - - fn new_colors(app: &VectorcraftApp) -> Vec { - super::rows(app.ui.dialog.as_ref().unwrap()).iter().map(|r| r["to"].clone()).collect() + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + (rc, art) } /// The Color Theme Picker's picks (the `themePicks` field) give the rows that aren't excluded @@ -3698,89 +3607,77 @@ mod tests { /// OK with rows that give the art its own colors back records no undo step. #[test] fn theme_picks_give_the_rows_the_palette_of_the_art_picked() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let [red, blue] = theme_setup(&mut app, &ctx); - let mut start = new_colors(&app); + let (mut rc, [red, blue]) = theme_setup(); + let mut start = new_colors(&rc); start.sort_by_key(Value::to_string); assert_eq!(start, [json!("rgb 0 0 255"), json!("rgb 255 0 0")]); // The red art's row and the blue art's row. - let row_of = |app: &VectorcraftApp, key: &str| super::rows(app.ui.dialog.as_ref().unwrap()).iter().position(|r| r["from"][0] == key).unwrap(); - let (r, b) = (row_of(&app, "rgb 255 0 0"), row_of(&app, "rgb 0 0 255")); - let undo = app.session.doc().unwrap().history.undo.len(); - let set = |app: &mut VectorcraftApp, picks: Value| { - app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks); - }; - set(&mut app, json!([{"at": [107, 17]}])); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")], "one color for both rows"); - assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#00ff00".into(), "#00ff00".into()), "the art previews it"); - set(&mut app, json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}])); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 255 255 0")], "a pick added: two colors"); + let row_of = |rc: &Recolor, key: &str| rc.rows().iter().position(|r| r["from"][0] == key).unwrap(); + let (r, b) = (row_of(&rc, "rgb 255 0 0"), row_of(&rc, "rgb 0 0 255")); + let undo = undo_len(&rc.app()); + let fills = |rc: &Recolor| (fill_hex(&rc,red), fill_hex(&rc,blue)); + rc.set(THEME_PICKS, json!([{"at": [107, 17]}])).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 255 0"), json!("rgb 0 255 0")], "one color for both rows"); + assert_eq!(fills(&rc), ("#00ff00".into(), "#00ff00".into()), "the art previews it"); + rc.set(THEME_PICKS, json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}])).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 255 0"), json!("rgb 255 255 0")], "a pick added: two colors"); // An excluded row (the red art's) keeps its new color. - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rs = rc.rows(); rs[r]["exclude"] = json!(true); - d.fields.insert("rows".into(), Value::Array(rs)); - let kept = new_colors(&app)[r].clone(); - set(&mut app, json!([{"at": [47, 17]}])); - frame(&mut app, &ctx, 0.3, vec![], 0); - let after = new_colors(&app); + rc.set("rows", Value::Array(rs)).unwrap(); + let kept = new_colors(&rc)[r].clone(); + rc.set(THEME_PICKS, json!([{"at": [47, 17]}])).unwrap(); + rc.frame(); + let after = new_colors(&rc); assert_eq!((&after[r], &after[b]), (&kept, &json!("rgb 0 0 255"))); - set(&mut app, json!([{"at": [250, 80]}])); - frame(&mut app, &ctx, 0.4, vec![], 0); - assert_eq!(new_colors(&app), after, "empty canvas: the rows stay"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing is committed before OK"); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#0000ff".into()), "the excluded row kept red"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "the art is unchanged: no undo step"); + rc.set(THEME_PICKS, json!([{"at": [250, 80]}])).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), after, "empty canvas: the rows stay"); + assert_eq!(undo_len(&rc.app()), undo, "nothing is committed before OK"); + rc.confirm().unwrap(); + assert_eq!(fills(&rc), ("#ff0000".into(), "#0000ff".into()), "the excluded row kept red"); + assert_eq!(undo_len(&rc.app()), undo, "the art is unchanged: no undo step"); } /// The Color Theme Picker gives its colors only to the rows that hold current colors: a row /// made with New Row keeps its new color and takes no place in the palette. #[test] fn theme_picks_leave_an_empty_row_out() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - theme_setup(&mut app, &ctx); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let (mut rc, _) = theme_setup(); + let mut rs = rc.rows(); let at = new_row(&mut rs, &[]); rs[at]["to"] = json!("rgb 9 9 9"); - d.fields.insert("rows".into(), Value::Array(rs)); - d.fields.insert(THEME_PICKS.into(), json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}])); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert_eq!(new_colors(&app), [json!("rgb 9 9 9"), json!("rgb 0 255 0"), json!("rgb 255 255 0")]); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.set(THEME_PICKS, json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}])).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 9 9 9"), json!("rgb 0 255 0"), json!("rgb 255 255 0")]); } /// A row made with New Row recolors nothing while it is empty, and OK keeps it; the blue art's /// color merged into it takes its new color, in the preview and at OK. #[test] fn colors_merged_into_a_new_row_take_its_new_color() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let [red, blue] = theme_setup(&mut app, &ctx); - let undo = app.session.doc().unwrap().history.undo.len(); - let set_rows = |app: &mut VectorcraftApp, rs: Vec| { - app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), Value::Array(rs)); - }; - let mut rs = super::rows(app.ui.dialog.as_ref().unwrap()); + let (mut rc, [red, blue]) = theme_setup(); + let undo = undo_len(&rc.app()); + let fills = |rc: &Recolor| (fill_hex(&rc,red), fill_hex(&rc,blue)); + let mut rs = rc.rows(); let at = new_row(&mut rs, &[]); rs[at]["to"] = json!("rgb 0 255 0"); - set_rows(&mut app, rs.clone()); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#0000ff".into()), "an empty row recolors nothing"); + rc.set("rows", Value::Array(rs.clone())).unwrap(); + rc.frame(); + assert_eq!(fills(&rc), ("#ff0000".into(), "#0000ff".into()), "an empty row recolors nothing"); let b = rs.iter().position(|r| r["from"] == json!([BLUE])).unwrap(); merge(&mut rs, &[at, b]); // A second empty row stays empty and is sent at OK too. new_row(&mut rs, &[]); - set_rows(&mut app, rs); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(fill_hex(&app, blue), "#00ff00", "the art previews the merge"); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#00ff00".into())); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.frame(); + assert_eq!(fill_hex(&rc,blue), "#00ff00", "the art previews the merge"); + rc.confirm().unwrap(); + assert_eq!(fills(&rc), ("#ff0000".into(), "#00ff00".into())); + assert_eq!(undo_len(&rc.app()), undo + 1, "one undo step"); } const RED: &str = "rgb 255 0 0"; @@ -3789,25 +3686,22 @@ mod tests { /// Two red squares, a purple one and a blue one, selected; Recolor Artwork open on them on the /// Edit tab with the Exact method and the rows set: the blue to yellow, then the red and purple - /// to green (the purple's square id last). One frame drawn. - fn prominent_setup(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - let ids = [square(app, 10.0, "#ff0000"), square(app, 40.0, "#ff0000"), square(app, 70.0, "#8000cc"), square(app, 100.0, "#0000ff")]; + /// to green (the purple's square id last). + fn prominent_setup() -> (Recolor, u64) { + let mut app = app(300); + let ids = [square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#ff0000"), square(&mut app, 70.0, "#8000cc"), square(&mut app, 100.0, "#0000ff")]; app.run("select.set", json!({"ids": ids})).unwrap(); - app.run("ui.recolorDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("method".into(), json!(Method::Exact.id())); - d.fields.insert("tab".into(), json!("edit")); - crate::theme::install_fonts(ctx); - frame(app, ctx, 0.0, vec![], 0); - let rows = json!([{"from": [BLUE], "to": "rgb 255 255 0"}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}]); - app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), rows); - frame(app, ctx, 0.01, vec![], 0); - ids[2] + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.set("tab", json!("edit")).unwrap(); + rc.frame(); + rc.set("rows", json!([{"from": [BLUE], "to": "rgb 255 255 0"}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}])).unwrap(); + rc.frame(); + (rc, ids[2]) } - fn froms(app: &VectorcraftApp) -> Vec { - super::rows(app.ui.dialog.as_ref().unwrap()).iter().map(|r| r["from"].clone()).collect() + fn froms(rc: &Recolor) -> Vec { + rc.rows().iter().map(|r| r["from"].clone()).collect() } /// The Prominent Colors bar holds each row's share of the art's uses, the largest first; new @@ -3815,88 +3709,69 @@ mod tests { /// OK commits it, as one undo step. #[test] fn weights_move_the_rows_colors_and_the_art_previews_them() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let purple = prominent_setup(&mut app, &ctx); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.fields[SHARES], json!([25.0, 75.0])); - assert_eq!(prominent_parts(d, &super::rows(d)), [(1, 75.0), (0, 25.0)], "the largest share first"); - assert_eq!(fill_hex(&app, purple), "#00ff00", "the art previews the rows"); - let undo = app.session.doc().unwrap().history.undo.len(); - app.ui.dialog.as_mut().unwrap().fields.insert(WEIGHTS.into(), json!([50, 50])); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert_eq!(froms(&app), [json!([BLUE, PURPLE]), json!([RED])]); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[SHARES], json!([50.0, 50.0])); - assert_eq!(fill_hex(&app, purple), "#ffff00", "the moved color previews its new row's color"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing is committed before OK"); + let (mut rc, purple) = prominent_setup(); + assert_eq!(rc.field(SHARES), Some(json!([25.0, 75.0]))); + assert_eq!(prominent_parts(&rc.fields(), &rc.rows()), [(1, 75.0), (0, 25.0)], "the largest share first"); + assert_eq!(fill_hex(&rc,purple), "#00ff00", "the art previews the rows"); + let undo = undo_len(&rc.app()); + rc.set(WEIGHTS, json!([50, 50])).unwrap(); + rc.frame(); + assert_eq!(froms(&rc), [json!([BLUE, PURPLE]), json!([RED])]); + assert_eq!(rc.field(SHARES), Some(json!([50.0, 50.0]))); + assert_eq!(fill_hex(&rc,purple), "#ffff00", "the moved color previews its new row's color"); + assert_eq!(undo_len(&rc.app()), undo, "nothing is committed before OK"); // A new count of Colors reduces the rows again and drops the weights. - app.ui.dialog.as_mut().unwrap().fields.insert("colors".into(), json!(2)); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get(WEIGHTS), None); - app.ui - .dialog - .as_mut() - .unwrap() - .fields - .insert("rows".into(), json!([{"from": [BLUE, PURPLE], "to": "rgb 255 255 0"}, {"from": [RED], "to": "rgb 0 255 0"}])); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(fill_hex(&app, purple), "#ffff00"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + rc.set("colors", json!(2)).unwrap(); + rc.frame(); + assert_eq!(rc.field(WEIGHTS), Some(Value::Null)); + rc.set("rows", json!([{"from": [BLUE, PURPLE], "to": "rgb 255 255 0"}, {"from": [RED], "to": "rgb 0 255 0"}])).unwrap(); + rc.confirm().unwrap(); + assert_eq!(fill_hex(&rc,purple), "#ffff00"); + assert_eq!(undo_len(&rc.app()), undo + 1, "one undo step"); } /// A row that takes a new color takes the colors it shares with other rows, so the bar reads /// the shares again. #[test] fn a_new_color_for_a_row_reads_the_shares_again() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - prominent_setup(&mut app, &ctx); - let rows = json!([{"from": [RED, PURPLE], "to": null}, {"from": [RED, BLUE], "to": "rgb 255 255 0"}]); - app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), rows); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[SHARES], json!([25.0, 75.0])); - let rows = json!([{"from": [RED, PURPLE], "to": "rgb 0 255 0"}, {"from": [RED, BLUE], "to": "rgb 255 255 0"}]); - app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), rows); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[SHARES], json!([75.0, 25.0])); + let (mut rc, _) = prominent_setup(); + rc.set("rows", json!([{"from": [RED, PURPLE], "to": null}, {"from": [RED, BLUE], "to": "rgb 255 255 0"}])).unwrap(); + rc.frame(); + assert_eq!(rc.field(SHARES), Some(json!([25.0, 75.0]))); + rc.set("rows", json!([{"from": [RED, PURPLE], "to": "rgb 0 255 0"}, {"from": [RED, BLUE], "to": "rgb 255 255 0"}])).unwrap(); + rc.frame(); + assert_eq!(rc.field(SHARES), Some(json!([75.0, 25.0]))); } /// Dragging the edge between two parts of the bar to the left gives the right-hand part more - /// weight; when the drag ends, the rows' current colors move. + /// weight; the rows wait for the drag to end, and when it ends the rows' current colors move. + // PLAN: assumed color-w20's `ProminentBar` names itself "Prominent Colors" and the edge after its first part + // "Prominent Colors edge 1" in the access tree. #[test] fn dragging_a_prominent_edge_moves_colors_between_rows() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let purple = prominent_setup(&mut app, &ctx); - let edge = |ctx: &egui::Context| ctx.read_response(egui::Id::unique((PROMINENT_EDGE, 0usize))).map(|r| r.rect); - let mut last = None; - for n in 0..10 { - frame(&mut app, &ctx, 0.02 + f64::from(n) * 0.001, vec![], 0); - let r = edge(&ctx); - if r.is_some() && r == last { - break; - } - last = r; - } - let at = edge(&ctx).expect("the edge between the two parts").center(); - let bar = ctx.read_response(egui::Id::unique((PROMINENT_PART, 0usize))).unwrap().rect; + let (mut rc, purple) = prominent_setup(); + rc.settled(); + let bar = rc.by_label("Prominent Colors").expect("the Prominent Colors bar").rect; + let edge = rc.by_label("Prominent Colors edge 1").expect("the edge between the two parts").center(); // From 75% to 50%: a quarter of the bar to the left. - let to = at - vec2((bar.width() / 0.75) * 0.25, 0.0); - let button = - |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - frame(&mut app, &ctx, 0.1, vec![egui::Event::PointerMoved(at), button(at, true)], 0); - for k in 1..=5 { - frame(&mut app, &ctx, 0.1 + f64::from(k) * 0.02, vec![egui::Event::PointerMoved(at + (to - at) * (k as f32 / 5.0))], 0); + let to = edge - egui::vec2(bar.width() * 0.25, 0.0); + rc.press("Prominent Colors edge 1"); + for k in 1..=4 { + rc.move_to(edge + (to - edge) * (k as f32 / 4.0)); } - assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key(BAR_DRAG), "the drag is under way"); - assert_eq!(froms(&app)[0], json!([BLUE]), "the rows wait for the drag to end"); - frame(&mut app, &ctx, 0.3, vec![button(to, false)], 0); - frame(&mut app, &ctx, 0.32, vec![], 0); - let d = app.ui.dialog.as_ref().unwrap(); - let w = d.fields[WEIGHTS].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect::>(); - assert!((w[0] - 50.0).abs() < 2.0 && (w[1] - 50.0).abs() < 2.0, "{w:?}"); - assert_eq!(froms(&app), [json!([BLUE, PURPLE]), json!([RED])]); - assert_eq!(fill_hex(&app, purple), "#ffff00"); + assert_eq!(froms(&rc)[0], json!([BLUE]), "the rows wait for the drag to end"); + rc.release(to); + let w: Vec = rc.field(WEIGHTS).and_then(|w| w.as_array().cloned()).unwrap_or_default().iter().filter_map(Value::as_f64).collect(); + assert!(w.len() == 2 && (w[0] - 50.0).abs() < 2.0 && (w[1] - 50.0).abs() < 2.0, "{w:?}"); + rc.frame(); + assert_eq!(froms(&rc), [json!([BLUE, PURPLE]), json!([RED])]); + assert_eq!(fill_hex(&rc,purple), "#ffff00"); + } + + /// The colors of the last color group, as hex. + fn last_group(app: &VectorcraftApp) -> Vec { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect() } /// The New Color Group menu's Save All Colors saves the new colors in row order and Save @@ -3904,24 +3779,17 @@ mod tests { /// preview of the recolor runs on. #[test] fn save_all_and_prominent_colors_make_color_groups() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let purple = prominent_setup(&mut app, &ctx); - let groups = |app: &VectorcraftApp| app.session.doc().unwrap().doc.swatch_groups.len(); - let last = |app: &VectorcraftApp| -> Vec { - let doc = &app.session.doc().unwrap().doc; - doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect() - }; - let (n, undo) = (groups(&app), app.session.doc().unwrap().history.undo.len()); - for (which, colors, t) in [("all", ["#ffff00", "#00ff00"], 0.1), ("prominent", ["#00ff00", "#ffff00"], 0.2)] { - app.ui.dialog.as_mut().unwrap().fields.insert(SAVE_GROUP.into(), json!(which)); - frame(&mut app, &ctx, t, vec![], 0); - frame(&mut app, &ctx, t + 0.01, vec![], 0); - assert_eq!(last(&app), colors, "{which}"); - assert_eq!(fill_hex(&app, purple), "#00ff00", "{which}: the art still previews the rows"); + let (mut rc, purple) = prominent_setup(); + let groups = |rc: &Recolor| rc.app().session.doc().unwrap().doc.swatch_groups.len(); + let (n, undo) = (groups(&rc), undo_len(&rc.app())); + for (which, colors) in [("all", ["#ffff00", "#00ff00"]), ("prominent", ["#00ff00", "#ffff00"])] { + rc.set(SAVE_GROUP, json!(which)).unwrap(); + rc.frame().frame(); + assert_eq!(last_group(&rc.app()), colors, "{which}"); + assert_eq!(fill_hex(&rc,purple), "#00ff00", "{which}: the art still previews the rows"); } - assert_eq!(groups(&app), n + 2); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "a step for each group"); + assert_eq!(groups(&rc), n + 2); + assert_eq!(undo_len(&rc.app()), undo + 2, "a step for each group"); } /// A color removed on the Edit tab leaves its row with no new color, and neither Save All @@ -3929,115 +3797,65 @@ mod tests { /// the new color group. #[test] fn a_removed_color_joins_no_saved_color_group() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - prominent_setup(&mut app, &ctx); - let last = |app: &VectorcraftApp| -> Vec { - let doc = &app.session.doc().unwrap().doc; - doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect() - }; - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("rows".into(), json!([{"from": [BLUE], "to": null}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}])); - d.fields.insert(SAVE_GROUP.into(), json!("all")); - frame(&mut app, &ctx, 0.1, vec![], 0); - frame(&mut app, &ctx, 0.11, vec![], 0); - assert_eq!(last(&app), ["#00ff00"], "Save All Colors"); - let n = app.session.doc().unwrap().doc.swatch_groups.len(); - app.ui.dialog.as_mut().unwrap().fields.insert(SAVE_GROUP.into(), json!("prominent")); - frame(&mut app, &ctx, 0.2, vec![], 0); - frame(&mut app, &ctx, 0.21, vec![], 0); - assert_eq!(app.session.doc().unwrap().doc.swatch_groups.len(), n + 1, "Save Prominent Colors makes a group"); - assert_eq!(last(&app), ["#00ff00"], "Save Prominent Colors"); + let (mut rc, _) = prominent_setup(); + rc.set("rows", json!([{"from": [BLUE], "to": null}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}])).unwrap(); + rc.set(SAVE_GROUP, json!("all")).unwrap(); + rc.frame().frame(); + assert_eq!(last_group(&rc.app()), ["#00ff00"], "Save All Colors"); + let n = rc.app().session.doc().unwrap().doc.swatch_groups.len(); + rc.set(SAVE_GROUP, json!("prominent")).unwrap(); + rc.frame().frame(); + assert_eq!(rc.app().session.doc().unwrap().doc.swatch_groups.len(), n + 1, "Save Prominent Colors makes a group"); + assert_eq!(last_group(&rc.app()), ["#00ff00"], "Save Prominent Colors"); - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("ui.recolorDialog", json!({"colors": ["#ff0000", "#0000ff"]})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("rows".into(), json!([{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, {"from": ["rgb 0 0 255"], "to": null}])); - let d = d.clone(); - confirm(&mut app, &d).unwrap(); - assert_eq!(last(&app), ["#ff0000"], "OK on colors opened alone"); + let mut rc = opened(app(100), json!({"colors": ["#ff0000", "#0000ff"]})); + rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, {"from": ["rgb 0 0 255"], "to": null}])).unwrap(); + rc.confirm().unwrap(); + assert_eq!(last_group(&rc.app()), ["#ff0000"], "OK on colors opened alone"); } /// Save All Colors leaves out a row made with New Row while it is empty; with only empty rows /// it saves no group and records no step. #[test] fn save_all_colors_leaves_an_empty_row_out() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - prominent_setup(&mut app, &ctx); - let groups = |app: &VectorcraftApp| app.session.doc().unwrap().doc.swatch_groups.len(); - let (n, undo) = (groups(&app), app.session.doc().unwrap().history.undo.len()); - let save = |app: &mut VectorcraftApp, rows: Value, t: f64| { - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("rows".into(), rows); - d.fields.insert(SAVE_GROUP.into(), json!("all")); - frame(app, &ctx, t, vec![], 0); - frame(app, &ctx, t + 0.01, vec![], 0); + let (mut rc, _) = prominent_setup(); + let groups = |rc: &Recolor| rc.app().session.doc().unwrap().doc.swatch_groups.len(); + let (n, undo) = (groups(&rc), undo_len(&rc.app())); + let save = |rc: &mut Recolor, rows: Value| { + rc.set("rows", rows).unwrap(); + rc.set(SAVE_GROUP, json!("all")).unwrap(); + rc.frame().frame(); }; let blank = json!({"from": [], "to": "rgb 255 0 255"}); - save(&mut app, json!([blank, {"from": [BLUE], "to": "rgb 255 255 0"}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}]), 0.1); - let doc = &app.session.doc().unwrap().doc; - let colors: Vec = doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); - assert_eq!(colors, ["#ffff00", "#00ff00"]); - assert_eq!(groups(&app), n + 1); - save(&mut app, json!([blank, {"from": [BLUE, RED, PURPLE], "to": "rgb 0 255 0", "exclude": true}]), 0.2); - assert_eq!(groups(&app), n + 1, "only an empty and an excluded row: no group"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "and no step"); + save(&mut rc, json!([blank, {"from": [BLUE], "to": "rgb 255 255 0"}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}])); + assert_eq!(last_group(&rc.app()), ["#ffff00", "#00ff00"]); + assert_eq!(groups(&rc), n + 1); + save(&mut rc, json!([blank, {"from": [BLUE, RED, PURPLE], "to": "rgb 0 255 0", "exclude": true}])); + assert_eq!(groups(&rc), n + 1, "only an empty and an excluded row: no group"); + assert_eq!(undo_len(&rc.app()), undo + 1, "and no step"); } - /// One frame with `modifiers` held. - fn frame_with(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec, modifiers: egui::Modifiers) { - let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); - let input = egui::RawInput { time: Some(time), events, ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); - } - - /// With the Color Theme Picker on, a click on the canvas picks the object there and a Shift-drag - /// adds the art inside its marquee; with it off the dialog takes no picks from the canvas. + /// The Color Theme Picker button turns picking from the canvas on: off, the canvas tool takes no + /// picks; on, it does, and the picks it files give the rows the palette of the art picked, which + /// the art previews. + // PLAN: the click and Shift-drag on the canvas are color-w20's `ThemePickTool` trials (Open question 2): this + // trial drives the button through the dialog and the gate `edit_tab::with_theme_pick` (cv.S3a) the canvas runs. #[test] fn the_theme_picker_takes_clicks_and_shift_drags_on_the_canvas() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let [red, _] = theme_setup(&mut app, &ctx); - // Clear of the dialog, which centers itself in the screen. - let canvas = Rect::from_min_size(pos2(-1000.0, -1000.0), vec2(3000.0, 3000.0)); - app.canvas_rect = Some(canvas); - let xf = crate::canvas::Xf::new(canvas, app.view().unwrap()); - let at = |x: f64, y: f64| xf.to_screen(vectorcraft_geom::Point::new(x, y)); - let button = |pos, pressed, modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; - let none = egui::Modifiers::NONE; - let click = |app: &mut VectorcraftApp, pos: egui::Pos2, t: f64| { - frame_with(app, &ctx, t, vec![egui::Event::PointerMoved(pos), button(pos, true, none)], none); - frame_with(app, &ctx, t + 0.05, vec![button(pos, false, none)], none); - frame_with(app, &ctx, t + 0.1, vec![], none); - }; - let green = at(107.0, 17.0); - assert!(canvas.contains(green), "{green:?}"); - click(&mut app, green, 1.0); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get(THEME_PICKS), Some(&json!([])), "off: no picks"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get(THEME_PICKER), Some(&json!(false)), "the fields `ui.dialog.set` can set"); - app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKER.into(), json!(true)); - for n in 0..5 { - frame_with(&mut app, &ctx, 2.0 + f64::from(n) * 0.01, vec![], none); - } - click(&mut app, green, 3.0); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[THEME_PICKS].as_array().map(Vec::len), Some(1)); - assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); - assert_eq!(fill_hex(&app, red), "#00ff00", "the art previews the picked color"); - // A Shift-drag around the yellow square. - let shift = egui::Modifiers::SHIFT; - let (a, b) = (at(125.0, 5.0), at(150.0, 30.0)); - frame_with(&mut app, &ctx, 4.0, vec![egui::Event::PointerMoved(a), button(a, true, shift)], shift); - frame_with(&mut app, &ctx, 4.05, vec![egui::Event::PointerMoved(a + (b - a) * 0.5)], shift); - frame_with(&mut app, &ctx, 4.1, vec![egui::Event::PointerMoved(b)], shift); - frame_with(&mut app, &ctx, 4.15, vec![button(b, false, shift)], shift); - frame_with(&mut app, &ctx, 4.2, vec![], none); - let picks = app.ui.dialog.as_ref().unwrap().fields[THEME_PICKS].clone(); - assert_eq!(picks.as_array().map(Vec::len), Some(2), "{picks}"); - assert!(picks[1].get("rect").is_some(), "{picks}"); - assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 255 255 0")]); + let (mut rc, [red, _]) = theme_setup(); + rc.settled(); + assert_eq!(rc.field(THEME_PICKS), Some(json!([])), "off: no picks"); + assert!(!edit_tab::with_theme_pick(&mut rc.app(), |_, _| {}), "off: the canvas keeps its tool"); + rc.click_label(tl!("Color Theme Picker")); + assert_eq!(rc.field(THEME_PICKER), Some(json!(true)), "the button turns the picker on"); + assert!(edit_tab::with_theme_pick(&mut rc.app(), |_, _| {}), "on: the picker takes the canvas"); + rc.set(THEME_PICKS, json!([{"at": [107, 17]}])).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); + assert_eq!(fill_hex(&rc,red), "#00ff00", "the art previews the picked color"); + rc.set(THEME_PICKS, json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}])).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 255 0"), json!("rgb 255 255 0")], "a Shift pick adds to the picks"); } /// Find previews nothing of its own while it is off, on the Edit tab, without art or without a @@ -4046,10 +3864,8 @@ mod tests { /// alone, without rewriting the color group. #[test] fn find_dims_the_colors_of_the_rows_not_selected() { - let mut d = Dialog::new( - KIND, - json!({"rows": rows(), "__art": true, "preview": true, "method": "exact", "limitTo": "", "group": "G", "groupName": "H", "__sel": [0]}), - ); + let mut d = + Fields::new(json!({"rows": rows(), "__art": true, "preview": true, "method": "exact", "limitTo": "", "group": "G", "groupName": "H", "__sel": [0]})); assert_eq!(find_params(&d), None, "off"); d.fields.insert(FIND.into(), json!(true)); let dim = |k: &str| key(&color_value(&json!(k)).unwrap().tinted(FIND_DIM)); @@ -4155,139 +3971,76 @@ mod tests { /// applies the rows to all the art, as one undo step. #[test] fn find_shows_the_selected_rows_art_and_dims_the_rest() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let [red, blue] = theme_setup(&mut app, &ctx); - let undo = app.session.doc().unwrap().history.undo.len(); - let set = |app: &mut VectorcraftApp, k: &str, v: Value| { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); - }; + let (mut rc, [red, blue]) = theme_setup(); + let undo = undo_len(&rc.app()); + let fills = |rc: &Recolor| (fill_hex(&rc,red), fill_hex(&rc,blue)); let rs = json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}, {"from": ["rgb 0 0 255"], "to": "rgb 255 255 0"}]); - set(&mut app, "rows", rs.clone()); - set(&mut app, "__sel", json!([0])); - frame(&mut app, &ctx, 0.1, vec![], 0); - let fills = |app: &VectorcraftApp| (fill_hex(app, red), fill_hex(app, blue)); - assert_eq!(fills(&app), ("#00ff00".into(), "#ffff00".into()), "off: the preview"); - set(&mut app, FIND, json!(true)); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(fills(&app), ("#00ff00".into(), "#bfbfff".into()), "on: the other art dimmed"); - set(&mut app, "preview", json!(false)); - frame(&mut app, &ctx, 0.3, vec![], 0); - assert_eq!(fills(&app), ("#ff0000".into(), "#bfbfff".into()), "Preview off: the current colors"); - set(&mut app, "__sel", json!([1])); - frame(&mut app, &ctx, 0.4, vec![], 0); - assert_eq!(fills(&app), ("#ffbfbf".into(), "#0000ff".into()), "the other row selected"); - set(&mut app, FIND, json!(false)); - frame(&mut app, &ctx, 0.5, vec![], 0); - assert_eq!(fills(&app), ("#ff0000".into(), "#0000ff".into()), "off with Preview off: the art as it is"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "Find records no undo step"); - set(&mut app, FIND, json!(true)); - frame(&mut app, &ctx, 0.6, vec![], 0); - crate::dialogs::cancel(&mut app); - assert!(app.ui.dialog.is_none()); - assert_eq!(fills(&app), ("#ff0000".into(), "#0000ff".into()), "Cancel: the art as it was"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + rc.set("rows", rs.clone()).unwrap(); + rc.set("__sel", json!([0])).unwrap(); + rc.frame(); + assert_eq!(fills(&rc), ("#00ff00".into(), "#ffff00".into()), "off: the preview"); + rc.set(FIND, json!(true)).unwrap(); + rc.frame(); + assert_eq!(fills(&rc), ("#00ff00".into(), "#bfbfff".into()), "on: the other art dimmed"); + rc.set("preview", json!(false)).unwrap(); + rc.frame(); + assert_eq!(fills(&rc), ("#ff0000".into(), "#bfbfff".into()), "Preview off: the current colors"); + rc.set("__sel", json!([1])).unwrap(); + rc.frame(); + assert_eq!(fills(&rc), ("#ffbfbf".into(), "#0000ff".into()), "the other row selected"); + rc.set(FIND, json!(false)).unwrap(); + rc.frame(); + assert_eq!(fills(&rc), ("#ff0000".into(), "#0000ff".into()), "off with Preview off: the art as it is"); + assert_eq!(undo_len(&rc.app()), undo, "Find records no undo step"); + rc.set(FIND, json!(true)).unwrap(); + rc.frame(); + rc.cancel(); + assert!(!rc.is_open()); + assert_eq!(fills(&rc), ("#ff0000".into(), "#0000ff".into()), "Cancel: the art as it was"); + assert_eq!(undo_len(&rc.app()), undo); // A black square joins the selection: Preserve Black leaves it out of the rows. - let black = square(&mut app, 70.0, "#000000"); - let undo = app.session.doc().unwrap().history.undo.len(); - app.run("select.set", json!({"ids": [red, blue, black]})).unwrap(); - app.run("ui.recolorDialog", json!({})).unwrap(); - set(&mut app, "method", json!(Method::Exact.id())); - frame(&mut app, &ctx, 1.0, vec![], 0); - set(&mut app, "rows", rs); - set(&mut app, "__sel", json!([0])); - set(&mut app, FIND, json!(true)); - frame(&mut app, &ctx, 1.1, vec![], 0); - assert_eq!(fills(&app), ("#00ff00".into(), "#bfbfff".into())); - assert_eq!(fill_hex(&app, black), "#bfbfbf", "the preserved black dims too"); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(fills(&app), ("#00ff00".into(), "#ffff00".into()), "OK applies the rows to all the art"); - assert_eq!(fill_hex(&app, black), "#000000", "and keeps the preserved black"); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let black = square(&mut rc.app(), 70.0, "#000000"); + let undo = undo_len(&rc.app()); + rc.app().run("select.set", json!({"ids": [red, blue, black]})).unwrap(); + rc.app().run("ui.recolorDialog", json!({})).unwrap(); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + rc.set("rows", rs).unwrap(); + rc.set("__sel", json!([0])).unwrap(); + rc.set(FIND, json!(true)).unwrap(); + rc.frame(); + assert_eq!(fills(&rc), ("#00ff00".into(), "#bfbfff".into())); + assert_eq!(fill_hex(&rc,black), "#bfbfbf", "the preserved black dims too"); + rc.confirm().unwrap(); + assert_eq!(fills(&rc), ("#00ff00".into(), "#ffff00".into()), "OK applies the rows to all the art"); + assert_eq!(fill_hex(&rc,black), "#000000", "and keeps the preserved black"); + assert_eq!(undo_len(&rc.app()), undo + 1, "one undo step"); } /// In a CMYK document colors opened alone are saved as a new color group in their own model. #[test] fn a_new_group_from_colors_keeps_their_model_in_a_cmyk_document() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 100, "height": 100, "colorMode": "cmyk"})).unwrap(); - app.run("ui.recolorDialog", json!({"colors": ["#ff8000"]})).unwrap(); - let d = app.ui.dialog.clone().expect("Recolor Artwork opens"); - confirm(&mut app, &d).unwrap(); + let mut rc = opened(app, json!({"colors": ["#ff8000"]})); + rc.confirm().unwrap(); + let app = rc.app(); let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), [Color::rgb8(255, 128, 0)]); } - /// Undo Changes keeps at most [`MAX_STEPS`] steps and [`MAX_STEP_BYTES`] of them, the oldest - /// going first; fields that change nothing make no step, and with fields larger than the limit - /// only the newest step is kept, so Undo Changes is never on with no step to go to. - #[test] - fn undo_changes_keeps_a_bounded_history() { - let mut d = Dialog::new(KIND, json!({"rows": [], "colors": null})); - let mut h = History::default(); - h.note(&d); - h.note(&d); - assert!(h.undo.is_empty(), "no change, no step"); - for n in 0..MAX_STEPS + 6 { - d.fields.insert("colors".into(), json!(n)); - h.note(&d); - } - assert_eq!(h.undo.len(), MAX_STEPS, "the oldest steps go first"); - assert_eq!(h.undo[0]["colors"], json!(5)); - // Rows of 100 KiB each: the steps kept stay within the byte limit. - let big = |n: usize| json!([{"from": [format!("{n}{}", "x".repeat(100 << 10))], "to": null}]); - for n in 0..60 { - d.fields.insert("rows".into(), big(n)); - h.note(&d); - } - let size = |s: &Snapshot| serde_json::to_vec(s).unwrap().len(); - let total: usize = h.base.iter().chain(&h.undo).map(size).sum(); - assert!(total <= MAX_STEP_BYTES, "{total}"); - assert!(h.undo.len() < 60 && !h.undo.is_empty(), "{}", h.undo.len()); - assert!(h.step(&mut d, true), "the newest step is kept"); - assert_eq!(d.fields["rows"], big(58)); - // Current fields past the limit alone: only the step to them is kept, so Undo Changes - // still goes back one step. - d.fields.insert("rows".into(), json!([{"from": ["x".repeat(MAX_STEP_BYTES)], "to": null}])); - h.note(&d); - assert!(h.undo.len() == 1 && h.redo.is_empty(), "{}", h.undo.len()); - d.fields.insert("colors".into(), json!(1)); - assert!(h.can(&d, true), "the change to colors is a step too"); - assert!(h.step(&mut d, true), "and it is kept"); - assert_eq!(d.fields["colors"], json!(MAX_STEPS + 5), "Undo Changes gives back the colors before it"); - assert_eq!(h.undo.len(), 0, "the step before it went to keep the newest"); - assert!(!h.can(&d, true)); - } - - /// Sets `field` of the open dialog to `value` as `ui.dialog.set` does: a refused value leaves - /// the dialog as it was. - fn set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { - let before = app.ui.dialog.clone(); - let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); - if let Some(d) = app.ui.dialog.as_mut() { - crate::dialogs::set_field(d, field.into(), value); - } - let r = crate::dialogs::field_set(app, field, old.as_ref()); - if r.is_err() { - app.ui.dialog = before; - } - r - } - fn group_hex(app: &VectorcraftApp, name: &str) -> Option> { let doc = &app.session.doc().unwrap().doc; doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect()) } - fn undo_len(app: &VectorcraftApp) -> usize { - app.session.doc().unwrap().history.undo.len() - } - - /// Sets `groupAction` to `a` as `ui.dialog.set` does and draws the frame that runs it. - fn act(app: &mut VectorcraftApp, ctx: &egui::Context, t: f64, a: &str) -> Result<(), String> { - set(app, GROUP_ACTION, json!(a))?; - frame(app, ctx, t, vec![], 0); - Ok(()) + /// An app whose document has the color groups `groups` (name and colors), without art. + fn groups_app(groups: &[(&str, &[&str])]) -> VectorcraftApp { + let mut app = app(100); + for (name, colors) in groups { + app.run("swatch.newGroup", json!({"name": name, "colors": colors, "keepModel": true})).unwrap(); + } + app } /// Without art: a group picked in the Color Groups list (the `group` field) gives the rows its @@ -4296,236 +4049,174 @@ mod tests { /// Delete removes it, after which OK saves the rows as a new group; New Color Group adds one. #[test] fn the_color_groups_list_selects_saves_and_deletes_groups() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); - app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); - assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], true, "the list opens shown"); + let mut rc = opened(groups_app(&[("A", &["#ff0000", "#00ff00"]), ("B", &["#0000ff", "#ffff00", "#ffffff"])]), json!({"group": "A"})); + assert_eq!(new_colors(&rc), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + assert_eq!(rc.field(GROUP_STORAGE), Some(json!(true)), "the list opens shown"); + rc.settled(); - set(&mut app, "group", json!("B")).unwrap(); - assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("groupName"), "B"); - assert_eq!(set(&mut app, "group", json!("Nope")), Err("no colour group `Nope`".into())); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "B", "a refused name leaves B selected"); - assert!(set(&mut app, GROUP_STORAGE, json!("yes")).is_err()); - assert!(set(&mut app, GROUP_ACTION, json!("rename")).is_err()); + rc.set("group", json!("B")).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + assert_eq!(rc.fields().str("groupName"), "B"); + assert_eq!(rc.set("group", json!("Nope")), Err("no colour group `Nope`".into())); + assert_eq!(rc.field("group"), Some(json!("B")), "a refused name leaves B selected"); + assert!(rc.set(GROUP_STORAGE, json!("yes")).is_err()); + assert!(rc.set(GROUP_ACTION, json!("rename")).is_err()); - let undo = undo_len(&app); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let undo = undo_len(&rc.app()); + let mut rs = rc.rows(); rs[0]["to"] = json!("rgb 0 0 0"); - d.fields.insert("rows".into(), Value::Array(rs)); - d.fields.insert("groupName".into(), json!("Night")); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "Night"), Some(vec!["#000000".into(), "#ffff00".into(), "#ffffff".into()])); - assert_eq!(group_hex(&app, "B"), None, "renamed"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "Night"); - assert_eq!(undo_len(&app), undo + 1, "one step"); - act(&mut app, &ctx, 0.2, "save").unwrap(); - assert_eq!(undo_len(&app), undo + 1, "saving the same colors again records no step"); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.set("groupName", json!("Night")).unwrap(); + rc.settled(); + assert!(rc.enabled(tl!("Save Changes")), "a selected group can be saved"); + rc.click_label(tl!("Save Changes")); + assert_eq!(group_hex(&rc.app(), "Night"), Some(vec!["#000000".into(), "#ffff00".into(), "#ffffff".into()])); + assert_eq!(group_hex(&rc.app(), "B"), None, "renamed"); + assert_eq!(rc.field("group"), Some(json!("Night"))); + assert_eq!(undo_len(&rc.app()), undo + 1, "one step"); + rc.act("save").unwrap(); + assert_eq!(undo_len(&rc.app()), undo + 1, "saving the same colors again records no step"); - act(&mut app, &ctx, 0.3, "delete").unwrap(); - assert_eq!(group_hex(&app, "Night"), None); - assert_eq!(undo_len(&app), undo + 2); - let d = app.ui.dialog.as_ref().unwrap(); + rc.settled().click_label(tl!("Delete")); + assert_eq!(group_hex(&rc.app(), "Night"), None); + assert_eq!(undo_len(&rc.app()), undo + 2); + let d = rc.fields(); assert!(d.fields["group"].is_null() && d.bool("__newGroup"), "{:?}", d.fields); - assert_eq!(act(&mut app, &ctx, 0.4, "delete"), Err("missing `group`".into())); - assert_eq!(act(&mut app, &ctx, 0.5, "save"), Err("missing `group`".into())); - assert_eq!(undo_len(&app), undo + 2, "a refused button records no step"); + assert_eq!(rc.act("delete"), Err("missing `group`".into())); + assert_eq!(rc.act("save"), Err("missing `group`".into())); + assert_eq!(undo_len(&rc.app()), undo + 2, "a refused button records no step"); - let n = app.session.doc().unwrap().doc.swatch_groups.len(); - act(&mut app, &ctx, 0.6, "new").unwrap(); + let n = rc.app().session.doc().unwrap().doc.swatch_groups.len(); + rc.settled().click_label(tl!("New Color Group")); + assert_eq!(rc.app().session.doc().unwrap().doc.swatch_groups.len(), n + 1); + assert_eq!(last_group_colors(&rc.app()), ["#000000", "#ffff00", "#ffffff"]); + assert_eq!(group_hex(&rc.app(), "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); + } + + /// The colors of the last color group that are colors, as hex. + fn last_group_colors(app: &VectorcraftApp) -> Vec { let doc = &app.session.doc().unwrap().doc; - assert_eq!(doc.swatch_groups.len(), n + 1); - let last: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); - assert_eq!(last, ["#000000", "#ffff00", "#ffffff"]); - assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); + doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect() } /// Without art: rows of a group picked in the list keep their swatches when a color bar moves, /// at OK and at Save Changes, and an excluded row's swatch stays as it is. #[test] fn a_moved_row_of_a_listed_group_keeps_its_swatch_at_save_changes() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "A", "colors": ["#000000"], "keepModel": true})).unwrap(); - app.run("swatch.newGroup", json!({"name": "G", "colors": ["#ff0000", "#0000ff", "#00ff00"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); - set(&mut app, "group", json!("G")).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(groups_app(&[("A", &["#000000"]), ("G", &["#ff0000", "#0000ff", "#00ff00"])]), json!({"group": "A"})); + rc.set("group", json!("G")).unwrap(); + rc.frame(); + let mut rs = rc.rows(); rs[1]["exclude"] = json!(true); rs[2]["to"] = json!("#ffff00"); let active = active_rows(&rs); // Drag the last bar (green, now yellow) above the first (red). assert_eq!(move_bar(&mut rs, &active, 1, 0), Some(0)); - d.fields.insert("rows".into(), Value::Array(rs)); - assert_eq!(apply_params(d)["groupColors"][1], json!("keep")); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "G"), Some(vec!["#ff0000".into(), "#0000ff".into(), "#ffff00".into()])); + rc.set("rows", Value::Array(rs)).unwrap(); + assert_eq!(apply_params(&rc.fields())["groupColors"][1], json!("keep")); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "G"), Some(vec!["#ff0000".into(), "#0000ff".into(), "#ffff00".into()])); + } + + /// Sets row 0's new color to `to`, as `ui.dialog.set` of the rows does. + fn edit_first(rc: &mut Recolor, to: &str) { + let mut rs = rc.rows(); + rs[0]["to"] = json!(to); + rc.set("rows", Value::Array(rs)).unwrap(); } /// Without art: selecting another color group in the list and Save Changes leave Undo Changes /// and Redo Changes no step to go to, so OK gives the selected group the rows read for it. #[test] fn another_group_or_save_changes_leaves_nothing_to_undo() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); - app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); - let edit = |app: &mut VectorcraftApp, to: &str| { - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - rs[0]["to"] = json!(to); - d.fields.insert("rows".into(), Value::Array(rs)); - }; - edit(&mut app, "rgb 0 0 0"); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert!(super::can_step(&app, true), "the edit is a step"); + let mut rc = opened(groups_app(&[("A", &["#ff0000", "#00ff00"]), ("B", &["#0000ff", "#ffff00", "#ffffff"])]), json!({"group": "A"})); + rc.frame(); + edit_first(&mut rc, "rgb 0 0 0"); + rc.frame(); + assert!(can(&rc,true), "the edit is a step"); - set(&mut app, "group", json!("B")).unwrap(); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "another group leaves no step"); - assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(false)); - assert_eq!(new_colors(&app).len(), 3, "the rows of B"); + rc.set("group", json!("B")).unwrap(); + rc.frame(); + assert!(!can(&rc,true) && !can(&rc,false), "another group leaves no step"); + assert_eq!(step(&mut rc.app(), true).unwrap()["changed"], json!(false)); + assert_eq!(new_colors(&rc).len(), 3, "the rows of B"); - edit(&mut app, "rgb 0 128 0"); - frame(&mut app, &ctx, 0.3, vec![], 0); - assert!(super::can_step(&app, true), "the edit is a step"); - act(&mut app, &ctx, 0.4, "save").unwrap(); - assert_eq!(group_hex(&app, "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()])); - assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "Save Changes leaves no step"); - assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(false)); + edit_first(&mut rc, "rgb 0 128 0"); + rc.frame(); + assert!(can(&rc,true), "the edit is a step"); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()])); + assert!(!can(&rc,true) && !can(&rc,false), "Save Changes leaves no step"); + assert_eq!(step(&mut rc.app(), true).unwrap()["changed"], json!(false)); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(group_hex(&app, "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()]), "OK keeps B's saved colors"); - assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "and leaves A as it was"); + rc.confirm().unwrap(); + assert_eq!(group_hex(&rc.app(), "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()]), "OK keeps B's saved colors"); + assert_eq!(group_hex(&rc.app(), "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "and leaves A as it was"); } /// Without art: rows set after another color group is selected, with no frame between, are a - /// step back to the rows read for that group. + /// step back to the rows read for that group, which Undo Changes and Redo Changes step through. #[test] fn an_edit_right_after_another_group_is_a_step() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); - app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); - set(&mut app, "group", json!("B")).unwrap(); - assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "another group leaves no step"); - let b = new_colors(&app); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - rs[0]["to"] = json!("rgb 0 0 0"); - d.fields.insert("rows".into(), Value::Array(rs)); - assert!(super::can_step(&app, true), "the edit is a step"); - assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(true)); - assert_eq!(new_colors(&app), b, "Undo Changes gives back the rows read for B"); - assert_eq!(super::step(&mut app, false).unwrap()["changed"], json!(true)); - assert_eq!(new_colors(&app)[0], json!("rgb 0 0 0"), "Redo Changes gives back the edit"); + let mut rc = opened(groups_app(&[("A", &["#ff0000", "#00ff00"]), ("B", &["#0000ff", "#ffff00", "#ffffff"])]), json!({"group": "A"})); + rc.frame(); + rc.set("group", json!("B")).unwrap(); + rc.frame(); + assert!(!can(&rc,true) && !can(&rc,false), "another group leaves no step"); + let b = new_colors(&rc); + edit_first(&mut rc, "rgb 0 0 0"); + assert!(can(&rc,true), "the edit is a step"); + assert_eq!(step(&mut rc.app(), true).unwrap()["changed"], json!(true)); + assert_eq!(new_colors(&rc), b, "Undo Changes gives back the rows read for B"); + assert_eq!(step(&mut rc.app(), false).unwrap()["changed"], json!(true)); + assert_eq!(new_colors(&rc)[0], json!("rgb 0 0 0"), "Redo Changes gives back the edit"); } /// With art not linked to the group: Save Changes with the rows as the last Save Changes left /// them, after an edit and Undo Changes, leaves Redo Changes no step to go to either. #[test] fn an_unchanged_save_changes_leaves_nothing_to_redo() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); - let edit = |app: &mut VectorcraftApp, to: &str| { - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - rs[0]["to"] = json!(to); - d.fields.insert("rows".into(), Value::Array(rs)); - }; - edit(&mut app, "rgb 0 128 0"); - frame(&mut app, &ctx, 0.1, vec![], 0); - act(&mut app, &ctx, 0.2, "save").unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key(SAVED_ROWS), "the art kept its colors"); - edit(&mut app, "rgb 0 0 0"); - frame(&mut app, &ctx, 0.3, vec![], 0); - assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(true)); - assert!(unchanged_since_save(app.ui.dialog.as_ref().unwrap()), "the rows are as saved"); - assert!(super::can_step(&app, false), "the edit can be redone"); - act(&mut app, &ctx, 0.4, "save").unwrap(); - assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "Save Changes leaves no step"); + let mut rc = opened(app, json!({"group": "Plain"})); + rc.frame(); + edit_first(&mut rc, "rgb 0 128 0"); + rc.frame(); + rc.act("save").unwrap(); + assert!(rc.fields().fields.contains_key(SAVED_ROWS), "the art kept its colors"); + edit_first(&mut rc, "rgb 0 0 0"); + rc.frame(); + assert_eq!(step(&mut rc.app(), true).unwrap()["changed"], json!(true)); + assert!(unchanged_since_save(&rc.fields()), "the rows are as saved"); + assert!(can(&rc,false), "the edit can be redone"); + rc.act("save").unwrap(); + assert!(!can(&rc,true) && !can(&rc,false), "Save Changes leaves no step"); } /// Without art: after a group is picked in the list, the same Color Theme Picker picks that gave /// the group before it its colors give the new group's rows the palette of the art picked too. #[test] fn theme_picks_apply_again_after_another_group_is_picked() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); square(&mut app, 100.0, "#00ff00"); app.run("select.set", json!({"ids": []})).unwrap(); app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); + let mut rc = opened(app, json!({"group": "A"})); + rc.frame(); let picks = json!([{"at": [107, 17]}]); - app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks.clone()); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); - set(&mut app, "group", json!("B")).unwrap(); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); - app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks); - frame(&mut app, &ctx, 0.3, vec![], 0); - assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0"), json!("rgb 0 255 0")], "the picks apply to B's rows"); - } - - /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and - /// leaves the group as it is: the rows hold only its colors. - #[test] - fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); - let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); - let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); - g.swatches.insert(1, fade_swatch()); - app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); - assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); - let undo = undo_len(&app); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - rs[0]["to"] = json!("rgb 0 0 0"); - d.fields.insert("rows".into(), Value::Array(rs)); - let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); - assert_eq!(act(&mut app, &ctx, 0.1, "save"), refused); - app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Renamed")); - assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); - // OK first runs a save set together with it, and the dialog stays open. - app.ui.dialog.as_mut().unwrap().fields.insert(GROUP_ACTION.into(), json!("save")); - assert!(crate::dialogs::confirm(&mut app).is_err()); - assert!(app.ui.dialog.is_some()); - let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); - assert_eq!(g.swatches[1], fade_swatch(), "the swatch is kept"); - assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#00ff00".into()])); - assert_eq!(undo_len(&app), undo, "no step"); + rc.set(THEME_PICKS, picks.clone()).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); + rc.set("group", json!("B")).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + rc.set(THEME_PICKS, picks).unwrap(); + rc.frame(); + assert_eq!(new_colors(&rc), [json!("rgb 0 255 0"), json!("rgb 0 255 0"), json!("rgb 0 255 0")], "the picks apply to B's rows"); } /// A gradient swatch, for a color group. @@ -4534,105 +4225,139 @@ mod tests { vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } } + /// The refusal of Save Changes on a group with a swatch that is not a color. + fn not_colors(group: &str) -> Result<(), String> { + Err(format!("color group `{group}` holds swatches that are not colors, which Save Changes can't keep")) + } + + /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and + /// leaves the group as it is: the rows hold only its colors. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused() { + let mut app = groups_app(&[("Mixed", &["#ff0000", "#00ff00"])]); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.insert(1, fade_swatch()); + let mut rc = opened(app, json!({"group": "Mixed"})); + assert_eq!(new_colors(&rc), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + let undo = undo_len(&rc.app()); + edit_first(&mut rc, "rgb 0 0 0"); + assert_eq!(rc.act("save"), not_colors("Mixed")); + rc.set("groupName", json!("Renamed")).unwrap(); + assert_eq!(rc.act("save"), not_colors("Mixed")); + assert_eq!(rc.field(GROUP_ACTION), None, "a refused button is not held for OK"); + rc.cancel(); + let app = rc.app(); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches[1], fade_swatch(), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#00ff00".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + /// With art, the preview rewrites the group being edited and keeps its other swatch; Save /// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was. #[test] fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); g.swatches.push(fade_swatch()); let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); - let undo = undo_len(&app); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - let row_of = |rs: &[Value], hex: &str| rs.iter().position(|r| super::from_colors(r).iter().any(|c| c.to_hex() == hex)).unwrap(); + let mut rc = opened(app, json!({"group": "Mixed"})); + rc.frame(); + let undo = undo_len(&rc.app()); + let mut rs = rc.rows(); + let row_of = |rs: &[Value], hex: &str| rs.iter().position(|r| from_colors(r).iter().any(|c| c.to_hex() == hex)).unwrap(); let red_row = row_of(&rs, "#ff0000"); rs[red_row]["to"] = json!("rgb 0 0 0"); - let blue_to = super::to_color(&rs[row_of(&rs, "#0000ff")]).unwrap().to_hex(); - d.fields.insert("rows".into(), Value::Array(rs)); - frame(&mut app, &ctx, 0.1, vec![], 0); - assert!(app.session.in_interaction(), "the art previews"); - let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.clone()); + let blue_to = to_color(&rs[row_of(&rs, "#0000ff")]).unwrap().to_hex(); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.frame(); + assert!(rc.app().session.in_interaction(), "the art previews"); + let previewed = rc.app().session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.clone()); assert_eq!(previewed.as_ref().map(Vec::len), Some(3), "the preview's rewrite of the group keeps its other swatch"); assert_eq!(previewed.and_then(|s| s.last().cloned()), Some(fade_swatch()), "with its paint"); - assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#000000".into(), blue_to]), "each color swatch takes its row's new color"); - let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); - assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); - crate::dialogs::cancel(&mut app); + assert_eq!(group_hex(&rc.app(), "Mixed"), Some(vec!["#000000".into(), blue_to]), "each color swatch takes its row's new color"); + assert_eq!(rc.act("save"), not_colors("Mixed")); + rc.cancel(); + let app = rc.app(); let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); assert_eq!(g.swatches.last(), Some(&fade_swatch()), "the swatch is kept"); assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#0000ff".into()])); assert_eq!(undo_len(&app), undo, "no step"); } + /// Red and blue squares and the squares of `more`, selected, whose colors are the global swatches + /// of the group "Linked"; Recolor Artwork open on it with the Exact method, one frame drawn. + fn linked_setup(more: &[(f64, &str)]) -> (Recolor, Vec) { + let mut app = app(300); + let mut ids = vec![square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")]; + for (x, fill) in more { + ids.push(square(&mut app, *x, fill)); + } + app.run("select.set", json!({"ids": ids})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let mut rc = opened(app, json!({"group": "Linked"})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + (rc, ids) + } + + /// Sets the new color of the rows whose first current color is `hex` to `to`. + fn set_row(rc: &mut Recolor, hex: &str, to: Value) { + let mut rs = rc.rows(); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some(hex) { + r["to"] = to.clone(); + } + } + rc.set("rows", Value::Array(rs)).unwrap(); + } + /// Save Changes on a group whose global swatches the selected art is linked to: the art takes /// the group's new colors, and the rows are read from the art again, so they list its colors as /// they are now. A color the art had before keeps its row's new color; a color the save gave /// it stays as it is. #[test] fn saving_a_group_the_art_links_to_reads_the_rows_again() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); - app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - for r in &mut rs { - if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { - r["to"] = json!("rgb 0 128 0"); - } - } - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); - frame(&mut app, &ctx, 0.2, vec![], 0); + let (mut rc, ids) = linked_setup(&[]); + let red = ids[0]; + set_row(&mut rc, "#ff0000", json!("rgb 0 128 0")); + rc.act("save").unwrap(); + rc.frame(); // The rows took the group's colors in their order, so one of the swatches is now green. - let saved = group_hex(&app, "Linked").unwrap(); + let saved = group_hex(&rc.app(), "Linked").unwrap(); assert!(saved.len() == 2 && saved.contains(&"#008000".to_string()), "{saved:?}"); let mut want = saved.clone(); want.sort(); - assert_eq!(fill_hex(&app, red), "#008000", "the red square keeps the new color its row gave it"); - for r in super::rows(app.ui.dialog.as_ref().unwrap()) { + assert_eq!(fill_hex(&rc,red), "#008000", "the red square keeps the new color its row gave it"); + for r in rc.rows() { if !from_colors(&r).iter().any(|c| ["#ff0000", "#0000ff"].contains(&c.to_hex().as_str())) { assert!(excluded(&r) && r["to"] == r["from"][0], "a color the save gave the art stays: {r}"); } } - let mut froms: Vec = super::rows(app.ui.dialog.as_ref().unwrap()).iter().flat_map(from_colors).map(|c| c.to_hex()).collect(); + let mut froms: Vec = rc.rows().iter().flat_map(from_colors).map(|c| c.to_hex()).collect(); froms.sort(); assert_eq!(froms, want, "the rows list the art's colors as they are now"); - assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + assert!(apply_params(&rc.fields()).get("group").is_none(), "OK leaves the saved group as it is"); // OK with only a new name keeps the preview as one step and renames the group, keeping its // saved colors. - let undo = undo_len(&app); - let mut d = app.ui.dialog.clone().unwrap(); - d.fields.insert("groupName".into(), json!("Renamed")); - confirm(&mut app, &d).unwrap(); - assert_eq!(group_hex(&app, "Renamed"), Some(saved)); - assert_eq!(group_hex(&app, "Linked"), None); - assert_eq!(fill_hex(&app, red), "#008000"); - assert_eq!(undo_len(&app), undo + 1); + let undo = undo_len(&rc.app()); + rc.set("groupName", json!("Renamed")).unwrap(); + rc.confirm().unwrap(); + assert_eq!(group_hex(&rc.app(), "Renamed"), Some(saved)); + assert_eq!(group_hex(&rc.app(), "Linked"), None); + assert_eq!(fill_hex(&rc,red), "#008000"); + assert_eq!(undo_len(&rc.app()), undo + 1); } /// OK with only a new name after Save Changes leaves every swatch of the group its exact color: /// a CMYK swatch no row lists keeps components finer than a hundredth of a percent. #[test] fn renaming_a_saved_group_keeps_its_exact_colors() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); app.run("select.set", json!({"ids": [red, blue]})).unwrap(); app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); @@ -4640,30 +4365,22 @@ mod tests { let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Linked").unwrap(); g.swatches.push(vectorcraft_color::Swatch { name: "Fine".into(), paint: vectorcraft_color::Paint::solid(fine), global: false, spot: false }); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - for r in &mut rs { - if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { - r["to"] = json!("rgb 0 128 0"); - } - } - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); - frame(&mut app, &ctx, 0.2, vec![], 0); - let swatches = |app: &VectorcraftApp, name: &str| { + let mut rc = opened(app, json!({"group": "Linked"})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + set_row(&mut rc, "#ff0000", json!("rgb 0 128 0")); + rc.act("save").unwrap(); + rc.frame(); + let swatches = |rc: &Recolor, name: &str| { + let app = rc.app(); let doc = &app.session.doc().unwrap().doc; doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect::>()) }; - let saved = swatches(&app, "Linked").unwrap(); + let saved = swatches(&rc, "Linked").unwrap(); assert_eq!(saved.last(), Some(&Some(fine)), "Save Changes keeps the swatch no row lists"); - let mut d = app.ui.dialog.clone().unwrap(); - d.fields.insert("groupName".into(), json!("Renamed")); - confirm(&mut app, &d).unwrap(); - assert_eq!(swatches(&app, "Renamed"), Some(saved), "the rename keeps every color exactly"); + rc.set("groupName", json!("Renamed")).unwrap(); + rc.confirm().unwrap(); + assert_eq!(swatches(&rc, "Renamed"), Some(saved), "the rename keeps every color exactly"); } /// Save Changes where one row's new color is another row's current color: the art linked to the @@ -4671,18 +4388,8 @@ mod tests { /// Global Adjust set afterwards gives OK the group again. #[test] fn saving_a_group_keeps_the_colors_it_gave_the_linked_art() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); - app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let (mut rc, ids) = linked_setup(&[]); + let mut rs = rc.rows(); for r in &mut rs { let from = from_colors(r).first().map(|c| c.to_hex()); r["to"] = match from.as_deref() { @@ -4690,26 +4397,25 @@ mod tests { _ => json!("rgb 0 128 0"), }; } - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); - frame(&mut app, &ctx, 0.2, vec![], 0); - let mut group = group_hex(&app, "Linked").unwrap(); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.act("save").unwrap(); + rc.frame(); + let mut group = group_hex(&rc.app(), "Linked").unwrap(); group.sort(); - let mut fills = vec![fill_hex(&app, red), fill_hex(&app, blue)]; + let mut fills = vec![fill_hex(&rc,ids[0]), fill_hex(&rc,ids[1])]; fills.sort(); assert_eq!(fills, group, "the art shows the saved group's colors, not a second recolor"); - assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none()); - app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); - assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_some(), "a new Global Adjust rewrites the group at OK"); + assert!(apply_params(&rc.fields()).get("group").is_none()); + let mut d = rc.fields(); + d.fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + assert!(apply_params(&d).get("group").is_some(), "a new Global Adjust rewrites the group at OK"); } /// Save Changes with art in only some colors of the group: the swatches keep their order, and a /// swatch no row lists keeps its color. #[test] fn saving_a_group_keeps_the_swatches_the_art_does_not_use() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); let red = square(&mut app, 10.0, "#ff0000"); let blue = square(&mut app, 40.0, "#0000ff"); let yellow = square(&mut app, 70.0, "#ffff00"); @@ -4717,12 +4423,10 @@ mod tests { app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); let order = group_hex(&app, "Linked").unwrap(); app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(app, json!({"group": "Linked"})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + let mut rs = rc.rows(); for r in &mut rs { let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { Some("#0000ff") => json!("rgb 0 128 0"), @@ -4730,32 +4434,20 @@ mod tests { }; r["to"] = to; } - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.act("save").unwrap(); let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); - assert_eq!(group_hex(&app, "Linked"), Some(want), "the swatches keep their order and the red one its color"); - assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); + assert_eq!(group_hex(&rc.app(), "Linked"), Some(want), "the swatches keep their order and the red one its color"); + assert_eq!(fill_hex(&rc,red), "#ff0000", "art linked to a swatch no row lists is left as it is"); } /// Save Changes with art in colors of the group keeps the Edit tab's changes: a removed color's /// swatch is removed, and a color added on the Edit tab joins the group after the others. #[test] fn saving_a_group_keeps_added_and_removed_colors() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - let red = square(&mut app, 10.0, "#ff0000"); - let blue = square(&mut app, 40.0, "#0000ff"); - let yellow = square(&mut app, 70.0, "#ffff00"); - app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); - let order = group_hex(&app, "Linked").unwrap(); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let (mut rc, ids) = linked_setup(&[(70.0, "#ffff00")]); + let order = group_hex(&rc.app(), "Linked").unwrap(); + let mut rs = rc.rows(); for r in &mut rs { let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { Some("#0000ff") => Value::Null, @@ -4764,19 +4456,39 @@ mod tests { r["to"] = to; } rs.push(json!({"from": [], "to": "rgb 0 128 0", "added": true})); - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.act("save").unwrap(); let mut want: Vec = order.into_iter().filter(|h| h != "#0000ff").collect(); want.push("#008000".into()); - assert_eq!(group_hex(&app, "Linked"), Some(want.clone()), "the removed swatch goes and the added color follows the others"); - assert_eq!(fill_hex(&app, blue), "#0000ff", "art linked to a removed swatch keeps its color"); - let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + assert_eq!(group_hex(&rc.app(), "Linked"), Some(want.clone()), "the removed swatch goes and the added color follows the others"); + assert_eq!(fill_hex(&rc,ids[1]), "#0000ff", "art linked to a removed swatch keeps its color"); + let rs = rc.rows(); assert!(rs.iter().all(|r| !r["to"].is_null() && !is_added(r)), "the rows follow the saved group: {rs:?}"); - let assign = app.ui.dialog.as_ref().unwrap().fields["__assign"].clone(); - let assign: Vec = assign.as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); - assert_eq!(Some(assign), group_hex(&app, "Linked"), "a later edit gives the group no removed swatch back"); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(group_hex(&app, "Linked"), Some(want), "OK removes and adds nothing more"); + let assign = rc.field("__assign").unwrap_or_default(); + let assign: Vec = assign.as_array().cloned().unwrap_or_default().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + assert_eq!(Some(assign), group_hex(&rc.app(), "Linked"), "a later edit gives the group no removed swatch back"); + rc.confirm().unwrap(); + assert_eq!(group_hex(&rc.app(), "Linked"), Some(want), "OK removes and adds nothing more"); + } + + /// The colors `d`'s OK gives the selected group, as hex, `"keep"` read as the color the swatch + /// at its place has. + fn sent_by(app: &VectorcraftApp, d: &Fields) -> Vec { + let own = group_hex(app, &d.str("group")).unwrap_or_default(); + let p = apply_params(d); + let hex = |(i, k): (usize, &Value)| if *k == json!("keep") { own.get(i).cloned() } else { color_value(k).map(|c| c.to_hex()) }; + p["groupColors"].as_array().unwrap().iter().enumerate().filter_map(hex).collect() + } + + /// The colors OK gives the selected group, as [`sent_by`] reads them. + fn sent_hex(rc: &Recolor) -> Vec { + let d = rc.fields(); + sent_by(&rc.app(), &d) + } + + /// Whether Undo Changes (`back`) or Redo Changes can run. + fn can(rc: &Recolor, back: bool) -> bool { + can_step(&rc.app(), back) } /// Save Changes that recolors linked art reads the rows from the art again; a color added on the @@ -4784,20 +4496,8 @@ mod tests { /// further edit keeps them as saved. #[test] fn saving_a_group_that_reads_the_rows_again_keeps_an_added_color() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - let red = square(&mut app, 10.0, "#ff0000"); - let blue = square(&mut app, 40.0, "#0000ff"); - let lime = square(&mut app, 70.0, "#00ff00"); - app.run("select.set", json!({"ids": [red, blue, lime]})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let (mut rc, ids) = linked_setup(&[(70.0, "#00ff00")]); + let mut rs = rc.rows(); for r in &mut rs { let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { Some("#ff0000") => json!("rgb 0 128 0"), @@ -4807,20 +4507,20 @@ mod tests { r["to"] = to; } rs.push(json!({"from": [], "to": "rgb 255 255 0", "added": true})); - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(fill_hex(&app, red), "#008000", "the save recolored the linked art"); - assert_eq!(fill_hex(&app, lime), "#00ff00", "art linked to the removed swatch keeps its color"); - let group = group_hex(&app, "Linked").unwrap(); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.act("save").unwrap(); + assert_eq!(fill_hex(&rc,ids[0]), "#008000", "the save recolored the linked art"); + assert_eq!(fill_hex(&rc,ids[2]), "#00ff00", "art linked to the removed swatch keeps its color"); + let group = group_hex(&rc.app(), "Linked").unwrap(); assert!(group.contains(&"#ffff00".to_string()) && !group.contains(&"#00ff00".to_string()), "{group:?}"); - let mut d = app.ui.dialog.clone().unwrap(); + let mut d = rc.fields(); let mut rs = super::rows(&d); assert!(rs.iter().all(|r| !is_added(r)), "{rs:?}"); if let Some(r) = rs.last_mut() { r["to"] = json!("rgb 10 10 10"); } d.fields.insert("rows".into(), Value::Array(rs)); - let colors = sent_by(&app, &d); + let colors = sent_by(&rc.app(), &d); assert_eq!(colors.iter().filter(|c| *c == "#ffff00").count(), 1, "OK after a further edit keeps the added color once: {colors:?}"); assert!(!colors.contains(&"#00ff00".to_string()), "nor brings the removed color back: {colors:?}"); } @@ -4830,9 +4530,7 @@ mod tests { /// color; read again afterwards, a row whose old entry was a hex keeps its new color. #[test] fn saving_a_group_matches_rows_that_list_hex_colors() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); let red = square(&mut app, 10.0, "#ff0000"); let blue = square(&mut app, 40.0, "#0000ff"); let yellow = square(&mut app, 70.0, "#ffff00"); @@ -4841,12 +4539,10 @@ mod tests { let order = group_hex(&app, "Linked").unwrap(); let orange = square(&mut app, 100.0, "#ff8000"); app.run("select.set", json!({"ids": [blue, yellow, orange]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(app, json!({"group": "Linked"})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + let mut rs = rc.rows(); for r in &mut rs { let hex: Vec = from_colors(r).iter().map(|c| c.to_hex()).collect(); r["to"] = match hex.first().map(String::as_str) { @@ -4856,32 +4552,35 @@ mod tests { }; r["from"] = json!(hex); } - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.act("save").unwrap(); let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); - assert_eq!(group_hex(&app, "Linked"), Some(want), "the blue swatch takes the green, the red one keeps its color"); - assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#008000".into())); - let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + assert_eq!(group_hex(&rc.app(), "Linked"), Some(want), "the blue swatch takes the green, the red one keeps its color"); + assert_eq!((fill_hex(&rc,red), fill_hex(&rc,blue)), ("#ff0000".into(), "#008000".into())); + let rs = rc.rows(); let o = rs.iter().find(|r| from_colors(r).iter().any(|c| c.to_hex() == "#ff8000")).unwrap(); assert!(!excluded(o) && o["to"] == json!("rgb 128 0 128"), "the orange row keeps its new color: {o}"); } + /// An app with the color group "Plain" of `colors`, not linked to art, and squares of `art` + /// selected; Recolor Artwork open on the group with the Exact method, one frame drawn. + fn plain_setup(colors: &[&str], art: &[&str]) -> (Recolor, Vec) { + let mut app = app(300); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": colors, "keepModel": true})).unwrap(); + let ids: Vec = art.iter().enumerate().map(|(n, fill)| square(&mut app, 10.0 + 30.0 * n as f64, fill)).collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + let mut rc = opened(app, json!({"group": "Plain"})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + (rc, ids) + } + /// Save Changes with art in the group's colors that is not linked to its swatches: the art is /// left to the preview, and OK leaves the saved group as it is until the rows change. #[test] fn saving_a_group_with_unlinked_art_keeps_the_saved_group_at_ok() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); - let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); - app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let (mut rc, ids) = plain_setup(&["#ff0000", "#0000ff"], &["#ff0000", "#0000ff"]); + let mut rs = rc.rows(); for r in &mut rs { let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { Some("#0000ff") => json!("rgb 0 128 0"), @@ -4889,38 +4588,12 @@ mod tests { }; r["to"] = to; } - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into()])); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(fill_hex(&app, blue), "#008000", "the art previews its row's new color"); - assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); - } - - /// The colors `d`'s OK gives the selected group, as hex, `"keep"` read as the color the swatch - /// at its place has. - fn sent_by(app: &VectorcraftApp, d: &Dialog) -> Vec { - let own = group_hex(app, &d.str("group")).unwrap_or_default(); - let p = apply_params(d); - let hex = |(i, k): (usize, &Value)| if *k == json!("keep") { own.get(i).cloned() } else { color_value(k).map(|c| c.to_hex()) }; - p["groupColors"].as_array().unwrap().iter().enumerate().filter_map(hex).collect() - } - - /// The colors OK gives the selected group, as [`sent_by`] reads them. - fn sent_hex(app: &VectorcraftApp) -> Vec { - sent_by(app, app.ui.dialog.as_ref().unwrap()) - } - - /// Sets the new color of the rows whose first current color is `hex` to `to`. - fn set_row(app: &mut VectorcraftApp, hex: &str, to: Value) { - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - for r in &mut rs { - if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some(hex) { - r["to"] = to.clone(); - } - } - d.fields.insert("rows".into(), Value::Array(rs)); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#ff0000".into(), "#008000".into()])); + rc.frame(); + assert_eq!(fill_hex(&rc,ids[1]), "#008000", "the art previews its row's new color"); + assert!(apply_params(&rc.fields()).get("group").is_none(), "OK leaves the saved group as it is"); } /// With unlinked art in some of the group's colors, a second Save Changes after a further edit of @@ -4928,176 +4601,131 @@ mod tests { /// too; the swatch no row lists keeps its color both times. #[test] fn saving_a_group_twice_with_unlinked_art_gives_a_row_its_swatch_again() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff", "#ffff00"], "keepModel": true})).unwrap(); - let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); - app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); - set_row(&mut app, "#ffff00", json!("rgb 255 255 0")); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into(), "#ffff00".into()])); - frame(&mut app, &ctx, 0.2, vec![], 0); - set_row(&mut app, "#0000ff", json!("rgb 128 0 128")); - let sent = sent_hex(&app); - assert_eq!(sent, ["#ff0000", "#800080", "#ffff00"], "OK gives the blue row's swatch its new color"); - act(&mut app, &ctx, 0.3, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#800080".into(), "#ffff00".into()]), "the second save does too"); + let (mut rc, _) = plain_setup(&["#ff0000", "#0000ff", "#ffff00"], &["#0000ff", "#ffff00"]); + set_row(&mut rc, "#0000ff", json!("rgb 0 128 0")); + set_row(&mut rc, "#ffff00", json!("rgb 255 255 0")); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#ff0000".into(), "#008000".into(), "#ffff00".into()])); + rc.frame(); + set_row(&mut rc, "#0000ff", json!("rgb 128 0 128")); + assert_eq!(sent_hex(&rc), ["#ff0000", "#800080", "#ffff00"], "OK gives the blue row's swatch its new color"); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#ff0000".into(), "#800080".into(), "#ffff00".into()]), "the second save does too"); } /// Without art, an excluded row leaves its swatch its own color at Save Changes and at OK, even /// when its new color was changed before it was excluded. #[test] fn saving_a_group_without_art_keeps_an_excluded_rows_color() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(groups_app(&[("Plain", &["#ff0000", "#0000ff"])]), json!({"group": "Plain"})); + rc.frame(); + let mut rs = rc.rows(); for r in &mut rs { if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#ff0000") { r["to"] = json!("rgb 0 128 0"); r["exclude"] = json!(true); } } - d.fields.insert("rows".into(), Value::Array(rs)); - let sent = sent_hex(&app); - assert_eq!(sent, ["#ff0000", "#0000ff"], "OK keeps the excluded row's swatch"); - let p = apply_params(app.ui.dialog.as_ref().unwrap()); + rc.set("rows", Value::Array(rs)).unwrap(); + assert_eq!(sent_hex(&rc), ["#ff0000", "#0000ff"], "OK keeps the excluded row's swatch"); + let p = apply_params(&rc.fields()); assert_eq!(p["groupColors"][0], "keep", "so the Global Adjust leaves it as it is too: {p}"); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); } /// With art in more colors than the group has swatches, an excluded row past the swatches adds /// no color at Save Changes, as at OK. #[test] fn saving_a_group_with_art_adds_no_color_for_an_excluded_row_past_its_swatches() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000"], "keepModel": true})).unwrap(); let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("method".into(), json!(Method::Exact.id())); - d.fields.insert("colors".into(), json!(2)); - d.fields.remove(REDUCED); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(app, json!({"group": "Plain"})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.set("colors", json!(2)).unwrap(); + rc.frame(); + let mut rs = rc.rows(); assert_eq!(rs.len(), 2, "a row for each color of the art: {rs:?}"); for r in &mut rs { r["exclude"] = json!(true); } - d.fields.insert("rows".into(), Value::Array(rs)); + rc.set("rows", Value::Array(rs)).unwrap(); // `recolor.apply` adds nothing for a "keep" past the group's swatches. - assert_eq!(apply_params(app.ui.dialog.as_ref().unwrap())["groupColors"], json!(["keep", "keep"]), "OK adds no color"); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into()]), "Save Changes adds none either"); + assert_eq!(apply_params(&rc.fields())["groupColors"], json!(["keep", "keep"]), "OK adds no color"); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#ff0000".into()]), "Save Changes adds none either"); } /// Without art, a row excluded after Save Changes gave its swatch a new color leaves the swatch /// that saved color at a second Save Changes, as OK does. #[test] fn saving_a_group_without_art_keeps_a_saved_color_when_its_row_is_excluded() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); - set_row(&mut app, "#ff0000", json!("rgb 0 128 0")); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()])); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(groups_app(&[("Plain", &["#ff0000", "#0000ff"])]), json!({"group": "Plain"})); + rc.frame(); + set_row(&mut rc, "#ff0000", json!("rgb 0 128 0")); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#008000".into(), "#0000ff".into()])); + let mut rs = rc.rows(); for r in &mut rs { if r["to"] == json!("rgb 0 128 0") { r["exclude"] = json!(true); } } - d.fields.insert("rows".into(), Value::Array(rs)); - assert_eq!(sent_hex(&app), ["#008000", "#0000ff"], "OK keeps the saved color"); - act(&mut app, &ctx, 0.2, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()]), "so does a second Save Changes"); + rc.set("rows", Value::Array(rs)).unwrap(); + assert_eq!(sent_hex(&rc), ["#008000", "#0000ff"], "OK keeps the saved color"); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#008000".into(), "#0000ff".into()]), "so does a second Save Changes"); } /// Save Changes that recolors linked art so that one swatch takes another swatch's old color: /// read again, the row of the second swatch's new color gives that swatch a later new color. #[test] fn saving_a_group_twice_with_linked_art_finds_the_row_of_a_swatchs_new_color() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); - let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); - app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); - assert_eq!(group_hex(&app, "Linked"), Some(vec!["#ff0000".into(), "#0000ff".into()])); - app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - set_row(&mut app, "#ff0000", json!("rgb 0 0 255")); - set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); - act(&mut app, &ctx, 0.1, "save").unwrap(); - frame(&mut app, &ctx, 0.2, vec![], 0); - assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#008000".into()])); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let (mut rc, _) = linked_setup(&[]); + assert_eq!(group_hex(&rc.app(), "Linked"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + set_row(&mut rc, "#ff0000", json!("rgb 0 0 255")); + set_row(&mut rc, "#0000ff", json!("rgb 0 128 0")); + rc.act("save").unwrap(); + rc.frame(); + assert_eq!(group_hex(&rc.app(), "Linked"), Some(vec!["#0000ff".into(), "#008000".into()])); + let mut rs = rc.rows(); for r in &mut rs { if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#008000") { r["to"] = json!("rgb 128 0 128"); r["exclude"] = json!(false); } } - d.fields.insert("rows".into(), Value::Array(rs)); - assert_eq!(sent_hex(&app), ["#0000ff", "#800080"], "OK gives the green swatch the green row's new color"); - act(&mut app, &ctx, 0.3, "save").unwrap(); - assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#800080".into()]), "so does Save Changes"); + rc.set("rows", Value::Array(rs)).unwrap(); + assert_eq!(sent_hex(&rc), ["#0000ff", "#800080"], "OK gives the green swatch the green row's new color"); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Linked"), Some(vec!["#0000ff".into(), "#800080".into()]), "so does Save Changes"); } /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. #[test] fn saving_a_group_with_a_global_adjust_applies_it_once() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("method".into(), json!(Method::Exact.id())); - d.fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - act(&mut app, &ctx, 0.1, "save").unwrap(); - let saved = group_hex(&app, "Plain").unwrap(); + let mut rc = opened(app, json!({"group": "Plain"})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.set("globalAdjust", json!({"brightness": -50.0})).unwrap(); + rc.frame(); + rc.act("save").unwrap(); + let saved = group_hex(&rc.app(), "Plain").unwrap(); assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); - frame(&mut app, &ctx, 0.2, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!(adjust_values(d), [0.0; 4]); - d.fields.insert("groupName".into(), json!("Dark")); - let p = apply_params(app.ui.dialog.as_ref().unwrap()); + rc.frame(); + assert_eq!(adjust_values(&rc.fields()), [0.0; 4]); + rc.set("groupName", json!("Dark")).unwrap(); + let p = apply_params(&rc.fields()); assert!(p.get("globalAdjust").is_none(), "{p}"); assert_eq!(p["groupColors"], json!(vec!["keep"; saved.len()]), "OK keeps each saved color"); - let d = app.ui.dialog.clone().unwrap(); - confirm(&mut app, &d).unwrap(); - assert_eq!(group_hex(&app, "Dark"), Some(saved), "OK renames the group with its saved colors"); + rc.confirm().unwrap(); + assert_eq!(group_hex(&rc.app(), "Dark"), Some(saved), "OK renames the group with its saved colors"); } /// Without art, Save Changes with a Global Adjust gives the group the rows' new colors with the @@ -5105,29 +4733,21 @@ mod tests { /// colors, not to the saved group. #[test] fn saving_a_group_without_art_with_a_global_adjust_applies_it_once() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); - frame(&mut app, &ctx, 0.0, vec![], 0); - act(&mut app, &ctx, 0.1, "save").unwrap(); - let saved = group_hex(&app, "Plain").unwrap(); + let mut rc = opened(groups_app(&[("Plain", &["#ff0000", "#0000ff"])]), json!({"group": "Plain"})); + rc.set("globalAdjust", json!({"brightness": -50.0})).unwrap(); + rc.frame(); + rc.act("save").unwrap(); + let saved = group_hex(&rc.app(), "Plain").unwrap(); assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); + rc.confirm().unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain").unwrap(), saved, "OK does not darken the group again"); } /// With Limit to Library, Save Changes gives the group the library's nearest color to a row's /// new color, as OK does, also when the rows were set without being snapped. #[test] fn saving_a_group_snaps_its_colors_to_the_library() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let mut app = app(100); let doc = &app.session.doc().unwrap().doc; let names: Vec<_> = doc .swatches @@ -5139,30 +4759,21 @@ mod tests { app.run("swatch.delete", json!({"names": names})).unwrap(); app.run("swatch.new", json!({"name": "Only Yellow", "color": "#ffff00"})).unwrap(); app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ffff00"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("limitTo".into(), json!("document")); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); - rs[0]["to"] = json!("rgb 250 250 10"); - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ffff00".into()]), "the saved color is the library's"); + let mut rc = opened(app, json!({"group": "Plain"})); + rc.set("limitTo", json!("document")).unwrap(); + rc.frame(); + edit_first(&mut rc, "rgb 250 250 10"); + rc.act("save").unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(vec!["#ffff00".into()]), "the saved color is the library's"); } /// Without art, Save Changes removes a removed color's swatch and adds a color added on the Edit /// tab, and OK afterwards gives the group the same colors: it removes and adds nothing more. #[test] fn saving_a_group_without_art_with_added_and_removed_colors_keeps_them_at_ok() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})).unwrap(); - app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); - frame(&mut app, &ctx, 0.0, vec![], 0); - let d = app.ui.dialog.as_mut().unwrap(); - let mut rs = super::rows(d); + let mut rc = opened(groups_app(&[("Plain", &["#ff0000", "#00ff00", "#0000ff"])]), json!({"group": "Plain"})); + rc.frame(); + let mut rs = rc.rows(); for r in &mut rs { if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#00ff00") { r["to"] = Value::Null; @@ -5170,61 +4781,60 @@ mod tests { } // The added color's row was moved ahead of the others. rs.insert(0, json!({"from": [], "to": "rgb 255 255 0", "added": true})); - d.fields.insert("rows".into(), Value::Array(rs)); - act(&mut app, &ctx, 0.1, "save").unwrap(); + rc.set("rows", Value::Array(rs)).unwrap(); + rc.act("save").unwrap(); let want: Vec = ["#ff0000", "#0000ff", "#ffff00"].map(String::from).to_vec(); - assert_eq!(group_hex(&app, "Plain"), Some(want.clone()), "the save removes green and adds yellow"); - crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(group_hex(&app, "Plain"), Some(want), "OK gives the group the same colors"); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(want.clone()), "the save removes green and adds yellow"); + rc.confirm().unwrap(); + assert_eq!(group_hex(&rc.app(), "Plain"), Some(want), "OK gives the group the same colors"); } /// With art: a group picked in the list reduces the art to a row per color of the group, which - /// become the rows' new colors, and the art previews them; the list draws beside the tabs and - /// hides with `groupStorage`. + /// become the rows' new colors, and the art previews them; a button set with the group runs on + /// the group's rows. The name the preview gives the group being edited picks that group, unless + /// the document has another group of that name. The list hides with `groupStorage`. #[test] fn a_group_picked_in_the_list_recolors_the_art() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let mut app = app(300); app.run("swatch.newGroup", json!({"name": "Warm", "colors": ["#ffff00", "#00ff00"], "keepModel": true})).unwrap(); app.run("swatch.newGroup", json!({"name": "Cool", "colors": ["#0000ff"], "keepModel": true})).unwrap(); let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); app.run("select.set", json!({"ids": [red, blue]})).unwrap(); - app.run("ui.recolorDialog", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); - crate::theme::install_fonts(&ctx); - frame(&mut app, &ctx, 0.0, vec![], 0); - assert_eq!(fill_hex(&app, red), "#ff0000"); + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + assert_eq!(fill_hex(&rc,red), "#ff0000"); // A button set with the group, before a frame, saves the rows the group gives the art. - let n = app.session.doc().unwrap().doc.swatch_groups.len(); - set(&mut app, "group", json!("Warm")).unwrap(); - act(&mut app, &ctx, 0.1, "new").unwrap(); - let doc = &app.session.doc().unwrap().doc; - let mut saved: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + let n = rc.app().session.doc().unwrap().doc.swatch_groups.len(); + rc.set("group", json!("Warm")).unwrap(); + rc.act("new").unwrap(); + let mut saved = last_group_colors(&rc.app()); saved.sort(); - assert_eq!((doc.swatch_groups.len(), saved), (n + 1, vec!["#00ff00".to_string(), "#ffff00".to_string()])); - frame(&mut app, &ctx, 0.2, vec![], 0); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(super::rows(d).len(), 2); - assert_eq!(d.str("groupName"), "Warm"); - let mut shown = [fill_hex(&app, red), fill_hex(&app, blue)]; + assert_eq!((rc.app().session.doc().unwrap().doc.swatch_groups.len(), saved), (n + 1, vec!["#00ff00".to_string(), "#ffff00".to_string()])); + rc.frame(); + assert_eq!(rc.rows().len(), 2); + assert_eq!(rc.fields().str("groupName"), "Warm"); + let mut shown = [fill_hex(&rc,red), fill_hex(&rc,blue)]; shown.sort(); assert_eq!(shown, ["#00ff00", "#ffff00"], "the art previews the group's colors"); // The name the preview gives the group being edited picks that group in the list. - app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Sunny")); - frame(&mut app, &ctx, 0.21, vec![], 0); - set(&mut app, "group", json!("Sunny")).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); + rc.set("groupName", json!("Sunny")).unwrap(); + rc.frame(); + rc.set("group", json!("Sunny")).unwrap(); + rc.frame(); + let d = rc.fields(); assert_eq!((&d.fields["group"], &d.fields[GROUP_LOADED], d.str("groupName")), (&json!("Warm"), &json!("Warm"), "Sunny".into())); // A group the document has under that name is picked instead. - app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Cool")); - frame(&mut app, &ctx, 0.22, vec![], 0); - set(&mut app, "group", json!("Cool")).unwrap(); - frame(&mut app, &ctx, 0.23, vec![], 0); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((&d.fields[GROUP_LOADED], super::rows(d).len()), (&json!("Cool"), 1)); - set(&mut app, GROUP_STORAGE, json!(false)).unwrap(); - frame(&mut app, &ctx, 0.3, vec![], 0); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], false); + rc.set("groupName", json!("Cool")).unwrap(); + rc.frame(); + rc.set("group", json!("Cool")).unwrap(); + rc.frame().frame(); + let d = rc.fields(); + assert_eq!((&d.fields[GROUP_LOADED], super::rows(&d).len()), (&json!("Cool"), 1)); + rc.settled(); + assert!(rc.by_label(tl!("Color Groups")).is_some(), "the list shows"); + rc.set(GROUP_STORAGE, json!(false)).unwrap(); + rc.settled(); + assert!(rc.by_label(tl!("Color Groups")).is_none(), "and hides with `groupStorage`"); } } diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs new file mode 100644 index 0000000000..09d03b884b --- /dev/null +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -0,0 +1,199 @@ +//! The one test harness of Recolor Artwork: an app whose window shows its dialog host in a framework +//! fixture, each frame the host's pass and then the app's dialog pump, as the app runs them. Controls +//! are found by their accessible names; the dialog's fields are read and set as automation does. + +use std::cell::{RefCell, RefMut}; +use std::rc::Rc; + +use craft::behavior::PartRef; +use craft::ui::dialog::{DialogHost, DialogId, HeldOk, dialog_id}; +use craft::ui::testing::{Fixture, Room, Target}; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Vec2}; +use serde_json::{Value, json}; + +use super::{Fields, GROUP_ACTION, KIND, RecolorDialog}; +use crate::VectorcraftApp; + +/// Recolor Artwork over an app, in a window-sized fixture. +pub(crate) struct Recolor { + fixture: Fixture, + app: Rc>, +} + +impl Recolor { + /// `app` in a fixture whose frames run the window's dialog host and then the app's dialog pump. + pub(crate) fn new(app: VectorcraftApp) -> Self { + let app = Rc::new(RefCell::new(app)); + let shared = Rc::clone(&app); + let mut fixture = Fixture::new(move |ui| { + let mut app = shared.borrow_mut(); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + let ctx = ui.ctx().clone(); + crate::dialogs::host::pump(&mut app, &ctx); + }); + fixture.in_room(Room::Window); + app.borrow_mut().ui_ctx = Some(fixture.ctx().clone()); + Recolor { fixture, app } + } + + /// The app, for commands and the document; drop it before the next frame. + pub(crate) fn app(&self) -> RefMut<'_, VectorcraftApp> { + self.app.borrow_mut() + } + + /// The dialog's id on the host. + fn id() -> DialogId { + dialog_id(KIND) + } + + /// Runs `f` on the window's dialog host with the fixture's context; `None` without a window. + pub(crate) fn host(&self, f: impl FnOnce(&mut DialogHost, &egui::Context) -> R) -> Option { + let dialogs = self.app.borrow().dialogs()?; + let ctx = self.fixture.ctx().clone(); + Some(dialogs.with(|host| f(host, &ctx))) + } + + /// Runs `f` on the open dialog with the app; `None` while it is not open. + pub(crate) fn with_dialog(&self, f: impl FnOnce(&VectorcraftApp, &mut RecolorDialog) -> R) -> Option { + let app = self.app.borrow(); + let dialogs = app.dialogs()?; + dialogs.with(|host| host.get_mut::().map(|d| f(&app, d))) + } + + /// Whether Recolor Artwork is open. + pub(crate) fn is_open(&self) -> bool { + self.host(|host, _| host.is_open::()).unwrap_or(false) + } + + /// The dialog's fields, the `__` marks included; empty while it is not open. + pub(crate) fn fields(&self) -> Fields { + self.with_dialog(|_, d| d.fields.clone()).unwrap_or_default() + } + + /// Field `k`. + pub(crate) fn field(&self, k: &str) -> Option { + self.fields().fields.get(k).cloned() + } + + /// The rows. + pub(crate) fn rows(&self) -> Vec { + super::rows(&self.fields()) + } + + /// One frame without input. + pub(crate) fn frame(&mut self) -> &mut Self { + self.fixture.frame(Vec::new()); + self + } + + /// One frame with `events` and `modifiers` held. + pub(crate) fn frame_with(&mut self, events: Vec, modifiers: Modifiers) -> &mut Self { + self.fixture.hold(modifiers); + self.fixture.frame(events); + self.fixture.hold(Modifiers::NONE); + self + } + + /// Frames until the window comes to rest. + pub(crate) fn settled(&mut self) -> &mut Self { + self.fixture.settle(); + self + } + + /// Sets `field` as `ui.dialog.set` does, before the next frame; a refused value leaves the + /// dialog as it was. + pub(crate) fn set(&mut self, field: &str, value: Value) -> Result<(), String> { + self.host(|host, ctx| host.set_json_field(ctx, Self::id(), field, value)).unwrap_or_else(|| Err("no window".into())) + } + + /// A Color Groups button as `ui.dialog.set` of `groupAction` gives it, and the frame that runs it. + pub(crate) fn act(&mut self, action: &str) -> Result<(), String> { + self.set(GROUP_ACTION, json!(action))?; + self.frame(); + Ok(()) + } + + /// OK as `ui.dialog.confirm` gives it: the frames in which the app commits the recolour and the + /// dialog closes. `Err` with the reason the app refused it, which keeps the dialog open. + pub(crate) fn confirm(&mut self) -> Result<(), String> { + self.host(|host, ctx| host.confirm_by_id(ctx, Self::id())); + self.frame().frame(); + match self.host(|host, _| host.held_state(Self::id())).flatten() { + Some(HeldOk::Refused(reason)) => Err(reason.as_str().to_owned()), + _ if self.is_open() => Err("Recolor Artwork stayed open".into()), + _ => Ok(()), + } + } + + /// Cancel as `ui.dialog.cancel` gives it, and the frame in which the preview goes. + pub(crate) fn cancel(&mut self) { + self.host(|host, ctx| host.cancel_by_id(ctx, Self::id())); + self.frame(); + } + + /// The control named `label`. + pub(crate) fn by_label(&self, label: &str) -> Option { + self.fixture.by_label(label) + } + + /// The control named `label`; a trial without it fails. + fn target(&self, label: &str) -> Target { + self.by_label(label).unwrap_or_else(|| panic!("no control named {label:?}")) + } + + /// Whether the control named `label` takes input. + pub(crate) fn enabled(&self, label: &str) -> bool { + !self.fixture.tree().is_disabled_key(self.target(label).node) + } + + /// A click on the control named `label`. + pub(crate) fn click_label(&mut self, label: &str) -> &mut Self { + let target = self.target(label); + self.fixture.click(&target); + self + } + + /// Two clicks on the control named `label` within the double-click time. + pub(crate) fn double_click(&mut self, label: &str) -> &mut Self { + let at = self.target(label).center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + self.fixture.frame(vec![Event::PointerMoved(at)]); + for pressed in [true, false, true, false] { + self.fixture.frame(vec![button(pressed)]); + } + self + } + + /// The rect of part `part` of component `owner`, for a part with no access node. + pub(crate) fn part_rect(&self, owner: egui::Id, part: impl Into) -> Option { + self.fixture.part_rect(owner, part) + } + + /// A drag of the control named `label` by `by`, released. + pub(crate) fn drag(&mut self, label: &str, by: Vec2) -> &mut Self { + let target = self.target(label); + self.fixture.drag(&target, by); + self + } + + /// A press on the control named `label`, held. + pub(crate) fn press(&mut self, label: &str) -> &mut Self { + let target = self.target(label); + self.fixture.press(&target); + self + } + + /// The held button moved to `to`. + pub(crate) fn move_to(&mut self, to: Pos2) -> &mut Self { + self.fixture.frame(vec![Event::PointerMoved(to)]); + self + } + + /// The held button released at `at`, then a frame without input. + pub(crate) fn release(&mut self, at: Pos2) -> &mut Self { + self.fixture.release_at(at); + self + } +}