Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Colour entry: panel number fields keep typed text; colours are read on a fixed scale

aionggd050223b7820
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index bd5e915de..ed150941a 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -141,7 +141,7 @@ impl Color {
let [r, g, b, _] = self.to_rgba8(1.0);
format!("#{r:02x}{g:02x}{b:02x}")
}
- /// Parse `#rgb`, `#rrggbb` or a few CSS names.
+ /// Parse `#rgb`, `#rrggbb` (the `#` optional, any case, spaces around) or a few CSS names.
pub fn from_hex(s: &str) -> Option<Self> {
let s = s.trim();
match s.to_ascii_lowercase().as_str() {
@@ -153,6 +153,10 @@ impl Color {
_ => {}
}
let h = s.strip_prefix('#').unwrap_or(s);
+ // `from_str_radix` takes a sign: "+f+f+f" is not a colour.
+ if !h.bytes().all(|b| b.is_ascii_hexdigit()) {
+ return None;
+ }
let p = |i: usize, n: usize| u8::from_str_radix(h.get(i..i + n)?, 16).ok();
match h.len() {
3 => Some(Color::rgb8(p(0, 1)? * 17, p(1, 1)? * 17, p(2, 1)? * 17)),
@@ -244,6 +248,13 @@ mod tests {
assert_eq!(c.to_hex(), "#ff8000");
assert_eq!(Color::from_hex("#fff").unwrap().to_hex(), "#ffffff");
assert_eq!(Color::from_hex("zz"), None);
+ for typed in ["#F59019", "f59019", " #f59019 "] {
+ assert_eq!(Color::from_hex(typed).map(|c| c.to_hex()).as_deref(), Some("#f59019"), "{typed:?}");
+ }
+ assert_eq!(Color::from_hex("F59").map(|c| c.to_hex()).as_deref(), Some("#ff5599"));
+ for partial in ["#f5", "#f590", "#f5901", "#f590190", "+f+f+f", "#+1+2+3"] {
+ assert_eq!(Color::from_hex(partial), None, "{partial:?}");
+ }
}
#[test]
diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs
index 4bf69ec41..d5fe5b25e 100644
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Color Swatch…",
[],
None,
- "{name?, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b], spot?: bool}",
+ "{name?, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255)|{model: rgb|cmyk|gray, …}(0..1), spot?: bool}",
has_doc,
create_swatch
),
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Color",
[],
None,
- "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection",
+ "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255)|{model: rgb|cmyk|gray, r,g,b|c,m,y,k|k}(0..1), target?: fill|stroke, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection",
super::has_selection,
apply_color
),
@@ -720,6 +720,8 @@ pub fn parse_color(v: &Value) -> Option<designcraft_color::Color> {
use designcraft_color::Color;
match v {
Value::String(s) => Color::from_hex(s),
+ // `{model, …}` is the colour's own form (as `color.convert` takes it): fractions, never guessed.
+ Value::Object(o) if o.contains_key("model") => model_color(v),
// One scale per colour, not per component: {c: 0.7, y: 12.2} is C 0.7 %, Y 12.2 %. Only a colour whose
// components are all within 0..1 is read as fractions (the older form).
Value::Array(a) if a.len() >= 3 => {
@@ -737,6 +739,20 @@ pub fn parse_color(v: &Value) -> Option<designcraft_color::Color> {
}
}
+/// `{model: rgb|cmyk|gray, …}` with every component in 0..=1; anything else is not a colour.
+fn model_color(v: &Value) -> Option<designcraft_color::Color> {
+ use designcraft_color::Color;
+ let color: Color = serde_json::from_value(v.clone()).ok()?;
+ // A float's last bit (100.0 / 100.0 ≠ 1.0 after an f32 round trip) is not out of range.
+ let unit = |x: f32| x.is_finite() && (-1e-4..=1.0 + 1e-4).contains(&x);
+ let q = |x: f32| x.clamp(0.0, 1.0);
+ match color {
+ Color::Rgb { r, g, b } => [r, g, b].into_iter().all(unit).then(|| Color::rgb(q(r), q(g), q(b))),
+ Color::Cmyk { c, m, y, k } => [c, m, y, k].into_iter().all(unit).then(|| Color::cmyk(q(c), q(m), q(y), q(k))),
+ Color::Gray { k } => unit(k).then_some(Color::Gray { k: q(k) }),
+ }
+}
+
fn apply_object(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("style.object.apply", "missing name"))?.to_string();
let os = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad("style.object.apply", format!("no object style `{name}`")))?;
@@ -957,16 +973,28 @@ fn apply_color(s: &mut Session, p: &Value) -> Result<Value> {
let stroke = str_param(p, "target") == Some("stroke");
let ids = super::targets(s, p)?;
s.edit(|d, _| {
- // Reuse a swatch holding exactly this colour, else add an unnamed one.
+ // Reuse a swatch holding this colour to the precision its name shows (whole CMYK percents,
+ // 0-255 RGB), else add an unnamed one: values a fraction of a percent apart would otherwise
+ // add hidden "C=0 M=50 Y=100 K=0 2" twins.
+ let shown = value_name(color);
+ let process = |w: &&Swatch| match &w.value {
+ SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } => Some(*c),
+ _ => None,
+ };
let existing = d
.swatches
.iter()
- .find(|w| matches!(&w.value, SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } if *c == color))
+ .find(|w| process(w) == Some(color))
+ .or_else(|| {
+ d.swatches
+ .iter()
+ .find(|w| process(w).is_some_and(|c| std::mem::discriminant(&c) == std::mem::discriminant(&color) && value_name(c) == shown))
+ })
.map(|w| w.name.clone());
let name = match existing {
Some(n) => n,
None => {
- let name = Styles::unique_name(|n| d.swatch(n).is_some(), &value_name(color));
+ let name = Styles::unique_name(|n| d.swatch(n).is_some(), &shown);
d.swatches.push(Swatch {
name: name.clone(),
value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },
@@ -1215,6 +1243,51 @@ mod color_tests {
assert!((r - 1.0 / 255.0).abs() < 1e-6 && (g - 128.0 / 255.0).abs() < 1e-6 && (b - 1.0).abs() < 1e-6);
}
+ #[test]
+ fn a_colour_with_a_model_is_read_as_fractions_without_guessing() {
+ use designcraft_color::Color;
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();
+ let fill = |s: &Session| {
+ let d = &s.doc().unwrap().doc;
+ d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap()
+ };
+ // M 1 % from the Color panel: not M 100 % (magenta), though every component is within 0..1.
+ s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0, "m": 0.01, "y": 0, "k": 0}})).unwrap();
+ let Color::Cmyk { c, m, y, k } = fill(&s) else { panic!("not CMYK") };
+ assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && y == 0.0 && k == 0.0, "got {c} {m} {y} {k}");
+ // R 1 of 255 is a near black, not pure red.
+ s.execute("object.color", &json!({"color": {"model": "rgb", "r": 1.0 / 255.0, "g": 0, "b": 0}})).unwrap();
+ let Color::Rgb { r, g, b } = fill(&s) else { panic!("not RGB") };
+ assert!((r - 1.0 / 255.0).abs() < 1e-6 && g == 0.0 && b == 0.0, "got {r} {g} {b}");
+ // Out of range or not a model: refused rather than guessed.
+ assert!(s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0, "m": 50, "y": 0, "k": 0}})).is_err());
+ assert!(s.execute("object.color", &json!({"color": {"model": "hsb", "h": 0, "s": 0, "b": 0}})).is_err());
+ }
+
+ #[test]
+ fn colours_that_round_to_the_same_name_share_one_swatch() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();
+ let n = |s: &Session| s.doc().unwrap().doc.swatches.len();
+ let first = s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0.1, "m": 0.5, "y": 1, "k": 0}})).unwrap();
+ let before = n(&s);
+ for m in [0.501, 0.499, 0.5041] {
+ let r = s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0.1, "m": m, "y": 1, "k": 0}})).unwrap();
+ assert_eq!(r["swatch"], first["swatch"], "M {m}");
+ }
+ s.execute("object.color", &json!({"color": {"model": "rgb", "r": 0.5, "g": 0.25, "b": 0}})).unwrap();
+ s.execute("object.color", &json!({"color": {"model": "rgb", "r": 0.5005, "g": 0.25, "b": 0}})).unwrap();
+ assert_eq!(n(&s), before + 1, "no hidden twins for values a fraction of a step apart");
+ // A whole percent apart is a different colour.
+ let r = s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0.1, "m": 0.51, "y": 1, "k": 0}})).unwrap();
+ assert_eq!(r["swatch"], "C=10 M=51 Y=100 K=0");
+ }
+
#[test]
fn style_groups_rename_every_use() {
let mut s = Session::new();
diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs
index 1aa11ddb3..eb8ac649a 100644
--- a/crates/ui-egui/src/panels/swatches.rs
+++ b/crates/ui-egui/src/panels/swatches.rs
@@ -287,7 +287,7 @@ pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
done |= channel(ui, label, &mut v[k], 100.0, "%", |x| cmyk_ramp(k, x));
}
if done {
- send = Some(json!({"c": v[0] * 100.0, "m": v[1] * 100.0, "y": v[2] * 100.0, "k": v[3] * 100.0}));
+ send = Some(json!({"model": "cmyk", "c": v[0], "m": v[1], "y": v[2], "k": v[3]}));
}
}
ColorMode::Rgb => {
@@ -301,7 +301,7 @@ pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
});
}
if done {
- send = Some(json!([(v[0] * 255.0).round(), (v[1] * 255.0).round(), (v[2] * 255.0).round()]));
+ send = Some(json!({"model": "rgb", "r": v[0], "g": v[1], "b": v[2]}));
}
}
ColorMode::Lab => {
@@ -347,12 +347,20 @@ fn channel(ui: &mut egui::Ui, label: &str, v: &mut f32, scale: f32, suffix: &str
*v = ((p.x - track.min.x) / track.width()).clamp(0.0, 1.0);
}
changed |= resp.drag_stopped() || resp.clicked();
- let mut num = (*v * scale).round();
- let field = ui.add(egui::DragValue::new(&mut num).range(0.0..=scale).suffix(suffix));
- if field.changed() {
- *v = num / scale;
+ // The value is applied when typing ends or a drag stops; until then the field's number
+ // lives here, because `v` is read back from the document every frame.
+ let pending_id = ui.id().with(("channel", label));
+ let mut num = ui.data(|d| d.get_temp::<f32>(pending_id)).unwrap_or((*v * scale).round());
+ let field = ui.add(egui::DragValue::new(&mut num).range(0.0..=scale).suffix(suffix).update_while_editing(false));
+ if field.dragged() {
+ ui.data_mut(|d| d.insert_temp(pending_id, num));
+ } else {
+ ui.data_mut(|d| d.remove::<f32>(pending_id));
+ if field.changed() || field.drag_stopped() {
+ *v = num / scale;
+ changed = true;
+ }
}
- changed |= field.lost_focus() || field.drag_stopped();
});
changed
}
@@ -386,7 +394,8 @@ fn spectrum(app: &mut DesignApp, ui: &mut egui::Ui, target: &str) {
&& let Some(p) = resp.interact_pointer_pos()
{
let c = at(((p.x - r.min.x) / r.width()).clamp(0.0, 1.0), ((p.y - r.min.y) / r.height()).clamp(0.0, 1.0));
- let _ = app.run("object.color", json!({"color": [(c[0] * 255.0).round(), (c[1] * 255.0).round(), (c[2] * 255.0).round()], "target": target}));
+ let q = |v: f32| (v * 255.0).round() / 255.0;
+ let _ = app.run("object.color", json!({"color": {"model": "rgb", "r": q(c[0]), "g": q(c[1]), "b": q(c[2])}, "target": target}));
}
}
@@ -573,3 +582,49 @@ pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
});
}
}
+
+#[cfg(test)]
+mod color_panel_tests {
+ use egui::vec2;
+ use egui_kittest::Harness;
+ use egui_kittest::kittest::Queryable;
+ use serde_json::json;
+
+ use crate::DesignApp;
+
+ fn fill(app: &DesignApp, id: u64) -> designcraft_color::Color {
+ let d = &app.session.active().unwrap().doc;
+ d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap()
+ }
+
+ /// A number typed into the M field stays while typing and applies as a percent on Enter:
+ /// M 1 is 1 %, not 100 %.
+ #[test]
+ fn a_typed_channel_value_is_kept_and_applied_as_a_percent() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let id = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();
+ app.run("selection.set", json!({"ids": [id]})).unwrap();
+ app.run("object.color", json!({"color": {"c": 0, "m": 50, "y": 100, "k": 0}})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(320.0, 300.0)).build_ui_state(|ui, app: &mut DesignApp| super::color_panel(app, ui), app);
+ h.run_steps(3);
+ let fields: Vec<egui::Rect> = h.query_all_by(|n| n.role() == egui::accesskit::Role::SpinButton).map(|n| n.rect()).collect();
+ assert_eq!(fields.len(), 4, "C, M, Y and K fields");
+ let m = fields[1].center();
+ h.hover_at(m);
+ h.drag_at(m);
+ h.drop_at(m);
+ h.run_steps(2);
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
+ h.event(egui::Event::Text("1".into()));
+ h.run_steps(4);
+ let typed = h.query_by(|n| n.role() == egui::accesskit::Role::SpinButton && n.is_focused()).and_then(|n| n.value());
+ assert_eq!(typed.as_deref(), Some("1"), "the typed text stays while the field has focus");
+ let designcraft_color::Color::Cmyk { m, .. } = fill(h.state(), id) else { panic!("not CMYK") };
+ assert!((m - 0.5).abs() < 1e-6, "nothing is applied while typing: {m}");
+ h.key_press(egui::Key::Enter);
+ h.run_steps(2);
+ let designcraft_color::Color::Cmyk { c, m, y, k } = fill(h.state(), id) else { panic!("not CMYK") };
+ assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && (y - 1.0).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");
+ }
+}