DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Swatches and layers: Swatch Options and Layer Options dialogs rename them
aionggbf8c3486f168
diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rsindex 42c30c3df..e47bf4eef 100644--- a/crates/color/src/swatch.rs+++ b/crates/color/src/swatch.rs@@ -90,6 +90,17 @@ pub fn cmyk_name(c: f32, m: f32, y: f32, k: f32) -> String {format!("C={} M={} Y={} K={}", p(c), p(m), p(y), p(k))}+/// The name Name with Color Value gives a colour: `C=100 M=0 Y=0 K=0`, or `R=16 G=128 B=128`.+pub fn value_name(c: Color) -> String {+ match c {+ Color::Cmyk { c, m, y, k } => cmyk_name(c, m, y, k),+ other => {+ let [r, g, b] = other.to_rgb();+ format!("R={} G={} B={}", (r * 255.0).round(), (g * 255.0).round(), (b * 255.0).round())+ }+ }+}+/// Resolve a swatch name + tint into a display colour. `None` for `[None]` or unknown names./// Gradients resolve to their first stop (callers that render gradients use [`resolve_gradient`]).pub fn resolve(swatches: &[Swatch], name: &str, tint: f32) -> Option<Color> {diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex c4b69e86d..6d4eab0b0 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -28,6 +28,7 @@ pub mod selection;mod slice;pub mod story;pub mod styles;+mod swatch_refs;pub mod table;pub mod vars;pub mod xref;diff --git a/crates/doc/src/swatch_refs.rs b/crates/doc/src/swatch_refs.rsnew file mode 100644index 000000000..617f2df3f--- /dev/null+++ b/crates/doc/src/swatch_refs.rs@@ -0,0 +1,214 @@+//! Renaming a swatch: every place the document names a swatch follows the new name.++use std::sync::Arc;++use designcraft_color::SwatchValue;++use crate::Document;+use crate::attrs::{CharAttrs, ParaAttrs};+use crate::item::{Fill, Item, Stroke, TextFrameOptions};+use crate::story::Story;+use crate::styles::{AltFillsAttrs, AltStrokesAttrs, CellStrokeAttrs};+use crate::table::{AltFills, AltStrokes, CellStroke, Table};++struct Names<'a> {+ from: &'a str,+ to: &'a str,+}++impl Names<'_> {+ fn s(&self, v: &mut String) {+ if v == self.from {+ *v = self.to.to_string();+ }+ }+ fn o(&self, v: &mut Option<String>) {+ if let Some(v) = v {+ self.s(v);+ }+ }+ fn fill(&self, f: &mut Fill) {+ self.s(&mut f.swatch);+ }+ fn stroke(&self, s: &mut Stroke) {+ self.s(&mut s.swatch);+ self.s(&mut s.gap_swatch);+ }+ fn frame(&self, o: &mut TextFrameOptions) {+ self.s(&mut o.column_rule_color);+ }+ fn chars(&self, c: &mut CharAttrs) {+ for v in [&mut c.fill, &mut c.stroke, &mut c.underline_color, &mut c.strikethrough_color] {+ self.o(v);+ }+ }+ fn para(&self, p: &mut ParaAttrs) {+ for r in [&mut p.rule_above, &mut p.rule_below].into_iter().flatten() {+ self.s(&mut r.color);+ }+ self.o(&mut p.shading_color);+ self.o(&mut p.border_color);+ }+ fn cell_stroke(&self, s: &mut CellStroke) {+ self.s(&mut s.color);+ }+ fn alt_fills(&self, f: &mut AltFills) {+ self.s(&mut f.first_color);+ self.s(&mut f.next_color);+ }+ fn alt_strokes(&self, s: &mut AltStrokes) {+ self.cell_stroke(&mut s.first_stroke);+ self.cell_stroke(&mut s.next_stroke);+ }+ fn stroke_attrs(&self, s: &mut CellStrokeAttrs) {+ self.o(&mut s.color);+ }+ fn alt_fill_attrs(&self, f: &mut AltFillsAttrs) {+ self.o(&mut f.first_color);+ self.o(&mut f.next_color);+ }+ fn alt_stroke_attrs(&self, s: &mut AltStrokesAttrs) {+ self.stroke_attrs(&mut s.first_stroke);+ self.stroke_attrs(&mut s.next_stroke);+ }+ /// An item and everything inside it (group members). Depth-bounded for hostile documents.+ fn item(&self, it: &mut Item, depth: u32) {+ if depth > 64 {+ return;+ }+ self.fill(&mut it.fill);+ self.stroke(&mut it.stroke);+ let e = &mut it.effects;+ for c in [&mut e.drop_shadow.color, &mut e.inner_shadow.color, &mut e.outer_glow.color, &mut e.inner_glow.color, &mut e.satin.color] {+ self.s(c);+ }+ if let Some(tf) = it.text_frame_mut() {+ self.frame(&mut tf.options);+ }+ if let Some(kids) = it.children_mut() {+ for k in kids {+ self.item(Arc::make_mut(k), depth + 1);+ }+ }+ }+ fn table(&self, t: &mut Table) {+ let o = &mut t.options;+ self.cell_stroke(&mut o.border);+ for b in o.borders.iter_mut().flatten() {+ self.cell_stroke(b);+ }+ for f in [&mut o.alt_rows, &mut o.alt_cols].into_iter().flatten() {+ self.alt_fills(f);+ }+ for s in [&mut o.row_strokes, &mut o.column_strokes].into_iter().flatten() {+ self.alt_strokes(s);+ }+ for c in &mut t.cells {+ self.s(&mut c.fill);+ for s in &mut c.strokes {+ self.cell_stroke(s);+ }+ }+ }+ /// One story's own text, objects and tables (cell and note text are visited separately).+ fn story(&self, st: &mut Story) {+ for f in &mut st.paras {+ self.para(&mut f.para);+ self.chars(&mut f.chars);+ }+ for r in &mut st.chars {+ self.chars(&mut r.format.over);+ }+ for o in &mut st.objects {+ self.item(&mut Arc::make_mut(o).item, 0);+ }+ for t in st.tables.values_mut() {+ self.table(Arc::make_mut(t));+ }+ st.rev += 1;+ }+}++impl Document {+ /// Point every reference to swatch `from` at `to`: tints based on it, colour groups, inks,+ /// styles, page items (fills, strokes, gaps, effects, column rules), text colours, rules,+ /// shading and borders, tables and the footnote rule. The swatch itself is renamed by the+ /// caller.+ pub fn rename_swatch_refs(&mut self, from: &str, to: &str) {+ if from == to {+ return;+ }+ let n = Names { from, to };+ for w in &mut self.swatches {+ if let SwatchValue::Tint { base, .. } = &mut w.value {+ n.s(base);+ }+ }+ for g in &mut self.color_groups {+ for w in &mut g.swatches {+ n.s(w);+ }+ }+ for w in &mut self.inks.to_process {+ n.s(w);+ }+ for (a, b) in &mut self.inks.aliases {+ n.s(a);+ n.s(b);+ }+ n.s(&mut self.footnote_options.rule.color);+ let styles = self.styles_mut();+ for p in &mut styles.paragraph {+ n.para(&mut p.para);+ n.chars(&mut p.chars);+ }+ for c in &mut styles.character {+ n.chars(&mut c.chars);+ }+ for o in &mut styles.object {+ if let Some(f) = &mut o.fill {+ n.fill(f);+ }+ if let Some(s) = &mut o.stroke {+ n.stroke(s);+ }+ if let Some(tf) = &mut o.text_frame {+ n.frame(tf);+ }+ }+ for c in &mut styles.cell {+ n.o(&mut c.fill);+ if let Some(s) = &mut c.stroke {+ n.cell_stroke(s);+ }+ for s in &mut c.strokes {+ n.stroke_attrs(s);+ }+ }+ for t in &mut styles.table {+ if let Some(b) = &mut t.border {+ n.cell_stroke(b);+ }+ for b in &mut t.borders {+ n.stroke_attrs(b);+ }+ if let Some(f) = &mut t.alt_rows {+ n.alt_fills(f);+ }+ n.alt_fill_attrs(&mut t.row_fills);+ n.alt_fill_attrs(&mut t.column_fills);+ n.alt_stroke_attrs(&mut t.row_strokes);+ n.alt_stroke_attrs(&mut t.column_strokes);+ }+ for sp in self.spreads.iter_mut().chain(self.parents.iter_mut()) {+ for it in &mut Arc::make_mut(sp).items {+ n.item(Arc::make_mut(it), 0);+ }+ }+ for sid in self.stories.keys().copied().collect::<Vec<_>>() {+ if let Some(story) = self.story_mut(sid) {+ story.for_each_text_mut(&mut |st| n.story(st));+ }+ }+ }+}diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rsindex bd5320799..189058a8e 100644--- a/crates/engine/src/cmd/layout.rs+++ b/crates/engine/src/cmd/layout.rs@@ -4,7 +4,7 @@ use designcraft_doc::{LAYER_COLORS, Layer, LayerId, Margins, SpreadId};use serde_json::{Value, json};use super::{CommandSpec, bad, cmd, has_doc, ok, str_param};-use crate::Result;+use crate::{Result, Session};/// Each page's margin box, by spread and page id.fn margin_boxes(d: &designcraft_doc::Document) -> Vec<(designcraft_doc::SpreadRef, designcraft_doc::PageId, designcraft_geom::Rect)> {@@ -475,29 +475,15 @@ pub fn specs() -> Vec<CommandSpec> {s.doc_mut()?.active_layer = r;Ok(json!({"id": r.0}))}),- cmd!("layer.set", "Layer Options…", [], None, "{id, name?, visible?, locked?, printable?, color?: [r,g,b]}", has_doc, |s, p| {- let id = LayerId(p.get("id").and_then(Value::as_u64).unwrap_or(0));- let p = p.clone();- s.edit(|d, _| {- let l = d.layer_mut(id).ok_or_else(|| bad("layer.set", "no such layer"))?;- if let Some(v) = p.get("name").and_then(Value::as_str) {- l.name = v.into();- }- if let Some(v) = p.get("visible").and_then(Value::as_bool) {- l.visible = v;- }- if let Some(v) = p.get("locked").and_then(Value::as_bool) {- l.locked = v;- }- if let Some(v) = p.get("printable").and_then(Value::as_bool) {- l.printable = v;- }- if let Some(c) = p.get("color").and_then(|c| serde_json::from_value(c.clone()).ok()) {- l.color = c;- }- ok()- })- }),+ cmd!(+ "layer.set",+ "Layer Options…",+ [],+ None,+ "{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, suppressWrapWhenHidden?} — names are unique and not empty",+ has_doc,+ set_layer+ ),cmd!("layer.delete", "Delete Layer", [], None, "{id}", has_doc, |s, p| {let id = LayerId(p.get("id").and_then(Value::as_u64).unwrap_or(0));s.edit(|d, sel| {@@ -708,6 +694,59 @@ fn document_setup(d: &designcraft_doc::Document) -> Value {"binding": if st.right_to_left_binding { "rightToLeft" } else { "leftToRight" }, "intent": st.intent, "bleed": st.bleed, "slug": st.slug})}+/// Layer Options: every field in one undo step; a bad name or colour changes nothing.+fn set_layer(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "layer.set";+ let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?);+ let name = match p.get("name") {+ Some(v) => Some(v.as_str().map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(ID, "a layer needs a name"))?.to_string()),+ None => None,+ };+ let color: Option<[u8; 3]> = match p.get("color") {+ None => None,+ Some(Value::String(n)) => Some(+ LAYER_COLORS+ .iter()+ .find(|(k, _)| k.eq_ignore_ascii_case(n))+ .map(|(_, c)| *c)+ .ok_or_else(|| bad(ID, format!("unknown layer colour `{n}`")))?,+ ),+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad(ID, "color is [r,g,b] (0–255) or a layer colour name"))?),+ };+ let flag = |k: &str| match p.get(k) {+ None => Ok(None),+ Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(ID, format!("`{k}` is true or false"))),+ };+ let (visible, locked, printable) = (flag("visible")?, flag("locked")?, flag("printable")?);+ let (guides, wrap) = (flag("showGuides")?, flag("suppressWrapWhenHidden")?);+ s.edit(|d, _| {+ if let Some(n) = &name+ && d.layers.iter().any(|l| l.id != id && l.name == *n)+ {+ return Err(bad(ID, format!("a layer named `{n}` exists")));+ }+ let l = d.layer_mut(id).ok_or_else(|| bad(ID, "no such layer"))?;+ if let Some(n) = name {+ l.name = n;+ }+ if let Some(c) = color {+ l.color = c;+ }+ for (slot, v) in [+ (&mut l.visible, visible),+ (&mut l.locked, locked),+ (&mut l.printable, printable),+ (&mut l.show_guides, guides),+ (&mut l.suppress_wrap_when_hidden, wrap),+ ] {+ if let Some(v) = v {+ *slot = v;+ }+ }+ ok()+ })+}+#[cfg(test)]mod setup_tests {use serde_json::json;@@ -921,3 +960,41 @@ mod adjust_tests {assert_eq!(b, b2);}}++#[cfg(test)]+mod layer_options_tests {+ use serde_json::json;++ #[test]+ fn layer_set_sets_every_field_and_rejects_bad_names() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let first = s.doc().unwrap().doc.layers[0].id.0;+ let id = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap();+ let all = json!({"id": id, "name": " Artwork ", "color": "Gold", "visible": false, "locked": true, "printable": false,+ "showGuides": false, "suppressWrapWhenHidden": true});+ s.execute("layer.set", &all).unwrap();+ let l = s.doc().unwrap().doc.layer(designcraft_doc::LayerId(id)).cloned().unwrap();+ assert_eq!(l.name, "Artwork");+ assert_eq!(l.color, [255, 153, 0]);+ assert!(!l.visible && l.locked && !l.printable && !l.show_guides && l.suppress_wrap_when_hidden);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.layer(designcraft_doc::LayerId(id)).unwrap().name, "Art", "one undo step");+ let first_name = s.doc().unwrap().doc.layers.iter().find(|l| l.id.0 == first).unwrap().name.clone();+ let before = s.doc().unwrap().doc.layers.clone();+ for p in [+ json!({"id": id, "name": ""}),+ json!({"id": id, "name": " "}),+ json!({"id": id, "name": first_name}),+ json!({"id": id, "name": "Fine", "color": "Plaid"}),+ json!({"id": id, "color": [300, 0, 0]}),+ json!({"id": id, "visible": "yes"}),+ json!({"id": 999_999, "name": "Ghost"}),+ ] {+ assert!(s.execute("layer.set", &p).is_err(), "{p}");+ }+ assert_eq!(s.doc().unwrap().doc.layers, before);+ // Keeping its own name is fine.+ s.execute("layer.set", &json!({"id": id, "name": "Art", "color": [1, 2, 3]})).unwrap();+ }+}diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rsindex 94bd92c6d..6f92c3b6a 100644--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@ -193,6 +193,15 @@ pub fn specs() -> Vec<CommandSpec> {has_doc,add_to_swatches),+ cmd!(+ "swatch.options",+ "Swatch Options…",+ [],+ None,+ "{name, to?: new name, nameWithValue?: bool, color?: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b]|{gray}(0..100), spot?: bool, tint?: 0–1 (tint swatches), base?: colour swatch (tint swatches)} → {name} — every use follows a rename; [None], [Registration], [Black] and [Paper] keep their names",+ has_doc,+ swatch_options+ ),cmd!("swatch.addUnnamed", "Add Unnamed Colors", [], None, "{} — every unnamed colour used becomes a swatch", has_doc, |s, _| {s.edit(|d, _| {let mut n = 0;@@ -689,13 +698,7 @@ fn create_swatch(s: &mut Session, p: &Value) -> Result<Value> {let c = p.get("color").ok_or_else(|| bad("swatch.create", "missing color"))?;let color = parse_color(c).ok_or_else(|| bad("swatch.create", "bad color"))?;let spot = p.get("spot").and_then(Value::as_bool).unwrap_or(false);- let name = str_param(p, "name").map(str::to_string).unwrap_or_else(|| match color {- designcraft_color::Color::Cmyk { c, m, y, k } => designcraft_color::swatch::cmyk_name(c, m, y, k),- other => {- let [r, g, b] = other.to_rgb();- format!("R={} G={} B={}", (r * 255.0).round(), (g * 255.0).round(), (b * 255.0).round())- }- });+ let name = str_param(p, "name").map(str::to_string).unwrap_or_else(|| value_name(color));s.edit(|d, _| {let name = Styles::unique_name(|n| d.swatch(n).is_some(), &name);d.swatches.push(Swatch {@@ -722,6 +725,9 @@ pub fn parse_color(v: &Value) -> Option<designcraft_color::Color> {}Value::Object(o) => {let g = |k: &str| o.get(k).and_then(Value::as_f64).map(|x| if x > 1.0 { x / 100.0 } else { x } as f32);+ if o.contains_key("gray") {+ return Some(Color::gray(g("gray")?));+ }Some(Color::cmyk(g("c")?, g("m")?, g("y")?, g("k")?))}_ => None,@@ -788,13 +794,7 @@ fn create_object(s: &mut Session, p: &Value) -> Result<Value> {/// The swatch name of a colour value ("C=… M=… Y=… K=…" / "R=… G=… B=…").fn value_name(color: designcraft_color::Color) -> String {- match color {- designcraft_color::Color::Cmyk { c, m, y, k } => designcraft_color::swatch::cmyk_name(c, m, y, k),- other => {- let [r, g, b] = other.to_rgb();- format!("R={} G={} B={}", (r * 255.0).round(), (g * 255.0).round(), (b * 255.0).round())- }- }+ designcraft_color::swatch::value_name(color)}fn load_swatches(s: &mut Session, p: &Value) -> Result<Value> {@@ -1003,39 +1003,111 @@ fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {let w = d.swatches.iter_mut().find(|w| w.name == name).ok_or_else(|| bad("swatch.addToSwatches", format!("no swatch `{name}`")))?;w.name = new.clone();w.named = true;- for g in &mut d.color_groups {- for w in &mut g.swatches {- if *w == name {- *w = new.clone();+ d.rename_swatch_refs(&name, &new);+ Ok(json!({"name": new}))+ })+}++/// Swatch Options: rename, Name with Color Value, colour type and value, a tint swatch's tint+/// and base — one undo step. Every use of the swatch follows a rename.+fn swatch_options(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "swatch.options";+ let name = str_param(p, "name").ok_or_else(|| bad(ID, "missing name"))?.to_string();+ let to = str_param(p, "to").map(|n| n.trim().to_string());+ let with_value = p.get("nameWithValue").and_then(Value::as_bool);+ let color = match p.get("color") {+ Some(c) => Some(parse_color(c).ok_or_else(|| bad(ID, "bad color"))?),+ None => None,+ };+ let spot = p.get("spot").and_then(Value::as_bool);+ let tint = match p.get("tint") {+ Some(v) => Some(v.as_f64().filter(|t| t.is_finite() && (0.0..=1.0).contains(t)).ok_or_else(|| bad(ID, "tint is 0–1"))? as f32),+ None => None,+ };+ let base = str_param(p, "base").map(str::to_string);+ s.edit(|d, _| {+ let w = d.swatch(&name).cloned().ok_or_else(|| bad(ID, format!("no swatch `{name}`")))?;+ let mut w2 = w.clone();+ if w.locked {+ if to.as_ref().is_some_and(|t| *t != name) || with_value == Some(true) {+ return Err(bad(ID, format!("`{name}` can't be renamed")));+ }+ match (&mut w2.value, color) {+ (_, None) => {}+ (SwatchValue::Paper { color: c }, Some(new)) => *c = new,+ _ => return Err(bad(ID, format!("`{name}` can't be edited"))),+ }+ if spot.is_some() || tint.is_some() || base.is_some() {+ return Err(bad(ID, format!("`{name}` can't be edited")));+ }+ } else {+ match &mut w2.value {+ SwatchValue::Color { color: c, color_type } => {+ if let Some(new) = color {+ *c = new;+ }+ if let Some(sp) = spot {+ *color_type = if sp { designcraft_color::ColorType::Spot } else { designcraft_color::ColorType::Process };+ }+ if tint.is_some() || base.is_some() {+ return Err(bad(ID, "only tint swatches have a tint"));+ }+ }+ SwatchValue::Tint { base: b, tint: t } => {+ if color.is_some() || spot.is_some() {+ return Err(bad(ID, "a tint swatch takes its colour from its base"));+ }+ if let Some(v) = tint {+ *t = v;+ }+ if let Some(nb) = &base {+ if !d.swatch(nb).is_some_and(|x| matches!(x.value, SwatchValue::Color { .. })) || *nb == name {+ return Err(bad(ID, format!("`{nb}` isn't a colour swatch")));+ }+ *b = nb.clone();+ }+ }+ _ => {+ if color.is_some() || spot.is_some() || tint.is_some() || base.is_some() {+ return Err(bad(ID, format!("`{name}` only takes a name here")));+ }}}- }- // Everything using the colour follows the rename.- for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) {- let sp = std::sync::Arc::make_mut(sp);- for top in &mut sp.items {- rename_in(std::sync::Arc::make_mut(top), &name, &new);+ // Name with Color Value: the name is the colour's values and tracks later edits.+ let auto = with_value.unwrap_or(!w.named && to.as_ref().is_none_or(|t| *t == name));+ let derived = match (&w2.value, auto) {+ (SwatchValue::Color { color, .. }, true) => Some(value_name(*color)),+ _ => None,+ };+ match derived {+ Some(n) => {+ w2.name = n;+ w2.named = false;+ }+ None => {+ if let Some(t) = &to {+ if t.is_empty() {+ return Err(bad(ID, "a swatch needs a name"));+ }+ w2.name = t.clone();+ }+ if with_value == Some(false) || w2.name != name {+ w2.named = true;+ }+ }+ }+ if w2.name != name && d.swatch(&w2.name).is_some() {+ return Err(bad(ID, format!("a swatch named `{}` exists", w2.name)));}}+ let new = w2.name.clone();+ let slot = d.swatches.iter_mut().find(|x| x.name == name).ok_or_else(|| bad(ID, format!("no swatch `{name}`")))?;+ *slot = w2;+ d.rename_swatch_refs(&name, &new);Ok(json!({"name": new}))})}-/// Point fills and strokes of an item (and its children) at a renamed swatch.-fn rename_in(it: &mut designcraft_doc::Item, from: &str, to: &str) {- if it.fill.swatch == from {- it.fill.swatch = to.to_string();- }- if it.stroke.swatch == from {- it.stroke.swatch = to.to_string();- }- if let Some(kids) = it.children_mut() {- for k in kids {- rename_in(std::sync::Arc::make_mut(k), from, to);- }- }-}-#[cfg(test)]mod color_tests {use super::*;@@ -1318,3 +1390,117 @@ mod cjk_tests {assert!(s.execute("style.compositeFont.set", &definition(-1.0)).is_err());}}++#[cfg(test)]+mod swatch_options_tests {+ use designcraft_color::SwatchValue;+ use designcraft_doc::{ItemId, StoryId};+ use serde_json::json;++ use crate::Session;++ /// A document whose frame, text, styles, tint swatch and colour group all use "Brand".+ fn brand_doc() -> (Session, u64, u64) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("swatch.create", &json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 100, "k": 0}})).unwrap();+ s.execute("swatch.create", &json!({"name": "Other", "color": "#108080"})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hello"})).unwrap();+ let (id, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());+ s.execute("object.fill", &json!({"swatch": "Brand", "ids": [id]})).unwrap();+ s.execute("object.stroke", &json!({"swatch": "Brand", "ids": [id]})).unwrap();+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 3})).unwrap();+ s.execute("type.char", &json!({"attrs": {"fill": "Brand"}})).unwrap();+ s.execute("swatch.newColorGroup", &json!({"name": "Brand Colors", "swatches": ["Brand"]})).unwrap();+ s.execute("style.character.create", &json!({"name": "Accent"})).unwrap();+ s.edit(|d, _| {+ d.swatches.push(designcraft_color::Swatch {+ name: "Brand 50%".into(),+ value: SwatchValue::Tint { base: "Brand".into(), tint: 0.5 },+ locked: false,+ named: true,+ hidden: false,+ });+ let st = d.styles_mut();+ if let Some(p) = st.para_mut(designcraft_doc::BASIC_PARAGRAPH) {+ p.chars.underline_color = Some("Brand".into());+ p.para.shading_color = Some("Brand".into());+ }+ if let Some(c) = st.char_style_mut("Accent") {+ c.chars.fill = Some("Brand".into());+ }+ Ok(())+ })+ .unwrap();+ (s, id, sid)+ }++ fn uses(s: &Session, id: u64, sid: u64, name: &str) -> Vec<bool> {+ let d = &s.doc().unwrap().doc;+ let it = d.item(ItemId(id)).unwrap();+ let story = d.story(StoryId(sid)).unwrap();+ let basic = d.styles.para(designcraft_doc::BASIC_PARAGRAPH).unwrap();+ vec![+ it.fill.swatch == name,+ it.stroke.swatch == name,+ story.chars.iter().any(|r| r.format.over.fill.as_deref() == Some(name)),+ basic.chars.underline_color.as_deref() == Some(name),+ basic.para.shading_color.as_deref() == Some(name),+ d.styles.char_style("Accent").unwrap().chars.fill.as_deref() == Some(name),+ matches!(&d.swatch("Brand 50%").unwrap().value, SwatchValue::Tint { base, .. } if base == name),+ d.color_groups[0].swatches == [name],+ ]+ }++ #[test]+ fn renaming_a_swatch_renames_every_use_in_one_undo_step() {+ let (mut s, id, sid) = brand_doc();+ assert!(uses(&s, id, sid, "Brand").iter().all(|u| *u));+ let r = s.execute("swatch.options", &json!({"name": "Brand", "to": "Signal Orange", "spot": true})).unwrap();+ assert_eq!(r["name"], "Signal Orange");+ let d = &s.doc().unwrap().doc;+ assert!(d.swatch("Brand").is_none());+ assert!(matches!(d.swatch("Signal Orange").unwrap().value, SwatchValue::Color { color_type: designcraft_color::ColorType::Spot, .. }));+ assert_eq!(uses(&s, id, sid, "Signal Orange"), vec![true; 8]);+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(s.doc().unwrap().doc.swatch("Brand").is_some());+ assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 8]);+ }++ #[test]+ fn bad_swatch_renames_change_nothing() {+ let (mut s, id, sid) = brand_doc();+ let before = s.doc().unwrap().doc.clone();+ for p in [+ json!({"name": "Brand", "to": "Other"}),+ json!({"name": "Brand", "to": " "}),+ json!({"name": "Brand", "to": "[Paper]"}),+ json!({"name": "[Black]", "to": "Ink"}),+ json!({"name": "[Registration]", "to": "Reg"}),+ json!({"name": "[None]", "to": "Nothing"}),+ json!({"name": "[Black]", "color": "#ff0000"}),+ json!({"name": "Brand 50%", "color": "#ff0000"}),+ json!({"name": "Missing", "to": "X"}),+ ] {+ assert!(s.execute("swatch.options", &p).is_err(), "{p}");+ }+ assert_eq!(s.doc().unwrap().doc.swatches, before.swatches);+ assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 8]);+ // [Paper]'s colour can change; its name can't.+ s.execute("swatch.options", &json!({"name": "[Paper]", "to": "[Paper]", "color": "#fff8e0"})).unwrap();+ }++ #[test]+ fn name_with_color_value_tracks_the_colour() {+ let (mut s, id, sid) = brand_doc();+ let r = s.execute("swatch.options", &json!({"name": "Brand", "nameWithValue": true, "color": {"c": 10, "m": 20, "y": 30, "k": 40}})).unwrap();+ assert_eq!(r["name"], "C=10 M=20 Y=30 K=40");+ assert_eq!(uses(&s, id, sid, "C=10 M=20 Y=30 K=40"), vec![true; 8]);+ // Later colour edits keep the name in step until the swatch is named by hand.+ let r = s.execute("swatch.options", &json!({"name": "C=10 M=20 Y=30 K=40", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap();+ assert_eq!(r["name"], "C=0 M=0 Y=0 K=50");+ let r = s.execute("swatch.options", &json!({"name": "C=0 M=0 Y=0 K=50", "to": "Warm Gray"})).unwrap();+ assert_eq!(r["name"], "Warm Gray");+ assert!(s.doc().unwrap().doc.swatch("Warm Gray").unwrap().named);+ }+}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 2ab7a3bad..9b2e68e2f 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -8,6 +8,9 @@ use serde_json::{Map, Value, json};use crate::DesignApp;use crate::theme::semibold;+mod options;+pub use options::{open_color_group_options, open_layer_options, open_swatch_options};+#[derive(Clone, Debug, Serialize)]pub struct Dialog {pub id: String,@@ -1150,6 +1153,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {"layerOptions" => crate::i18n::tr(&app.ui.language, "Object Layer Options"),"keyboardShortcuts" => crate::i18n::tr(&app.ui.language, "Keyboard Shortcuts"),"colorPicker" => crate::i18n::tr(&app.ui.language, "Color Picker"),+ "swatchOptions" => crate::i18n::tr(&app.ui.language, "Swatch Options"),+ "colorGroupOptions" => crate::i18n::tr(&app.ui.language, "Color Group Options"),+ "layerSettings" => crate::i18n::tr(&app.ui.language, "Layer Options"),id => match id.strip_prefix("cmd:").and_then(designcraft_engine::find_command) {Some(c) => crate::i18n::tr(&app.ui.language, c.label.trim_end_matches('…')),None => crate::i18n::tr(&app.ui.language, "Dialog"),@@ -1396,6 +1402,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {"insertXref" => insert_xref(app, ui, &mut d),"findFont" => find_font(app, ui, &mut d),"colorPicker" => color_picker(ui, &mut d),+ "swatchOptions" => options::swatch_options(app, ui, &mut d),+ "colorGroupOptions" => options::color_group_options(app, ui, &mut d),+ "layerSettings" => options::layer_options(app, ui, &mut d),"preferences" => preferences(app, ui, &mut d, body_height),"print" => print_dialog(app, ui, &mut d),"pdfImport" => {@@ -1899,6 +1908,20 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {}r}+ "swatchOptions" | "colorGroupOptions" | "layerSettings" => {+ let r = match d.id.as_str() {+ "swatchOptions" => options::confirm_swatch_options(app, &d),+ "colorGroupOptions" => options::confirm_color_group_options(app, &d),+ _ => options::confirm_layer_options(app, &d),+ };+ if let Err(e) = &r {+ // Keep the dialog open with the reason (a taken or empty name).+ let mut d = d.clone();+ d.fields.insert("status".into(), json!(e));+ app.ui.dialog = Some(d);+ }+ r+ }"colorPicker" => {let hex = d.s("hex");app.run("object.color", json!({"color": hex, "target": d.s("target")}))diff --git a/crates/ui-egui/src/dialogs/options.rs b/crates/ui-egui/src/dialogs/options.rsnew file mode 100644index 000000000..915156010--- /dev/null+++ b/crates/ui-egui/src/dialogs/options.rs@@ -0,0 +1,423 @@+//! Swatch Options, Color Group Options and Layer Options.++use designcraft_color::{Color, ColorType, SwatchValue};+use serde_json::{Map, Value, json};++use super::{Dialog, check, text_field};+use crate::DesignApp;+use crate::i18n::tr;++/// Swatch Options for `name`: its name, and what its kind lets the user change.+pub fn open_swatch_options(app: &mut DesignApp, name: &str) -> Result<(), String> {+ let doc = &app.session.active().ok_or("no document open")?.doc;+ let w = doc.swatch(name).ok_or_else(|| format!("no swatch `{name}`"))?;+ let mut f = Map::new();+ f.insert("name".into(), json!(name));+ f.insert("swatchName".into(), json!(name));+ f.insert("locked".into(), json!(w.locked));+ let kind = match &w.value {+ SwatchValue::Color { color, color_type } if !w.locked => {+ f.insert("nameWithValue".into(), json!(!w.named));+ f.insert("colorType".into(), json!(if *color_type == ColorType::Spot { "spot" } else { "process" }));+ set_color(&mut f, *color, None);+ "color"+ }+ SwatchValue::Paper { color } => {+ set_color(&mut f, *color, None);+ "paper"+ }+ SwatchValue::Tint { base, tint } => {+ f.insert("base".into(), json!(base));+ f.insert("tint".into(), json!((f64::from(*tint) * 100.0).round()));+ "tint"+ }+ SwatchValue::Gradient { .. } => "gradient",+ _ => "fixed",+ };+ f.insert("kind".into(), json!(kind));+ if let Some(c) = dialog_color(&f) {+ f.insert("origColor".into(), color_json(c));+ }+ app.ui.dialog = Some(Dialog::new("swatchOptions", Value::Object(f)));+ Ok(())+}++/// Write `c`'s channels in `mode` (default: the colour's own model).+fn set_color(f: &mut Map<String, Value>, c: Color, mode: Option<&str>) {+ let mode = mode.unwrap_or(match c {+ Color::Cmyk { .. } => "cmyk",+ Color::Rgb { .. } => "rgb",+ Color::Gray { .. } => "gray",+ });+ f.insert("mode".into(), json!(mode));+ match mode {+ "rgb" => {+ for (k, v) in ["r", "g", "b"].iter().zip(c.to_rgb()) {+ f.insert((*k).into(), json!((f64::from(v) * 255.0).round()));+ }+ }+ "gray" => {+ let k = match c {+ Color::Gray { k } => k,+ other => other.to_cmyk()[3],+ };+ f.insert("gray".into(), json!((f64::from(k) * 1000.0).round() / 10.0));+ }+ _ => {+ for (k, v) in ["c", "m", "y", "k"].iter().zip(c.to_cmyk()) {+ f.insert((*k).into(), json!((f64::from(v) * 1000.0).round() / 10.0));+ }+ }+ }+}++/// The colour the dialog's channels describe.+fn dialog_color(f: &Map<String, Value>) -> Option<Color> {+ let n = |k: &str, max: f64| f.get(k).and_then(Value::as_f64).map(|v| (v.clamp(0.0, max) / max) as f32);+ match f.get("mode").and_then(Value::as_str)? {+ "rgb" => Some(Color::rgb(n("r", 255.0)?, n("g", 255.0)?, n("b", 255.0)?)),+ "gray" => Some(Color::gray(n("gray", 100.0)?)),+ _ => Some(Color::cmyk(n("c", 100.0)?, n("m", 100.0)?, n("y", 100.0)?, n("k", 100.0)?)),+ }+}++/// A colour as `swatch.options` takes it (fractions, so 1% isn't read as 100%).+fn color_json(c: Color) -> Value {+ match c {+ Color::Cmyk { c, m, y, k } => json!({"c": c, "m": m, "y": y, "k": k}),+ Color::Rgb { r, g, b } => json!([r, g, b]),+ Color::Gray { k } => json!({"gray": k}),+ }+}++fn caption(ui: &mut egui::Ui, lang: &str, s: &str) {+ crate::rtl::label(ui, tr(lang, s));+}++fn channel(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, max: f64, suffix: &str) {+ ui.label(egui::RichText::new(label).monospace());+ let mut v = d.n(key).unwrap_or(0.0);+ if ui.add(egui::DragValue::new(&mut v).range(0.0..=max).speed(0.5).max_decimals(1).suffix(suffix)).changed() {+ d.fields.insert(key.into(), json!(v));+ }+ ui.end_row();+}++pub fn swatch_options(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let lang = app.ui.language.as_str();+ let kind = d.s("kind");+ let auto = kind == "color" && d.b("nameWithValue");+ if auto && let Some(c) = dialog_color(&d.fields) {+ d.fields.insert("swatchName".into(), json!(designcraft_color::swatch::value_name(c)));+ }+ egui::Grid::new("swatch_options").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ caption(ui, lang, "Swatch Name:");+ ui.add_enabled_ui(!d.b("locked") && !auto, |ui| text_field(ui, d, "swatchName", 220.0));+ ui.end_row();+ });+ if kind == "color" {+ check(ui, d, "nameWithValue", tr(lang, "Name with Color Value"));+ }+ ui.add_space(6.0);+ match kind.as_str() {+ "color" | "paper" => {+ egui::Grid::new("swatch_color").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ if kind == "color" {+ caption(ui, lang, "Color Type:");+ let cur = d.s("colorType");+ egui::ComboBox::from_id_salt("swatch_color_type")+ .selected_text(crate::rtl::widget(ui, tr(lang, if cur == "spot" { "Spot" } else { "Process" })))+ .show_ui(ui, |ui| {+ for (v, l) in [("process", "Process"), ("spot", "Spot")] {+ if ui.selectable_label(cur == v, crate::rtl::widget(ui, tr(lang, l))).clicked() {+ d.fields.insert("colorType".into(), json!(v));+ }+ }+ });+ ui.end_row();+ }+ caption(ui, lang, "Color Mode:");+ let cur = d.s("mode");+ let label = |m: &str| match m {+ "rgb" => "RGB",+ "gray" => "Gray",+ _ => "CMYK",+ };+ egui::ComboBox::from_id_salt("swatch_color_mode").selected_text(crate::rtl::widget(ui, tr(lang, label(&cur)))).show_ui(ui, |ui| {+ for m in ["cmyk", "rgb", "gray"] {+ if ui.selectable_label(cur == m, crate::rtl::widget(ui, tr(lang, label(m)))).clicked()+ && cur != m+ && let Some(c) = dialog_color(&d.fields)+ {+ set_color(&mut d.fields, c, Some(m));+ }+ }+ });+ ui.end_row();+ match d.s("mode").as_str() {+ "rgb" => {+ for k in ["r", "g", "b"] {+ channel(ui, d, k, &k.to_uppercase(), 255.0, "");+ }+ }+ "gray" => channel(ui, d, "gray", "K", 100.0, "%"),+ _ => {+ for k in ["c", "m", "y", "k"] {+ channel(ui, d, k, &k.to_uppercase(), 100.0, "%");+ }+ }+ }+ });+ if let Some(c) = dialog_color(&d.fields) {+ let [r, g, b] = c.to_rgb();+ let (rect, _) = ui.allocate_exact_size(egui::vec2(48.0, 24.0), egui::Sense::hover());+ let col = egui::Color32::from_rgb((r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8);+ ui.painter().rect_filled(rect, 2.0, col);+ }+ }+ "tint" => {+ egui::Grid::new("swatch_tint").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ caption(ui, lang, "Base Color:");+ ui.label(d.s("base"));+ ui.end_row();+ caption(ui, lang, "Tint:");+ let mut v = d.n("tint").unwrap_or(100.0);+ if ui.add(egui::Slider::new(&mut v, 0.0..=100.0).suffix("%").integer()).changed() {+ d.fields.insert("tint".into(), json!(v));+ }+ ui.end_row();+ });+ }+ "gradient" => caption(ui, lang, "Edit the gradient's stops in the Gradient panel."),+ _ => caption(ui, lang, "This swatch can't be edited."),+ }+ status(ui, d);+}++/// A failed OK's reason.+fn status(ui: &mut egui::Ui, d: &Dialog) {+ let s = d.s("status");+ if !s.is_empty() {+ ui.add_space(6.0);+ crate::rtl::label(ui, egui::RichText::new(s).color(crate::theme::Tokens::get(ui.ctx()).text_strong));+ }+}++pub fn confirm_swatch_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {+ let kind = d.s("kind");+ let mut p = json!({"name": d.s("name")});+ if !d.b("locked") {+ p["to"] = json!(d.s("swatchName").trim());+ }+ if let Some(c) = dialog_color(&d.fields).map(color_json)+ && d.fields.get("origColor") != Some(&c)+ {+ p["color"] = c;+ }+ match kind.as_str() {+ "color" => {+ p["nameWithValue"] = json!(d.b("nameWithValue"));+ p["spot"] = json!(d.s("colorType") == "spot");+ }+ "tint" => p["tint"] = json!((d.n("tint").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0)),+ "paper" => {}+ "gradient" => {}+ _ => return Ok(Value::Null),+ }+ app.run("swatch.options", p)+}++pub fn open_color_group_options(app: &mut DesignApp, name: &str) -> Result<(), String> {+ let doc = &app.session.active().ok_or("no document open")?.doc;+ if !doc.color_groups.iter().any(|g| g.name == name) {+ return Err(format!("no color group `{name}`"));+ }+ app.ui.dialog = Some(Dialog::new("colorGroupOptions", json!({"name": name, "groupName": name})));+ Ok(())+}++pub fn color_group_options(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ ui.horizontal(|ui| {+ caption(ui, &app.ui.language, "Name:");+ text_field(ui, d, "groupName", 220.0);+ });+ status(ui, d);+}++pub fn confirm_color_group_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {+ let (name, to) = (d.s("name"), d.s("groupName").trim().to_string());+ if to == name {+ return Ok(Value::Null);+ }+ app.run("swatch.renameColorGroup", json!({"name": name, "to": to}))+}++/// Layer Options for layer `id` (default: the active layer).+pub fn open_layer_options(app: &mut DesignApp, id: Option<u64>) -> Result<(), String> {+ let st = app.session.active().ok_or("no document open")?;+ let id = id.map_or(st.active_layer, designcraft_doc::LayerId);+ let l = st.doc.layer(id).ok_or("no such layer")?;+ let f = json!({"id": l.id.0, "name": l.name, "rgb": l.color, "visible": l.visible, "locked": l.locked, "printable": l.printable,+ "showGuides": l.show_guides, "suppressWrapWhenHidden": l.suppress_wrap_when_hidden});+ app.ui.dialog = Some(Dialog::new("layerSettings", f));+ Ok(())+}++pub fn layer_options(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let lang = app.ui.language.as_str();+ let rgb: [u8; 3] = d.fields.get("rgb").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or([0, 0, 0]);+ let named = designcraft_doc::LAYER_COLORS.iter().find(|(_, c)| *c == rgb).map(|(n, _)| *n);+ egui::Grid::new("layer_options").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ caption(ui, lang, "Name:");+ text_field(ui, d, "name", 220.0);+ ui.end_row();+ caption(ui, lang, "Color:");+ ui.horizontal(|ui| {+ egui::ComboBox::from_id_salt("layer_color")+ .selected_text(crate::rtl::widget(ui, tr(lang, named.unwrap_or("Custom"))))+ .width(140.0)+ .show_ui(ui, |ui| {+ for (n, c) in designcraft_doc::LAYER_COLORS {+ let swatch = egui::RichText::new("■ ").color(egui::Color32::from_rgb(c[0], c[1], c[2]));+ let mut job = egui::text::LayoutJob::default();+ swatch.append_to(&mut job, ui.style(), egui::FontSelection::Default, egui::Align::Center);+ egui::RichText::new(tr(lang, n)).append_to(&mut job, ui.style(), egui::FontSelection::Default, egui::Align::Center);+ if ui.selectable_label(named == Some(*n), job).clicked() {+ d.fields.insert("rgb".into(), json!(c));+ }+ }+ });+ super::color_field(ui, d, "rgb");+ });+ ui.end_row();+ });+ ui.add_space(6.0);+ egui::Grid::new("layer_flags").num_columns(2).spacing([16.0, 6.0]).show(ui, |ui| {+ check(ui, d, "visible", tr(lang, "Show Layer"));+ check(ui, d, "locked", tr(lang, "Lock Layer"));+ ui.end_row();+ check(ui, d, "showGuides", tr(lang, "Show Guides"));+ check(ui, d, "printable", tr(lang, "Print Layer"));+ ui.end_row();+ });+ check(ui, d, "suppressWrapWhenHidden", tr(lang, "Suppress Text Wrap When Layer is Hidden"));+ status(ui, d);+}++pub fn confirm_layer_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {+ let mut p = json!({"id": d.fields.get("id").cloned().unwrap_or(Value::Null), "name": d.s("name"), "color": d.fields.get("rgb").cloned().unwrap_or(Value::Null)});+ for k in ["visible", "locked", "printable", "showGuides", "suppressWrapWhenHidden"] {+ p[k] = json!(d.b(k));+ }+ app.run("layer.set", p)+}++#[cfg(test)]+mod tests {+ use egui::vec2;+ use egui_kittest::Harness;+ use egui_kittest::kittest::{NodeT, Queryable};+ use serde_json::json;++ use crate::DesignApp;++ /// `panel` and the dialogs, in a small window.+ fn harness(app: DesignApp, panel: fn(&mut DesignApp, &mut egui::Ui)) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(vec2(360.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ move |ui, app: &mut DesignApp| {+ // The fonts are installed before the first frame that draws.+ let id = egui::Id::new("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ panel(app, ui);+ crate::dialogs::show(app, &ui.ctx().clone());+ },+ app,+ );+ h.run_steps(3);+ h+ }++ fn double_click(h: &mut Harness<'static, DesignApp>, label: &str) {+ let at = h.get_by_label(label).rect().center();+ h.hover_at(at);+ // Two clicks without the pointer leaving (`drop_at` would end the double click).+ for pressed in [true, false, true, false] {+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });+ }+ h.run_steps(3);+ }++ /// Replace the text of the dialog field showing `old` with `new`.+ fn retype(h: &mut Harness<'static, DesignApp>, old: &str, new: &str) {+ let field = h.get_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some(old)).rect().center();+ h.hover_at(field);+ h.drag_at(field);+ h.drop_at(field);+ h.run_steps(2);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text(new.into()));+ h.run_steps(2);+ }++ fn app() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app+ }++ #[test]+ fn double_clicking_a_swatch_opens_swatch_options_and_ok_renames_it() {+ let mut app = app();+ app.run("swatch.create", json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 100, "k": 0}})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("object.fill", json!({"swatch": "Brand", "ids": [id]})).unwrap();+ let mut h = harness(app, crate::panels::swatches::show);+ double_click(&mut h, "Brand");+ let d = h.state().ui.dialog.clone().expect("Swatch Options is open");+ assert_eq!(d.id, "swatchOptions");+ assert_eq!(d.s("swatchName"), "Brand");+ retype(&mut h, "Brand", "Signal Orange");+ h.get_by_label(" OK ").click();+ h.run_steps(3);+ assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.dialog);+ let doc = &h.state().session.active().unwrap().doc;+ assert!(doc.swatch("Signal Orange").is_some() && doc.swatch("Brand").is_none());+ assert_eq!(doc.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, "Signal Orange");+ }++ #[test]+ fn a_system_swatch_name_cant_be_edited() {+ let mut h = harness(app(), crate::panels::swatches::show);+ double_click(&mut h, "[Black]");+ assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.id.as_str()), Some("swatchOptions"));+ let field = h.get_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("[Black]"));+ assert!(field.accesskit_node().is_disabled(), "the name field is disabled");+ h.get_by_label(" OK ").click();+ h.run_steps(3);+ assert!(h.state().session.active().unwrap().doc.swatch("[Black]").is_some());+ }++ #[test]+ fn double_clicking_a_layer_opens_layer_options_and_ok_renames_it() {+ let mut app = app();+ app.run("layer.new", json!({"name": "Art"})).unwrap();+ let mut h = harness(app, crate::panels::layers::show);+ double_click(&mut h, "Art");+ let d = h.state().ui.dialog.clone().expect("Layer Options is open");+ assert_eq!(d.id, "layerSettings");+ assert_eq!(d.s("name"), "Art");+ retype(&mut h, "Art", "Artwork");+ h.get_by_label("Print Layer").click();+ h.run_steps(2);+ h.get_by_label(" OK ").click();+ h.run_steps(3);+ assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.dialog);+ let doc = &h.state().session.active().unwrap().doc;+ let l = doc.layers.iter().find(|l| l.name == "Artwork").expect("renamed");+ assert!(!l.printable);+ }+}diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rsindex e5e8a8d08..f69f47f66 100644--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@ -2811,6 +2811,81 @@ const TABLE: &[(&str, [&str; 5])] = &[("Rule Below", ["Linie unterhalb", "Filet après", "Filete después", "後境界線", "下方横线"]),("Tint:", ["Farbton:", "Teinte:", "Matiz:", "濃淡:", "色调:"]),("Column", ["Spalte", "Colonne", "Columna", "段", "栏"]),+ ("Swatch Options…", ["Farbfeldoptionen …", "Options de nuance…", "Opciones de muestra…", "スウォッチオプション…", "色板选项…"]),+ ("Swatch Options", ["Farbfeldoptionen", "Options de nuance", "Opciones de muestra", "スウォッチオプション", "色板选项"]),+ (+ "Color Group Options…",+ ["Farbgruppenoptionen …", "Options du groupe de couleurs…", "Opciones de grupo de colores…", "カラーグループオプション…", "颜色组选项…"],+ ),+ ("Layer Options", ["Ebenenoptionen", "Options de calque", "Opciones de capa", "レイヤーオプション", "图层选项"]),+ (+ "Layer Options for \"{name}\"…",+ [+ "Ebenenoptionen für „{name}“ …",+ "Options du calque « {name} »…",+ "Opciones de capa para «{name}»…",+ "「{name}」のレイヤーオプション…",+ "“{name}”的图层选项…",+ ],+ ),+ ("Swatch Name:", ["Farbfeldname:", "Nom de la nuance :", "Nombre de muestra:", "スウォッチ名:", "色板名称:"]),+ (+ "Name with Color Value",+ ["Name mit Farbwert", "Nommer d'après la valeur chromatique", "Nombre con valor de color", "カラー値を名前にする", "以颜色值命名"],+ ),+ ("Color Type:", ["Farbtyp:", "Type de couleur :", "Tipo de color:", "カラータイプ:", "颜色类型:"]),+ ("Process", ["Prozessfarbe", "Quadrichromie", "Cuatricromía", "プロセス", "印刷色"]),+ ("Spot", ["Volltonfarbe", "Ton direct", "Tinta plana", "特色", "专色"]),+ ("Color Mode:", ["Farbmodus:", "Mode colorimétrique :", "Modo de color:", "カラーモード:", "颜色模式:"]),+ ("Base Color:", ["Grundfarbe:", "Couleur de base :", "Color base:", "ベースカラー:", "基准颜色:"]),+ (+ "Edit the gradient's stops in the Gradient panel.",+ [+ "Die Verlaufsregler bearbeiten Sie im Verlaufsbedienfeld.",+ "Modifiez les arrêts du dégradé dans le panneau Dégradé.",+ "Edite las paradas del degradado en el panel Degradado.",+ "グラデーションの分岐点はグラデーションパネルで編集します。",+ "在“渐变”面板中编辑渐变的色标。",+ ],+ ),+ (+ "This swatch can't be edited.",+ [+ "Dieses Farbfeld kann nicht bearbeitet werden.",+ "Cette nuance ne peut pas être modifiée.",+ "Esta muestra no se puede editar.",+ "このスウォッチは編集できません。",+ "此色板无法编辑。",+ ],+ ),+ ("Light Blue", ["Hellblau", "Bleu clair", "Azul claro", "ライトブルー", "浅蓝色"]),+ ("Red", ["Rot", "Rouge", "Rojo", "レッド", "红色"]),+ ("Green", ["Grün", "Vert", "Verde", "グリーン", "绿色"]),+ ("Blue", ["Blau", "Bleu", "Azul", "ブルー", "蓝色"]),+ ("Yellow", ["Gelb", "Jaune", "Amarillo", "イエロー", "黄色"]),+ ("Magenta", ["Magenta", "Magenta", "Magenta", "マゼンタ", "洋红色"]),+ ("Cyan", ["Cyan", "Cyan", "Cian", "シアン", "青色"]),+ ("Black", ["Schwarz", "Noir", "Negro", "ブラック", "黑色"]),+ ("Orange", ["Orange", "Orange", "Naranja", "オレンジ", "橙色"]),+ ("Dark Green", ["Dunkelgrün", "Vert foncé", "Verde oscuro", "ダークグリーン", "深绿色"]),+ ("Teal", ["Blaugrün", "Bleu canard", "Verde azulado", "ティール", "蓝绿色"]),+ ("Tan", ["Hellbraun", "Fauve", "Tostado", "タン", "棕褐色"]),+ ("Brown", ["Braun", "Marron", "Marrón", "ブラウン", "褐色"]),+ ("Violet", ["Violett", "Violet", "Violeta", "バイオレット", "紫罗兰色"]),+ ("Gold", ["Gold", "Or", "Dorado", "ゴールド", "金色"]),+ ("Show Layer", ["Ebene einblenden", "Afficher le calque", "Mostrar capa", "レイヤーを表示", "显示图层"]),+ ("Lock Layer", ["Ebene fixieren", "Verrouiller le calque", "Bloquear capa", "レイヤーをロック", "锁定图层"]),+ ("Print Layer", ["Ebene drucken", "Imprimer le calque", "Imprimir capa", "レイヤーをプリント", "打印图层"]),+ (+ "Suppress Text Wrap When Layer is Hidden",+ [+ "Textumfluss bei ausgeblendeter Ebene unterdrücken",+ "Supprimer l'habillage quand le calque est masqué",+ "Suprimir ceñir texto cuando la capa está oculta",+ "非表示レイヤーのテキストの回り込みを無視",+ "图层隐藏时禁止文本绕排",+ ],+ ),];/// Interface direction; independent of document binding and paragraph direction.diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rsindex 10e393cd2..22f191662 100644--- a/crates/ui-egui/src/i18n/ar.rs+++ b/crates/ui-egui/src/i18n/ar.rs@@ -1469,4 +1469,37 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paragraph Rules…", "خطوط الفقرة…"),("Paragraph Rules", "خطوط الفقرة"),("Rule Below", "خط سفلي"),+ ("Swatch Options…", "خيارات حامل اللون…"),+ ("Swatch Options", "خيارات حامل اللون"),+ ("Color Group Options…", "خيارات مجموعة الألوان…"),+ ("Layer Options", "خيارات الطبقة"),+ ("Layer Options for \"{name}\"…", "خيارات الطبقة \"{name}\"…"),+ ("Swatch Name:", "اسم حامل اللون:"),+ ("Name with Color Value", "التسمية بقيمة اللون"),+ ("Color Type:", "نوع اللون:"),+ ("Process", "لون معالجة"),+ ("Spot", "لون خاص"),+ ("Color Mode:", "وضع اللون:"),+ ("Base Color:", "اللون الأساسي:"),+ ("Edit the gradient's stops in the Gradient panel.", "حرّر نقاط التدرج في لوحة التدرج."),+ ("This swatch can't be edited.", "لا يمكن تحرير حامل اللون هذا."),+ ("Light Blue", "أزرق فاتح"),+ ("Red", "أحمر"),+ ("Green", "أخضر"),+ ("Blue", "أزرق"),+ ("Yellow", "أصفر"),+ ("Magenta", "أرجواني"),+ ("Cyan", "سماوي"),+ ("Black", "أسود"),+ ("Orange", "برتقالي"),+ ("Dark Green", "أخضر داكن"),+ ("Teal", "أزرق مخضر"),+ ("Tan", "أسمر"),+ ("Brown", "بني"),+ ("Violet", "بنفسجي"),+ ("Gold", "ذهبي"),+ ("Show Layer", "إظهار الطبقة"),+ ("Lock Layer", "قفل الطبقة"),+ ("Print Layer", "طباعة الطبقة"),+ ("Suppress Text Wrap When Layer is Hidden", "إيقاف التفاف النص عند إخفاء الطبقة"),];diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rsindex c91afd6ba..764d6be70 100644--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@ -1492,4 +1492,37 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paragraph Rules", "Filetti paragrafo"),("Rule Below", "Filetto sotto"),("Tint:", "Tinta:"),+ ("Swatch Options…", "Opzioni campione…"),+ ("Swatch Options", "Opzioni campione"),+ ("Color Group Options…", "Opzioni gruppo colori…"),+ ("Layer Options", "Opzioni livello"),+ ("Layer Options for \"{name}\"…", "Opzioni livello \"{name}\"…"),+ ("Swatch Name:", "Nome campione:"),+ ("Name with Color Value", "Nome con valore colore"),+ ("Color Type:", "Tipo colore:"),+ ("Process", "Quadricromia"),+ ("Spot", "Tinta piatta"),+ ("Color Mode:", "Metodo colore:"),+ ("Base Color:", "Colore base:"),+ ("Edit the gradient's stops in the Gradient panel.", "Modifica le interruzioni della sfumatura nel pannello Sfumatura."),+ ("This swatch can't be edited.", "Questo campione non può essere modificato."),+ ("Light Blue", "Azzurro"),+ ("Red", "Rosso"),+ ("Green", "Verde"),+ ("Blue", "Blu"),+ ("Yellow", "Giallo"),+ ("Magenta", "Magenta"),+ ("Cyan", "Ciano"),+ ("Black", "Nero"),+ ("Orange", "Arancione"),+ ("Dark Green", "Verde scuro"),+ ("Teal", "Verde acqua"),+ ("Tan", "Marrone chiaro"),+ ("Brown", "Marrone"),+ ("Violet", "Viola"),+ ("Gold", "Oro"),+ ("Show Layer", "Mostra livello"),+ ("Lock Layer", "Blocca livello"),+ ("Print Layer", "Stampa livello"),+ ("Suppress Text Wrap When Layer is Hidden", "Elimina contorna con testo se il livello è nascosto"),];diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rsindex be6e2c4da..4377d9a49 100644--- a/crates/ui-egui/src/i18n/ja.rs+++ b/crates/ui-egui/src/i18n/ja.rs@@ -1670,6 +1670,35 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Vertical:", "垂直方向:"),("Working CMYK", "作業用 CMYK"),("Yellow", "イエロー"),+ ("Swatch Options…", "スウォッチオプション…"),+ ("Swatch Options", "スウォッチオプション"),+ ("Color Group Options…", "カラーグループオプション…"),+ ("Layer Options", "レイヤーオプション"),+ ("Layer Options for \"{name}\"…", "「{name}」のレイヤーオプション…"),+ ("Swatch Name:", "スウォッチ名:"),+ ("Name with Color Value", "カラー値を名前にする"),+ ("Color Type:", "カラータイプ:"),+ ("Process", "プロセス"),+ ("Spot", "特色"),+ ("Color Mode:", "カラーモード:"),+ ("Base Color:", "ベースカラー:"),+ ("Edit the gradient's stops in the Gradient panel.", "グラデーションの分岐点はグラデーションパネルで編集します。"),+ ("This swatch can't be edited.", "このスウォッチは編集できません。"),+ ("Light Blue", "ライトブルー"),+ ("Red", "レッド"),+ ("Green", "グリーン"),+ ("Blue", "ブルー"),+ ("Orange", "オレンジ"),+ ("Dark Green", "ダークグリーン"),+ ("Teal", "ティール"),+ ("Tan", "タン"),+ ("Brown", "ブラウン"),+ ("Violet", "バイオレット"),+ ("Gold", "ゴールド"),+ ("Show Layer", "レイヤーを表示"),+ ("Lock Layer", "レイヤーをロック"),+ ("Print Layer", "レイヤーをプリント"),+ ("Suppress Text Wrap When Layer is Hidden", "非表示レイヤーのテキストの回り込みを無視"),];#[cfg(test)]diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rsindex d25717dc6..ef87d8ef1 100644--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@ -1073,4 +1073,37 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paragraph Rules…", "Linhas de parágrafo…"),("Paragraph Rules", "Linhas de parágrafo"),("Rule Below", "Linha abaixo"),+ ("Swatch Options…", "Opções de amostra…"),+ ("Swatch Options", "Opções de amostra"),+ ("Color Group Options…", "Opções do grupo de cores…"),+ ("Layer Options", "Opções de camada"),+ ("Layer Options for \"{name}\"…", "Opções da camada \"{name}\"…"),+ ("Swatch Name:", "Nome da amostra:"),+ ("Name with Color Value", "Nome com valor da cor"),+ ("Color Type:", "Tipo de cor:"),+ ("Process", "Escala"),+ ("Spot", "Especial"),+ ("Color Mode:", "Modo de cor:"),+ ("Base Color:", "Cor base:"),+ ("Edit the gradient's stops in the Gradient panel.", "Edite as paradas do degradê no painel Degradê."),+ ("This swatch can't be edited.", "Esta amostra não pode ser editada."),+ ("Light Blue", "Azul-claro"),+ ("Red", "Vermelho"),+ ("Green", "Verde"),+ ("Blue", "Azul"),+ ("Yellow", "Amarelo"),+ ("Magenta", "Magenta"),+ ("Cyan", "Ciano"),+ ("Black", "Preto"),+ ("Orange", "Laranja"),+ ("Dark Green", "Verde-escuro"),+ ("Teal", "Azul-petróleo"),+ ("Tan", "Castanho-claro"),+ ("Brown", "Marrom"),+ ("Violet", "Violeta"),+ ("Gold", "Dourado"),+ ("Show Layer", "Mostrar camada"),+ ("Lock Layer", "Bloquear camada"),+ ("Print Layer", "Imprimir camada"),+ ("Suppress Text Wrap When Layer is Hidden", "Suprimir disposição do texto quando a camada estiver oculta"),];diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rsindex 9a9fb89ba..812f714f2 100644--- a/crates/ui-egui/src/i18n/uk.rs+++ b/crates/ui-egui/src/i18n/uk.rs@@ -1455,6 +1455,39 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Selection", "Виділення"),("All Documents", "Усі документи"),("On", "Увімкнено"),+ ("Swatch Options…", "Параметри зразка…"),+ ("Swatch Options", "Параметри зразка"),+ ("Color Group Options…", "Параметри групи кольорів…"),+ ("Layer Options", "Параметри шару"),+ ("Layer Options for \"{name}\"…", "Параметри шару «{name}»…"),+ ("Swatch Name:", "Назва зразка:"),+ ("Name with Color Value", "Назва за значенням кольору"),+ ("Color Type:", "Тип кольору:"),+ ("Process", "Тріадний"),+ ("Spot", "Плашковий"),+ ("Color Mode:", "Колірна модель:"),+ ("Base Color:", "Базовий колір:"),+ ("Edit the gradient's stops in the Gradient panel.", "Точки градієнта редагуються на панелі «Градієнт»."),+ ("This swatch can't be edited.", "Цей зразок не можна змінити."),+ ("Light Blue", "Світло-синій"),+ ("Red", "Червоний"),+ ("Green", "Зелений"),+ ("Blue", "Синій"),+ ("Yellow", "Жовтий"),+ ("Magenta", "Пурпуровий"),+ ("Cyan", "Ціан"),+ ("Black", "Чорний"),+ ("Orange", "Помаранчевий"),+ ("Dark Green", "Темно-зелений"),+ ("Teal", "Бірюзовий"),+ ("Tan", "Пісочний"),+ ("Brown", "Коричневий"),+ ("Violet", "Фіолетовий"),+ ("Gold", "Золотий"),+ ("Show Layer", "Показати шар"),+ ("Lock Layer", "Заблокувати шар"),+ ("Print Layer", "Друкувати шар"),+ ("Suppress Text Wrap When Layer is Hidden", "Вимикати обтікання текстом, коли шар приховано"),];/// Contexts whose Ukrainian noun differs from the shared action/text-layout label.diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 94e5c0971..52c4f1740 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -106,6 +106,14 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[("window.nextDocument", "Next Document", Some("Cmd+F6"), "{}"),("window.previousDocument", "Previous Document", Some("Cmd+Shift+F6"), "{}"),("app.layerOptions", "Object Layer Options…", None, "{} — show or hide the layers of the selected placed PDF"),+ (+ "app.layerOptionsDialog",+ "Layer Options…",+ None,+ "{id?} (default: the active layer) — name, colour, show, lock, print, guides, text wrap (layer.set)",+ ),+ ("app.swatchOptionsDialog", "Swatch Options…", None, "{name} — name, colour type, mode and values, tint (swatch.options)"),+ ("app.colorGroupOptionsDialog", "Color Group Options…", None, "{name} — rename a colour group (swatch.renameColorGroup)"),("view.tagMarkers", "Show Tag Markers", None, "{on?: bool} — brackets around inline-tagged text"),("view.flattenerPreview", "Flattener Preview", None, "{on?: bool} — highlight objects that involve transparency"),("view.rotateSpread", "Rotate Spread", None, "{angle: 90 (clockwise) | -90 | 180 | 0 (clear)} — turn the view in quarter turns"),@@ -1129,6 +1137,13 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,}Ok(json!(app.session.active_index()))}+ "app.layerOptionsDialog" => crate::dialogs::open_layer_options(app, p.get("id").and_then(Value::as_u64)).map(|()| Value::Null),+ "app.swatchOptionsDialog" => {+ crate::dialogs::open_swatch_options(app, p.get("name").and_then(Value::as_str).unwrap_or("")).map(|()| Value::Null)+ }+ "app.colorGroupOptionsDialog" => {+ crate::dialogs::open_color_group_options(app, p.get("name").and_then(Value::as_str).unwrap_or("")).map(|()| Value::Null)+ }"app.layerOptions" => {let layers = match app.session.execute("object.pdfLayers", &json!({})) {Ok(v) => v,diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rsindex a9c842116..c74e6d2bd 100644--- a/crates/ui-egui/src/panels/layers.rs+++ b/crates/ui-egui/src/panels/layers.rs@@ -121,6 +121,7 @@ pub fn show(app: &mut DesignApp, ui: &mut Ui) {let open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(l.id == active);let lc = c32(l.color);let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &l.name));if l.id == active {ui.painter().rect_filled(row, 0.0, t.row_selected);} else if resp.hovered() {@@ -160,10 +161,18 @@ pub fn show(app: &mut DesignApp, ui: &mut Ui) {} else if sq {let ids: Vec<u64> = spread_items.iter().filter(|i| i.layer == l.id).map(|i| i.id.0).collect();let _ = app.run("selection.set", json!({"ids": ids}));+ } else if resp.double_clicked() {+ let _ = app.run("app.layerOptionsDialog", json!({"id": l.id.0}));} else if resp.clicked() {let _ = app.run("layer.activate", json!({"id": l.id.0}));}resp.context_menu(|ui| {+ let options = crate::i18n::tr(&app.ui.language, "Layer Options for \"{name}\"…").replace("{name}", &l.name);+ if ui.button(crate::rtl::widget(ui, options)).clicked() {+ let _ = app.run("app.layerOptionsDialog", json!({"id": l.id.0}));+ ui.close();+ }+ ui.separator();if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Layer"))).clicked() {let _ = app.run("layer.delete", json!({"id": l.id.0}));ui.close();diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rsindex 1aa11ddb3..039da097e 100644--- a/crates/ui-egui/src/panels/swatches.rs+++ b/crates/ui-egui/src/panels/swatches.rs@@ -31,6 +31,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {let open_id = egui::Id::new(("color_group_open", &g.name));let mut open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(true);let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &g.name));if resp.hovered() {ui.painter().rect_filled(row, 0.0, t.hover);}@@ -45,11 +46,19 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {ui.painter().rect_stroke(f, 1.5, egui::Stroke::new(1.2, t.text_dim), egui::StrokeKind::Inside);ui.painter().line_segment([f.left_top() + vec2(1.0, 3.0), f.right_top() + vec2(-1.0, 3.0)], egui::Stroke::new(1.0, t.text_dim));ui.painter().text(row.min + vec2(42.0, 11.0), egui::Align2::LEFT_CENTER, &g.name, egui::FontId::proportional(12.5), t.text);+ // A double click's first click folded the group: it stays as it was.if resp.clicked() {open = !open;ui.data_mut(|d| d.insert_temp(open_id, open));}+ if resp.double_clicked() {+ let _ = app.run("app.colorGroupOptionsDialog", json!({"name": g.name}));+ }resp.context_menu(|ui| {+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Color Group Options…"))).clicked() {+ let _ = app.run("app.colorGroupOptionsDialog", json!({"name": g.name}));+ ui.close();+ }if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Ungroup Color Group"))).clicked() {let _ = app.run("swatch.ungroupColorGroup", json!({"name": g.name}));ui.close();@@ -74,6 +83,14 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {let _ = app.run("swatch.create", json!({"color": {"c": 0, "m": 50, "y": 100, "k": 0}}));}crate::menus::menu_button(ui, "☰", |ui| {+ let current = fill_cur.as_deref().filter(|n| doc.swatch(n).is_some_and(|w| !w.hidden));+ if ui+ .add_enabled(current.is_some(), egui::Button::new(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Swatch Options…"))))+ .clicked()+ {+ let _ = app.run("app.swatchOptionsDialog", json!({"name": current}));+ ui.close();+ }crate::menus::menu_button(ui, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Ink Manager")), |ui| {let Ok(l) = app.session.execute("ink.list", &json!({})) else { return };let mut all = l["allToProcess"].as_bool().unwrap_or(false);@@ -127,6 +144,7 @@ fn swatch_row() {let t = Tokens::get(ui.ctx());let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &sw.name));if fill_cur == Some(sw.name.as_str()) {ui.painter().rect_filled(row, 0.0, t.row_selected);} else if resp.hovered() {@@ -154,11 +172,19 @@ fn swatch_row(icons::paint(ui.painter(), egui::Rect::from_min_size(egui::pos2(row.max.x - 64.0, row.min.y + 4.0), vec2(13.0, 13.0)), "lock", t.text_dim);}ui.painter().text(row.right_center() - vec2(6.0, 0.0), egui::Align2::RIGHT_CENTER, kind, egui::FontId::proportional(10.5), t.text_dim);- if resp.clicked() {+ if resp.clicked() && !resp.double_clicked() {let r = if text { app.run("type.char", json!({"attrs": {"fill": sw.name}})) } else { app.run("object.fill", json!({"swatch": sw.name})) };let _ = r;}+ // Double-click: Swatch Options (the first click has applied the swatch).+ if resp.double_clicked() {+ let _ = app.run("app.swatchOptionsDialog", json!({"name": sw.name}));+ }resp.context_menu(|ui| {+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Swatch Options…"))).clicked() {+ let _ = app.run("app.swatchOptionsDialog", json!({"name": sw.name}));+ ui.close();+ }if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Apply to Stroke"))).clicked() {let _ = app.run("object.stroke", json!({"swatch": sw.name}));ui.close();