DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Print color: gradient stops keep the swatch they were given
aiongg6c9709e11f8b
diff --git a/apps/designcraft-cli/src/perf.rs b/apps/designcraft-cli/src/perf.rsindex bed57cfcc..5125a5d3f 100644--- a/apps/designcraft-cli/src/perf.rs+++ b/apps/designcraft-cli/src/perf.rs@@ -164,10 +164,7 @@ pub fn synthetic(spec: &Spec) -> Result<Document, String> {value: SwatchValue::Gradient {gradient: Gradient {kind: GradientKind::Linear,- stops: vec![- GradientStop { offset: 0.0, color: Color::cmyk(0.6, 0.9, 0.3, 0.2), opacity: 1.0, midpoint: 0.5 },- GradientStop { offset: 1.0, color: Color::cmyk(0.0, 0.6, 0.8, 0.0), opacity: 1.0, midpoint: 0.5 },- ],+ stops: vec![GradientStop::new(0.0, Color::cmyk(0.6, 0.9, 0.3, 0.2)), GradientStop::new(1.0, Color::cmyk(0.0, 0.6, 0.8, 0.0))],},},locked: false,diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rsindex 6c19aabb1..2e2fdc18b 100644--- a/crates/color/src/gradient.rs+++ b/crates/color/src/gradient.rs@@ -24,16 +24,29 @@ impl GradientKind {}}-#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct GradientStop {/// 0..=1 along the gradient.pub offset: f32,+ /// The display colour. For a stop with a `swatch`, the swatch's colour when it was last+ /// resolved ([`GradientStop::swatch`]).pub color: Color,#[serde(default = "one")]pub opacity: f32,/// Midpoint to the next stop, 0.13..=0.87 (InDesign's diamond), default 0.5.#[serde(default = "half")]pub midpoint: f32,+ /// The colour swatch the stop takes its ink from: a spot or process colour, a tint of one,+ /// or `[Paper]`. Print export writes the stop in that swatch's inks; `None` is a plain colour.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub swatch: Option<String>,+}++impl GradientStop {+ /// A plain-colour stop, opaque, with the midpoint halfway to the next stop.+ pub fn new(offset: f32, color: Color) -> Self {+ Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None }+ }}fn one() -> f32 {@@ -52,13 +65,7 @@ pub struct Gradient {impl Default for Gradient {/// InDesign's default "White, Black" gradient.fn default() -> Self {- Self {- kind: GradientKind::Linear,- stops: vec![- GradientStop { offset: 0.0, color: Color::WHITE, opacity: 1.0, midpoint: 0.5 },- GradientStop { offset: 1.0, color: Color::BLACK, opacity: 1.0, midpoint: 0.5 },- ],- }+ Self { kind: GradientKind::Linear, stops: vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)] }}}@@ -238,6 +245,16 @@ mod tests {assert!(matches!(Color::rgb(1.0, 0.0, 0.0).lerp(&Color::cmyk(1.0, 0.0, 0.0, 0.0), 0.5), Color::Rgb { .. }));}+ #[test]+ fn saved_stops_without_a_swatch_are_plain_colours() {+ let old = r#"{"offset": 0.0, "color": {"model": "cmyk", "c": 0.0, "m": 0.3, "y": 0.9, "k": 0.1}, "opacity": 1.0, "midpoint": 0.5}"#;+ let stop: GradientStop = serde_json::from_str(old).unwrap();+ assert_eq!(stop, GradientStop::new(0.0, Color::cmyk(0.0, 0.3, 0.9, 0.1)));+ assert!(!serde_json::to_string(&stop).unwrap().contains("swatch"), "plain stops save as before");+ let on = GradientStop { swatch: Some("Gold".into()), ..stop };+ assert_eq!(serde_json::from_str::<GradientStop>(&serde_json::to_string(&on).unwrap()).unwrap(), on);+ }+#[test]fn midpoint_shifts() {let mut g = Gradient::default();@@ -272,7 +289,7 @@ mod tests {// With several stops, the reversed gradient is the original mirrored.let mut g = Gradient::default();g.stops[0].midpoint = 0.3;- g.stops.insert(1, GradientStop { offset: 0.4, color: Color::rgb(1.0, 0.0, 0.0), opacity: 0.5, midpoint: 0.8 });+ g.stops.insert(1, GradientStop { offset: 0.4, color: Color::rgb(1.0, 0.0, 0.0), opacity: 0.5, midpoint: 0.8, swatch: None });let original = g.clone();g.reverse();for t in [0.1, 0.3, 0.5, 0.7, 0.9] {diff --git a/crates/doc/src/swatch_refs.rs b/crates/doc/src/swatch_refs.rsindex d15519fcf..ada364ad6 100644--- a/crates/doc/src/swatch_refs.rs+++ b/crates/doc/src/swatch_refs.rs@@ -142,9 +142,50 @@ impl Names<'_> {}impl Document {+ /// Give gradient stops that name a colour swatch that swatch's current colour, after a+ /// swatch edit. Stops whose swatch is gone or isn't a colour keep the colour they have.+ pub fn refresh_gradient_stops(&mut self) {+ let mut fresh: Vec<(usize, usize, designcraft_color::Color)> = Vec::new();+ for (wi, w) in self.swatches.iter().enumerate() {+ let SwatchValue::Gradient { gradient } = &w.value else { continue };+ for (si, stop) in gradient.stops.iter().enumerate() {+ let Some(name) = &stop.swatch else { continue };+ if designcraft_color::swatch::resolve_gradient(&self.swatches, name).is_some() {+ continue;+ }+ if let Some(c) = self.resolve_color(name, 1.0)+ && c != stop.color+ {+ fresh.push((wi, si, c));+ }+ }+ }+ for (wi, si, c) in fresh {+ if let Some(SwatchValue::Gradient { gradient }) = self.swatches.get_mut(wi).map(|w| &mut w.value)+ && let Some(stop) = gradient.stops.get_mut(si)+ {+ stop.color = c;+ }+ }+ }++ /// Turn gradient stops that name swatch `name` into plain colours (the swatch is being+ /// deleted); each keeps the colour it shows.+ pub fn forget_gradient_stop_swatch(&mut self, name: &str) {+ for w in &mut self.swatches {+ let SwatchValue::Gradient { gradient } = &mut w.value else { continue };+ for stop in &mut gradient.stops {+ if stop.swatch.as_deref() == Some(name) {+ stop.swatch = None;+ }+ }+ }+ }+/// 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, kenten and ruby/// colours, rules, shading, borders and border gaps, tables (with stroke gaps), footnotes,+ /// gradient stops,/// endnotes and the footnote rule. The swatch itself is renamed by the/// caller.pub fn rename_swatch_refs(&mut self, from: &str, to: &str) {@@ -153,8 +194,14 @@ impl Document {}let n = Names { from, to };for w in &mut self.swatches {- if let SwatchValue::Tint { base, .. } = &mut w.value {- n.s(base);+ match &mut w.value {+ SwatchValue::Tint { base, .. } => n.s(base),+ SwatchValue::Gradient { gradient } => {+ for stop in &mut gradient.stops {+ n.o(&mut stop.swatch);+ }+ }+ _ => {}}}for g in &mut self.color_groups {diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rsindex d1bd06ad0..28fbb25c4 100644--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@ -404,7 +404,7 @@ pub fn specs() -> Vec<CommandSpec> {"Gradient",[],None,- "{kind?: linear|radial, stops?: [{location: 0–100, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255)|{model: rgb|cmyk|gray, …}(0..1) | swatch: name (its colour, as dropped on the Gradient panel), opacity?: 0–100, midpoint?: 13–87}], reverse?: bool, angle?: degrees, from?: [x,y], to?: [x,y] (spread coords: the Gradient Swatch tool's drag), target?: fill|stroke, ids?} → {swatch, kind, stops} — edits the fill's (or the stroke's) gradient (an unnamed gradient unless it equals a gradient swatch)",+ "{kind?: linear|radial, stops?: [{location: 0–100, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255)|{model: rgb|cmyk|gray, …}(0..1) | swatch: a colour swatch's name (as dropped on the Gradient panel: its colour on screen, its inks in print), opacity?: 0–100, midpoint?: 13–87}], reverse?: bool, angle?: degrees, from?: [x,y], to?: [x,y] (spread coords: the Gradient Swatch tool's drag), target?: fill|stroke, ids?} → {swatch, kind, stops: [{location, color, swatch?, opacity, midpoint}]} — edits the fill's (or the stroke's) gradient (an unnamed gradient unless it equals a gradient swatch)",super::has_selection,apply_gradient),@@ -490,6 +490,7 @@ pub fn specs() -> Vec<CommandSpec> {return Err(bad("swatch.delete", "special swatches can't be deleted"));}d.swatches.retain(|w| w.name != name);+ d.forget_gradient_stop_swatch(&name);for g in &mut d.color_groups {g.swatches.retain(|w| *w != name);}@@ -1295,13 +1296,14 @@ fn create_gradient_swatch(s: &mut Session, p: &Value, g: &Value) -> Result<Valuelet doc = &s.doc()?.doc;let mut stops = Vec::new();for st in g.get("stops").and_then(Value::as_array).ok_or_else(|| bad(ID, "a gradient needs stops"))? {- let color = match (st.get("swatch").and_then(Value::as_str), st.get("color")) {+ // The stop keeps the swatch, so print export writes it in that swatch's inks.+ let (color, swatch) = match (st.get("swatch").and_then(Value::as_str), st.get("color")) {(Some(n), _) => match doc.swatch(n).map(|w| &w.value) {Some(SwatchValue::Gradient { .. }) => return Err(bad(ID, format!("`{n}` is a gradient; a stop takes a colour"))),- Some(_) => doc.resolve_color(n, 1.0).ok_or_else(|| bad(ID, format!("`{n}` has no colour")))?,+ Some(_) => (doc.resolve_color(n, 1.0).ok_or_else(|| bad(ID, format!("`{n}` has no colour")))?, Some(n.to_string())),None => return Err(bad(ID, format!("no swatch named `{n}`"))),},- (None, Some(c)) => parse_color(c).ok_or_else(|| bad(ID, "a stop has a bad color"))?,+ (None, Some(c)) => (parse_color(c).ok_or_else(|| bad(ID, "a stop has a bad color"))?, None),(None, None) => return Err(bad(ID, "a stop needs a swatch or a color")),};let pct = |k: &str, d: f64| st.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(d).clamp(0.0, 100.0) as f32 / 100.0;@@ -1310,6 +1312,7 @@ fn create_gradient_swatch(s: &mut Session, p: &Value, g: &Value) -> Result<Valuecolor,opacity: pct("opacity", 100.0),midpoint: pct("midpoint", 50.0).clamp(0.13, 0.87),+ swatch,});}if stops.len() < 2 {@@ -1660,7 +1663,13 @@ fn gradient_json(name: &str, g: &designcraft_color::Gradient) -> Value {let stops: Vec<Value> = g.stops.iter()- .map(|s| json!({"location": (s.offset as f64 * 1000.0).round() / 10.0, "color": s.color.to_hex(), "opacity": (s.opacity * 100.0).round(), "midpoint": (s.midpoint * 100.0).round()}))+ .map(|s| {+ let mut v = json!({"location": (s.offset as f64 * 1000.0).round() / 10.0, "color": s.color.to_hex(), "opacity": (s.opacity * 100.0).round(), "midpoint": (s.midpoint * 100.0).round()});+ if let (Some(o), Some(w)) = (v.as_object_mut(), &s.swatch) {+ o.insert("swatch".into(), json!(w));+ }+ v+ }).collect();json!({"swatch": name, "kind": if g.kind == designcraft_color::GradientKind::Radial { "radial" } else { "linear" }, "stops": stops})}@@ -1678,13 +1687,18 @@ fn apply_gradient(s: &mut Session, p: &Value) -> Result<Value> {let doc = &s.doc()?.doc;let mut v = Vec::new();for st in a {- // A swatch dropped on a stop gives it the swatch's colour (a tint's mixed in).- let color = match st.get("swatch").and_then(Value::as_str) {- Some(name) => doc- .resolve_color(name, 1.0)- .filter(|_| designcraft_color::swatch::resolve_gradient(&doc.swatches, name).is_none())- .ok_or_else(|| bad("object.gradient", format!("`{name}` isn't a colour swatch")))?,- None => st.get("color").and_then(parse_color).ok_or_else(|| bad("object.gradient", "a stop needs a color or a swatch"))?,+ // A swatch dropped on a stop gives it the swatch's colour (a tint's mixed in) and+ // its inks for print.+ // A stop naming a swatch that's gone keeps the colour given with it.+ let color = st.get("color").and_then(parse_color);+ let (color, swatch) = match st.get("swatch").and_then(Value::as_str) {+ Some(name) => {+ match doc.resolve_color(name, 1.0).filter(|_| designcraft_color::swatch::resolve_gradient(&doc.swatches, name).is_none()) {+ Some(c) => (c, Some(name.to_string())),+ None => (color.ok_or_else(|| bad("object.gradient", format!("`{name}` isn't a colour swatch")))?, None),+ }+ }+ None => (color.ok_or_else(|| bad("object.gradient", "a stop needs a color or a swatch"))?, None),};let pct = |k: &str, d: f64| st.get(k).and_then(Value::as_f64).unwrap_or(d).clamp(0.0, 100.0) as f32 / 100.0;v.push(GradientStop {@@ -1692,6 +1706,7 @@ fn apply_gradient(s: &mut Session, p: &Value) -> Result<Value> {color,opacity: pct("opacity", 100.0),midpoint: pct("midpoint", 50.0).clamp(0.13, 0.87),+ swatch,});}if v.len() < 2 {@@ -2107,6 +2122,7 @@ fn swatch_options(s: &mut Session, p: &Value) -> Result<Value> {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);+ d.refresh_gradient_stops();Ok(json!({"name": new}))})?;if let Some(new) = result.get("name").and_then(Value::as_str) {@@ -3445,6 +3461,31 @@ mod gradient_swatch_tests {}}+ #[test]+ fn gradient_stops_follow_their_swatch() {+ let mut s = doc();+ s.execute("swatch.create", &json!({"name": "Gold", "color": {"c": 0, "m": 30, "y": 90, "k": 10}, "spot": true})).unwrap();+ s.execute(+ "swatch.create",+ &json!({"name": "G", "gradient": {"stops": [{"location": 0, "swatch": "Gold"}, {"location": 100, "swatch": "[Paper]"}]}}),+ )+ .unwrap();+ let stops = |s: &crate::Session| match &s.doc().unwrap().doc.swatch("G").unwrap().value {+ SwatchValue::Gradient { gradient } => gradient.stops.clone(),+ v => panic!("{v:?}"),+ };+ assert_eq!(stops(&s)[0].swatch.as_deref(), Some("Gold"));+ assert_eq!(stops(&s)[1].swatch.as_deref(), Some("[Paper]"));+ // Renamed and edited: the stop names the new name and shows the new colour.+ s.execute("swatch.options", &json!({"name": "Gold", "to": "Gold 871", "color": {"c": 0, "m": 20, "y": 80, "k": 20}})).unwrap();+ assert_eq!(stops(&s)[0].swatch.as_deref(), Some("Gold 871"));+ assert_eq!(stops(&s)[0].color, designcraft_color::Color::cmyk(0.0, 0.2, 0.8, 0.2));+ // Deleted: the stop keeps its colour as a plain one.+ s.execute("swatch.delete", &json!({"name": "Gold 871"})).unwrap();+ assert_eq!(stops(&s)[0].swatch, None);+ assert_eq!(stops(&s)[0].color, designcraft_color::Color::cmyk(0.0, 0.2, 0.8, 0.2));+ }+#[test]fn new_swatch_names_the_selections_gradient_or_duplicates_a_swatch() {let mut s = doc();diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rsindex 0009b4adb..281891f0c 100644--- a/crates/engine/src/sample.rs+++ b/crates/engine/src/sample.rs@@ -127,10 +127,7 @@ fn build() -> designcraft_doc::Result<Document> {value: SwatchValue::Gradient {gradient: Gradient {kind: GradientKind::Linear,- stops: vec![- GradientStop { offset: 0.0, color: Color::cmyk(0.62, 0.95, 0.30, 0.25), opacity: 1.0, midpoint: 0.5 },- GradientStop { offset: 1.0, color: Color::cmyk(0.0, 0.62, 0.78, 0.0), opacity: 1.0, midpoint: 0.5 },- ],+ stops: vec![GradientStop::new(0.0, Color::cmyk(0.62, 0.95, 0.30, 0.25)), GradientStop::new(1.0, Color::cmyk(0.0, 0.62, 0.78, 0.0))],},},locked: false,diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex 86fef8e46..8b7e91000 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -594,9 +594,16 @@ impl<'a> Ex<'a> {.attr("Visible", "true").attr("SwatchCreatorID", "7937");for (i, stop) in gradient.stops.iter().enumerate() {- let cid = match by_value.iter().find(|(c, _)| *c == stop.color) {- Some((_, id)) => id.clone(),- None => {+ // A stop on a swatch names it; a plain colour names an equal colour swatch or+ // an unnamed colour.+ let named = stop+ .swatch+ .as_deref()+ .filter(|n| d.swatch(n).is_some_and(|w| !matches!(w.value, SwatchValue::Gradient { .. } | SwatchValue::None)));+ let cid = match (named, by_value.iter().find(|(c, _)| *c == stop.color)) {+ (Some(n), _) => self.sw(n),+ (None, Some((_, id))) => id.clone(),+ (None, None) => {let cid = format!("Color/{}", self.fresh());colors.push(color_el(&cid, "$ID/", "Process", &stop.color, "Normal", true, true, false));by_value.push((stop.color, cid.clone()));diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex d770aef79..371df63c2 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -976,12 +976,17 @@ impl<'r> Importer<'r> {let Some(id) = e.get("Self") else { continue };let mut stops: Vec<GradientStop> = Vec::new();for s in e.find_all("GradientStop") {- let c = s.get("StopColor").map(|r| self.color_for_ref(r, &order)).unwrap_or(Color::BLACK);+ let r = s.get("StopColor");+ let c = r.map(|r| self.color_for_ref(r, &order)).unwrap_or(Color::BLACK);+ // A stop on a named swatch (a spot, a tint, [Paper]) keeps it for its inks;+ // unnamed colours stay plain. The id becomes the swatch's name below, once+ // repeated names are numbered.+ let swatch = r.filter(|r| self.swatch_names.get(*r).is_some_and(|n| n != swatch::NONE)).map(str::to_string);let loc = s.num("Location").unwrap_or(0.0) / 100.0;if let (Some(prev), Some(m)) = (stops.last_mut(), s.num("Midpoint")) {prev.midpoint = (m / 100.0) as f32;}- stops.push(GradientStop { offset: loc as f32, color: c, opacity: 1.0, midpoint: 0.5 });+ stops.push(GradientStop { swatch, ..GradientStop::new(loc as f32, c) });}let kind = if e.get("Type") == Some("Radial") { GradientKind::Radial } else { GradientKind::Linear };let unnamed = e.get("Visible") == Some("false") || e.get("Name").is_none_or(|n| n.is_empty() || n == "$ID/");@@ -1006,6 +1011,7 @@ impl<'r> Importer<'r> {order.sort_by_key(|(id, _)| group_order.iter().position(|g| g == id).unwrap_or(usize::MAX));}let mut names: HashSet<String> = self.swatches.iter().map(|s| s.name.clone()).collect();+ let first_new = self.swatches.len();for (id, mut s) in order {if names.contains(&s.name) {let base = s.name.clone();@@ -1015,6 +1021,16 @@ impl<'r> Importer<'r> {names.insert(s.name.clone());self.swatches.push(s);}+ let stop_names = |stops: &mut Vec<GradientStop>, ids: &HashMap<String, String>| {+ for stop in stops {+ stop.swatch = stop.swatch.take().and_then(|id| ids.get(&id).cloned());+ }+ };+ for s in self.swatches.iter_mut().skip(first_new).chain(self.hidden_swatches.values_mut()) {+ if let SwatchValue::Gradient { gradient } = &mut s.value {+ stop_names(&mut gradient.stops, &self.swatch_names);+ }+ }// Colour groups other than the root one become Swatches panel folders.for g in top.iter().filter(|e| e.local() == "ColorGroup" && e.get("IsRootColorGroup") != Some("true")) {let swatches: Vec<String> =diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex 035333da4..5336973d5 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -707,6 +707,8 @@ fn imports_hand_written_fixture() {assert_eq!(gradient.kind, designcraft_color::GradientKind::Radial);assert_eq!(gradient.stops[1].color, Color::cmyk(0.1, 0.2, 0.3, 0.4));assert!((gradient.stops[0].midpoint - 0.3).abs() < 1e-6);+ assert_eq!(gradient.stops[0].swatch.as_deref(), Some("Brand"), "a stop on a swatch keeps it");+ assert_eq!(gradient.stops[1].swatch, None, "an unnamed colour stays plain");// The parent rectangle used an unnamed colour → value-named swatch.let mr = &d.parents[0].items[0];assert_eq!(mr.fill.swatch, "C=10 M=20 Y=30 K=40");@@ -988,6 +990,29 @@ fn round_trips_small_document() {assert!(back.swatch("Brand 30").is_some());}+#[test]+fn gradient_stops_keep_their_swatches_through_a_round_trip() {+ use designcraft_color::{ColorType, Gradient, GradientKind, GradientStop};+ let mut d = Document::new(&NewDocument::default());+ let gold = Color::cmyk(0.0, 0.3, 0.9, 0.1);+ d.swatches.push(Swatch { value: SwatchValue::Color { color: gold, color_type: ColorType::Spot }, ..Swatch::color("Gold", gold) });+ d.swatches.push(Swatch { value: SwatchValue::Tint { base: "Gold".into(), tint: 0.4 }, ..Swatch::color("Gold 40%", gold) });+ let on = |offset: f32, name: &str| GradientStop {+ swatch: Some(name.into()),+ ..GradientStop::new(offset, designcraft_color::swatch::resolve(&d.swatches, name, 1.0).unwrap())+ };+ let stops = vec![on(0.0, "Gold"), on(0.3, "Gold 40%"), GradientStop::new(0.6, Color::cmyk(0.5, 0.0, 0.0, 0.0)), on(1.0, "[Paper]")];+ d.swatches.push(Swatch {+ value: SwatchValue::Gradient { gradient: Gradient { kind: GradientKind::Linear, stops } },+ ..Swatch::color("Gold fade", gold)+ });+ let back = import_idml(&export_idml(&d)).unwrap();+ let SwatchValue::Gradient { gradient } = &back.swatch("Gold fade").unwrap().value else { panic!("gradient") };+ let names: Vec<Option<&str>> = gradient.stops.iter().map(|s| s.swatch.as_deref()).collect();+ assert_eq!(names, [Some("Gold"), Some("Gold 40%"), None, Some("[Paper]")]);+ assert_eq!(gradient.stops[2].color, Color::cmyk(0.5, 0.0, 0.0, 0.0));+}+#[test]fn round_trips_overridden_parent_items() {let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() });diff --git a/crates/pdf/tests/gradient_color_spaces.rs b/crates/pdf/tests/gradient_color_spaces.rsindex 05806a120..01cd64b85 100644--- a/crates/pdf/tests/gradient_color_spaces.rs+++ b/crates/pdf/tests/gradient_color_spaces.rs@@ -14,7 +14,7 @@ fn document(colors: &[Color], kind: GradientKind, midpoint: f32, opacity: f32) -let stops = colors.iter().enumerate()- .map(|(i, &color)| GradientStop { offset: i as f32 / (colors.len() - 1) as f32, color, opacity, midpoint })+ .map(|(i, &color)| GradientStop { offset: i as f32 / (colors.len() - 1) as f32, color, opacity, midpoint, swatch: None }).collect();doc.swatches.push(Swatch {name: "Mixed inks".into(),diff --git a/crates/render/tests/gradient_inks.rs b/crates/render/tests/gradient_inks.rsindex 8bb407a66..0eb7f0f15 100644--- a/crates/render/tests/gradient_inks.rs+++ b/crates/render/tests/gradient_inks.rs@@ -10,7 +10,7 @@ use designcraft_render::{Placed, RenderOptions, Renderer};#[test]fn a_cmyk_gradient_is_c50_m50_halfway() {let mut d = Document::new(&NewDocument { width: 100.0, height: 20.0, facing_pages: false, ..Default::default() });- let stop = |offset: f32, color: Color| GradientStop { offset, color, opacity: 1.0, midpoint: 0.5 };+ let stop = |offset: f32, color: Color| GradientStop::new(offset, color);let gradient =Gradient { kind: GradientKind::Linear, stops: vec![stop(0.0, Color::cmyk(0.0, 1.0, 0.0, 0.0)), stop(1.0, Color::cmyk(1.0, 0.0, 0.0, 0.0))] };d.swatches.push(Swatch { name: "Magenta to Cyan".into(), value: SwatchValue::Gradient { gradient }, locked: false, named: true, hidden: false });diff --git a/crates/render/tests/gradients.rs b/crates/render/tests/gradients.rsindex 619d3103b..477e2c746 100644--- a/crates/render/tests/gradients.rs+++ b/crates/render/tests/gradients.rs@@ -11,7 +11,7 @@ use designcraft_render::{Placed, RenderOptions, Rendered, Renderer};/// A 100×200 rectangle at (50, 20) filled with a black-to-white radial gradient.fn portrait(vector: Option<[f64; 4]>) -> Document {let mut d = Document::new(&NewDocument { width: 200.0, height: 240.0, facing_pages: false, ..Default::default() });- let stop = |offset: f32, color: Color| GradientStop { offset, color, opacity: 1.0, midpoint: 0.5 };+ let stop = |offset: f32, color: Color| GradientStop::new(offset, color);d.swatches.push(Swatch {name: "Radial".into(),value: SwatchValue::Gradient {diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rsindex 3e7030e87..b4f7f2f9a 100644--- a/crates/ui-egui/src/panels/swatches.rs+++ b/crates/ui-egui/src/panels/swatches.rs@@ -586,11 +586,17 @@ fn color_json(c: &designcraft_color::Color) -> serde_json::Value {}}-/// Stops in `object.gradient` form.+/// Stops in `object.gradient` form: a stop on a swatch also names it, so it keeps its inks.fn stops_json(g: &designcraft_color::Gradient) -> Vec<serde_json::Value> {g.stops.iter()- .map(|s| json!({"location": s.offset as f64 * 100.0, "color": color_json(&s.color), "opacity": s.opacity as f64 * 100.0, "midpoint": s.midpoint as f64 * 100.0}))+ .map(|s| {+ let mut v = json!({"location": s.offset as f64 * 100.0, "color": color_json(&s.color), "opacity": s.opacity as f64 * 100.0, "midpoint": s.midpoint as f64 * 100.0});+ if let (Some(o), Some(w)) = (v.as_object_mut(), &s.swatch) {+ o.insert("swatch".to_string(), json!(w));+ }+ v+ }).collect()}@@ -847,6 +853,10 @@ pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {let mut rgb = [(r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8];if egui::color_picker::color_edit_button_srgb(ui, &mut rgb).changed() {let mut stops = stops_json(&g);+ // A picked colour replaces the stop's swatch.+ if let Some(o) = stops.get_mut(i).and_then(serde_json::Value::as_object_mut) {+ o.remove("swatch");+ }set_stop(&mut stops, i, "color", json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])));send = Some(json!({"stops": stops}));}@@ -980,6 +990,8 @@ mod gradient_panel_tests {assert_eq!(g.stops[1].color, Color::gray(0.6));assert!((g.stops[1].offset - 0.8).abs() < 1e-6);assert_eq!(g.stops[2].color, Color::gray(0.01), "a 1 % grey stays 1 %");+ assert_eq!(g.stops[0].swatch.as_deref(), Some("C=0 M=100 Y=0 K=0"), "a stop keeps its swatch");+ assert_eq!(g.stops[1].swatch, None);}#[test]diff --git a/docs/target-app-parity.md b/docs/target-app-parity.mdindex cdd6da689..ce1c26867 100644--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@ -436,7 +436,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level- View › Display Performance: Fast (grey boxes, no effects, ⌥⇧⌘Z), Typical (72 ppi proxies, ⌥⌘Z), High Quality (⌥⌘H, our default — the renderer is fast enough).- OpenType menu (Character panel): discretionary ligatures, fractions, ordinal, swash, titling, contextual alternates, slashed zero, the four figure styles and stylistic sets 1–20; `type.openType`; mapped to IDML's OTF attributes.- Add Anchor Point (=), Delete Anchor Point (-) and Convert Direction Point (⇧C) tools (click toggles smooth/corner, drag pulls out handles), with `path.addAnchor`, `path.deleteAnchor`, `path.convertAnchor`.-- Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel (InDesign's layout: thumbnail, Type, Location, Angle, Reverse) sets type, angle, reverse and edits stops and midpoints on a ramp (drag, add, drag off to remove, location; drop a swatch from the Swatches panel on a stop or the ramp; stops keep their CMYK), and follows the Fill/Stroke proxy. Edited gradients are unnamed swatches until the Swatches panel's New Swatch names one "New Gradient Swatch" (`swatch.new`, which also duplicates a named swatch); `swatch.create {gradient}` builds one from colour swatches; `object.gradient` (`target: stroke` for a stroke's gradient, drawn across the path's box on screen and in PDF); the vector round-trips through IDML (`GradientFill…`/`GradientStroke…`). A radial gradient stretches with the object's box as InDesign's does (an ellipse reaching the sides of a non-square frame, on screen and in PDF). Text takes a gradient swatch as its fill or stroke, laid across its frame's box as in InDesign (screen and PDF).+- Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel (InDesign's layout: thumbnail, Type, Location, Angle, Reverse) sets type, angle, reverse and edits stops and midpoints on a ramp (drag, add, drag off to remove, location; drop a swatch from the Swatches panel on a stop or the ramp; stops keep their CMYK, and a stop on a swatch keeps it, so spot stops shade as Separation or DeviceN in PDF), and follows the Fill/Stroke proxy. Edited gradients are unnamed swatches until the Swatches panel's New Swatch names one "New Gradient Swatch" (`swatch.new`, which also duplicates a named swatch); `swatch.create {gradient}` builds one from colour swatches; `object.gradient` (`target: stroke` for a stroke's gradient, drawn across the path's box on screen and in PDF); the vector round-trips through IDML (`GradientFill…`/`GradientStroke…`). A radial gradient stretches with the object's box as InDesign's does (an ellipse reaching the sides of a non-square frame, on screen and in PDF). Text takes a gradient swatch as its fill or stroke, laid across its frame's box as in InDesign (screen and PDF).- New Document (⌘N) as in InDesign: Recent, Saved, Print, Web and Mobile tabs of page cards (double-click creates) beside the preset's details: document name, size with arrows, units, orientation, pages, start page #, facing pages, primary text frame, columns, margins, bleed and slug per edge (linked or not); Save Document Preset (`file.savePreset`, `file.deletePreset`; saved presets are kept with the preferences, listed by `file.presets` and made by `file.new {preset: name}`); `file.new` takes `intent`, `units`, `startPage` and per-edge `bleed`/`slug`. Preview shows a document with the window's settings in the workspace while it is open; Create keeps it, Close removes it.- Document Setup (⌥⌘P), laid out like InDesign's: intent, number of pages, start page # (an even start begins with a left page), facing pages, binding, Page Size (presets keeping the orientation, width and height with arrows, orientation), margins for every page and parent page, bleed and slug per edge (each group linked or not), and Adjust Layout (objects follow the new page size and margins), all in one undo step; measures are read in the document's units, and a value that can't be read keeps the dialog open; `layout.documentSetup {}` reports the setup, margins included.- Stroke panel: cap, join, miter limit, alignment, type, Start/End arrowheads (12 kinds, drawn on screen and in PDF; the path is shortened under pointed heads) and gap colour under dashes and dots; with text selected (or text frames selected with Formatting Affects Text on) it shows the text's stroke weight, colour and Stroke Behind Fill.