Merge pull request #10379 from dotCooCoo/fix/gradient-stop-swatch-identity

Gradient: the stop popover keeps the swatch picked among swatches of one color
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-03 07:24:27 -08:00
commit 7836fbbe1c
12 files changed
+668 -26

No files matched your search

+3
View File
@@ -28,6 +28,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
// file, format and saved state share their data with the open ones until a step changes them.
let start = s.docs.clone();
let active = s.active;
// A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record.
let swatch_renames = s.swatch_renames.clone();
let opens = s.plugin_events_mark();
s.batch_stash = Some(vec![]);
let mut grouped = Vec::with_capacity(cmds.len());
@@ -42,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
results
}
Err(e) => {
s.swatch_renames = swatch_renames;
roll_back(s, start, &stash);
// The documents the steps opened are closed again: plug-ins are not told of them.
s.forget_plugin_opens_since(opens);
+56 -5
View File
@@ -128,6 +128,13 @@ impl StopOwner {
#[derive(PartialEq)]
pub struct GradientEditPaints(Vec<EditedPaint>);
impl GradientEditPaints {
/// Whether every edited paint, including every text run's paint, satisfies `matches`.
pub fn all_paints_match(&self, matches: impl FnMut(&Paint) -> bool) -> bool {
self.0.iter().flat_map(|target| &target.paints).all(matches)
}
}
#[derive(PartialEq)]
struct EditedPaint {
id: NodeId,
@@ -520,12 +527,20 @@ fn apply_gradient_edit_in_model(
switched = true;
}
}
let recolor = p.get("stops").is_some() || bool_or(p, "reverse", false);
let reverse = bool_or(p, "reverse", false);
let recolor = p.get("stops").is_some() || reverse;
if let Some(stops) = p.get("stops") {
gp.gradient.stops = parse_stops(stops)?;
gp.swatch = None;
}
if bool_or(p, "reverse", false) {
let stops = parse_stops(stops)?;
let before = std::mem::replace(&mut gp.gradient.stops, stops);
if reverse {
// Midpoints mirrored with their segments.
gp.gradient.reverse();
}
// A paint whose final stops stay as they are keeps its gradient swatch.
if gp.gradient.stops != before {
gp.swatch = None;
}
} else if reverse {
// Midpoints mirrored with their segments.
gp.gradient.reverse();
}
@@ -894,3 +909,39 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_color::Color;
fn linked(stops: &[(f32, &str)]) -> Paint {
let stops = stops.iter().map(|(offset, hex)| GradientStop::new(*offset, Color::from_hex(hex).unwrap())).collect();
let mut paint = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
paint.swatch = Some("Linked".into());
Paint::Gradient(Box::new(paint))
}
fn swatch(paint: &Paint) -> Option<&str> {
match paint {
Paint::Gradient(g) => g.swatch.as_deref(),
_ => None,
}
}
#[test]
fn writing_the_stops_a_paint_already_has_keeps_its_gradient_swatch() {
let paint = linked(&[(0.0, "#ffffff"), (1.0, "#000000")]);
let same = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]});
assert_eq!(swatch(&apply_gradient_edit(&paint, &same, None).unwrap()), Some("Linked"));
let other = json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]});
assert_eq!(swatch(&apply_gradient_edit(&paint, &other, None).unwrap()), None, "new stops unlink the swatch");
}
#[test]
fn writing_the_same_stops_reversed_unlinks_the_gradient_swatch() {
let paint = linked(&[(0.0, "#ffffff"), (1.0, "#000000")]);
let reversed = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}], "reverse": true});
assert_eq!(swatch(&apply_gradient_edit(&paint, &reversed, None).unwrap()), None, "reversed stops unlink the swatch");
}
}
+7
View File
@@ -977,6 +977,13 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
Ok(relinked)
})?;
relink.defaults(s)?;
if to != name && !s.previewing {
let uid = s.doc()?.uid;
if s.swatch_renames.len() == crate::MAX_SWATCH_RENAMES {
s.swatch_renames.remove(0);
}
s.swatch_renames.push((uid, name, to.clone()));
}
Ok(json!({"name": to, "relinked": relinked}))
}
+6
View File
@@ -54,6 +54,9 @@ pub use vectorcraft_tools as tools;
pub use vectorcraft_doc::MAX_COORD;
const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap");
/// The maximum number of newest swatch renames a session keeps until they are taken.
pub(crate) const MAX_SWATCH_RENAMES: usize = 64;
pub struct Session {
docs: Vec<DocState>,
active: Option<usize>,
@@ -309,6 +312,9 @@ pub struct Session {
/// appearance: the documents ([`DocState::uid`]) whose newest history step takes the colors the
/// command finally left.
pub(crate) batch_paint_docs: Vec<u64>,
/// Committed swatch renames as (document uid, old name, new name), in execution order until taken by the frontend.
/// The uid is [`DocState::uid`]; the record is never saved in documents or history.
pub(crate) swatch_renames: Vec<(u64, String, String)>,
/// The composite fonts (lowercase names) that the open documents defined when the font
/// database was last brought in step with them ([`cmd::compositefonts::sync`]).
pub(crate) composite_names: Vec<String>,
+1
View File
@@ -138,6 +138,7 @@ impl Session {
batch_stash: None,
batch_steps: None,
batch_paint_docs: Vec::new(),
swatch_renames: Vec::new(),
composite_names: Vec::new(),
composite_names_registered: HashSet::new(),
reading: false,
+6
View File
@@ -5,6 +5,12 @@ use super::{
use crate::doc_state::{kept_from, objects_only};
impl Session {
/// Takes committed swatch renames as (document uid, old name, new name) in execution order and leaves the record empty.
/// The uid identifies the originating document through [`crate::DocState::uid`].
pub fn take_swatch_renames(&mut self) -> Vec<(u64, String, String)> {
std::mem::take(&mut self.swatch_renames)
}
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
/// undo step labelled `label`; inside one it just mutates (the interaction commits later).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
+58
View File
@@ -989,6 +989,64 @@ fn linked(hex: &str, name: &str) -> Paint {
Paint::Solid { color: Color::from_hex(hex).unwrap(), swatch: Some(name.into()), tint: 1.0 }
}
#[test]
fn swatch_edits_record_only_renames_and_taking_empties_the_record() {
let mut s = session();
let uid = s.active().unwrap().uid;
run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"}));
run(&mut s, "swatch.edit", json!({"name": "Teal", "color": "#009090"}));
assert!(s.take_swatch_renames().is_empty());
run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Renamed teal"}));
assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Renamed teal".to_owned())]);
assert!(s.take_swatch_renames().is_empty());
}
#[test]
fn failed_batches_restore_pending_swatch_renames_after_eviction() {
let mut s = session();
let uid = s.active().unwrap().uid;
run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"}));
run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Ink 0 letter"}));
let mut commands = Vec::new();
for i in 0..=MAX_SWATCH_RENAMES {
commands.push(json!({"command": "swatch.edit", "params": {"name": format!("Ink {i} letter"), "newName": format!("Ink {} letter", i + 1)}}));
}
commands.push(json!({"command": "command.batch", "params": {"commands": []}}));
assert!(s.execute("command.batch", &json!({"commands": commands})).is_err());
assert!(doc(&s).swatch("Ink 0 letter").is_some());
assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Ink 0 letter".to_owned())]);
commands.pop();
run(&mut s, "command.batch", json!({"commands": commands}));
let renames = s.take_swatch_renames();
let expected: Vec<_> = (1..=MAX_SWATCH_RENAMES).map(|i| (uid, format!("Ink {i} letter"), format!("Ink {} letter", i + 1))).collect();
assert_eq!(renames, expected, "only the newest renames remain, in order");
}
#[test]
fn swatch_rename_previews_leave_no_record_and_confirmation_records_once() {
let mut s = session();
let uid = s.active().unwrap().uid;
run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"}));
s.begin_interaction("Swatch Options").unwrap();
for name in ["Preview teal", "Replacement teal"] {
s.preview("swatch.edit", &json!({"name": "Teal", "newName": name})).unwrap();
assert!(doc(&s).swatch(name).is_some());
assert!(s.take_swatch_renames().is_empty());
}
s.cancel_interaction().unwrap();
assert!(doc(&s).swatch("Teal").is_some());
assert!(s.take_swatch_renames().is_empty());
// Swatch Options cancels its preview and runs the confirmed edit again.
s.begin_interaction("Swatch Options").unwrap();
s.preview("swatch.edit", &json!({"name": "Teal", "newName": "Renamed teal"})).unwrap();
assert!(s.take_swatch_renames().is_empty());
s.cancel_interaction().unwrap();
run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Renamed teal"}));
assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Renamed teal".to_owned())]);
assert!(s.take_swatch_renames().is_empty());
}
#[test]
fn editing_a_global_swatch_recolours_linked_art_in_one_step() {
let mut s = session();
+3
View File
@@ -97,6 +97,9 @@ impl VectorcraftApp {
crate::plugin_runs::show_notice(self, id, r);
}
placing::settle_swatch_paste(self);
for (uid, from, to) in self.session.take_swatch_renames() {
dialogs::gradient_stop::follow_swatch_rename(self, uid, &from, &to);
}
result
}
+501 -18
View File
@@ -105,6 +105,22 @@ impl TargetKey {
}
}
/// The swatch last picked in the Swatches view and the stop or point it is picked for.
#[derive(Clone)]
struct PickedSwatch {
target: TargetKey,
name: String,
}
impl PickedSwatch {
/// The active document's swatch `name`, picked for `target`.
fn of(app: &VectorcraftApp, target: &Target, name: &str) -> Option<Self> {
let key = TargetKey::of(app, target)?;
app.session.active()?.doc.swatch(name)?;
Some(Self { target: key, name: name.to_owned() })
}
}
/// A Color mode command from the popover's menu that has not been seen to finish.
struct OwnMode {
/// The document's history step when it ran.
@@ -262,11 +278,42 @@ fn recolor(mut stops: Vec<GradientStop>, i: usize, color: Color, link: Option<(S
stops
}
/// Solid colours of the document's swatches (groups included), with their names.
fn swatch_colors(app: &VectorcraftApp) -> Vec<(String, Color)> {
let Some(st) = app.session.active() else { return vec![] };
let d = &st.doc;
d.swatches.iter().chain(d.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter_map(|s| Some((s.name.clone(), s.paint.color()?))).collect()
/// Solid colors of the document's swatches (groups included), with their names, and the entry the target's color
/// comes from: a linked color's tint swatch for that tint, or its global swatch at 100%; an unlinked color's process
/// swatch of that very color. Where several entries qualify, `picked`, the swatch last picked in the popover for this
/// target, is the one.
fn swatch_colors(app: &VectorcraftApp, target: &Target, picked: Option<&PickedSwatch>) -> (Vec<(String, Color)>, Option<usize>) {
let Some(st) = app.session.active() else { return (vec![], None) };
let picked = picked.filter(|p| p.target.matches(app, target));
let (link, color) = match target {
Target::Stop(paint, i) => {
let stop = &paint.gradient.stops[*i];
(stop.swatch.as_deref().map(|base| (base, stop.tint)), stop.color)
}
Target::Point(_, point, _) => (None, point.color),
};
let mut colors = Vec::new();
let mut selected = None;
for swatch in st.doc.swatches_iter() {
let is_picked = picked.is_some_and(|p| p.name == swatch.name);
let Some(own) = swatch.paint.color() else { continue };
// Picking this swatch would give the target the color and link it has now.
let source = match (link, swatch.tint_of()) {
(Some((base, tint)), Some((of, own_tint))) => of == base && same_tint(tint, own_tint),
(Some((base, tint)), None) => swatch.global && swatch.name == base && same_tint(tint, 1.0),
(None, _) => !swatch.global && matches!(swatch.paint, Paint::Solid { color: c, swatch: None, .. } if c == color),
};
if source && (selected.is_none() || is_picked) {
selected = Some(colors.len());
}
colors.push((swatch.name.clone(), own));
}
(colors, selected)
}
/// Whether two tints are the same: stop commands carry a tint as a floating-point percentage.
fn same_tint(first: f32, second: f32) -> bool {
(first - second).abs() <= 2.0 * f32::EPSILON
}
/// The popover's two views.
@@ -317,6 +364,10 @@ struct Feed {
/// Percent: the stop's location or the point's spread.
amount: f64,
swatches: Vec<(String, Color)>,
/// The entry of `swatches` the target's color comes from.
selected_swatch: Option<usize>,
/// Picking the displayed swatch changes at least one edited paint.
displayed_swatch_changes_paints: bool,
/// `swatches` as the palette draws them, in the same order.
tiles: Vec<(Label, Srgba)>,
shown: ColorPanelShown,
@@ -327,6 +378,8 @@ struct Feed {
struct Filed {
fields: PopoverFields,
swatch: Option<(String, Color)>,
/// Whether the pending swatch pick applies paint.
swatch_changes_paints: bool,
eyedropper: bool,
panels: Vec<ColorPanelOutput>,
/// Only an actual Shift-cycle changes this; an unchanged local snapshot must not overwrite a menu command.
@@ -346,6 +399,8 @@ pub(crate) struct GradientStopPopover {
at: Pos2,
panel: ColorPanelState,
feed: Option<Feed>,
/// The swatch last picked in the Swatches view and the stop or point it was picked for.
picked_swatch: Option<PickedSwatch>,
/// The fields set from outside, applied at confirm.
set: PopoverFields,
filed: Filed,
@@ -363,6 +418,7 @@ impl GradientStopPopover {
at: Pos2::ZERO,
panel: ColorPanelState::default(),
feed: None,
picked_swatch: None,
set: PopoverFields::default(),
filed: Filed::default(),
own_mode: None,
@@ -522,11 +578,18 @@ fn swatches(ui: &mut Ui, feed: &Feed, filed: &mut Filed) {
Notice::new(Tone::Info, tl!("The document has no colour swatches.").to_owned()).show(ui);
return;
}
let shown = SwatchPalette::new("Swatches", Bind::given(feed.current), &feed.tiles).show(ui);
let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()) else { return };
// The first swatch of that colour: the palette reports colours, not cells.
let at = feed.tiles.iter().position(|(_, c)| c.to_rgba() == picked.to_rgba());
filed.swatch = at.and_then(|i| feed.swatches.get(i)).cloned();
// Only the entry the target's color comes from is selected, and none when no entry is: a swatch that only draws
// the same color, such as a spot ink an unlinked stop has the color of, is not.
let shown =
SwatchPalette::new("Swatches", Bind::given(feed.current), &feed.tiles).selected_swatch(feed.selected_swatch).select_by_color(false).show(ui);
// Every click remembers the pick. The displayed swatch applies only when an edited paint differs at this stop or point.
// Other swatches apply even when they have the same color.
if let Some(i) = shown.picked_swatch
&& let Some(swatch) = feed.swatches.get(i)
{
filed.swatch = Some(swatch.clone());
filed.swatch_changes_paints = feed.displayed_swatch_changes_paints || Some(i) != feed.selected_swatch;
}
}
/// A percent field named `label` over `value`; the number the user entered in this pass, or the number a canceled
@@ -581,10 +644,11 @@ fn place(app: &VectorcraftApp, ctx: &egui::Context, anchor: Anchor) -> Pos2 {
}
}
/// `target`'s values, the document's swatches and what the Color panel shows, for the popover's body.
fn feed(app: &VectorcraftApp, target: &Target) -> Feed {
/// `target`'s values, the document's swatches with the one `picked` for it selected, and what the Color panel shows,
/// for the popover's body.
fn feed(app: &VectorcraftApp, target: &Target, picked: Option<&PickedSwatch>) -> Feed {
let shown = crate::panels::color::shown(app, &crate::panels::color::target_now(app));
let swatches = swatch_colors(app);
let (swatches, selected_swatch) = swatch_colors(app, target, picked);
Feed {
point: matches!(target, Target::Point(..)),
color: target.color(),
@@ -593,6 +657,19 @@ fn feed(app: &VectorcraftApp, target: &Target) -> Feed {
amount: f64::from(target.amount()) * 100.0,
tiles: swatches.iter().map(|(name, c)| (Label::from(name.clone()), Srgba::from(c32(c)))).collect(),
swatches,
selected_swatch,
displayed_swatch_changes_paints: app.session.gradient_edit_paints(!app.session.fill_active).map_or(true, |paints| {
!paints.all_paints_match(|paint| {
let Paint::Gradient(paint) = paint else { return false };
match target {
Target::Stop(shown, i) => paint.gradient.stops.get(*i).is_some_and(|stop| {
let shown = &shown.gradient.stops[*i];
stop.swatch == shown.swatch && stop.tint == shown.tint && stop.color == shown.color
}),
Target::Point(_, shown, i) => shown_points(paint).points.get(*i).is_some_and(|point| point.color == shown.color),
}
})
}),
shown,
}
}
@@ -600,8 +677,12 @@ fn feed(app: &VectorcraftApp, target: &Target) -> Feed {
/// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`.
fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) {
let Some(dialogs) = app.dialogs() else { return };
let Some(anchor) = dialogs.with(|host| host.get_by_id::<GradientStopPopover>(id).map(|popover| popover.anchor)) else { return };
let feed = feed(app, target);
let Some((anchor, picked)) =
dialogs.with(|host| host.get_by_id::<GradientStopPopover>(id).map(|popover| (popover.anchor, popover.picked_swatch.clone())))
else {
return;
};
let feed = feed(app, target, picked.as_ref());
let at = place(app, ctx, anchor);
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id) {
@@ -613,6 +694,23 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar
});
}
/// After the swatch `from` of the document `uid` was renamed `to`, the open popover's remembered pick takes the new name
/// when it is that swatch, picked for the selected stop or point.
pub(crate) fn follow_swatch_rename(app: &VectorcraftApp, uid: u64, from: &str, to: &str) {
let Some(target) = selected(app) else { return };
let Some(dialogs) = app.dialogs() else { return };
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND))
&& let Some(picked) = &mut popover.picked_swatch
&& picked.target.document.0 == uid
&& picked.target.matches(app, &target)
&& picked.name == from
{
picked.name = to.to_owned();
}
});
}
/// Opens the popover on the selected stop (a freeform gradient's selected point) of the active gradient, the stop
/// at `index` when it is not the selected one. Nothing opens without a window or a stop to edit.
pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) {
@@ -640,6 +738,9 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) {
/// Once per frame: applies what the user did in the popover and its confirmed answer, closes it when its stop or
/// point goes away, and pushes the target's values for the next frame. One line of `dialogs::host::pump`.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
for (uid, from, to) in app.session.take_swatch_renames() {
follow_swatch_rename(app, uid, &from, &to);
}
let Some(dialogs) = app.dialogs() else { return };
let id = dialog_id(KIND);
match dialogs.with(|host| host.take_by_id::<GradientStopPopover>(id)) {
@@ -697,13 +798,31 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
&& !owner.key.point
&& let Some(index) = app.session.selected_stop()
{
// The stop can cross its neighbor when its location changes.
// The stop can cross its neighbor when its location changes. A swatch picked for it moves with it.
let moved = owner.key.clone();
owner.key.index = index;
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id)
&& let Some(picked) = &mut popover.picked_swatch
&& picked.target == moved
{
picked.target.index = index;
}
});
}
if let Some((name, color)) = filed.swatch
&& let Some(target) = selected(app)
{
pick_swatch(app, &target, &name, color);
if filed.swatch_changes_paints {
pick_swatch(app, &target, &name, color);
}
// Swatches of one color draw alike: the Swatches view shows the one picked, not the first of them.
let picked = selected(app).and_then(|target| PickedSwatch::of(app, &target, &name));
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id) {
popover.picked_swatch = picked;
}
});
}
for output in &filed.panels {
// PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision).
@@ -866,6 +985,370 @@ mod tests {
}
}
/// The popover over `app`, drawn and pumped each frame, open on stop 1 at its Swatches view.
fn swatches_view(app: VectorcraftApp) -> crate::tests::panel_harness::Panel {
let mut panel = crate::tests::panel_harness::Panel::new(app, |app, ui| {
app.dialogs().unwrap().with(|host| host.run(ui));
host::pump(app, ui.ctx());
});
// The popover opens on the fixture's window, which the panel made the app's.
open_popover(&mut panel.app());
set(&panel.app(), "tab", json!("swatches")).unwrap();
panel.frame();
panel
}
#[test]
fn picking_one_of_two_spot_colors_of_one_color_links_the_stop_to_that_one() {
let mut app = app();
for name in ["First green ink", "Second green ink"] {
app.run("swatch.new", json!({"name": name, "color": "#00ff00", "spot": true})).unwrap();
}
let target = selected(&app).unwrap();
pick_swatch(&mut app, &target, "First green ink", Color::from_hex("#00ff00").unwrap());
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First green ink"));
panel.click("Second green ink");
assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Second green ink"));
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second green ink"), "the view shows the swatch picked");
panel.app().run("swatch.edit", json!({"name": "Second green ink", "color": "#123456"})).unwrap();
assert_eq!(stops(&panel.app())[1].color.to_hex(), "#123456", "the stop follows the swatch it was given");
}
/// The swatch the open popover's Swatches view shows as the target's, after two fresh frames: the first one's pump
/// feeds the view an edit made outside it, and the second draws that feed. The view draws that swatch's cell
/// selected and no other, and no cell selected when it shows none.
fn shown_swatch(panel: &mut crate::tests::panel_harness::Panel) -> Option<String> {
panel.frame();
panel.frame();
let (names, shown) = panel.app().dialogs().unwrap().with(|host| {
let feed = host.get_by_id::<GradientStopPopover>(dialog_id(KIND)).and_then(|popover| popover.feed.as_ref()).expect("the view's feed");
let shown = feed.selected_swatch.and_then(|i| feed.swatches.get(i)).map(|(name, _)| name.clone());
(feed.swatches.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(), shown)
});
let drawn: Vec<String> =
names.into_iter().filter(|name| panel.selected_role(name, craft::ui::contract::Role::LIST_BOX_OPTION) == Some(true)).collect();
assert_eq!(drawn, shown.iter().cloned().collect::<Vec<_>>(), "the cells the view draws selected");
shown
}
#[test]
fn the_swatches_view_shows_the_process_swatch_picked_among_two_of_one_color() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel), None, "the stop's green is no swatch's");
panel.click("Second teal");
assert_eq!(stops(&panel.app())[1].color.to_hex(), "#008080");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
let undo = panel.app().session.active().unwrap().history.undo.len();
panel.click("First teal");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"));
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "the same color again is no edit");
}
#[test]
fn the_swatches_view_remembers_a_pick_of_the_fallback_swatch_after_reordering() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
crate::panels::gradient::recolor_selected(&mut app, Color::from_hex("#008080").unwrap(), &json!({}));
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the first matching process swatch is the fallback");
let undo = panel.app().session.active().unwrap().history.undo.len();
panel.click("First teal");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "the displayed swatch changes no paint");
let first = panel.app().session.active().unwrap().doc.swatches_iter().position(|s| s.name == "First teal").unwrap();
panel.app().run("swatch.move", json!({"name": "Second teal", "to": first})).unwrap();
assert_eq!(
shown_swatch(&mut panel).as_deref(),
Some("First teal"),
"the explicit pick stays selected after the other swatch moves before it"
);
}
#[test]
fn the_swatches_view_keeps_the_picked_process_swatch_through_a_rename() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
panel.click("Second teal");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
panel.app().run("swatch.edit", json!({"name": "Second teal", "newName": "Renamed teal"})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal"), "the renamed swatch stays the one shown");
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "Undo of the rename falls back to the first qualifying swatch");
panel.click("Second teal");
panel.app().run("swatch.edit", json!({"name": "First teal", "newName": "Other teal"})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "a rename of the other swatch moves nothing");
let first = panel.app().session.active().unwrap().doc.swatches_iter().position(|s| s.name == "Other teal").unwrap();
panel.app().run("swatch.move", json!({"name": "Second teal", "to": first})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "the picked swatch moved before the other stays the one shown");
}
#[test]
fn the_swatches_view_keeps_the_picked_swatch_when_the_popover_moves_its_stop_past_a_neighbor() {
let mut app = app();
let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#008080"}, {"offset": 0.7, "color": "#000000"}]);
app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [100, 150], "end": [200, 150]}})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
panel.click("Second teal");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
panel.app().dialogs().unwrap().with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).expect("the popover").filed.fields.location = Some(90.0);
});
panel.frame();
assert_eq!(panel.app().session.selected_stop(), Some(2), "the stop crossed its neighbor");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "the pick moved with its stop");
}
#[test]
fn the_swatches_view_keeps_the_picked_swatch_through_a_rename_in_a_batch() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
panel.click("Second teal");
panel
.app()
.run("command.batch", json!({"commands": [{"command": "swatch.edit", "params": {"name": "Second teal", "newName": "Renamed teal"}}]}))
.unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal"));
}
#[test]
fn the_swatches_view_keeps_the_pick_when_a_batch_renames_a_swatch_in_another_document() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
app.run("document.activate", json!({"index": 0})).unwrap();
let mut panel = swatches_view(app);
panel.click("Second teal");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
panel
.app()
.run(
"command.batch",
json!({"commands": [
{"command": "document.activate", "params": {"index": 1}},
{"command": "swatch.edit", "params": {"name": "Second teal", "newName": "Renamed teal"}},
{"command": "document.activate", "params": {"index": 0}}
]}),
)
.unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
assert!(panel.app().session.documents()[1].doc.swatch("Renamed teal").is_some());
}
#[test]
fn the_swatches_view_follows_renames_that_bypass_app_run() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
panel.click("Second teal");
panel.app().session.execute("swatch.edit", &json!({"name": "Second teal", "newName": "Renamed teal"})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal"));
}
#[test]
fn the_swatches_view_does_not_give_a_deleted_picked_swatch_to_its_neighbor() {
let mut app = app();
for name in ["First teal", "Second teal", "Third teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
panel.click("Second teal");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
panel.app().run("swatch.delete", json!({"name": "Second teal"})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the swatch after the deleted one is not taken for it");
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "Undo of the deletion shows the picked swatch again");
}
#[test]
fn the_swatches_view_does_not_give_a_deleted_picked_swatch_to_a_replacement() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
panel.click("Second teal");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
panel.app().run("swatch.delete", json!({"name": "Second teal"})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"));
panel.app().run("swatch.new", json!({"name": "New teal", "color": "#008080"})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "a new swatch in the deleted one's place is not taken for it");
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"));
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "Undo of the deletion shows the picked swatch again");
}
#[test]
fn the_swatches_view_does_not_follow_a_replacement_in_a_batch() {
let mut app = app();
for name in ["First teal", "Second teal"] {
app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap();
}
let mut panel = swatches_view(app);
panel.click("Second teal");
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"));
panel
.app()
.run(
"command.batch",
json!({"commands": [
{"command": "swatch.delete", "params": {"name": "Second teal"}},
{"command": "swatch.new", "params": {"name": "New teal", "color": "#008080"}}
]}),
)
.unwrap();
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the replacement does not inherit the pick");
}
#[test]
fn the_swatches_view_shows_the_tint_swatch_picked_among_two_of_one_tint() {
let mut app = app();
app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap();
let tints: Vec<String> =
(0..2).map(|_| app.run("swatch.new", json!({"swatch": "Green ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_owned()).collect();
assert_ne!(tints[0], tints[1]);
let mut panel = swatches_view(app);
panel.click(&tints[1]);
let stop = stops(&panel.app())[1].clone();
assert_eq!((stop.swatch.as_deref(), (stop.tint * 100.0).round()), (Some("Green ink"), 40.0));
assert_eq!(shown_swatch(&mut panel).as_deref(), Some(tints[1].as_str()));
panel.click(&tints[0]);
assert_eq!(shown_swatch(&mut panel).as_deref(), Some(tints[0].as_str()));
panel.click("Green ink");
assert_eq!(stops(&panel.app())[1].tint, 1.0);
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink"));
}
#[test]
fn a_spot_color_of_the_stop_color_links_the_stop_and_its_base_resets_a_tint() {
let mut app = app();
app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap();
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel), None, "the stop's green is not linked to the ink");
panel.click("Green ink");
assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Green ink"));
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink"));
// Two spot inks of the stop's green: the unlinked stop shows neither, and a pick links the stop to that one.
let mut app = self::app();
for name in ["First green ink", "Second green ink"] {
app.run("swatch.new", json!({"name": name, "color": "#00ff00", "spot": true})).unwrap();
}
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel), None, "the stop's green is linked to neither ink");
panel.click("Second green ink");
assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Second green ink"));
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second green ink"));
let mut app = self::app();
app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap();
crate::panels::gradient::recolor_selected(&mut app, Color::from_hex("#00ff00").unwrap(), &json!({"swatch": "Green ink", "tint": 40}));
assert_eq!((stops(&app)[1].tint * 100.0).round(), 40.0);
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel), None, "a 40% tint is not the ink at 100%");
panel.click("Green ink");
let stop = stops(&panel.app())[1].clone();
assert_eq!((stop.swatch.as_deref(), stop.tint), (Some("Green ink"), 1.0));
}
#[test]
fn picking_the_displayed_swatch_recolors_every_selected_objects_stop() {
let mut app = app();
let first = app.session.active().unwrap().selection.objects[0];
let mut second_stops = stops(&app);
second_stops[1].set_color(Color::from_hex("#0000ff").unwrap(), None);
let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"gradient": {"stops": vectorcraft_tools::params::stops_json(&second_stops)}})).unwrap();
app.run("swatch.new", json!({"name": "Stop green", "color": "#00ff00"})).unwrap();
app.run("select.set", json!({"ids": [first.0, second]})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Stop green"));
panel.click("Stop green");
let app = panel.app();
let st = app.session.active().unwrap();
for id in &st.selection.objects {
let Paint::Gradient(paint) = st.doc.node(*id).unwrap().appearance.paint_at(None, true).unwrap() else {
panic!("expected a gradient");
};
assert_eq!(paint.gradient.stops[1].color.to_hex(), "#00ff00");
}
assert_eq!(st.selection.objects.len(), 2);
}
#[test]
fn picking_the_displayed_swatch_keeps_every_selected_objects_gradient_swatch_link() {
let mut app = app();
let first = app.session.active().unwrap().selection.objects[0];
app.run("swatch.new", json!({"name": "Stop green", "color": stops(&app)[1].color.to_hex()})).unwrap();
let mut params = crate::panels::swatch_paint_params(&active_paint(&app));
params["name"] = json!("Linked gradient");
app.run("swatch.new", params).unwrap();
app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap();
let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap();
app.run("select.set", json!({"ids": [first.0, second]})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Stop green"));
let undo = panel.app().session.active().unwrap().history.undo.len();
panel.click("Stop green");
let app = panel.app();
let st = app.session.active().unwrap();
assert_eq!(st.selection.objects.len(), 2);
for id in &st.selection.objects {
let Paint::Gradient(paint) = st.doc.node(*id).unwrap().appearance.paint_at(None, true).unwrap() else {
panic!("expected a gradient");
};
assert_eq!(paint.swatch.as_deref(), Some("Linked gradient"));
}
assert_eq!(st.history.undo.len(), undo, "the displayed swatch changes no paint");
}
#[test]
fn picking_the_stop_swatch_again_keeps_the_gradient_swatch_link() {
let mut app = app();
app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap();
let green = Color::from_hex("#00ff00").unwrap();
let target = selected(&app).unwrap();
pick_swatch(&mut app, &target, "Green ink", green);
let mut params = crate::panels::swatch_paint_params(&active_paint(&app));
params["name"] = json!("Linked gradient");
app.run("swatch.new", params).unwrap();
app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = swatches_view(app);
assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink"));
panel.click("Green ink");
let Paint::Gradient(paint) = active_paint(&panel.app()) else { panic!("expected a gradient") };
assert_eq!(paint.swatch.as_deref(), Some("Linked gradient"));
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
}
#[test]
fn confirm_applies_colour_opacity_and_location() {
let mut app = app();
@@ -1259,7 +1742,7 @@ mod tests {
let mut fx = Fixture::new(move |ui| {
let mut app = app.borrow_mut();
let Some(target) = selected(&app) else { return };
let feed = feed(&app, &target);
let feed = feed(&app, &target, None);
let mut filed = Filed::default();
body(ui, &feed, &mut tab, &mut panel, &mut filed);
for output in &filed.panels {
+2 -3
View File
@@ -1058,9 +1058,8 @@ pub(crate) fn recent_colors(app: &VectorcraftApp, ui: &mut Ui) -> Option<Color>
.spacing(SwatchSpacing::Spaced)
.drag_payload(move |drag: &ListDrag<usize>| dragged.get(drag.grabbed).map(|c| PanelDrag::paint(Paint::solid(*c))))
.show(ui);
// The palette reports the cell's sRGB; the stored colour keeps its own model.
let rgba = out.edit?.value()?.to_rgba();
stored.into_iter().zip(&cells).find(|(_, (_, cell))| cell.to_rgba() == rgba).map(|(c, _)| c)
// The stored color of the cell clicked, in its own model: colors in two models can draw alike.
out.picked_swatch.and_then(|i| stored.get(i).copied())
}
/// A colour as command JSON, keeping its model.
@@ -1123,6 +1123,25 @@ fn a_color_alt_dropped_on_registration_becomes_a_new_swatch() {
assert_eq!(d.swatch(REGISTRATION).map(|w| w.paint.clone()), registration, "Registration is unchanged");
}
/// Of two Recent Colors chips that draw the same color, the one clicked paints the art, in its own model.
#[test]
fn a_recent_color_chip_paints_its_own_color_when_another_chip_draws_the_same() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let mut app = app();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"ids": [id], "color": {"c": 10, "m": 60, "y": 20, "k": 5}, "keepModel": true})).unwrap();
let cmyk = app.session.recent_colors[0];
let hex = cmyk.to_hex();
app.run("paint.setFill", json!({"ids": [id], "color": hex})).unwrap();
assert_eq!(app.session.recent_colors[..2], [Color::from_hex(&hex).unwrap(), cmyk], "two chips of one drawn color");
app.run("select.set", json!({"ids": [id]})).unwrap();
let mut panel = Panel::new(app, show);
panel.click_role_nth(&hex, Role::LIST_BOX_OPTION, 1);
assert_eq!(fill_of(&panel.app(), vectorcraft_doc::NodeId(id)), Some(Paint::solid(cmyk)), "the second chip's CMYK color");
}
/// A rectangle filled with a CMYK color and then an RGB one, so Recent Colors holds the RGB color
/// first and the CMYK one second; → its id and the CMYK color.
fn art_with_two_recent_colors(app: &mut VectorcraftApp) -> (vectorcraft_doc::NodeId, Color) {
@@ -494,6 +494,12 @@ impl Panel {
self.fixture.tree().toggled_of(self.look(name).node)
}
/// The selected state of the control of `role` named `name`, where nodes of other roles share the name (a list
/// option beside its tooltip).
pub(crate) fn selected_role(&self, name: &str, role: craft::ui::contract::Role) -> Option<bool> {
self.fixture.tree().selected_of(self.look_role(name, role).node)
}
/// The kind of popup the control named `name` reports that it opens.
pub(crate) fn popup_kind(&self, name: &str) -> Option<craft::ui::contract::PopupKind> {
self.fixture.tree().has_popup_of(self.look(name).node)