diff --git a/contributors/people.toml b/contributors/people.toml index bf35bff30..6b0f2d421 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -92,6 +92,9 @@ display_name = "Jonathan Cardoso" real_name = "Adithya Shankaran" sync_github_name = true +[people.AlPaka1234] +real_name = "Christian Holtbrügger" + [people.alejo-c] sync_github_name = true diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 338f122f4..aa2e6fa50 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -502,7 +502,7 @@ fn is_origin(p: &[f64; 2]) -> bool { p[0] == 0.0 && p[1] == 0.0 } -/// The colours of new shapes (see [`DocSettings::new_object`]). +/// The colours and stroke defaults of new shapes (see [`DocSettings::new_object`]). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct NewObjectColors { @@ -510,12 +510,126 @@ pub struct NewObjectColors { pub fill_tint: f32, pub stroke: String, pub stroke_tint: f32, + #[serde(skip_serializing_if = "is_default_stroke_weight")] + pub stroke_weight: f64, + #[serde(rename = "strokeType", skip_serializing_if = "is_default_stroke_type")] + pub stroke_type: StrokeType, + #[serde(skip_serializing_if = "is_default_stroke_align")] + pub stroke_align: StrokeAlign, + #[serde(skip_serializing_if = "is_default_cap")] + pub stroke_cap: Cap, + #[serde(skip_serializing_if = "is_default_join")] + pub stroke_join: Join, + #[serde(skip_serializing_if = "is_default_miter_limit")] + pub stroke_miter_limit: f64, + #[serde(skip_serializing_if = "is_default_arrowhead")] + pub stroke_start: Arrowhead, + #[serde(skip_serializing_if = "is_default_arrowhead")] + pub stroke_end: Arrowhead, + #[serde(skip_serializing_if = "is_default_gap_swatch")] + pub gap_swatch: String, + #[serde(skip_serializing_if = "is_one_f32")] + pub gap_tint: f32, + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub gap_overprint: bool, +} + +fn is_default_stroke_weight(w: &f64) -> bool { + *w == 1.0 +} + +fn is_default_stroke_type(t: &StrokeType) -> bool { + matches!(t, StrokeType::Solid) +} + +fn is_default_stroke_align(a: &StrokeAlign) -> bool { + *a == StrokeAlign::Center +} + +fn is_default_cap(c: &Cap) -> bool { + *c == Cap::Butt +} + +fn is_default_join(j: &Join) -> bool { + *j == Join::Miter +} + +fn is_default_miter_limit(m: &f64) -> bool { + *m == 4.0 +} + +fn is_default_arrowhead(a: &Arrowhead) -> bool { + *a == Arrowhead::None +} + +fn is_default_gap_swatch(s: &str) -> bool { + s == designcraft_color::swatch::NONE +} + +fn is_one_f32(v: &f32) -> bool { + *v == 1.0 } impl Default for NewObjectColors { - /// No fill and a black stroke, as new documents have. + /// No fill and a 1 pt black stroke, as new documents have. fn default() -> Self { - NewObjectColors { fill: "[None]".into(), fill_tint: 1.0, stroke: "[Black]".into(), stroke_tint: 1.0 } + let s = Stroke::default(); + NewObjectColors { + fill: "[None]".into(), + fill_tint: 1.0, + stroke: s.swatch, + stroke_tint: s.tint, + stroke_weight: s.weight, + stroke_type: s.kind, + stroke_align: s.align, + stroke_cap: s.cap, + stroke_join: s.join, + stroke_miter_limit: s.miter_limit, + stroke_start: s.start, + stroke_end: s.end, + gap_swatch: s.gap_swatch, + gap_tint: s.gap_tint, + gap_overprint: s.gap_overprint, + } + } +} + +impl NewObjectColors { + /// The default stroke applied to newly drawn shapes and paths. + pub fn to_stroke(&self) -> Stroke { + Stroke { + swatch: self.stroke.clone(), + tint: self.stroke_tint, + weight: self.stroke_weight, + kind: self.stroke_type.clone(), + align: self.stroke_align, + cap: self.stroke_cap, + join: self.stroke_join, + miter_limit: self.stroke_miter_limit, + start: self.stroke_start, + end: self.stroke_end, + gap_swatch: self.gap_swatch.clone(), + gap_tint: self.gap_tint, + gap_overprint: self.gap_overprint, + ..Stroke::default() + } + } + + /// Copy `s` into the stroke defaults for new shapes. + pub fn set_stroke(&mut self, s: &Stroke) { + self.stroke = s.swatch.clone(); + self.stroke_tint = s.tint; + self.stroke_weight = s.weight; + self.stroke_type = s.kind.clone(); + self.stroke_align = s.align; + self.stroke_cap = s.cap; + self.stroke_join = s.join; + self.stroke_miter_limit = s.miter_limit; + self.stroke_start = s.start; + self.stroke_end = s.end; + self.gap_swatch = s.gap_swatch.clone(); + self.gap_tint = s.gap_tint; + self.gap_overprint = s.gap_overprint; } } diff --git a/crates/doc/src/swatch_refs.rs b/crates/doc/src/swatch_refs.rs index 2c9af65b8..a7a1ccb06 100644 --- a/crates/doc/src/swatch_refs.rs +++ b/crates/doc/src/swatch_refs.rs @@ -238,10 +238,10 @@ 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, the swatch an image is - /// coloured with), text, kenten and ruby colours, rules, shading, borders and border gaps, - /// tables (with stroke gaps, diagonal lines and cell images), footnotes, gradient stops, - /// endnotes and the footnote rule. The swatch itself is renamed by the caller. + /// styles, new-object defaults, page items (fills, strokes, gaps, effects, column rules, the + /// swatch an image is coloured with), text, kenten and ruby colours, rules, shading, borders + /// and border gaps, tables (with stroke gaps, diagonal lines and cell images), 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) { if from == to { return; @@ -271,6 +271,9 @@ impl Document { n.s(b); } n.s(&mut self.footnote_options.rule.color); + n.s(&mut self.settings.new_object.fill); + n.s(&mut self.settings.new_object.stroke); + n.s(&mut self.settings.new_object.gap_swatch); n.styles(self.styles_mut()); for sp in self.spreads.iter_mut().chain(self.parents.iter_mut()) { for it in &mut Arc::make_mut(sp).items { @@ -287,3 +290,22 @@ impl Document { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rename_swatch_refs_updates_new_object_defaults() { + let mut d = Document::new(&crate::build::NewDocument::default()); + d.settings.new_object.fill = "Gap".into(); + d.settings.new_object.stroke = "Keep".into(); + d.settings.new_object.gap_swatch = "Gap".into(); + + d.rename_swatch_refs("Gap", "Renamed Gap"); + + assert_eq!(d.settings.new_object.fill, "Renamed Gap"); + assert_eq!(d.settings.new_object.stroke, "Keep"); + assert_eq!(d.settings.new_object.gap_swatch, "Renamed Gap"); + } +} diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 5f25da50b..b0051194e 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -249,6 +249,9 @@ pub fn specs() -> Vec { return set_new_object(s, |c| { std::mem::swap(&mut c.fill, &mut c.stroke); std::mem::swap(&mut c.fill_tint, &mut c.stroke_tint); + if c.stroke != designcraft_color::swatch::NONE && c.stroke_weight <= 0.0 { + c.stroke_weight = Stroke::default().weight; + } }); } has_editable_selection(s).map_err(|e| bad("object.swapFillStroke", e))?; @@ -264,7 +267,13 @@ pub fn specs() -> Vec { has_doc, |s, p| { if nothing_targeted(s, p)? { - return set_new_object(s, |c| *c = designcraft_doc::NewObjectColors::default()); + return set_new_object(s, |c| { + let d = designcraft_doc::NewObjectColors::default(); + (c.fill, c.fill_tint, c.stroke, c.stroke_tint) = (d.fill, d.fill_tint, d.stroke, d.stroke_tint); + if c.stroke_weight <= 0.0 { + c.stroke_weight = d.stroke_weight; + } + }); } has_editable_selection(s).map_err(|e| bad("object.defaultFillStroke", e))?; edit_unlocked(s, p, default_fill_stroke) @@ -275,7 +284,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{swatch?, tint?: 0–1, weight?: 0–1000 pt, align?: center|inside|outside, type?: {kind: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed|stripes|style, pattern?: [dash, gap, …] (dashed: required, points), bands?: [[start, width], …] (stripes: required, fractions of stroke weight), name?: string (style: required, document stroke style name)} (other kinds take no extra fields; unknown type fields are errors), cap?: butt|round|projecting, join?: miter|round|bevel, miterLimit?: 1–500, start?, end?: none|simple|simpleWide|triangle|triangleWide|barbed|curved|circle|circleSolid|square|squareSolid|bar, gapSwatch?, gapTint?: 0–1, gapOverprint?: bool, ids?} (a value out of range or not listed is an error)", + "{swatch?, tint?: 0–1, weight?: 0–1000 pt, align?: center|inside|outside, type?: {kind: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed|stripes|style, pattern?: [dash, gap, …] (dashed: required, points), bands?: [[start, width], …] (stripes: required, fractions of stroke weight), name?: string (style: required, document stroke style name)} (other kinds take no extra fields; unknown type fields are errors), cap?: butt|round|projecting, join?: miter|round|bevel, miterLimit?: 1–500, start?, end?: none|simple|simpleWide|triangle|triangleWide|barbed|curved|circle|circleSolid|square|squareSolid|bar, gapSwatch?, gapTint?: 0–1, gapOverprint?: bool, ids?} (a value out of range or not listed is an error). With nothing selected: the stroke of new shapes", has_doc, |s, p| { let kind: Option = p @@ -312,18 +321,68 @@ pub fn specs() -> Vec { let arrowheads = "none, simple, simpleWide, triangle, triangleWide, barbed, curved, circle, circleSolid, square, squareSolid or bar"; let start = stroke_choice_param(p, "start", arrowheads)?; let end = stroke_choice_param(p, "end", arrowheads)?; - // With nothing selected, the swatch and tint are those of new shapes. + // With nothing selected, the stroke settings become the defaults for new shapes. if nothing_targeted(s, p)? { let sw = str_param(p, "swatch").map(str::to_string); - if sw.is_none() && tint.is_none() { + let gap_sw = str_param(p, "gapSwatch").map(str::to_string); + if sw.is_none() + && tint.is_none() + && weight.is_none() + && miter_limit.is_none() + && gap_sw.is_none() + && gap_tint.is_none() + && gap_overprint.is_none() + && kind.is_none() + && align.is_none() + && cap.is_none() + && join.is_none() + && start.is_none() + && end.is_none() + { return Err(bad("object.stroke", super::NOTHING_SELECTED)); } + let activates_stroke = weight != Some(0.0) + && (weight.is_some() + || kind.is_some() + || align.is_some() + || cap.is_some() + || join.is_some() + || miter_limit.is_some() + || start.is_some() + || end.is_some()); return set_new_object(s, |c| { - if let Some(sw) = &sw { - c.stroke = sw.clone(); - c.stroke_tint = 1.0; + let mut st = c.to_stroke(); + if st.swatch == designcraft_color::swatch::NONE && sw.is_none() && activates_stroke { + let def = Stroke::default(); + st.swatch = def.swatch; + st.tint = def.tint; + if st.weight <= 0.0 { + st.weight = def.weight; + } } - c.stroke_tint = tint.unwrap_or(c.stroke_tint); + if let Some(sw) = &sw { + st.swatch = sw.clone(); + st.tint = 1.0; + } + if st.swatch != designcraft_color::swatch::NONE { + st.tint = tint.unwrap_or(st.tint); + } + st.weight = weight.unwrap_or(st.weight); + st.miter_limit = miter_limit.unwrap_or(st.miter_limit); + if let Some(gap_sw) = &gap_sw { + st.gap_swatch = gap_sw.clone(); + } + st.gap_tint = gap_tint.unwrap_or(st.gap_tint); + st.gap_overprint = gap_overprint.unwrap_or(st.gap_overprint); + if let Some(kind) = &kind { + st.kind = kind.clone(); + } + st.align = align.unwrap_or(st.align); + st.cap = cap.unwrap_or(st.cap); + st.join = join.unwrap_or(st.join); + st.start = start.unwrap_or(st.start); + st.end = end.unwrap_or(st.end); + c.set_stroke(&st); }); } let p2 = p.clone(); @@ -978,16 +1037,24 @@ pub(crate) fn nothing_targeted(s: &Session, p: &Value) -> Result { && st.selection.cells.is_none()) } -/// Change the colours new shapes are drawn with (one undo step). +/// Change the fill and stroke defaults new shapes are drawn with (one undo step). pub(crate) fn set_new_object(s: &mut Session, f: impl FnOnce(&mut designcraft_doc::NewObjectColors)) -> Result { s.edit(|d, _| { f(&mut d.settings.new_object); let c = &d.settings.new_object; - Ok(json!({"newObject": {"fill": c.fill, "fillTint": c.fill_tint, "stroke": c.stroke, "strokeTint": c.stroke_tint}})) + Ok(json!({ + "newObject": { + "fill": c.fill, + "fillTint": c.fill_tint, + "stroke": c.stroke, + "strokeTint": c.stroke_tint, + "strokeWeight": c.stroke_weight, + } + })) }) } -/// A new shape's fill and stroke: the document's colours for new objects (a swatch deleted +/// A new shape's fill and stroke: the document's defaults for new objects (a swatch deleted /// since leaves the shape's own). fn new_object_colors(d: &designcraft_doc::Document, it: &mut Item) { let c = &d.settings.new_object; @@ -995,10 +1062,16 @@ fn new_object_colors(d: &designcraft_doc::Document, it: &mut Item) { if known(&c.fill) { it.fill = Fill { swatch: c.fill.clone(), tint: c.fill_tint, ..it.fill.clone() }; } - if known(&c.stroke) { - it.stroke.swatch = c.stroke.clone(); - it.stroke.tint = c.stroke_tint; + let mut st = c.to_stroke(); + if !known(&st.swatch) { + st.swatch = it.stroke.swatch.clone(); + st.tint = it.stroke.tint; } + if !known(&st.gap_swatch) { + st.gap_swatch = designcraft_color::swatch::NONE.into(); + st.gap_tint = 1.0; + } + it.stroke = st; } fn frame_create(s: &mut Session, p: &Value) -> Result { @@ -1044,8 +1117,8 @@ fn frame_create(s: &mut Session, p: &Value) -> Result { it.effects = e.clone(); } } else { - // Shapes drawn with Rectangle/Ellipse/Polygon get a 1 pt stroke in the document's - // colours for new objects (no fill and black at first). + // Shapes drawn with Rectangle/Ellipse/Polygon get the document's fill and stroke + // defaults for new objects (no fill and 1 pt black stroke at first). it.stroke = Stroke::default(); new_object_colors(d, &mut it); } @@ -4427,6 +4500,257 @@ mod step_repeat_tests { assert_eq!(s.doc().unwrap().doc.settings.new_object.fill, "[Paper]"); } + /// Regression test for #2858: with nothing selected, setting stroke weight and style attributes + /// updates the document defaults for newly drawn Pencil, Pen, Line, and shape items without + /// altering existing items. + #[test] + fn with_nothing_selected_stroke_defaults_apply_to_pencil_pen_line_and_shapes() { + use designcraft_doc::{Arrowhead, Cap, Join, StrokeAlign, StrokeType}; + use designcraft_tools::{PointerEvent, PointerKind}; + + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let existing = s.execute("frame.create", &json!({"rect": [20, 20, 80, 80], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(s.doc().unwrap().doc.item(ItemId(existing)).unwrap().stroke.weight, 1.0); + + // Deselect all objects and change stroke defaults. + s.execute("selection.set", &json!({"ids": []})).unwrap(); + let res = s + .execute( + "object.stroke", + &json!({ + "weight": 6, + "cap": "round", + "join": "bevel", + "align": "inside", + "miterLimit": 12, + "start": "circle", + "end": "triangle", + "type": {"kind": "dashed", "pattern": [8.0, 3.0]}, + "gapSwatch": "[Paper]", + "gapTint": 0.5, + "gapOverprint": true + }), + ) + .unwrap(); + assert_eq!(res["newObject"]["strokeWeight"], 6.0); + // Existing item is unchanged. + assert_eq!(s.doc().unwrap().doc.item(ItemId(existing)).unwrap().stroke.weight, 1.0); + + // Draw with the Pencil tool: the created path inherits the 6 pt stroke and all attributes. + s.set_tool("pencil"); + let v = crate::ViewInfo::at_zoom(1.0); + s.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 120.0), v).unwrap(); + for i in 1..=20 { + s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0 + i as f64 * 5.0, 120.0 + (i as f64 * 0.4).sin() * 15.0), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 220.0, 125.0), v).unwrap(); + let pencil_id = *s.doc().unwrap().selection.items.first().expect("pencil stroke should select created path"); + let pencil_stroke = s.doc().unwrap().doc.item(pencil_id).unwrap().stroke.clone(); + assert_eq!(pencil_stroke.weight, 6.0); + assert_eq!(pencil_stroke.cap, Cap::Round); + assert_eq!(pencil_stroke.join, Join::Bevel); + assert_eq!(pencil_stroke.align, StrokeAlign::Inside); + assert_eq!(pencil_stroke.miter_limit, 12.0); + assert_eq!(pencil_stroke.start, Arrowhead::Circle); + assert_eq!(pencil_stroke.end, Arrowhead::Triangle); + assert_eq!(pencil_stroke.kind, StrokeType::Dashed { pattern: vec![8.0, 3.0] }); + assert_eq!(pencil_stroke.gap_swatch, "[Paper]"); + assert_eq!(pencil_stroke.gap_tint, 0.5); + assert!(pencil_stroke.gap_overprint); + + // New Pen path, Line, and unassigned shape also inherit the defaults. + s.execute("selection.set", &json!({"ids": []})).unwrap(); + let pen_id = + ItemId(s.execute("path.create", &json!({"anchors": [{"p": [0, 0]}, {"p": [50, 20]}, {"p": [100, 0]}]})).unwrap()["id"].as_u64().unwrap()); + let line_id = ItemId(s.execute("line.create", &json!({"a": [0, 0], "b": [100, 0]})).unwrap()["id"].as_u64().unwrap()); + let rect_id = ItemId(s.execute("frame.create", &json!({"rect": [10, 10, 90, 90], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap()); + for id in [pen_id, line_id, rect_id] { + let st = &s.doc().unwrap().doc.item(id).unwrap().stroke; + assert_eq!(st.weight, 6.0, "{id:?}"); + assert_eq!(st.cap, Cap::Round, "{id:?}"); + } + + // Editing a selected object leaves the document defaults alone. + s.execute("selection.set", &json!({"ids": [existing]})).unwrap(); + s.execute("object.stroke", &json!({"weight": 2})).unwrap(); + assert_eq!(s.doc().unwrap().doc.item(ItemId(existing)).unwrap().stroke.weight, 2.0); + assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke_weight, 6.0); + + // Save/load round-trips the stroke defaults. + let reloaded = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap(); + assert_eq!(reloaded.settings.new_object, s.doc().unwrap().doc.settings.new_object); + + // Undo/redo restores and re-applies default stroke changes. + s.execute("selection.set", &json!({"ids": []})).unwrap(); + s.execute("object.stroke", &json!({"weight": 9})).unwrap(); + assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke_weight, 9.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke_weight, 6.0); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke_weight, 9.0); + } + + #[test] + fn with_nothing_selected_stroke_edge_cases_and_validation() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + + // Empty `object.stroke {}` still requires a parameter or selection. + let err = s.execute("object.stroke", &json!({})).unwrap_err(); + assert!(matches!(err, crate::EngineError::BadParams { .. })); + + // Out-of-range weight with nothing selected is refused without mutating defaults. + let before = s.doc().unwrap().doc.settings.new_object.clone(); + assert!(s.execute("object.stroke", &json!({"weight": 1500})).is_err()); + assert_eq!(s.doc().unwrap().doc.settings.new_object, before); + + // When default stroke swatch is [None], tint alone does not add a stroke, whereas setting + // weight activates a [Black] stroke at that weight. + s.execute("object.stroke", &json!({"swatch": "[None]"})).unwrap(); + s.execute("object.stroke", &json!({"tint": 0.5})).unwrap(); + assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke, "[None]"); + s.execute("object.stroke", &json!({"weight": 4})).unwrap(); + assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke, "[Black]"); + assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke_weight, 4.0); + s.execute("object.fill", &json!({"swatch": "[Paper]", "tint": 0.5})).unwrap(); + s.execute( + "object.stroke", + &json!({"swatch": "[Paper]", "tint": 0.25, "weight": 6, "cap": "round", "type": {"kind": "dashed", "pattern": [8.0, 3.0]}}), + ) + .unwrap(); + s.execute("object.defaultFillStroke", &json!({})).unwrap(); + let c = &s.doc().unwrap().doc.settings.new_object; + assert_eq!((c.fill.as_str(), c.fill_tint, c.stroke.as_str(), c.stroke_tint), ("[None]", 1.0, "[Black]", 1.0)); + assert_eq!(c.stroke_weight, 6.0); + assert_eq!(c.stroke_cap, designcraft_doc::Cap::Round); + assert_eq!(c.stroke_type, designcraft_doc::StrokeType::Dashed { pattern: vec![8.0, 3.0] }); + + // Visible-weight rule: resetting to a black stroke restores a 0 pt default weight to 1 pt + // while keeping the other stroke attributes intact. + s.execute("object.stroke", &json!({"weight": 0})).unwrap(); + s.execute("object.defaultFillStroke", &json!({})).unwrap(); + let c = &s.doc().unwrap().doc.settings.new_object; + assert_eq!(c.stroke_weight, 1.0); + assert_eq!(c.stroke_cap, designcraft_doc::Cap::Round); + assert_eq!(c.stroke_type, designcraft_doc::StrokeType::Dashed { pattern: vec![8.0, 3.0] }); + } + + #[test] + fn restoring_zero_default_stroke_weight_preserves_stroke_style() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + + s.execute( + "object.stroke", + &json!({ + "swatch": "[Paper]", + "tint": 0.5, + "weight": 6, + "cap": "round", + "type": {"kind": "dashed", "pattern": [8.0, 3.0]} + }), + ) + .unwrap(); + s.execute("object.stroke", &json!({"weight": 0})).unwrap(); + s.execute("object.stroke", &json!({"weight": 6})).unwrap(); + + let c = &s.doc().unwrap().doc.settings.new_object; + assert_eq!(c.stroke, "[Paper]"); + assert_eq!(c.stroke_tint, 0.5); + assert_eq!(c.stroke_weight, 6.0); + assert_eq!(c.stroke_cap, designcraft_doc::Cap::Round); + assert_eq!(c.stroke_type, designcraft_doc::StrokeType::Dashed { pattern: vec![8.0, 3.0] }); + + let shape_id = + ItemId(s.execute("frame.create", &json!({"rect": [10, 10, 90, 90], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap()); + let st = &s.doc().unwrap().doc.item(shape_id).unwrap().stroke; + assert_eq!(st.swatch, "[Paper]"); + assert_eq!(st.tint, 0.5); + assert_eq!(st.weight, 6.0); + assert_eq!(st.cap, designcraft_doc::Cap::Round); + assert_eq!(st.kind, designcraft_doc::StrokeType::Dashed { pattern: vec![8.0, 3.0] }); + } + + #[test] + fn gap_only_default_stroke_edits_keep_disabled_stroke_none() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + + s.execute("object.stroke", &json!({"swatch": "[None]"})).unwrap(); + s.execute("object.stroke", &json!({"gapSwatch": "[Paper]"})).unwrap(); + s.execute("object.stroke", &json!({"gapTint": 0.5})).unwrap(); + s.execute("object.stroke", &json!({"gapOverprint": true})).unwrap(); + + let c = &s.doc().unwrap().doc.settings.new_object; + assert_eq!(c.stroke, "[None]"); + assert_eq!(c.gap_swatch, "[Paper]"); + assert_eq!(c.gap_tint, 0.5); + assert!(c.gap_overprint); + + let shape_id = + ItemId(s.execute("frame.create", &json!({"rect": [10, 10, 90, 90], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap()); + let st = &s.doc().unwrap().doc.item(shape_id).unwrap().stroke; + assert_eq!(st.swatch, "[None]"); + assert!(st.is_none()); + assert_eq!(st.gap_swatch, "[Paper]"); + assert_eq!(st.gap_tint, 0.5); + assert!(st.gap_overprint); + } + + #[test] + fn tint_edit_at_zero_default_stroke_weight_applies_when_weight_restored() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + + s.execute("object.stroke", &json!({"weight": 0})).unwrap(); + s.execute("object.stroke", &json!({"tint": 0.25})).unwrap(); + let c = &s.doc().unwrap().doc.settings.new_object; + assert_eq!(c.stroke, "[Black]"); + assert_eq!(c.stroke_tint, 0.25); + assert_eq!(c.stroke_weight, 0.0); + + s.execute("object.stroke", &json!({"weight": 6})).unwrap(); + let shape_id = + ItemId(s.execute("frame.create", &json!({"rect": [10, 10, 90, 90], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap()); + let st = &s.doc().unwrap().doc.item(shape_id).unwrap().stroke; + assert_eq!(st.swatch, "[Black]"); + assert_eq!(st.tint, 0.25); + assert_eq!(st.weight, 6.0); + } + + #[test] + fn renaming_default_gap_swatch_applies_to_next_shape() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("swatch.create", &json!({"name": "Gap", "color": "#ff4020"})).unwrap(); + let expected_color = s.doc().unwrap().doc.resolve_color("Gap", 1.0).unwrap(); + + s.execute("selection.set", &json!({"ids": []})).unwrap(); + s.execute( + "object.stroke", + &json!({ + "type": {"kind": "dashed", "pattern": [6.0, 2.0]}, + "gapSwatch": "Gap" + }), + ) + .unwrap(); + + s.execute("swatch.options", &json!({"name": "Gap", "to": "Renamed Gap"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.settings.new_object.gap_swatch, "Renamed Gap"); + + let shape_id = + ItemId(s.execute("frame.create", &json!({"rect": [10, 10, 90, 90], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let st = &doc.item(shape_id).unwrap().stroke; + assert_eq!(st.gap_swatch, "Renamed Gap"); + assert_eq!(doc.resolve_color(&st.gap_swatch, st.gap_tint), Some(expected_color)); + } + #[test] fn swap_and_default_fill_stroke_are_one_undo_step_per_object() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/object_control.rs b/crates/ui-egui/src/object_control.rs index 056ea68cf..1d88f2429 100644 --- a/crates/ui-egui/src/object_control.rs +++ b/crates/ui-egui/src/object_control.rs @@ -160,21 +160,21 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) { }); separator(ui); group(ui, "appearance", 224.0, |ui, rect| { + let defaults = if info.is_none() { app.session.active().map(|d| d.doc.settings.new_object.clone()) } else { None }; + let has_stroke_target = selected || defaults.is_some(); for (row, stroke) in [(0, false), (1, true)] { // The chips open with nothing selected too, as they always have. cell(ui, rect, 0.0, row, 30.0, true, |ui| { - let chip_resp = panels::swatch_picker( - app, - ui, - if stroke { "ctlstroke" } else { "ctlfill" }, - info.as_ref().map(|i| if stroke { i.stroke.clone() } else { i.fill.clone() }), - |app, name| { - let _ = app.run(if stroke { "object.stroke" } else { "object.fill" }, json!({"swatch": name})); - }, - ); + let swatch = info + .as_ref() + .map(|i| if stroke { i.stroke.clone() } else { i.fill.clone() }) + .or_else(|| defaults.as_ref().map(|c| if stroke { c.stroke.clone() } else { c.fill.clone() })); + let chip_resp = panels::swatch_picker(app, ui, if stroke { "ctlstroke" } else { "ctlfill" }, swatch.clone(), |app, name| { + let _ = app.run(if stroke { "object.stroke" } else { "object.fill" }, json!({"swatch": name})); + }); let chip = Rect::from_min_size(rect.min + vec2(0.0, row as f32 * ROW_PITCH + 1.5), vec2(18.0, 18.0)); if stroke && let Some(doc) = app.session.active().map(|st| &st.doc) { - let (color, gradient) = info.as_ref().map_or((Some(Color32::GRAY), None), |i| widgets::swatch_colors(doc, &i.stroke, 1.0)); + let (color, gradient) = swatch.as_deref().map_or((Some(Color32::GRAY), None), |s| widgets::swatch_colors(doc, s, 1.0)); let inner = Tokens::get(ui.ctx()).panel; if gradient.is_some() { widgets::paint_chip(ui.painter(), chip, color, gradient); @@ -191,14 +191,18 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) { }); } icon(ui, rect, 36.0, 0, "panel-stroke", &tr("Stroke Weight")); - if let Some(v) = cell(ui, rect, 56.0, 0, 74.0, selected, |ui| { - NumField::points("csw", info.as_ref().map(|i| i.stroke_weight), 3).width(74.0).spinner().range(0.0, 1000.0).show(ui) + let weight = info.as_ref().map(|i| i.stroke_weight).or_else(|| defaults.as_ref().map(|c| c.stroke_weight)); + if let Some(v) = cell(ui, rect, 56.0, 0, 74.0, has_stroke_target, |ui| { + NumField::points("csw", weight, 3).width(74.0).spinner().range(0.0, 1000.0).show(ui) }) { let _ = app.run("object.stroke", json!({"weight": v})); } - cell(ui, rect, 36.0, 1, 94.0, selected, |ui| { - properties::stroke_type_dropdown(app, ui, info.as_ref().map_or("solid", |i| &i.stroke_kind), 94.0) - }); + let kind = info + .as_ref() + .map(|i| i.stroke_kind.clone()) + .or_else(|| defaults.as_ref().map(|c| panels::stroke_kind_id(&c.stroke_type))) + .unwrap_or_else(|| "solid".into()); + cell(ui, rect, 36.0, 1, 94.0, has_stroke_target, |ui| properties::stroke_type_dropdown(app, ui, &kind, 94.0)); icon(ui, rect, 138.0, 0, "opacity", &tr("Opacity")); if let Some(v) = cell(ui, rect, 158.0, 0, 66.0, selected, |ui| { NumField::number("cop", info.as_ref().map(|i| i.opacity * 100.0), "%", 0).width(66.0).spinner().range(0.0, 100.0).show(ui) @@ -410,4 +414,14 @@ mod tests { let after = ctx.read_response(id).unwrap().rect; assert!(after.left() < before.left() && after.right() <= 900.0, "scrolling reaches the last group: {before:?} -> {after:?}"); } + + #[test] + fn empty_selection_allows_editing_default_stroke_weight_in_control_bar() { + let (ctx, mut app) = fixture(false); + assert_eq!(app.session.active().unwrap().doc.settings.new_object.stroke_weight, 1.0); + let group = ctx.read_response(egui::Id::unique(("object_control", "appearance"))).unwrap().rect; + let stroke_up = group.min + vec2(56.0 + widgets::SEG_W / 2.0, FIELD_H / 4.0); + click(&ctx, &mut app, stroke_up); + assert_eq!(app.session.active().unwrap().doc.settings.new_object.stroke_weight, 2.0); + } } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 650bab97d..8c9496d93 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -253,10 +253,7 @@ pub fn sel_info(app: &DesignApp) -> Option { kind: first.default_label(), is_graphic: matches!(first.content, Content::Graphic(_)), is_text: first.is_text_frame(), - stroke_kind: serde_json::to_value(&first.stroke.kind) - .ok() - .and_then(|v| v.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| v.as_str().map(str::to_string))) - .unwrap_or_else(|| "solid".into()), + stroke_kind: stroke_kind_id(&first.stroke.kind), corner: (first.corners.corners[0].shape, first.corners.corners[0].size), wrap_invert: tw.invert, wrap_side: serde_json::to_value(tw.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), @@ -267,6 +264,14 @@ pub fn sel_info(app: &DesignApp) -> Option { }) } +/// The JSON kind string for a stroke type (`solid`, `dashed`, `thickThin`, …). +pub fn stroke_kind_id(kind: &designcraft_doc::StrokeType) -> String { + serde_json::to_value(kind) + .ok() + .and_then(|v| v.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| v.as_str().map(str::to_string))) + .unwrap_or_else(|| "solid".into()) +} + /// Resolved attributes at the text selection (or the selected text frames). /// The fonts the active document sees: its own (its `Document Fonts` folder) ahead of the shared /// ones. diff --git a/crates/ui-egui/src/panels/properties/object_panels.rs b/crates/ui-egui/src/panels/properties/object_panels.rs index a2756621d..d8ec899c5 100644 --- a/crates/ui-egui/src/panels/properties/object_panels.rs +++ b/crates/ui-egui/src/panels/properties/object_panels.rs @@ -16,17 +16,21 @@ pub fn stroke_panel(app: &mut DesignApp, ui: &mut egui::Ui) { text_stroke_panel(app, ui, &a["chars"]); return; } - let Some(i) = sel_info(app) else { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Select an object.")); - return; - }; - let Some(st) = app.session.active().and_then(|d| d.selection.items.first().and_then(|id| d.doc.item(*id)).map(|it| it.stroke.clone())) else { + let st = if sel_info(app).is_some() { + let Some(st) = app.session.active().and_then(|d| d.selection.items.first().and_then(|id| d.doc.item(*id)).map(|it| it.stroke.clone())) else { + return; + }; + st + } else if let Some(d) = app.session.active() { + d.doc.settings.new_object.to_stroke() + } else { + crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "No document open")); return; }; let t = Tokens::get(ui.ctx()); egui::Grid::new("stroke_panel").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| { caption(ui, crate::i18n::tr(&app.ui.language, "Weight:")); - if let Some(v) = number(ui, "sw", Some(i.stroke_weight), " pt", 60.0, 3) { + if let Some(v) = number(ui, "sw", Some(st.weight), " pt", 60.0, 3) { let _ = app.run("object.stroke", json!({"weight": v.clamp(0.0, 1000.0)})); } ui.end_row(); @@ -134,7 +138,7 @@ pub fn stroke_panel(app: &mut DesignApp, ui: &mut egui::Ui) { }); ui.end_row(); caption(ui, crate::i18n::tr(&app.ui.language, "Color:")); - crate::panels::swatch_picker(app, ui, "spick", Some(i.stroke.clone()), |app, n| { + crate::panels::swatch_picker(app, ui, "spick", Some(st.swatch.clone()), |app, n| { let _ = app.run("object.stroke", json!({"swatch": n})); }); ui.end_row(); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 12f5a0253..a976ac366 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -135,6 +135,48 @@ fn stroke_panel_shows_the_text_stroke_options_while_text_is_selected() { h.get_by_label("Stroke Behind Fill"); } +#[test] +fn stroke_panel_with_no_selection_edits_default_stroke_for_pencil_tool() { + use designcraft_tools::{PointerEvent, PointerKind}; + + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let existing = app.run("frame.create", json!({"rect": [10, 10, 50, 50], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": []})).unwrap(); + + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state( + move |ui, app: &mut DesignApp| { + if !ready { + crate::theme::install_fonts(ui.ctx(), ""); + crate::theme::apply(ui.ctx(), &Tokens::for_brightness(Default::default())); + ready = true; + return; + } + stroke_panel(app, ui); + }, + app, + ); + h.run_steps(3); + assert!(h.query_by_label("Select an object.").is_none()); + let field = h.get_all_by_role(egui::accesskit::Role::TextInput).next().unwrap().rect(); + type_in_field(&mut h, field, "6"); + + let app = h.state_mut(); + assert_eq!(app.session.active().unwrap().doc.settings.new_object.stroke_weight, 6.0); + assert_eq!(app.session.active().unwrap().doc.item(designcraft_doc::ItemId(existing)).unwrap().stroke.weight, 1.0); + + app.session.set_tool("pencil"); + let v = designcraft_engine::ViewInfo::at_zoom(1.0); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + for i in 1..=15 { + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 100.0 + i as f64 * 4.0, 100.0 + i as f64 * 2.0), v).unwrap(); + } + app.session.pointer(&PointerEvent::new(PointerKind::Up, 160.0, 130.0), v).unwrap(); + let drawn = *app.session.active().unwrap().selection.items.first().unwrap(); + assert_eq!(app.session.active().unwrap().doc.item(drawn).unwrap().stroke.weight, 6.0); +} + /// The text Stroke panel's Weight keeps a typed value inside the character stroke weight's /// range of 0 to 800 pt, as the character style's Weight field does. #[test]