From 73e0ce11756ef91484cc46841cf1063ae06fb549 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:09:30 +0000 Subject: [PATCH 01/17] Fix default stroke weight and style for Pencil and drawing tools (#2858) --- crates/doc/src/lib.rs | 120 ++++++++++- crates/engine/src/cmd/object.rs | 199 ++++++++++++++++-- crates/ui-egui/src/object_control.rs | 44 ++-- crates/ui-egui/src/panels.rs | 13 +- .../src/panels/properties/object_panels.rs | 18 +- crates/ui-egui/src/panels/properties/tests.rs | 42 ++++ 6 files changed, 392 insertions(+), 44 deletions(-) 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/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 32316f235..8fe8f0649 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))?; @@ -275,7 +278,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 +315,54 @@ 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 tint_only = p.as_object().is_some_and(|o| o.contains_key("tint") && o.keys().all(|k| k == "tint")); return set_new_object(s, |c| { - if let Some(sw) = &sw { - c.stroke = sw.clone(); - c.stroke_tint = 1.0; + let cur = c.to_stroke(); + if tint_only && cur.is_none() { + return; } - c.stroke_tint = tint.unwrap_or(c.stroke_tint); + let mut st = if cur.is_none() && sw.is_none() { Stroke::default() } else { cur }; + if let Some(sw) = &sw { + st.swatch = sw.clone(); + st.tint = 1.0; + } + 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 +1017,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 +1042,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 +1097,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); } @@ -4274,6 +4327,122 @@ 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); + } + #[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 194fecc2e..6f7534152 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 4325c3444..e78e98f9f 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] From 91f20fba1c485d65d6b817c07658e9370c34d608 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:09:30 +0000 Subject: [PATCH 02/17] Add AlPaka1234 to contributors/people.toml --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 617091888..de411454f 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -91,3 +91,6 @@ display_name = "Jonathan Cardoso" [people.adikshan11] real_name = "Adithya Shankaran" sync_github_name = true + +[people.AlPaka1234] +real_name = "Christian Holtbrügger" From 5104339c343e31fbb74c5e875263b6708df0025f Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:53:35 +0000 Subject: [PATCH 03/17] Update new-object swatch defaults when renaming a swatch (#2858) --- crates/doc/src/swatch_refs.rs | 30 ++++++++++++++++++++++++++---- crates/engine/src/cmd/object.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/swatch_refs.rs b/crates/doc/src/swatch_refs.rs index b3a885f89..c5999377b 100644 --- a/crates/doc/src/swatch_refs.rs +++ b/crates/doc/src/swatch_refs.rs @@ -237,10 +237,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 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 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; @@ -270,6 +270,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 { @@ -286,3 +289,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 8fe8f0649..a630f29b0 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -4443,6 +4443,34 @@ mod step_repeat_tests { assert_eq!(s.doc().unwrap().doc.settings.new_object.stroke_weight, 4.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(); From 76d8b7f6bcf6c305b0b1e04ba3902e4b884eeca7 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:48:57 +0000 Subject: [PATCH 04/17] 2880: keep bottom-aligned text anchored when fitting or resizing from top - Pass the opposite local reference point (ref 0..=8) from SelectionTool handle double-clicks into object.fit (omitting ref on mixed-orientation multi-selections). - Add ref?: 0..8 anchoring to object.fit (fitFrameToContent) and default vertical text-frame fitting to the edge implied by vertical justification (bottom/center) while preserving non-rectangular frame paths such as ovals. - Pin the unchanged edge in transform.resize before clamping scale at 1e-3 or flipping, and validate finite bounds and resulting transforms. - Add unit and SelectionTool integration regression tests covering handle double-clicks, rotations, drags, clamped drags, flips, overset growth, right alignment with inside stroke/inset, ovals, and undo. --- ROADMAP.md | 1 + crates/doc/src/item.rs | 2 +- crates/engine/src/cmd/object.rs | 387 ++++++++++++++++++++++++++++---- crates/engine/src/tests.rs | 63 ++++++ crates/tools/src/select.rs | 95 ++++++-- crates/tools/src/tests.rs | 56 ++++- docs/ui-parity.md | 4 +- 7 files changed, 538 insertions(+), 70 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 4727979cd..8851b1fc9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -394,6 +394,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-16** · Fitting or resizing a bottom-aligned text frame from its top handle keeps its bottom edge and text in place (#2880): double-clicking any selection handle passes the opposite local reference point (`ref` 0..=8) to `object.fit`, bottom- and center-justified text frames default to their aligned edge when `ref` is omitted, ovals keep their path shapes when fitted, and `transform.resize` keeps unchanged edges pinned across scale clamps and flips. No readiness percentage change. - **2026-11-15** · Removed the obsolete gap saying pull requests have no test workflow: [CI](.github/workflows/ci.yml) runs the shared quality gate on every pull request and push to main (#1352). No readiness percentage change. - **2026-11-15** · Accepting tracked deletions or rejecting insertions follows body-text selections through the removed text, including resolving all changes, and preserves independent cell and footnote insertion points. No readiness percentage change. - **2026-11-15** · Format follow-ups to the craft-libs cutover (craft-libs#778; ported from #2734 by Dylan M. Taylor): IDML export keeps CDATA image contents and table spans such as `inf` reach the table edge; DOCX plain-text import leaves out deleted tracked changes and expands inline objects; an XLSX number cell that isn't a number shows as written; unmarked CMYK JPEGs keep the shared decoder's ink polarity; PPTX export writes exact opacity; PDF export repins craft-pdf and craft-prepress to craft-libs main. No readiness percentage change. diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 29b97e15d..7e1647d22 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -336,7 +336,7 @@ impl Item { /// How far a visible stroke reaches inside the path: half its weight centred, all of it inside, /// none outside. - fn stroke_inside(&self) -> f64 { + pub fn stroke_inside(&self) -> f64 { let w = self.stroke.weight; if self.stroke.is_none() || !w.is_finite() { return 0.0; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 32316f235..77bf52bef 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -646,7 +646,7 @@ pub fn specs() -> Vec { "Fitting", ["Object", "Fitting"], None, - "{mode: fillProportionally (preserves aspect ratio, covers frame, clips overflow)|fitProportionally (preserves aspect ratio, shows whole image, may leave empty space)|fitContentToFrame (stretches content to frame)|centerContent (keeps current size, positions at fitting alignment)|fitFrameToContent (resizes frame to content), axis?: both|height|width (frame-local sides Fit Frame to Content moves; default both), ids?} — locked objects and objects on locked layers are left as they are", + "{mode: fillProportionally (preserves aspect ratio, covers frame, clips overflow)|fitProportionally (preserves aspect ratio, shows whole image, may leave empty space)|fitContentToFrame (stretches content to frame)|centerContent (keeps current size, positions at fitting alignment)|fitFrameToContent (resizes frame to content), axis?: both|height|width (frame-local sides Fit Frame to Content moves; default both), ref?: 0..8 (reference point 0..=8, row-major from top-left, kept fixed when fitting text frames; default follows vertical justification), ids?} — locked objects and objects on locked layers are left as they are", has_selection, fit ), @@ -1424,19 +1424,41 @@ fn move_content(s: &mut Session, ids: &[ItemId], d: Vec2) -> Result { }) } +/// One-axis affine `(scale, from_anchor, to_anchor)` mapping `[f0, f1]` toward `[t0, t1]`. +/// Anchors the unchanged edge (before clamping or flipping) so near-zero clamps never drift it, +/// and leaves an unchanged axis as exact identity. +fn resize_axis_transform(f0: f64, f1: f64, t0: f64, t1: f64) -> (f64, f64, f64) { + if t0 == f0 && t1 == f1 { + return (1.0, 0.0, 0.0); + } + let old = f1 - f0; + // A flat source (a horizontal or vertical line) has no size to scale on its flat axis: that axis only moves. + if old.abs() < 1e-9 { + return (1.0, f0, t0); + } + let raw = (t1 - t0) / old; + let s = if raw.abs() < 1e-3 { 1e-3f64.copysign(raw) } else { raw }; + if (t1 - f1).abs() <= 1e-9 && (t0 - f0).abs() > 1e-9 { + (s, f1, t1) + } else if (t0 - f0).abs() <= 1e-9 && (t1 - f1).abs() > 1e-9 { + (s, f0, t0) + } else { + (s, (f0 + f1) * 0.5, (t0 + t1) * 0.5) + } +} + fn transform_resize(s: &mut Session, p: &Value) -> Result { let ids = targets(s, p)?; - let from = rect_param(p, "from").ok_or_else(|| bad("transform.resize", "missing from"))?; - let to = rect_param(p, "to").ok_or_else(|| bad("transform.resize", "missing to"))?; + let from = super::finite_rect("transform.resize", rect_param(p, "from").ok_or_else(|| bad("transform.resize", "missing from"))?)?; + let to = super::finite_rect("transform.resize", rect_param(p, "to").ok_or_else(|| bad("transform.resize", "missing to"))?)?; let scale_content = bool_or(p, "content", false); let distribute = bool_or(p, "distribute", false); - // A flat source (a horizontal or vertical line) has no size to scale on its flat axis: that axis only moves. - let ratio = |new: f64, old: f64| if old.abs() < 1e-9 { 1.0 } else { new / old }; - let sx = ratio(to.width(), from.width()); - let sy = ratio(to.height(), from.height()); - let sx = if sx.abs() < 1e-3 { 1e-3f64.copysign(sx) } else { sx }; - let sy = if sy.abs() < 1e-3 { 1e-3f64.copysign(sy) } else { sy }; - let m = Affine::translate((to.x0, to.y0)) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0)); + let (sx, fx, tx) = resize_axis_transform(from.x0, from.x1, to.x0, to.x1); + let (sy, fy, ty) = resize_axis_transform(from.y0, from.y1, to.y0, to.y1); + let m = Affine::translate((tx, ty)) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-fx, -fy)); + if !m.as_coeffs().iter().all(|v| v.is_finite()) { + return Err(bad("transform.resize", "the position and size must stay finite numbers")); + } let strokes = s.prefs.scale_strokes; s.edit(|d, _| { for id in &ids { @@ -3388,23 +3410,34 @@ fn clear_fitting_options(s: &mut Session, p: &Value) -> Result { }) } +fn fit_ref_param(p: &Value) -> Result> { + let Some(v) = p.get("ref").filter(|v| !v.is_null()) else { + return Ok(None); + }; + let Some(r) = v.as_u64().and_then(|n| usize::try_from(n).ok()).filter(|&n| n <= 8) else { + return Err(bad("object.fit", "ref must be an integer from 0 to 8")); + }; + Ok(Some(r)) +} + fn fit(s: &mut Session, p: &Value) -> Result { - let doc = &s.doc()?.doc; - let ids: Vec<_> = - targets(s, p)?.into_iter().filter(|id| doc.item(*id).is_some_and(|it| !it.locked && doc.layer(it.layer).is_none_or(|l| !l.locked))).collect(); - let mode = str_param(p, "mode").unwrap_or("fitProportionally").to_string(); + let ref_pt = fit_ref_param(p)?; let (height, width) = match str_param(p, "axis").unwrap_or("both") { "height" => (true, false), "width" => (false, true), "both" => (true, true), other => return Err(bad("object.fit", format!("unknown axis `{other}`"))), }; + let mode = str_param(p, "mode").unwrap_or("fitProportionally").to_string(); + let doc = &s.doc()?.doc; + let ids: Vec<_> = + targets(s, p)?.into_iter().filter(|id| doc.item(*id).is_some_and(|it| !it.locked && doc.layer(it.layer).is_none_or(|l| !l.locked))).collect(); // Text frames: Fit Frame to Content fits the frame to its composed text. let mut text_fits = Vec::new(); if mode == "fitFrameToContent" { let d = s.doc()?.doc.clone(); for id in &ids { - if let Some(r) = fitted_text_frame(&d, *id, height, width)? { + if let Some(r) = fitted_text_frame(&d, *id, height, width, ref_pt)? { text_fits.push((*id, r)); } } @@ -3412,7 +3445,7 @@ fn fit(s: &mut Session, p: &Value) -> Result { s.edit(|d, _| { for (id, r) in &text_fits { if let Some(it) = d.item_mut(*id) { - it.path = shapes::rectangle(*r); + it.path = resized_frame_path(&it.path, it.inner_bounds(), *r); } } for id in &ids { @@ -3441,12 +3474,130 @@ fn fit(s: &mut Session, p: &Value) -> Result { }) } +#[derive(Clone, Copy)] +enum FitSide { + Start, + Center, + End, +} + +#[derive(Clone, Copy)] +struct FitAnchors { + x: FitSide, + y: FitSide, +} + +fn fit_text_anchors(tf: &TextFrame, ref_pt: Option) -> FitAnchors { + if let Some(r) = ref_pt { + let side = |k: usize| match k { + 0 => FitSide::Start, + 1 => FitSide::Center, + _ => FitSide::End, + }; + return FitAnchors { x: side(r % 3), y: side(r / 3) }; + } + let y = match tf.options.vertical_justification { + designcraft_doc::VerticalJustification::Bottom => FitSide::End, + designcraft_doc::VerticalJustification::Center => FitSide::Center, + designcraft_doc::VerticalJustification::Top | designcraft_doc::VerticalJustification::Justify => FitSide::Start, + }; + FitAnchors { x: FitSide::Start, y } +} + +fn anchored_span(start: f64, end: f64, size: f64, side: FitSide) -> (f64, f64) { + match side { + FitSide::Start => (start, start + size), + FitSide::Center => { + let mid = (start + end) * 0.5; + let half = size * 0.5; + (mid - half, mid + half) + } + FitSide::End => (end - size, end), + } +} + +fn rect_with_width(cur: Rect, width: f64, side: FitSide) -> Rect { + let (x0, x1) = anchored_span(cur.x0, cur.x1, width, side); + Rect::new(x0, cur.y0, x1, cur.y1) +} + +fn rect_with_height(cur: Rect, height: f64, side: FitSide) -> Rect { + let (y0, y1) = anchored_span(cur.y0, cur.y1, height, side); + Rect::new(cur.x0, y0, cur.x1, y1) +} + +fn fit_axis_scale(f0: f64, f1: f64, t0: f64, t1: f64) -> (f64, f64, f64) { + if t0 == f0 && t1 == f1 { + return (1.0, 0.0, 0.0); + } + let s = (t1 - t0) / (f1 - f0); + if (t1 - f1).abs() <= 1e-9 && (t0 - f0).abs() > 1e-9 { + (s, f1, t1) + } else if (t0 - f0).abs() <= 1e-9 && (t1 - f1).abs() > 1e-9 { + (s, f0, t0) + } else { + (s, (f0 + f1) * 0.5, (t0 + t1) * 0.5) + } +} + +fn resized_frame_path(orig_path: &designcraft_geom::PathData, orig: Rect, to: Rect) -> designcraft_geom::PathData { + if orig.width() < 1e-6 || orig.height() < 1e-6 { + return shapes::rectangle(to); + } + let (sx, fx, tx) = fit_axis_scale(orig.x0, orig.x1, to.x0, to.x1); + let (sy, fy, ty) = fit_axis_scale(orig.y0, orig.y1, to.y0, to.y1); + let xf = Affine::translate((tx, ty)) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-fx, -fy)); + let path = orig_path.transformed(xf); + if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) { path } else { shapes::rectangle(to) } +} + +fn line_indents(d: &Document, story: &Story, line: &designcraft_compose::Line) -> (f64, f64) { + let Some(pf) = story.paras.get(line.para) else { + return (0.0, 0.0); + }; + let (pp, _) = d.styles.resolve_para(pf); + let first = if line.first_in_para && line.drop_cap.is_none() { pp.first_line_indent } else { 0.0 }; + if pp.direction == designcraft_doc::TextDirection::RightToLeft { + (pp.left_indent, pp.right_indent + first) + } else { + (pp.left_indent + first, pp.right_indent) + } +} + +fn fitted_column_width(d: &Document, story: &Story, ft: &designcraft_compose::FrameText) -> Option { + let mut max_w: Option = None; + let mut push = |w: f64| { + if w.is_finite() { + let w = w.max(0.0); + max_w = Some(max_w.map_or(w, |m| m.max(w))); + } + }; + for l in &ft.lines { + let col = ft.columns.get(l.column as usize); + let (lo, hi) = l.glyphs.iter().filter(|g| g.spans_rules()).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), g| { + let pen = g.x - g.dx; + (lo.min(pen), hi.max(pen + g.adv)) + }); + let ink = if hi >= lo { hi - lo } else { 0.0 }; + let (ind_l, ind_r) = line_indents(d, story, l); + let wrap = col.map_or(0.0, |c| (l.x0 - c.x0).max(0.0) + (c.x1 - l.x1).max(0.0)); + push(ink + ind_l + ind_r + wrap); + } + for t in &ft.tables { + let col = ft.columns.get(t.column as usize); + let wrap = col.map_or(0.0, |c| (t.rect.x0 - c.x0).max(0.0) + (c.x1 - t.rect.x1).max(0.0)); + push(t.rect.width() + wrap); + } + max_w +} + /// The inner rectangle that fits text frame `id` to its text (Fit Frame to Content): the smallest -/// fitting height and the right side at the longest line's end (`width`, one column only), -/// including insets; the top-left stays. Overset text grows the frame first. None for -/// frames that aren't horizontal text frames, have no text, or are threaded on to another frame, -/// and for auto-size frames, which already fit their text around their reference point. -fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool) -> Result> { +/// fitting height and column width (`width`, one column only), including insets and inside stroke, +/// keeping `ref_pt` (or the edge implied by vertical justification) fixed. Overset text grows the +/// frame first. None for frames that aren't horizontal text frames, have no text, or are threaded +/// on to another frame, and for auto-size frames, which already fit their text around their +/// reference point. +fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt: Option) -> Result> { let Some(it) = d.item(id) else { return Ok(None) }; let Some(tf) = it.text_frame() else { return Ok(None) }; if tf.options.auto_size != designcraft_doc::AutoSize::Off { @@ -3464,6 +3615,12 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool) -> Res if !(r.width().is_finite() && r.height().is_finite() && r.width() > 0.0 && r.height() > 0.0) { return Err(bad("object.fit", "text frame bounds must be finite and nonempty")); } + let [_, in_l, in_b, in_r] = tf.options.inset; + let stroke_in = it.stroke_inside(); + let sanitize = |v: f64| if v.is_finite() { v.max(0.0) } else { 0.0 }; + let (pad_l, pad_b, pad_r) = (sanitize(in_l) + stroke_in, sanitize(in_b) + stroke_in, sanitize(in_r) + stroke_in); + let anchors = fit_text_anchors(tf, ref_pt); + let orig_path = it.path.clone(); // Keep trial layouts out of the session cache. Search with the actual columns and frame // options: measuring a very tall frame collapses columns and includes vertical alignment's // extra space. A fitting trial must compose all the text, regardless of its justification. @@ -3471,7 +3628,7 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool) -> Res let mut trial = d.clone(); let mut compose = |rect| { if let Some(it) = trial.item_mut(id) { - it.path = shapes::rectangle(rect); + it.path = resized_frame_path(&orig_path, r, rect); } cache.get(&trial, tf.story, None) }; @@ -3483,40 +3640,41 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool) -> Res // First fit the height at the existing width, then measure the complete text's width. // Recheck height after fitting width, since a small width change can change a line break. if height { - out = fit_text_height(out, id, tf.options.inset[2], &mut compose)?; + out = fit_text_height(out, id, pad_b, anchors.y, &mut compose)?; } if width && tf.options.columns <= 1 { let cs = compose(out); - if let Some(ft) = cs.frame(id) { - let right = ft.lines.iter().map(|l| l.end_x).fold(f64::NEG_INFINITY, f64::max); - if right.is_finite() { - out.x1 = (right + tf.options.inset[3] + 0.001).max(r.x0 + 1.0); + if let Some(col_w) = cs.frame(id).and_then(|ft| fitted_column_width(d, story, ft)) { + let total_w = (pad_l + col_w + pad_r + 0.001).max(1.0); + if total_w.is_finite() { + out = rect_with_width(out, total_w, anchors.x); } } if height { - out = fit_text_height(out, id, tf.options.inset[2], &mut compose)?; + out = fit_text_height(out, id, pad_b, anchors.y, &mut compose)?; } } - Ok(Some(out)) + super::finite_rect("object.fit", out).map(Some) } fn fit_text_height( - mut rect: Rect, + rect: Rect, id: ItemId, - inset_bottom: f64, + pad_bottom: f64, + anchor_y: FitSide, compose: &mut impl FnMut(Rect) -> Arc, ) -> Result { let mut low = 1.0; let limit = 20_000.0; let mut high = rect.height().clamp(1.0, limit); - rect.y1 = rect.y0 + high; - while compose(rect).is_overset() { + let mut cur = rect_with_height(rect, high, anchor_y); + while compose(cur).is_overset() { if high >= limit { return Err(bad("object.fit", "text does not fit within the 20,000 pt fitting limit")); } low = high; high = (high * 2.0).min(limit); - rect.y1 = rect.y0 + high; + cur = rect_with_height(rect, high, anchor_y); } // Bounded search, always retaining a verified fitting upper bound. for _ in 0..32 { @@ -3524,22 +3682,23 @@ fn fit_text_height( break; } let mid = low + (high - low) / 2.0; - rect.y1 = rect.y0 + mid; - if compose(rect).is_overset() { + let candidate = rect_with_height(rect, mid, anchor_y); + if compose(candidate).is_overset() { low = mid; } else { high = mid; } } - rect.y1 = rect.y0 + high; + cur = rect_with_height(rect, high, anchor_y); // A line is set when its baseline is within 0.01 pt of the bottom, so the search stops just - // short of the lowest baseline. The bottom goes onto it (plus the inset): the frame then fits - // its text exactly and still does when it is scaled up. - let lowest = compose(rect).frame(id).and_then(|ft| ft.lines.iter().map(|l| l.baseline).reduce(f64::max)); - if let Some(b) = lowest.map(|b| b + inset_bottom).filter(|b| b.is_finite() && *b > rect.y1 && *b - rect.y1 <= 0.02) { - rect.y1 = b; + // short of the lowest baseline. Growing height along `anchor_y` by that residual keeps the + // pinned edge in place while making the frame fit exactly, even when scaled up. + let cs = compose(cur); + let lowest = cs.frame(id).and_then(|ft| ft.lines.iter().map(|l| l.baseline).chain(ft.tables.iter().map(|t| t.rect.y1)).reduce(f64::max)); + if let Some(extra) = lowest.map(|b| b + pad_bottom - cur.y1).filter(|e| e.is_finite() && *e > 0.0 && *e <= 0.02) { + cur = rect_with_height(rect, high + extra, anchor_y); } - Ok(rect) + Ok(cur) } pub(crate) trait RemoveKeep { @@ -4836,6 +4995,39 @@ mod fitting_tests { assert!((r.x0 - 100.0).abs() < 1e-9 && (r.x1 - 300.0).abs() < 1e-9 && (r.y0 - 100.0).abs() < 1e-9 && r.height().abs() < 1e-9, "{r:?}"); } + #[test] + fn transform_resize_pins_unchanged_edge_across_clamp_and_flip() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("frame.create", &json!({"rect": [100, 100, 400, 300], "content": "text", "text": "Bottom anchored"})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [id], "verticalJustification": "bottom"})).unwrap(); + let baselines = |s: &Session| { + let d = &s.doc().unwrap().doc; + let sid = d.item(ItemId(id)).unwrap().text_frame().unwrap().story; + s.cache.get(d, sid, None).frame(ItemId(id)).unwrap().lines.iter().map(|l| l.baseline).collect::>() + }; + let before_y = baselines(&s); + // Dragging the top edge down while keeping room for the text leaves text and y1 fixed. + s.execute("transform.resize", &json!({"ids": [id], "from": [100, 100, 400, 300], "to": [100, 200, 400, 300]})).unwrap(); + let mid = s.doc().unwrap().doc.item(ItemId(id)).unwrap().bounds(); + assert!((mid.y0 - 200.0).abs() < 1e-9 && (mid.y1 - 300.0).abs() < 1e-9, "{mid:?}"); + assert!((baselines(&s)[0] - before_y[0]).abs() < 1e-9); + // Dragging near the bottom edge hits the 1e-3 clamp: y1 must stay pinned instead of drifting. + s.execute("transform.resize", &json!({"ids": [id], "from": [100, 200, 400, 300], "to": [100, 299.99, 400, 300]})).unwrap(); + let tiny = s.doc().unwrap().doc.item(ItemId(id)).unwrap().bounds(); + assert!((tiny.y1 - 300.0).abs() < 1e-9, "bottom edge drifted under clamp: {tiny:?}"); + // Flipping the top edge past the bottom keeps the fixed bottom edge at y = 300. + s.execute("transform.resize", &json!({"ids": [id], "from": [tiny.x0, tiny.y0, tiny.x1, tiny.y1], "to": [100, 340, 400, 300]})).unwrap(); + let flipped = s.doc().unwrap().doc.item(ItemId(id)).unwrap().bounds(); + assert!((flipped.y0 - 300.0).abs() < 1e-9 && (flipped.y1 - 340.0).abs() < 1e-9, "{flipped:?}"); + // Non-finite or overflowing target bounds are refused without changing the frame. + assert!(s.execute("transform.resize", &json!({"ids": [id], "from": [100, 300, 400, 340], "to": [100, 1e308, 400, 340]})).is_err()); + assert!(s.execute("transform.resize", &json!({"ids": [id], "from": [100, 300, 400, 340], "to": [100, null, 400, 340]})).is_err()); + assert_eq!(s.doc().unwrap().doc.item(ItemId(id)).unwrap().bounds(), flipped); + } + #[test] fn live_distribute_spreads_objects_without_resizing() { let mut s = Session::new(); @@ -6555,6 +6747,115 @@ mod fit_text_frame_tests { assert!(s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ids": [a.0, b.0]})).is_err()); assert_eq!([bounds(&s, a), bounds(&s, b)], before); } + + #[test] + fn bottom_aligned_fit_keeps_bottom_edge_and_text_in_place() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Line one\nLine two"); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "verticalJustification": "bottom"})).unwrap(); + let baselines = |s: &Session| { + let d = &s.doc().unwrap().doc; + let sid = d.item(id).unwrap().text_frame().unwrap().story; + let cs = s.cache.get(d, sid, None); + (!cs.is_overset(), cs.frame(id).unwrap().lines.iter().map(|l| l.baseline).collect::>()) + }; + let (ok0, lines0) = baselines(&s); + assert!(ok0 && lines0.len() == 2); + + // Top-edge double click sends ref = 7 (bottom-center fixed): top edge drops onto the text. + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ref": 7, "ids": [id.0]})).unwrap(); + let b1 = bounds(&s, id); + let (ok1, lines1) = baselines(&s); + assert!(ok1 && (b1.y1 - 300.0).abs() < 1e-9 && b1.y0 > 200.0 && b1.x0 == 100.0 && b1.x1 == 500.0, "{b1:?}"); + assert!((lines1[0] - lines0[0]).abs() < 1e-6 && (lines1[1] - lines0[1]).abs() < 1e-6, "{lines0:?} vs {lines1:?}"); + + // Without an explicit ref (menu Fit Frame to Content), bottom-aligned frames also keep their bottom edge. + s.execute("transform.resize", &json!({"ids": [id.0], "from": [b1.x0, b1.y0, b1.x1, b1.y1], "to": [100.0, 100.0, 500.0, 300.0]})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [id.0]})).unwrap(); + let b2 = bounds(&s, id); + let (ok2, lines2) = baselines(&s); + assert!(ok2 && (b2.y1 - 300.0).abs() < 1e-9 && (b2.y0 - b1.y0).abs() < 1e-6, "{b2:?} vs {b1:?}"); + assert!((lines2[0] - lines0[0]).abs() < 1e-6 && (lines2[1] - lines0[1]).abs() < 1e-6, "{lines0:?} vs {lines2:?}"); + + // Invalid `ref` is rejected without touching the frame. + for bad_ref in [json!(9), json!(-1), json!("bottom")] { + assert!(s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ref": bad_ref, "ids": [id.0]})).is_err(), "{bad_ref}"); + } + assert_eq!(bounds(&s, id), b2); + } + + #[test] + fn fit_frame_handles_top_overset_center_right_align_stroke_inset_and_ovals() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + // Overset bottom-aligned frame grows upward while bottom edge stays put. + let id = frame(&mut s, [100.0, 265.0, 500.0, 300.0], "one\ntwo\nthree\nfour"); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "verticalJustification": "bottom"})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ref": 7, "ids": [id.0]})).unwrap(); + let b = bounds(&s, id); + let d = s.doc().unwrap().doc.clone(); + let sid = d.item(id).unwrap().text_frame().unwrap().story; + assert!(!s.cache.get(&d, sid, None).is_overset() && (b.y1 - 300.0).abs() < 1e-9 && b.y0 < 200.0, "{b:?}"); + + // Right-aligned single line with bottom-right fixed (top-left corner double-click, ref = 8). + let right = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); + s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [right.0], "verticalJustification": "bottom", "inset": [4, 6, 8, 10]})).unwrap(); + s.edit(|d, _| { + let it = d.item_mut(right).unwrap(); + it.stroke = Stroke { weight: 4.0, align: designcraft_doc::StrokeAlign::Inside, ..Stroke::default() }; + Ok(Value::Null) + }) + .unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [right.0]})).unwrap(); + let rb = bounds(&s, right); + assert!((rb.x1 - 500.0).abs() < 1e-9 && (rb.y1 - 300.0).abs() < 1e-9, "bottom-right pinned: {rb:?}"); + assert!(rb.width() < 200.0 && rb.height() < 60.0, "shrunk flush around short right-aligned line: {rb:?}"); + let d = s.doc().unwrap().doc.clone(); + let it = d.item(right).unwrap(); + let sid = it.text_frame().unwrap().story; + let cs = s.cache.get(&d, sid, None); + assert!(!cs.is_overset()); + assert!((cs.frame(right).unwrap().lines[0].baseline - it.text_area().y1).abs() < 1e-6); + + // Center-aligned without ref keeps vertical center. + let ctr = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Centered"); + s.execute("object.textFrameOptions", &json!({"ids": [ctr.0], "verticalJustification": "center"})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [ctr.0]})).unwrap(); + assert!((bounds(&s, ctr).center().y - 200.0).abs() < 1e-6); + + // Oval text frame retains its ellipse path rather than flattening into a rectangle. + let oval = ItemId( + s.execute("frame.create", &json!({"rect": [100, 400, 400, 700], "shape": "ellipse", "content": "text", "text": "Oval"})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("selection.set", &json!({"ids": [oval.0]})).unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [oval.0], "verticalJustification": "bottom"})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ref": 7, "ids": [oval.0]})).unwrap(); + let oval_it = s.doc().unwrap().doc.item(oval).unwrap(); + assert!((oval_it.bounds().y1 - 700.0).abs() < 1e-9); + assert!(oval_it.path.subpaths[0].anchors.iter().all(|a| a.kind == designcraft_geom::AnchorKind::Smooth)); + let sid = oval_it.text_frame().unwrap().story; + assert!(!s.cache.get(&s.doc().unwrap().doc, sid, None).is_overset()); + + // Rotated 90° bottom-aligned frame: fitting keeps its local bottom-center pinned in spread space. + let rot = frame(&mut s, [200.0, 100.0, 500.0, 300.0], "Rotated bottom"); + s.execute("object.textFrameOptions", &json!({"ids": [rot.0], "verticalJustification": "bottom"})).unwrap(); + s.execute("transform.rotate", &json!({"angle": 90, "ids": [rot.0]})).unwrap(); + let bottom_spread = |s: &Session| { + let it = s.doc().unwrap().doc.item(rot).unwrap(); + let r = it.inner_bounds(); + it.xf * Point::new(r.center().x, r.y1) + }; + let p0 = bottom_spread(&s); + let h0 = s.doc().unwrap().doc.item(rot).unwrap().inner_bounds().height(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ref": 7, "ids": [rot.0]})).unwrap(); + let p1 = bottom_spread(&s); + let h1 = s.doc().unwrap().doc.item(rot).unwrap().inner_bounds().height(); + assert!(h1 < h0 * 0.5 && (p1 - p0).hypot() < 1e-9, "{p0:?} vs {p1:?}, h: {h0} -> {h1}"); + } } #[cfg(test)] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 08c30cdef..bfccabbd3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2718,3 +2718,66 @@ fn deleting_the_active_layer_moves_to_a_usable_layer() { s.execute("layer.delete", &json!({"id": bottom.0})).unwrap(); assert_eq!(s.doc().unwrap().active_layer, artwork); } + +#[test] +fn selection_tool_drag_and_double_click_at_top_keeps_bottom_aligned_text_in_place() { + use designcraft_doc::{ItemId, SpreadRef}; + use designcraft_geom::{Point, Rect}; + use designcraft_tools::{PointerEvent, PointerKind}; + + let mut s = session(); + let r = s.execute("frame.create", &json!({"rect": [100, 100, 500, 300], "content": "text", "text": "Line one\nLine two"})).unwrap(); + let id = ItemId(r["id"].as_u64().unwrap()); + let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "verticalJustification": "bottom"})).unwrap(); + s.execute("selection.set", &json!({"ids": [id.0]})).unwrap(); + s.set_tool("selection"); + + let baselines = |s: &Session| { + let d = &s.doc().unwrap().doc; + let cs = s.cache.get(d, sid, None); + (!cs.is_overset(), cs.frame(id).unwrap().lines.iter().map(|l| l.baseline).collect::>()) + }; + let (ok0, lines0) = baselines(&s); + assert!(ok0 && lines0.len() == 2); + let original = Rect::new(100.0, 100.0, 500.0, 300.0); + + let v = ViewInfo { snap: designcraft_tools::SnapView::OFF, ..ViewInfo::at_zoom(1.0) }; + let canvas_pt = |s: &Session, x: f64, y: f64| s.layout().to_canvas(SpreadRef::Doc(0), Point::new(x, y)); + + // Drag the top-center handle down to y = 200: bottom edge and text stay anchored. + let top = canvas_pt(&s, 300.0, 100.0); + let mid = canvas_pt(&s, 300.0, 200.0); + s.pointer(&PointerEvent::new(PointerKind::Down, top.x, top.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, mid.x, mid.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, mid.x, mid.y), v).unwrap(); + let dragged = s.doc().unwrap().doc.item(id).unwrap().bounds(); + let (ok1, lines1) = baselines(&s); + assert!(ok1 && (dragged.y0 - 200.0).abs() < 1e-6 && (dragged.y1 - 300.0).abs() < 1e-9, "{dragged:?}"); + assert!((lines1[0] - lines0[0]).abs() < 1e-6 && (lines1[1] - lines0[1]).abs() < 1e-6, "{lines0:?} vs {lines1:?}"); + + // Undo and drag near the bottom edge (triggering the 1e-3 clamp): y1 still does not drift. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.item(id).unwrap().bounds(), original); + let top = canvas_pt(&s, 300.0, 100.0); + let near_bottom = canvas_pt(&s, 300.0, 299.99); + s.pointer(&PointerEvent::new(PointerKind::Down, top.x, top.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, near_bottom.x, near_bottom.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, near_bottom.x, near_bottom.y), v).unwrap(); + let clamped = s.doc().unwrap().doc.item(id).unwrap().bounds(); + assert!((clamped.y1 - 300.0).abs() < 1e-9, "bottom edge drifted on clamped drag: {clamped:?}"); + + // Undo and double-click the top-center handle: aligns flush with the text while bottom stays pinned. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.item(id).unwrap().bounds(), original); + let top = canvas_pt(&s, 300.0, 100.0); + let undo_before = s.doc().unwrap().history.undo.len(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, top.x, top.y), v).unwrap(); + let fitted = s.doc().unwrap().doc.item(id).unwrap().bounds(); + let (ok2, lines2) = baselines(&s); + assert!(ok2 && (fitted.y1 - 300.0).abs() < 1e-9 && fitted.y0 > 200.0 && fitted.x0 == 100.0 && fitted.x1 == 500.0, "{fitted:?}"); + assert!((lines2[0] - lines0[0]).abs() < 1e-6 && (lines2[1] - lines0[1]).abs() < 1e-6, "{lines0:?} vs {lines2:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.item(id).unwrap().bounds(), original); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1fb30e6f7..e50da7b0d 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -539,24 +539,76 @@ fn handle_at(cx: &ToolContext, p: Point) -> Option { handles(b).iter().position(|h| (h.x - p.x).abs() <= tol && (h.y - p.y).abs() <= tol) } -/// Side handles are drawn on the canvas bounding box; fitting uses the frame's local axes. -fn fitting_axis(cx: &ToolContext, handle: usize) -> &'static str { - if handle.is_multiple_of(2) { - return "both"; +/// Side handles are drawn on the canvas bounding box; fitting uses the frame's local axes and +/// keeps the opposite local edge/corner (`ref` 0..=8) fixed. When a multi-selection has differing +/// local orientations for the handle, `ref` is omitted so each frame keeps its own default. +fn fitting_params(cx: &ToolContext, handle: usize) -> (&'static str, Option) { + let dir = match handle { + 0 => Point::new(-1.0, -1.0), + 1 => Point::new(0.0, -1.0), + 2 => Point::new(1.0, -1.0), + 3 => Point::new(1.0, 0.0), + 4 => Point::new(1.0, 1.0), + 5 => Point::new(0.0, 1.0), + 6 => Point::new(-1.0, 1.0), + _ => Point::new(-1.0, 0.0), + }; + let corner = handle.is_multiple_of(2); + let fallback_axis = if corner { + "both" + } else if matches!(handle, 3 | 7) { + "width" + } else { + "height" + }; + let for_item = |id: ItemId| -> Option<(&'static str, usize)> { + let it = cx.doc.item(id)?; + let xf = cx.item_canvas_xf(id)? * it.xf; + fitting_item_params(xf, dir, corner, fallback_axis) + }; + let mut results = cx.selection.items.iter().filter_map(|id| for_item(*id)); + let Some((first_axis, first_ref)) = results.next() else { + return (fallback_axis, None); + }; + let all_match = results.all(|(ax, rf)| ax == first_axis && rf == first_ref); + (first_axis, all_match.then_some(first_ref)) +} + +fn fitting_item_params(xf: designcraft_geom::Affine, dir: Point, corner: bool, fallback_axis: &'static str) -> Option<(&'static str, usize)> { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let det = a * d - b * c; + if !(det.is_finite() && det.abs() > 1e-12) { + return None; } - let canvas_height = matches!(handle, 1 | 5); - let local_width_is_vertical = cx - .selection - .items - .first() - .and_then(|id| { - let it = cx.doc.item(*id)?; - let xf = cx.item_canvas_xf(*id)? * it.xf; - let [a, b, _, _, _, _] = xf.as_coeffs(); - Some(b.abs() > a.abs()) - }) - .unwrap_or(false); - if canvas_height == local_width_is_vertical { "width" } else { "height" } + let lx = (d * dir.x - c * dir.y) / det; + let ly = (-b * dir.x + a * dir.y) / det; + if !(lx.is_finite() && ly.is_finite()) { + return None; + } + let axis = if corner { + "both" + } else if (lx.abs() - ly.abs()).abs() <= 1e-9 { + fallback_axis + } else if lx.abs() > ly.abs() { + "width" + } else { + "height" + }; + let anchor = |v: f64| { + if v < -1e-6 { + 2 + } else if v > 1e-6 { + 0 + } else { + 1 + } + }; + let (rx, ry) = match axis { + "width" => (anchor(lx), 1), + "height" => (1, anchor(ly)), + _ => (anchor(lx), anchor(ly)), + }; + Some((axis, ry * 3 + rx)) } /// Just outside a corner handle of the selection → rotate. @@ -1276,14 +1328,19 @@ impl Tool for SelectionTool { return actions; } // The second press of a double click on a selection handle: Fit Frame to Content, along - // that handle's side (a corner fits both). + // that handle's side (a corner fits both), anchoring the opposite side. if !self.direct && matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick) && ev.click_count() == 2 && let Some(h) = handle_at(cx, p) { self.drag = Drag::None; - return vec![Action::Exec("object.fit".into(), json!({"mode": "fitFrameToContent", "axis": fitting_axis(cx, h)}))]; + let (axis, rf) = fitting_params(cx, h); + let params = match rf { + Some(rf) => json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}), + None => json!({"mode": "fitFrameToContent", "axis": axis}), + }; + return vec![Action::Exec("object.fit".into(), params)]; } // The second press of a double click on a text frame: edit its text. if matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick) diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index acbef71fa..b62dd3f29 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -1845,9 +1845,9 @@ fn double_clicking_a_handle_fits_the_frame_to_its_content_along_that_side() { let off = l.xf(SpreadRef::Doc(0)).translation(); let cx = ctx(&d, &s, &c, &l); let mut t = create("selection"); - for ((x, y), axis) in [((300.0, 200.0), "both"), ((200.0, 200.0), "height"), ((300.0, 150.0), "width")] { + for ((x, y), axis, rf) in [((300.0, 200.0), "both", 0), ((200.0, 200.0), "height", 1), ((300.0, 150.0), "width", 3)] { let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x + off.x, y + off.y)); - assert_eq!(a, vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))], "{axis}"); + assert_eq!(a, vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}))], "{axis}"); } } @@ -1864,13 +1864,19 @@ fn fitting_handle_axes_follow_spread_and_frame_rotation() { let cx = ctx(&d, &s, &c, &l); let b = cx.selection_bounds().unwrap(); let mut t = create("selection"); - let swapped = (spread_turn + frame_turn) % 2 == 1; - for (index, axis) in [(1, if swapped { "width" } else { "height" }), (3, if swapped { "height" } else { "width" }), (4, "both")] { + let total_turn = ((spread_turn + frame_turn) % 4) as usize; + let swapped = total_turn % 2 == 1; + let expected = [ + (1, if swapped { "width" } else { "height" }, [7, 5, 1, 3][total_turn]), + (3, if swapped { "height" } else { "width" }, [3, 7, 5, 1][total_turn]), + (4, "both", [0, 6, 8, 2][total_turn]), + ]; + for (index, axis, rf) in expected { let p = select::handles(b)[index]; let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y)); assert_eq!( a, - vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))], + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}))], "spread={spread_turn}, frame={frame_turn}, handle={index}" ); } @@ -1878,6 +1884,46 @@ fn fitting_handle_axes_follow_spread_and_frame_rotation() { } } +#[test] +fn double_clicking_top_and_rotated_handles_sets_opposite_ref() { + let mut d = Document::new(&NewDocument::default()); + let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0)); + let s = Selection { items: vec![id], ..Default::default() }; + let (c, l) = (Cache::new(), CanvasLayout::new(&d, false)); + let off = l.xf(SpreadRef::Doc(0)).translation(); + let cx = ctx(&d, &s, &c, &l); + let mut t = create("selection"); + // Handle 1 (top) fixes bottom-center (7); TL (0) fixes BR (8); L (7) fixes right-center (5). + for (handle, axis, rf) in [(1, "height", 7), (0, "both", 8), (2, "both", 6), (7, "width", 5)] { + let p = select::handles(Rect::new(100.0 + off.x, 100.0 + off.y, 300.0 + off.x, 200.0 + off.y))[handle]; + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y)); + assert_eq!( + a, + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}))], + "handle={handle}" + ); + } + // Rotating the frame 180 deg maps canvas top (1) to local bottom, so local top (1) stays fixed. + d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate(std::f64::consts::PI); + let cx = ctx(&d, &s, &c, &l); + let b = cx.selection_bounds().unwrap(); + let top = select::handles(b)[1]; + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, top.x, top.y)), + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": "height", "ref": 1}))] + ); + // Mixed rotations in one selection omit `ref` so each frame uses its own default. + let other = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0)); + let s2 = Selection { items: vec![id, other], ..Default::default() }; + let cx2 = ctx(&d, &s2, &c, &l); + let b2 = cx2.selection_bounds().unwrap(); + let top2 = select::handles(b2)[1]; + assert_eq!( + t.pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, top2.x, top2.y)), + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": "height"}))] + ); +} + #[test] fn pen_continues_an_open_path_from_either_end_point() { let mut d = Document::new(&NewDocument::default()); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7adf8fead..91c6b3499 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** patch (the Pen previews the curve while a smooth point is dragged and curves the rubber band after one, #1438; a Custom text variable defined with a number shows its digits, #2093; Table of Contents dialog: title field keeps its width, More Options toggles without losing hidden settings; Story panel; text Control panel Character/Paragraph modes; Properties ••• expands Character and Paragraph; live corners work; document views row: scrollbars, Alt pans while editing text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; paragraph style override feedback and clearing) · **Target:** Adobe InDesign 2026 (21.6, Medium Dark, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** patch (the Pen previews the curve while a smooth point is dragged and curves the rubber band after one, #1438; a Custom text variable defined with a number shows its digits, #2093; Table of Contents dialog: title field keeps its width, More Options toggles without losing hidden settings; Story panel; text Control panel Character/Paragraph modes; Properties ••• expands Character and Paragraph; live corners work; document views row: scrollbars, Alt pans while editing text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; paragraph style override feedback and clearing; double-clicking a handle anchors its opposite side when fitting, #2880) · **Target:** Adobe InDesign 2026 (21.6, Medium Dark, macOS) Tools, handles, snapping, nudging, modifiers, shortcuts, panels, menus, context menus and feel, against InDesign 2026. The look was measured from the running app @@ -31,7 +31,7 @@ basics of editing fail for too many users on Windows and Linux. | Selection tool: click, marquee, move, Alt-duplicate, resize handles, rotate from corners | ✓ | ✓ | ✓ | Cmd/Ctrl held with another tool borrows the selection tool used last (Selection or Direct Selection) for one gesture, #919 | | Direct Selection, Pen family, Pencil, Scissors | ✓ | ✓ | ~ | the Pen previews the segment while a smooth point is dragged out and curves the rubber band out of a smooth point's direction line (`pen_previews_the_curve_while_dragging_and_after_a_smooth_point`, #1438); moving reference point "0" fails (#337) | | Live corners (yellow handle) | ✓ | ✓ widget on a selected rectangle frame; diamonds drag the corner size (Shift: one corner), Alt-click steps the shape (Shift+Alt: all) | ✓ | #186 | -| Content grabber, frame fitting by double-click | ✓ | ✓ | ✓ | | +| Content grabber, frame fitting by double-click | ✓ | ✓ double-clicking a handle anchors its opposite side (#2880) | ✓ | `object::fit_text_frame_tests::bottom_aligned_fit_keeps_bottom_edge_and_text_in_place` | | Overset mark (red + at the out port) | selected frame only | every overset frame, groups included, while frame edges show | ✓ | a deliberate step past InDesign: grouped labels that overflow were invisible until Preflight | | Smart guides, snapping to guides/grid/baseline | ✓ | ✓ (2,049-line `snap.rs`) | ~ | vertical smart spacing between two rectangles (#188) | | Nudging with arrows, Shift ×10 | ✓ | ✓ | ✓ | | From 246288f19a5bc80b12f3876746f1e33e3daea2ab Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:38:24 +0000 Subject: [PATCH 05/17] 2880: measure table width without column whitespace in fit --- crates/engine/src/cmd/object.rs | 45 ++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 77bf52bef..6dce51863 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3584,9 +3584,13 @@ fn fitted_column_width(d: &Document, story: &Story, ft: &designcraft_compose::Fr push(ink + ind_l + ind_r + wrap); } for t in &ft.tables { - let col = ft.columns.get(t.column as usize); - let wrap = col.map_or(0.0, |c| (t.rect.x0 - c.x0).max(0.0) + (c.x1 - t.rect.x1).max(0.0)); - push(t.rect.width() + wrap); + // TableFrag::rect is the table's placed bounds (not a column slot), so gaps to the column + // edges are unused whitespace; only add horizontal indents that place_table reserves. + let indents = ft.lines.get(t.line).and_then(|l| story.paras.get(l.para)).map(|pf| d.styles.resolve_para(pf).0).map_or(0.0, |pp| { + let pos = |v: f64| if v.is_finite() { v.max(0.0) } else { 0.0 }; + pos(pp.left_indent) + pos(pp.right_indent) + }); + push(t.rect.width() + indents); } max_w } @@ -6856,6 +6860,41 @@ mod fit_text_frame_tests { let h1 = s.doc().unwrap().doc.item(rot).unwrap().inner_bounds().height(); assert!(h1 < h0 * 0.5 && (p1 - p0).hypot() < 1e-9, "{p0:?} vs {p1:?}, h: {h0} -> {h1}"); } + + #[test] + fn fit_frame_shrinks_around_narrow_table() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let created = s.execute("frame.create", &json!({"rect": [100, 100, 500, 300], "content": "text"})).unwrap(); + let id = ItemId(created["id"].as_u64().unwrap()); + let sid = designcraft_doc::StoryId(created["story"].as_u64().unwrap()); + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2, "width": 120.0})).unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "verticalJustification": "bottom"})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [id.0]})).unwrap(); + let b = bounds(&s, id); + assert!((b.x1 - 500.0).abs() < 1e-9 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); + assert!((b.width() - 120.001).abs() < 1e-6, "width should fit the 120 pt table: {b:?}"); + let d = &s.doc().unwrap().doc; + let cs = s.cache.get(d, sid, None); + assert!(!cs.is_overset()); + assert!((cs.frame(id).unwrap().tables[0].rect.width() - 120.0).abs() < 1e-6); + + // Paragraph horizontal indents are still preserved so fitting does not squeeze the table. + let created2 = s.execute("frame.create", &json!({"rect": [100, 400, 500, 600], "content": "text"})).unwrap(); + let id2 = ItemId(created2["id"].as_u64().unwrap()); + let sid2 = designcraft_doc::StoryId(created2["story"].as_u64().unwrap()); + s.execute("text.select", &json!({"story": sid2.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("type.para", &json!({"attrs": {"leftIndent": 20.0, "rightIndent": 10.0}})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2, "width": 100.0})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ids": [id2.0]})).unwrap(); + let b2 = bounds(&s, id2); + assert!((b2.width() - 130.001).abs() < 1e-6, "100 pt table + 20/10 indents: {b2:?}"); + let d2 = &s.doc().unwrap().doc; + let cs2 = s.cache.get(d2, sid2, None); + assert!((cs2.frame(id2).unwrap().tables[0].rect.width() - 100.0).abs() < 1e-6); + } } #[cfg(test)] From 73f478bd7107ba470e1c5b06734d0ac13bacc737 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:19:28 +0000 Subject: [PATCH 06/17] 2880: scope fit changes to anchoring and omitted-ref defaults --- ROADMAP.md | 2 +- crates/doc/src/item.rs | 2 +- crates/engine/src/cmd/object.rs | 217 +++++++++----------------------- 3 files changed, 61 insertions(+), 160 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8851b1fc9..d6c03cac0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -394,7 +394,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log -- **2026-11-16** · Fitting or resizing a bottom-aligned text frame from its top handle keeps its bottom edge and text in place (#2880): double-clicking any selection handle passes the opposite local reference point (`ref` 0..=8) to `object.fit`, bottom- and center-justified text frames default to their aligned edge when `ref` is omitted, ovals keep their path shapes when fitted, and `transform.resize` keeps unchanged edges pinned across scale clamps and flips. No readiness percentage change. +- **2026-11-16** · Fitting a bottom-aligned text frame from its top handle keeps its bottom edge and text in place (#2880): double-clicking any selection handle passes the opposite local reference point (`ref` 0..=8) to `object.fit`, menu/panel/scripting fits without `ref` anchor to vertical justification (`Bottom`/`Center`/`Top`/`Justify`), and `transform.resize` keeps unchanged edges pinned across its `1e-3` scale clamp and flips. No readiness percentage change. - **2026-11-15** · Removed the obsolete gap saying pull requests have no test workflow: [CI](.github/workflows/ci.yml) runs the shared quality gate on every pull request and push to main (#1352). No readiness percentage change. - **2026-11-15** · Accepting tracked deletions or rejecting insertions follows body-text selections through the removed text, including resolving all changes, and preserves independent cell and footnote insertion points. No readiness percentage change. - **2026-11-15** · Format follow-ups to the craft-libs cutover (craft-libs#778; ported from #2734 by Dylan M. Taylor): IDML export keeps CDATA image contents and table spans such as `inf` reach the table edge; DOCX plain-text import leaves out deleted tracked changes and expands inline objects; an XLSX number cell that isn't a number shows as written; unmarked CMYK JPEGs keep the shared decoder's ink polarity; PPTX export writes exact opacity; PDF export repins craft-pdf and craft-prepress to craft-libs main. No readiness percentage change. diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 7e1647d22..29b97e15d 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -336,7 +336,7 @@ impl Item { /// How far a visible stroke reaches inside the path: half its weight centred, all of it inside, /// none outside. - pub fn stroke_inside(&self) -> f64 { + fn stroke_inside(&self) -> f64 { let w = self.stroke.weight; if self.stroke.is_none() || !w.is_finite() { return 0.0; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 6dce51863..326fc091d 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3445,7 +3445,7 @@ fn fit(s: &mut Session, p: &Value) -> Result { s.edit(|d, _| { for (id, r) in &text_fits { if let Some(it) = d.item_mut(*id) { - it.path = resized_frame_path(&it.path, it.inner_bounds(), *r); + it.path = shapes::rectangle(*r); } } for id in &ids { @@ -3526,81 +3526,12 @@ fn rect_with_height(cur: Rect, height: f64, side: FitSide) -> Rect { Rect::new(cur.x0, y0, cur.x1, y1) } -fn fit_axis_scale(f0: f64, f1: f64, t0: f64, t1: f64) -> (f64, f64, f64) { - if t0 == f0 && t1 == f1 { - return (1.0, 0.0, 0.0); - } - let s = (t1 - t0) / (f1 - f0); - if (t1 - f1).abs() <= 1e-9 && (t0 - f0).abs() > 1e-9 { - (s, f1, t1) - } else if (t0 - f0).abs() <= 1e-9 && (t1 - f1).abs() > 1e-9 { - (s, f0, t0) - } else { - (s, (f0 + f1) * 0.5, (t0 + t1) * 0.5) - } -} - -fn resized_frame_path(orig_path: &designcraft_geom::PathData, orig: Rect, to: Rect) -> designcraft_geom::PathData { - if orig.width() < 1e-6 || orig.height() < 1e-6 { - return shapes::rectangle(to); - } - let (sx, fx, tx) = fit_axis_scale(orig.x0, orig.x1, to.x0, to.x1); - let (sy, fy, ty) = fit_axis_scale(orig.y0, orig.y1, to.y0, to.y1); - let xf = Affine::translate((tx, ty)) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-fx, -fy)); - let path = orig_path.transformed(xf); - if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) { path } else { shapes::rectangle(to) } -} - -fn line_indents(d: &Document, story: &Story, line: &designcraft_compose::Line) -> (f64, f64) { - let Some(pf) = story.paras.get(line.para) else { - return (0.0, 0.0); - }; - let (pp, _) = d.styles.resolve_para(pf); - let first = if line.first_in_para && line.drop_cap.is_none() { pp.first_line_indent } else { 0.0 }; - if pp.direction == designcraft_doc::TextDirection::RightToLeft { - (pp.left_indent, pp.right_indent + first) - } else { - (pp.left_indent + first, pp.right_indent) - } -} - -fn fitted_column_width(d: &Document, story: &Story, ft: &designcraft_compose::FrameText) -> Option { - let mut max_w: Option = None; - let mut push = |w: f64| { - if w.is_finite() { - let w = w.max(0.0); - max_w = Some(max_w.map_or(w, |m| m.max(w))); - } - }; - for l in &ft.lines { - let col = ft.columns.get(l.column as usize); - let (lo, hi) = l.glyphs.iter().filter(|g| g.spans_rules()).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), g| { - let pen = g.x - g.dx; - (lo.min(pen), hi.max(pen + g.adv)) - }); - let ink = if hi >= lo { hi - lo } else { 0.0 }; - let (ind_l, ind_r) = line_indents(d, story, l); - let wrap = col.map_or(0.0, |c| (l.x0 - c.x0).max(0.0) + (c.x1 - l.x1).max(0.0)); - push(ink + ind_l + ind_r + wrap); - } - for t in &ft.tables { - // TableFrag::rect is the table's placed bounds (not a column slot), so gaps to the column - // edges are unused whitespace; only add horizontal indents that place_table reserves. - let indents = ft.lines.get(t.line).and_then(|l| story.paras.get(l.para)).map(|pf| d.styles.resolve_para(pf).0).map_or(0.0, |pp| { - let pos = |v: f64| if v.is_finite() { v.max(0.0) } else { 0.0 }; - pos(pp.left_indent) + pos(pp.right_indent) - }); - push(t.rect.width() + indents); - } - max_w -} - /// The inner rectangle that fits text frame `id` to its text (Fit Frame to Content): the smallest -/// fitting height and column width (`width`, one column only), including insets and inside stroke, -/// keeping `ref_pt` (or the edge implied by vertical justification) fixed. Overset text grows the -/// frame first. None for frames that aren't horizontal text frames, have no text, or are threaded -/// on to another frame, and for auto-size frames, which already fit their text around their -/// reference point. +/// fitting height and column width (`width`, one column only), including insets, keeping `ref_pt` +/// (or, when omitted, the vertical edge implied by vertical justification) fixed. Overset text +/// grows the frame first. None for frames that aren't horizontal text frames, have no text, or are +/// threaded on to another frame, and for auto-size frames, which already fit their text around +/// their reference point. fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt: Option) -> Result> { let Some(it) = d.item(id) else { return Ok(None) }; let Some(tf) = it.text_frame() else { return Ok(None) }; @@ -3619,12 +3550,9 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt if !(r.width().is_finite() && r.height().is_finite() && r.width() > 0.0 && r.height() > 0.0) { return Err(bad("object.fit", "text frame bounds must be finite and nonempty")); } - let [_, in_l, in_b, in_r] = tf.options.inset; - let stroke_in = it.stroke_inside(); - let sanitize = |v: f64| if v.is_finite() { v.max(0.0) } else { 0.0 }; - let (pad_l, pad_b, pad_r) = (sanitize(in_l) + stroke_in, sanitize(in_b) + stroke_in, sanitize(in_r) + stroke_in); + let inset_b = if tf.options.inset[2].is_finite() { tf.options.inset[2] } else { 0.0 }; + let inset_r = if tf.options.inset[3].is_finite() { tf.options.inset[3] } else { 0.0 }; let anchors = fit_text_anchors(tf, ref_pt); - let orig_path = it.path.clone(); // Keep trial layouts out of the session cache. Search with the actual columns and frame // options: measuring a very tall frame collapses columns and includes vertical alignment's // extra space. A fitting trial must compose all the text, regardless of its justification. @@ -3632,7 +3560,7 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt let mut trial = d.clone(); let mut compose = |rect| { if let Some(it) = trial.item_mut(id) { - it.path = resized_frame_path(&orig_path, r, rect); + it.path = shapes::rectangle(rect); } cache.get(&trial, tf.story, None) }; @@ -3644,18 +3572,21 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt // First fit the height at the existing width, then measure the complete text's width. // Recheck height after fitting width, since a small width change can change a line break. if height { - out = fit_text_height(out, id, pad_b, anchors.y, &mut compose)?; + out = fit_text_height(out, id, inset_b, anchors.y, &mut compose)?; } if width && tf.options.columns <= 1 { let cs = compose(out); - if let Some(col_w) = cs.frame(id).and_then(|ft| fitted_column_width(d, story, ft)) { - let total_w = (pad_l + col_w + pad_r + 0.001).max(1.0); - if total_w.is_finite() { - out = rect_with_width(out, total_w, anchors.x); + if let Some(ft) = cs.frame(id) { + let right = ft.lines.iter().map(|l| l.end_x).fold(f64::NEG_INFINITY, f64::max); + if right.is_finite() { + let span_w = (right - out.x0 + inset_r + 0.001).max(1.0); + if span_w.is_finite() { + out = rect_with_width(out, span_w, anchors.x); + } } } if height { - out = fit_text_height(out, id, pad_b, anchors.y, &mut compose)?; + out = fit_text_height(out, id, inset_b, anchors.y, &mut compose)?; } } super::finite_rect("object.fit", out).map(Some) @@ -3664,7 +3595,7 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt fn fit_text_height( rect: Rect, id: ItemId, - pad_bottom: f64, + inset_bottom: f64, anchor_y: FitSide, compose: &mut impl FnMut(Rect) -> Arc, ) -> Result { @@ -3698,8 +3629,8 @@ fn fit_text_height( // short of the lowest baseline. Growing height along `anchor_y` by that residual keeps the // pinned edge in place while making the frame fit exactly, even when scaled up. let cs = compose(cur); - let lowest = cs.frame(id).and_then(|ft| ft.lines.iter().map(|l| l.baseline).chain(ft.tables.iter().map(|t| t.rect.y1)).reduce(f64::max)); - if let Some(extra) = lowest.map(|b| b + pad_bottom - cur.y1).filter(|e| e.is_finite() && *e > 0.0 && *e <= 0.02) { + let lowest = cs.frame(id).and_then(|ft| ft.lines.iter().map(|l| l.baseline).reduce(f64::max)); + if let Some(extra) = lowest.map(|b| b + inset_bottom - cur.y1).filter(|e| e.is_finite() && *e > 0.0 && *e <= 0.02) { cur = rect_with_height(rect, high + extra, anchor_y); } Ok(cur) @@ -6790,7 +6721,7 @@ mod fit_text_frame_tests { } #[test] - fn fit_frame_handles_top_overset_center_right_align_stroke_inset_and_ovals() { + fn fit_frame_keeps_anchor_for_overset_corners_center_and_rotation() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); // Overset bottom-aligned frame grows upward while bottom edge stays put. @@ -6802,47 +6733,52 @@ mod fit_text_frame_tests { let sid = d.item(id).unwrap().text_frame().unwrap().story; assert!(!s.cache.get(&d, sid, None).is_overset() && (b.y1 - 300.0).abs() < 1e-9 && b.y0 < 200.0, "{b:?}"); - // Right-aligned single line with bottom-right fixed (top-left corner double-click, ref = 8). - let right = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); - s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); - s.execute("object.textFrameOptions", &json!({"ids": [right.0], "verticalJustification": "bottom", "inset": [4, 6, 8, 10]})).unwrap(); - s.edit(|d, _| { - let it = d.item_mut(right).unwrap(); - it.stroke = Stroke { weight: 4.0, align: designcraft_doc::StrokeAlign::Inside, ..Stroke::default() }; - Ok(Value::Null) - }) - .unwrap(); - s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [right.0]})).unwrap(); - let rb = bounds(&s, right); - assert!((rb.x1 - 500.0).abs() < 1e-9 && (rb.y1 - 300.0).abs() < 1e-9, "bottom-right pinned: {rb:?}"); - assert!(rb.width() < 200.0 && rb.height() < 60.0, "shrunk flush around short right-aligned line: {rb:?}"); + // Top-left corner double-click (ref = 8) on bottom-aligned text keeps bottom-right fixed. + let corner = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); + s.execute("object.textFrameOptions", &json!({"ids": [corner.0], "verticalJustification": "bottom", "inset": [4, 6, 8, 10]})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [corner.0]})).unwrap(); + let cb = bounds(&s, corner); + assert!((cb.x1 - 500.0).abs() < 1e-9 && (cb.y1 - 300.0).abs() < 1e-9, "bottom-right pinned: {cb:?}"); + assert!(cb.width() < 200.0 && cb.height() < 60.0, "shrunk flush around short line: {cb:?}"); let d = s.doc().unwrap().doc.clone(); - let it = d.item(right).unwrap(); + let it = d.item(corner).unwrap(); let sid = it.text_frame().unwrap().story; let cs = s.cache.get(&d, sid, None); assert!(!cs.is_overset()); - assert!((cs.frame(right).unwrap().lines[0].baseline - it.text_area().y1).abs() < 1e-6); + assert!((cs.frame(corner).unwrap().lines[0].baseline - it.text_area().y1).abs() < 1e-6); - // Center-aligned without ref keeps vertical center. + // Center-justified without ref keeps vertical center and text baselines in place. let ctr = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Centered"); s.execute("object.textFrameOptions", &json!({"ids": [ctr.0], "verticalJustification": "center"})).unwrap(); + let ctr_sid = s.doc().unwrap().doc.item(ctr).unwrap().text_frame().unwrap().story; + let ctr_y0 = s.cache.get(&s.doc().unwrap().doc, ctr_sid, None).frame(ctr).unwrap().lines[0].baseline; s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [ctr.0]})).unwrap(); - assert!((bounds(&s, ctr).center().y - 200.0).abs() < 1e-6); + let ctr_b = bounds(&s, ctr); + let ctr_cs = s.cache.get(&s.doc().unwrap().doc, ctr_sid, None); + assert!(!ctr_cs.is_overset() && (ctr_b.center().y - 200.0).abs() < 1e-6 && ctr_b.height() < 50.0, "{ctr_b:?}"); + assert!((ctr_cs.frame(ctr).unwrap().lines[0].baseline - ctr_y0).abs() < 1.0); - // Oval text frame retains its ellipse path rather than flattening into a rectangle. - let oval = ItemId( - s.execute("frame.create", &json!({"rect": [100, 400, 400, 700], "shape": "ellipse", "content": "text", "text": "Oval"})).unwrap()["id"] - .as_u64() - .unwrap(), - ); - s.execute("selection.set", &json!({"ids": [oval.0]})).unwrap(); - s.execute("object.textFrameOptions", &json!({"ids": [oval.0], "verticalJustification": "bottom"})).unwrap(); - s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ref": 7, "ids": [oval.0]})).unwrap(); - let oval_it = s.doc().unwrap().doc.item(oval).unwrap(); - assert!((oval_it.bounds().y1 - 700.0).abs() < 1e-9); - assert!(oval_it.path.subpaths[0].anchors.iter().all(|a| a.kind == designcraft_geom::AnchorKind::Smooth)); - let sid = oval_it.text_frame().unwrap().story; - assert!(!s.cache.get(&s.doc().unwrap().doc, sid, None).is_overset()); + // Top and Justify without ref stay anchored to the top edge. + for vj in ["top", "justify"] { + let f = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Anchored top\nLine two"); + s.execute("object.textFrameOptions", &json!({"ids": [f.0], "verticalJustification": vj})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [f.0]})).unwrap(); + let fb = bounds(&s, f); + let f_sid = s.doc().unwrap().doc.item(f).unwrap().text_frame().unwrap().story; + assert!(!s.cache.get(&s.doc().unwrap().doc, f_sid, None).is_overset()); + assert!((fb.y0 - 100.0).abs() < 1e-9 && fb.height() < 100.0, "{vj}: {fb:?}"); + } + + // Right-aligned text fitted without ref keeps its right edge (does not shift left). + let right = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); + s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [right.0], "verticalJustification": "bottom"})).unwrap(); + let right_sid = s.doc().unwrap().doc.item(right).unwrap().text_frame().unwrap().story; + let glyph_x0 = s.cache.get(&s.doc().unwrap().doc, right_sid, None).frame(right).unwrap().lines[0].glyphs[0].x; + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ids": [right.0]})).unwrap(); + let rb = bounds(&s, right); + let after_x0 = s.cache.get(&s.doc().unwrap().doc, right_sid, None).frame(right).unwrap().lines[0].glyphs[0].x; + assert!((rb.x1 - 500.001).abs() < 1e-6 && (after_x0 - glyph_x0).abs() < 0.002, "right-aligned text moved: {rb:?}, {glyph_x0} -> {after_x0}"); // Rotated 90° bottom-aligned frame: fitting keeps its local bottom-center pinned in spread space. let rot = frame(&mut s, [200.0, 100.0, 500.0, 300.0], "Rotated bottom"); @@ -6860,41 +6796,6 @@ mod fit_text_frame_tests { let h1 = s.doc().unwrap().doc.item(rot).unwrap().inner_bounds().height(); assert!(h1 < h0 * 0.5 && (p1 - p0).hypot() < 1e-9, "{p0:?} vs {p1:?}, h: {h0} -> {h1}"); } - - #[test] - fn fit_frame_shrinks_around_narrow_table() { - let mut s = Session::new(); - s.execute("file.new", &json!({})).unwrap(); - let created = s.execute("frame.create", &json!({"rect": [100, 100, 500, 300], "content": "text"})).unwrap(); - let id = ItemId(created["id"].as_u64().unwrap()); - let sid = designcraft_doc::StoryId(created["story"].as_u64().unwrap()); - s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); - s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); - s.execute("table.insert", &json!({"rows": 1, "cols": 2, "width": 120.0})).unwrap(); - s.execute("object.textFrameOptions", &json!({"ids": [id.0], "verticalJustification": "bottom"})).unwrap(); - s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [id.0]})).unwrap(); - let b = bounds(&s, id); - assert!((b.x1 - 500.0).abs() < 1e-9 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); - assert!((b.width() - 120.001).abs() < 1e-6, "width should fit the 120 pt table: {b:?}"); - let d = &s.doc().unwrap().doc; - let cs = s.cache.get(d, sid, None); - assert!(!cs.is_overset()); - assert!((cs.frame(id).unwrap().tables[0].rect.width() - 120.0).abs() < 1e-6); - - // Paragraph horizontal indents are still preserved so fitting does not squeeze the table. - let created2 = s.execute("frame.create", &json!({"rect": [100, 400, 500, 600], "content": "text"})).unwrap(); - let id2 = ItemId(created2["id"].as_u64().unwrap()); - let sid2 = designcraft_doc::StoryId(created2["story"].as_u64().unwrap()); - s.execute("text.select", &json!({"story": sid2.0, "anchor": 0, "focus": 0})).unwrap(); - s.execute("type.para", &json!({"attrs": {"leftIndent": 20.0, "rightIndent": 10.0}})).unwrap(); - s.execute("table.insert", &json!({"rows": 1, "cols": 2, "width": 100.0})).unwrap(); - s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ids": [id2.0]})).unwrap(); - let b2 = bounds(&s, id2); - assert!((b2.width() - 130.001).abs() < 1e-6, "100 pt table + 20/10 indents: {b2:?}"); - let d2 = &s.doc().unwrap().doc; - let cs2 = s.cache.get(d2, sid2, None); - assert!((cs2.frame(id2).unwrap().tables[0].rect.width() - 100.0).abs() < 1e-6); - } } #[cfg(test)] From f6808d3023f109839c55d048fd4f0411512f207f Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:11:00 +0000 Subject: [PATCH 07/17] 2880: measure anchored text width from text start --- crates/engine/src/cmd/object.rs | 118 +++++++++++++++++++++++++++++++- 1 file changed, 115 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 326fc091d..6c9223028 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3526,6 +3526,23 @@ fn rect_with_height(cur: Rect, height: f64, side: FitSide) -> Rect { Rect::new(cur.x0, y0, cur.x1, y1) } +fn line_h_indents(d: &Document, story: &designcraft_doc::Story, para_idx: usize, first_in_para: bool) -> (f64, f64) { + let Some(pf) = story.paras.get(para_idx) else { + return (0.0, 0.0); + }; + let (pp, _) = d.styles.resolve_para(pf); + let left = if pp.left_indent.is_finite() { pp.left_indent } else { 0.0 }; + let right = if pp.right_indent.is_finite() { pp.right_indent } else { 0.0 }; + let first = if first_in_para && pp.first_line_indent.is_finite() { pp.first_line_indent } else { 0.0 }; + if pp.direction == designcraft_doc::TextDirection::RightToLeft { + let ind_r = right + first; + (left.max(0.0), if ind_r.is_finite() { ind_r.max(0.0) } else { 0.0 }) + } else { + let ind_l = left + first; + (if ind_l.is_finite() { ind_l.max(0.0) } else { 0.0 }, right.max(0.0)) + } +} + /// The inner rectangle that fits text frame `id` to its text (Fit Frame to Content): the smallest /// fitting height and column width (`width`, one column only), including insets, keeping `ref_pt` /// (or, when omitted, the vertical edge implied by vertical justification) fixed. Overset text @@ -3550,6 +3567,7 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt if !(r.width().is_finite() && r.height().is_finite() && r.width() > 0.0 && r.height() > 0.0) { return Err(bad("object.fit", "text frame bounds must be finite and nonempty")); } + let inset_l = if tf.options.inset[1].is_finite() { tf.options.inset[1] } else { 0.0 }; let inset_b = if tf.options.inset[2].is_finite() { tf.options.inset[2] } else { 0.0 }; let inset_r = if tf.options.inset[3].is_finite() { tf.options.inset[3] } else { 0.0 }; let anchors = fit_text_anchors(tf, ref_pt); @@ -3577,9 +3595,41 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt if width && tf.options.columns <= 1 { let cs = compose(out); if let Some(ft) = cs.frame(id) { - let right = ft.lines.iter().map(|l| l.end_x).fold(f64::NEG_INFINITY, f64::max); - if right.is_finite() { - let span_w = (right - out.x0 + inset_r + 0.001).max(1.0); + let (start, right) = if matches!(anchors.x, FitSide::Start) { + // Keep measuring from out.x0 when left-anchored or when `ref` is omitted so menu + // Fit Frame to Content does not shift right- or center-aligned text leftward. + let hi = ft.lines.iter().map(|l| l.end_x).fold(f64::NEG_INFINITY, f64::max); + (out.x0, hi) + } else { + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + for l in &ft.lines { + let (ind_l, ind_r) = line_h_indents(d, story, l.para, l.first_in_para); + if l.end_x.is_finite() { + hi = hi.max(l.end_x + ind_r); + } + for g in l.glyphs.iter().filter(|g| g.visible) { + let pen = g.x - g.dx; + let edge = pen.min(pen + g.adv); + if edge.is_finite() { + lo = lo.min(edge - ind_l); + } + } + } + for t in &ft.tables { + let (ind_l, ind_r) = ft.lines.get(t.line).map_or((0.0, 0.0), |l| line_h_indents(d, story, l.para, false)); + if t.rect.x0.is_finite() { + lo = lo.min(t.rect.x0 - ind_l); + } + if t.rect.x1.is_finite() { + hi = hi.max(t.rect.x1 + ind_r); + } + } + let start = if lo.is_finite() { lo - inset_l } else { out.x0 }; + (start, hi) + }; + if right.is_finite() && start.is_finite() { + let span_w = (right - start + inset_r + 0.001).max(1.0); if span_w.is_finite() { out = rect_with_width(out, span_w, anchors.x); } @@ -6796,6 +6846,68 @@ mod fit_text_frame_tests { let h1 = s.doc().unwrap().doc.item(rot).unwrap().inner_bounds().height(); assert!(h1 < h0 * 0.5 && (p1 - p0).hypot() < 1e-9, "{p0:?} vs {p1:?}, h: {h0} -> {h1}"); } + + #[test] + fn right_and_center_anchored_width_fit_starts_from_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + + // Right-aligned bottom-aligned frame [100,100,500,300] fitted with ref=8 (bottom-right fixed) + // shrinks from the left flush to the text instead of keeping empty space from out.x0. + let right = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); + s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [right.0], "verticalJustification": "bottom", "inset": [4, 6, 8, 10]})).unwrap(); + let right_sid = s.doc().unwrap().doc.item(right).unwrap().text_frame().unwrap().story; + let glyph_x0 = s.cache.get(&s.doc().unwrap().doc, right_sid, None).frame(right).unwrap().lines[0].glyphs[0].x; + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [right.0]})).unwrap(); + let rb = bounds(&s, right); + let after_x0 = s.cache.get(&s.doc().unwrap().doc, right_sid, None).frame(right).unwrap().lines[0].glyphs[0].x; + let cs = s.cache.get(&s.doc().unwrap().doc, right_sid, None); + assert!(!cs.is_overset()); + assert!((rb.x1 - 500.0).abs() < 1e-9 && (rb.y1 - 300.0).abs() < 1e-9, "{rb:?}"); + assert!(rb.width() < 200.0 && rb.height() < 60.0, "did not shrink flush around right-aligned text: {rb:?}"); + assert!((after_x0 - glyph_x0).abs() < 0.002, "right-aligned text moved: {glyph_x0} -> {after_x0}"); + assert!((cs.frame(right).unwrap().lines[0].baseline - s.doc().unwrap().doc.item(right).unwrap().text_area().y1).abs() < 1e-6); + + // Width-only fit with ref=5 (right edge pinned) shrinks from the left without moving height or glyphs. + let w_only = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); + s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); + let w_sid = s.doc().unwrap().doc.item(w_only).unwrap().text_frame().unwrap().story; + let w_x0 = s.cache.get(&s.doc().unwrap().doc, w_sid, None).frame(w_only).unwrap().lines[0].glyphs[0].x; + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [w_only.0]})).unwrap(); + let wb = bounds(&s, w_only); + let w_after = s.cache.get(&s.doc().unwrap().doc, w_sid, None).frame(w_only).unwrap().lines[0].glyphs[0].x; + assert!(!s.cache.get(&s.doc().unwrap().doc, w_sid, None).is_overset()); + assert!((wb.x1 - 500.0).abs() < 1e-9 && (wb.y0 - 100.0).abs() < 1e-9 && (wb.y1 - 300.0).abs() < 1e-9, "{wb:?}"); + assert!(wb.width() < 200.0 && (w_after - w_x0).abs() < 0.002, "{wb:?}, {w_x0} -> {w_after}"); + + // Center-aligned frame fitted around center (ref=4) shrinks symmetrically from both sides. + let center = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); + s.execute("type.para", &json!({"attrs": {"align": "center"}})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 4, "ids": [center.0]})).unwrap(); + let cb = bounds(&s, center); + let c_sid = s.doc().unwrap().doc.item(center).unwrap().text_frame().unwrap().story; + assert!(!s.cache.get(&s.doc().unwrap().doc, c_sid, None).is_overset()); + assert!((cb.center().x - 300.0).abs() < 1e-6 && (cb.center().y - 200.0).abs() < 1e-6 && cb.width() < 200.0, "{cb:?}"); + + // Paragraph indents remain accounted for so left-indented text does not wrap when shrunk. + let indented = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "SHORT"); + s.execute("type.para", &json!({"attrs": {"leftIndent": 20.0, "rightIndent": 15.0}})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [indented.0]})).unwrap(); + let ib = bounds(&s, indented); + let i_sid = s.doc().unwrap().doc.item(indented).unwrap().text_frame().unwrap().story; + let i_cs = s.cache.get(&s.doc().unwrap().doc, i_sid, None); + assert!(!i_cs.is_overset() && i_cs.frame(indented).unwrap().lines.len() == 1); + assert!((ib.x1 - 500.0).abs() < 1e-9 && ib.width() < 250.0, "{ib:?}"); + + // Whitespace-only frame (no visible glyphs) falls back cleanly to finite bounds. + let blank = frame(&mut s, [100.0, 100.0, 500.0, 300.0], " "); + s.execute("type.para", &json!({"attrs": {"align": "right"}})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "both", "ref": 8, "ids": [blank.0]})).unwrap(); + let bb = bounds(&s, blank); + let b_sid = s.doc().unwrap().doc.item(blank).unwrap().text_frame().unwrap().story; + assert!(bb.is_finite() && (bb.x1 - 500.0).abs() < 1e-9 && !s.cache.get(&s.doc().unwrap().doc, b_sid, None).is_overset(), "{bb:?}"); + } } #[cfg(test)] From 48e240e90ace16d020afd0bc1bdf6d312399f033 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:01:29 +0000 Subject: [PATCH 08/17] 2880: keep tab advances when fitting text width --- crates/engine/src/cmd/object.rs | 40 +++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 6c9223028..11029840d 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3608,11 +3608,13 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt if l.end_x.is_finite() { hi = hi.max(l.end_x + ind_r); } - for g in l.glyphs.iter().filter(|g| g.visible) { + for g in l.glyphs.iter().filter(|g| g.visible || (g.rendered_char == '\t' && g.adv > 0.0)) { let pen = g.x - g.dx; - let edge = pen.min(pen + g.adv); - if edge.is_finite() { - lo = lo.min(edge - ind_l); + if pen.is_finite() && g.adv.is_finite() { + let edge = pen.min(pen + g.adv); + if edge.is_finite() { + lo = lo.min(edge - ind_l); + } } } } @@ -6908,6 +6910,36 @@ mod fit_text_frame_tests { let b_sid = s.doc().unwrap().doc.item(blank).unwrap().text_frame().unwrap().story; assert!(bb.is_finite() && (bb.x1 - 500.0).abs() < 1e-9 && !s.cache.get(&s.doc().unwrap().doc, b_sid, None).is_overset(), "{bb:?}"); } + + #[test] + fn leading_tab_width_fit_keeps_tab_advance() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + + // Left-aligned leading-tab text in a one-line frame with axis="width", ref=5 retains + // the tab's 36 pt advance so recomposition keeps one line and stays non-overset. + let tabbed = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "\tSHORT"); + let t_sid = s.doc().unwrap().doc.item(tabbed).unwrap().text_frame().unwrap().story; + assert!(!s.cache.get(&s.doc().unwrap().doc, t_sid, None).is_overset()); + assert_eq!(s.cache.get(&s.doc().unwrap().doc, t_sid, None).frame(tabbed).unwrap().lines.len(), 1); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [tabbed.0]})).unwrap(); + let tb = bounds(&s, tabbed); + let t_cs = s.cache.get(&s.doc().unwrap().doc, t_sid, None); + assert!(!t_cs.is_overset(), "leading tab caused overset after width fit: {tb:?}"); + assert_eq!(t_cs.frame(tabbed).unwrap().lines.len(), 1, "leading tab wrapped after width fit: {tb:?}"); + assert!((tb.x1 - 500.0).abs() < 1e-9 && tb.width() < 250.0, "{tb:?}"); + + // Stretchy right-indent tab still allows shrinking down to the visible content width. + let rtab_text = format!("{}SHORT", designcraft_doc::story::RIGHT_INDENT_TAB); + let rtab = frame(&mut s, [100.0, 100.0, 500.0, 145.0], &rtab_text); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [rtab.0]})).unwrap(); + let rb = bounds(&s, rtab); + let r_sid = s.doc().unwrap().doc.item(rtab).unwrap().text_frame().unwrap().story; + let r_cs = s.cache.get(&s.doc().unwrap().doc, r_sid, None); + assert!(!r_cs.is_overset() && r_cs.frame(rtab).unwrap().lines.len() == 1); + assert!((rb.x1 - 500.0).abs() < 1e-9 && rb.width() < 200.0, "{rb:?}"); + assert!(tb.width() > rb.width() + 25.0, "leading tab advance missing: tb={tb:?} vs rb={rb:?}"); + } } #[cfg(test)] From bfde0e6d37373cb8fd4f8081dff572e54097f035 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:37:12 +0000 Subject: [PATCH 09/17] Apply review fixes - crates/engine/src/cmd/object.rs --- crates/engine/src/cmd/object.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a630f29b0..1dbdc25a9 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -267,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) @@ -4441,6 +4447,10 @@ mod step_repeat_tests { 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.stroke", &json!({"cap": "round"})).unwrap(); + s.execute("object.defaultFillStroke", &json!({})).unwrap(); + let c = &s.doc().unwrap().doc.settings.new_object; + assert_eq!((c.fill.as_str(), c.stroke.as_str(), c.stroke_weight, c.stroke_cap), ("[None]", "[Black]", 4.0, designcraft_doc::Cap::Round)); } #[test] From 0bab0f96cd0985f4e4c1a47db1379ac70436d90a Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:21:57 +0000 Subject: [PATCH 10/17] 2880: keep right indent in left-anchored fit and tighten center-VJ check --- crates/engine/src/cmd/object.rs | 89 +++++++++++++++++++++++---------- 1 file changed, 62 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 11029840d..a9edec238 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3595,19 +3595,15 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt if width && tf.options.columns <= 1 { let cs = compose(out); if let Some(ft) = cs.frame(id) { - let (start, right) = if matches!(anchors.x, FitSide::Start) { - // Keep measuring from out.x0 when left-anchored or when `ref` is omitted so menu - // Fit Frame to Content does not shift right- or center-aligned text leftward. - let hi = ft.lines.iter().map(|l| l.end_x).fold(f64::NEG_INFINITY, f64::max); - (out.x0, hi) - } else { - let mut lo = f64::INFINITY; - let mut hi = f64::NEG_INFINITY; - for l in &ft.lines { - let (ind_l, ind_r) = line_h_indents(d, story, l.para, l.first_in_para); - if l.end_x.is_finite() { - hi = hi.max(l.end_x + ind_r); - } + let measure_start = !matches!(anchors.x, FitSide::Start); + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + for l in &ft.lines { + let (ind_l, ind_r) = line_h_indents(d, story, l.para, l.first_in_para); + if l.end_x.is_finite() { + hi = hi.max(l.end_x + ind_r); + } + if measure_start { for g in l.glyphs.iter().filter(|g| g.visible || (g.rendered_char == '\t' && g.adv > 0.0)) { let pen = g.x - g.dx; if pen.is_finite() && g.adv.is_finite() { @@ -3618,20 +3614,21 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt } } } - for t in &ft.tables { - let (ind_l, ind_r) = ft.lines.get(t.line).map_or((0.0, 0.0), |l| line_h_indents(d, story, l.para, false)); - if t.rect.x0.is_finite() { - lo = lo.min(t.rect.x0 - ind_l); - } - if t.rect.x1.is_finite() { - hi = hi.max(t.rect.x1 + ind_r); - } + } + for t in &ft.tables { + let (ind_l, ind_r) = ft.lines.get(t.line).map_or((0.0, 0.0), |l| line_h_indents(d, story, l.para, false)); + if measure_start && t.rect.x0.is_finite() { + lo = lo.min(t.rect.x0 - ind_l); } - let start = if lo.is_finite() { lo - inset_l } else { out.x0 }; - (start, hi) - }; - if right.is_finite() && start.is_finite() { - let span_w = (right - start + inset_r + 0.001).max(1.0); + if t.rect.x1.is_finite() { + hi = hi.max(t.rect.x1 + ind_r); + } + } + // Keep measuring from out.x0 when left-anchored or when `ref` is omitted so menu + // Fit Frame to Content does not shift right- or center-aligned text leftward. + let start = if measure_start && lo.is_finite() { lo - inset_l } else { out.x0 }; + if hi.is_finite() && start.is_finite() { + let span_w = (hi - start + inset_r + 0.001).max(1.0); if span_w.is_finite() { out = rect_with_width(out, span_w, anchors.x); } @@ -6808,7 +6805,8 @@ mod fit_text_frame_tests { let ctr_b = bounds(&s, ctr); let ctr_cs = s.cache.get(&s.doc().unwrap().doc, ctr_sid, None); assert!(!ctr_cs.is_overset() && (ctr_b.center().y - 200.0).abs() < 1e-6 && ctr_b.height() < 50.0, "{ctr_b:?}"); - assert!((ctr_cs.frame(ctr).unwrap().lines[0].baseline - ctr_y0).abs() < 1.0); + let ctr_y1 = ctr_cs.frame(ctr).unwrap().lines[0].baseline; + assert!((ctr_y1 - ctr_y0).abs() < 1e-3, "center-VJ baseline shifted: {ctr_y0} -> {ctr_y1}"); // Top and Justify without ref stay anchored to the top edge. for vj in ["top", "justify"] { @@ -6940,6 +6938,43 @@ mod fit_text_frame_tests { assert!((rb.x1 - 500.0).abs() < 1e-9 && rb.width() < 200.0, "{rb:?}"); assert!(tb.width() > rb.width() + 25.0, "leading tab advance missing: tb={tb:?} vs rb={rb:?}"); } + + #[test] + fn left_anchored_width_fit_keeps_right_indent() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + + // Left-anchored width fit (e.g. double-clicking the right handle, ref=3) accounts for + // paragraph right indent so a one-line paragraph does not rewrap or overset. + let id = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "Hello world"); + s.execute("type.para", &json!({"attrs": {"rightIndent": 24.0}})).unwrap(); + let sid = s.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().story; + assert!(!s.cache.get(&s.doc().unwrap().doc, sid, None).is_overset()); + assert_eq!(s.cache.get(&s.doc().unwrap().doc, sid, None).frame(id).unwrap().lines.len(), 1); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 3, "ids": [id.0]})).unwrap(); + let b = bounds(&s, id); + let cs = s.cache.get(&s.doc().unwrap().doc, sid, None); + assert!(!cs.is_overset(), "right indent caused overset after left-anchored width fit: {b:?}"); + assert_eq!(cs.frame(id).unwrap().lines.len(), 1, "right indent caused rewrap after left-anchored width fit: {b:?}"); + assert!((b.x0 - 100.0).abs() < 1e-9 && b.width() < 300.0, "{b:?}"); + + // Baseline-grid aligned bottom-justified text keeps its bottom edge and grid baselines. + let grid = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Grid line one\nGrid line two"); + s.execute("type.para", &json!({"attrs": {"gridAlign": "allLines"}})).unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [grid.0], "verticalJustification": "bottom"})).unwrap(); + let g_sid = s.doc().unwrap().doc.item(grid).unwrap().text_frame().unwrap().story; + let before: Vec = s.cache.get(&s.doc().unwrap().doc, g_sid, None).frame(grid).unwrap().lines.iter().map(|l| l.baseline).collect(); + assert_eq!(before.len(), 2); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ref": 7, "ids": [grid.0]})).unwrap(); + let gb = bounds(&s, grid); + let g_cs = s.cache.get(&s.doc().unwrap().doc, g_sid, None); + let after: Vec = g_cs.frame(grid).unwrap().lines.iter().map(|l| l.baseline).collect(); + assert!(!g_cs.is_overset() && (gb.y1 - 300.0).abs() < 1e-9 && gb.height() < 120.0, "{gb:?}"); + assert_eq!(after.len(), 2); + for (a, b) in before.iter().zip(after.iter()) { + assert!((a - b).abs() < 1e-6, "baseline-grid line shifted: {before:?} -> {after:?}"); + } + } } #[cfg(test)] From b730bbb1859bf65d98ea6d18fad914f61d055a32 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:13:16 +0000 Subject: [PATCH 11/17] 2880: ignore first-line indent on table lines in width fit --- crates/engine/src/cmd/object.rs | 56 ++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a9edec238..893708753 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3599,7 +3599,10 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt let mut lo = f64::INFINITY; let mut hi = f64::NEG_INFINITY; for l in &ft.lines { - let (ind_l, ind_r) = line_h_indents(d, story, l.para, l.first_in_para); + // Tables ignore first_line_indent in composition even when their first fragment is + // marked first_in_para; applying it here would inflate RTL table widths. + let first_in_para = l.first_in_para && story.para_table(l.para).is_none(); + let (ind_l, ind_r) = line_h_indents(d, story, l.para, first_in_para); if l.end_x.is_finite() { hi = hi.max(l.end_x + ind_r); } @@ -6975,6 +6978,57 @@ mod fit_text_frame_tests { assert!((a - b).abs() < 1e-6, "baseline-grid line shifted: {before:?} -> {after:?}"); } } + + #[test] + fn rtl_table_width_fit_ignores_first_line_indent_while_text_keeps_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + + // A 100-pt table in an RTL paragraph with firstLineIndent=24 must not retain 24 pt of + // unused width when fitted, because the compositor ignores first_line_indent for tables. + let tbl = frame(&mut s, [100.0, 100.0, 500.0, 300.0], ""); + let t_sid = s.doc().unwrap().doc.item(tbl).unwrap().text_frame().unwrap().story; + s.execute("type.para", &json!({"attrs": {"direction": "rightToLeft", "firstLineIndent": 24.0}})).unwrap(); + s.execute("text.select", &json!({"story": t_sid.0, "anchor": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2, "width": 100.0})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [tbl.0]})).unwrap(); + let tb = bounds(&s, tbl); + let t_cs = s.cache.get(&s.doc().unwrap().doc, t_sid, None); + assert!(!t_cs.is_overset(), "table overset after width fit: {tb:?}"); + assert!((tb.x1 - 500.0).abs() < 1e-9, "{tb:?}"); + assert!((tb.width() - 100.0).abs() < 0.01, "table fit retained unused first-line indent width: {tb:?}"); + assert!((t_cs.frame(tbl).unwrap().tables[0].rect.width() - 100.0).abs() < 0.01); + + // Paragraph left/right indents still apply to tables, while firstLineIndent is ignored. + let tbl_ind = frame(&mut s, [100.0, 100.0, 500.0, 300.0], ""); + let ti_sid = s.doc().unwrap().doc.item(tbl_ind).unwrap().text_frame().unwrap().story; + s.execute("type.para", &json!({"attrs": {"direction": "rightToLeft", "leftIndent": 10.0, "rightIndent": 12.0, "firstLineIndent": 24.0}})) + .unwrap(); + s.execute("text.select", &json!({"story": ti_sid.0, "anchor": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2, "width": 100.0})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [tbl_ind.0]})).unwrap(); + let tib = bounds(&s, tbl_ind); + let ti_cs = s.cache.get(&s.doc().unwrap().doc, ti_sid, None); + assert!(!ti_cs.is_overset(), "indented table overset after width fit: {tib:?}"); + assert!((tib.x1 - 500.0).abs() < 1e-9, "{tib:?}"); + assert!((tib.width() - 122.0).abs() < 0.01, "table fit should keep left+right indents only: {tib:?}"); + assert!((ti_cs.frame(tbl_ind).unwrap().tables[0].rect.width() - 100.0).abs() < 0.01); + + // Actual RTL text lines still keep first_line_indent so a single-line paragraph does not wrap. + let plain = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "Hello world"); + s.execute("type.para", &json!({"attrs": {"direction": "rightToLeft"}})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [plain.0]})).unwrap(); + let pb = bounds(&s, plain); + + let rtl_first = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "Hello world"); + s.execute("type.para", &json!({"attrs": {"direction": "rightToLeft", "firstLineIndent": 24.0}})).unwrap(); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [rtl_first.0]})).unwrap(); + let rfb = bounds(&s, rtl_first); + let rf_sid = s.doc().unwrap().doc.item(rtl_first).unwrap().text_frame().unwrap().story; + let rf_cs = s.cache.get(&s.doc().unwrap().doc, rf_sid, None); + assert!(!rf_cs.is_overset() && rf_cs.frame(rtl_first).unwrap().lines.len() == 1, "RTL text wrapped/overset: {rfb:?}"); + assert!((rfb.width() - (pb.width() + 24.0)).abs() < 0.5, "RTL text lost first_line_indent: rfb={rfb:?} vs pb={pb:?}"); + } } #[cfg(test)] From f68d7a0c49fb8ed0d0b53a00589397f2e526a633 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:23:10 +0000 Subject: [PATCH 12/17] Address review feedback: expand defaultFillStroke test and rewrap doc comment (#2858) --- crates/doc/src/swatch_refs.rs | 4 ++-- crates/engine/src/cmd/object.rs | 21 +++++++++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/swatch_refs.rs b/crates/doc/src/swatch_refs.rs index c7e9d6429..a7a1ccb06 100644 --- a/crates/doc/src/swatch_refs.rs +++ b/crates/doc/src/swatch_refs.rs @@ -240,8 +240,8 @@ impl Document { /// Point every reference to swatch `from` at `to`: tints based on it, colour groups, inks, /// 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. + /// 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; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 1dbdc25a9..0ec6ca252 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -4447,10 +4447,27 @@ mod step_repeat_tests { 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.stroke", &json!({"cap": "round"})).unwrap(); + 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.stroke.as_str(), c.stroke_weight, c.stroke_cap), ("[None]", "[Black]", 4.0, designcraft_doc::Cap::Round)); + 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] From 265f0ca75ee8007529d8252a3735722c45adbc74 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:10:37 +0000 Subject: [PATCH 13/17] Preserve default stroke attributes when restoring zero weight (#2858) --- crates/engine/src/cmd/object.rs | 50 +++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 0ec6ca252..23ef14b58 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -343,11 +343,18 @@ pub fn specs() -> Vec { } let tint_only = p.as_object().is_some_and(|o| o.contains_key("tint") && o.keys().all(|k| k == "tint")); return set_new_object(s, |c| { - let cur = c.to_stroke(); - if tint_only && cur.is_none() { + let mut st = c.to_stroke(); + if tint_only && st.is_none() { return; } - let mut st = if cur.is_none() && sw.is_none() { Stroke::default() } else { cur }; + if st.swatch == designcraft_color::swatch::NONE && sw.is_none() && weight != Some(0.0) { + let def = Stroke::default(); + st.swatch = def.swatch; + st.tint = def.tint; + if st.weight <= 0.0 { + st.weight = def.weight; + } + } if let Some(sw) = &sw { st.swatch = sw.clone(); st.tint = 1.0; @@ -4470,6 +4477,43 @@ mod step_repeat_tests { 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 renaming_default_gap_swatch_applies_to_next_shape() { let mut s = Session::new(); From a4a4dbdd4c3831f440c3994d48734f90a2656231 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:33:14 +0000 Subject: [PATCH 14/17] Keep [None] default stroke on gap edits and allow tint edits at zero weight (#2858) --- crates/engine/src/cmd/object.rs | 68 ++++++++++++++++++++++++++++++--- 1 file changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 23ef14b58..5b6f5aa06 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -341,13 +341,18 @@ pub fn specs() -> Vec { { return Err(bad("object.stroke", super::NOTHING_SELECTED)); } - let tint_only = p.as_object().is_some_and(|o| o.contains_key("tint") && o.keys().all(|k| k == "tint")); + 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| { let mut st = c.to_stroke(); - if tint_only && st.is_none() { - return; - } - if st.swatch == designcraft_color::swatch::NONE && sw.is_none() && weight != Some(0.0) { + if st.swatch == designcraft_color::swatch::NONE && sw.is_none() && activates_stroke { let def = Stroke::default(); st.swatch = def.swatch; st.tint = def.tint; @@ -359,7 +364,9 @@ pub fn specs() -> Vec { st.swatch = sw.clone(); st.tint = 1.0; } - st.tint = tint.unwrap_or(st.tint); + 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 { @@ -4514,6 +4521,55 @@ mod step_repeat_tests { 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(); From 930171ef29e1e4488107e0069994753796ba9fd7 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:52:51 +0000 Subject: [PATCH 15/17] 2880: account for inside stroke in width fit and keep sheared handle axis --- crates/doc/src/item.rs | 2 +- crates/engine/src/cmd/object.rs | 64 +++++++++++++++++++++++++++++++-- crates/tools/src/select.rs | 37 ++++++++++--------- crates/tools/src/tests.rs | 35 ++++++++++++++++++ 4 files changed, 117 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 29b97e15d..7e1647d22 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -336,7 +336,7 @@ impl Item { /// How far a visible stroke reaches inside the path: half its weight centred, all of it inside, /// none outside. - fn stroke_inside(&self) -> f64 { + pub fn stroke_inside(&self) -> f64 { let w = self.stroke.weight; if self.stroke.is_none() || !w.is_finite() { return 0.0; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 893708753..5f25da50b 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3567,9 +3567,16 @@ fn fitted_text_frame(d: &Document, id: ItemId, height: bool, width: bool, ref_pt if !(r.width().is_finite() && r.height().is_finite() && r.width() > 0.0 && r.height() > 0.0) { return Err(bad("object.fit", "text frame bounds must be finite and nonempty")); } - let inset_l = if tf.options.inset[1].is_finite() { tf.options.inset[1] } else { 0.0 }; - let inset_b = if tf.options.inset[2].is_finite() { tf.options.inset[2] } else { 0.0 }; - let inset_r = if tf.options.inset[3].is_finite() { tf.options.inset[3] } else { 0.0 }; + // Composition reserves `stroke_inside()` inside every edge before applying the frame's text + // insets (`Item::text_area()`). Include the same allowance so stroked frames do not overset. + let stroke_in = it.stroke_inside(); + let edge_inset = |v: f64| { + let total = if v.is_finite() { v + stroke_in } else { stroke_in }; + if total.is_finite() { total } else { 0.0 } + }; + let inset_l = edge_inset(tf.options.inset[1]); + let inset_b = edge_inset(tf.options.inset[2]); + let inset_r = edge_inset(tf.options.inset[3]); let anchors = fit_text_anchors(tf, ref_pt); // Keep trial layouts out of the session cache. Search with the actual columns and frame // options: measuring a very tall frame collapses columns and includes vertical alignment's @@ -7029,6 +7036,57 @@ mod fit_text_frame_tests { assert!(!rf_cs.is_overset() && rf_cs.frame(rtl_first).unwrap().lines.len() == 1, "RTL text wrapped/overset: {rfb:?}"); assert!((rfb.width() - (pb.width() + 24.0)).abs() < 0.5, "RTL text lost first_line_indent: rfb={rfb:?} vs pb={pb:?}"); } + + #[test] + fn stroked_frame_width_fit_preserves_inside_stroke_allowance() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + + // One-line frame with a 4 pt inside stroke: width fit from the left handle (ref=5) must + // keep both sides' inside-stroke allowance so recomposition stays one line and non-overset. + let inside_l = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "Hello world"); + s.execute("object.stroke", &json!({"ids": [inside_l.0], "swatch": "[Black]", "weight": 4.0, "align": "inside"})).unwrap(); + let il_sid = s.doc().unwrap().doc.item(inside_l).unwrap().text_frame().unwrap().story; + assert!(!s.cache.get(&s.doc().unwrap().doc, il_sid, None).is_overset()); + assert_eq!(s.cache.get(&s.doc().unwrap().doc, il_sid, None).frame(inside_l).unwrap().lines.len(), 1); + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [inside_l.0]})).unwrap(); + let il_b = bounds(&s, inside_l); + let il_cs = s.cache.get(&s.doc().unwrap().doc, il_sid, None); + assert!(!il_cs.is_overset(), "4 pt inside stroke caused overset on ref=5 width fit: {il_b:?}"); + assert_eq!(il_cs.frame(inside_l).unwrap().lines.len(), 1, "4 pt inside stroke caused wrap on ref=5 width fit: {il_b:?}"); + assert!((il_b.x1 - 500.0).abs() < 1e-9 && il_b.width() < 250.0, "{il_b:?}"); + + // Left-anchored width fit (right handle, ref=3) also keeps the inside-stroke allowance. + let inside_r = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "Hello world"); + s.execute("object.stroke", &json!({"ids": [inside_r.0], "swatch": "[Black]", "weight": 4.0, "align": "inside"})).unwrap(); + let ir_sid = s.doc().unwrap().doc.item(inside_r).unwrap().text_frame().unwrap().story; + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 3, "ids": [inside_r.0]})).unwrap(); + let ir_b = bounds(&s, inside_r); + let ir_cs = s.cache.get(&s.doc().unwrap().doc, ir_sid, None); + assert!(!ir_cs.is_overset(), "4 pt inside stroke caused overset on ref=3 width fit: {ir_b:?}"); + assert_eq!(ir_cs.frame(inside_r).unwrap().lines.len(), 1, "4 pt inside stroke caused wrap on ref=3 width fit: {ir_b:?}"); + assert!((ir_b.x0 - 100.0).abs() < 1e-9 && (ir_b.width() - il_b.width()).abs() < 0.01, "ir={ir_b:?} vs il={il_b:?}"); + + // Centered 8 pt stroke reaches 4 pt inside (same inner width as 4 pt inside); outside 8 pt + // reaches 0 pt inside (~8 pt narrower inner rect). + let centered = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "Hello world"); + s.execute("object.stroke", &json!({"ids": [centered.0], "swatch": "[Black]", "weight": 8.0, "align": "center"})).unwrap(); + let c_sid = s.doc().unwrap().doc.item(centered).unwrap().text_frame().unwrap().story; + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [centered.0]})).unwrap(); + let c_inner = s.doc().unwrap().doc.item(centered).unwrap().inner_bounds(); + let c_cs = s.cache.get(&s.doc().unwrap().doc, c_sid, None); + assert!(!c_cs.is_overset() && c_cs.frame(centered).unwrap().lines.len() == 1, "{c_inner:?}"); + assert!((c_inner.width() - il_b.width()).abs() < 0.01, "centered={c_inner:?} vs inside={il_b:?}"); + + let outside = frame(&mut s, [100.0, 100.0, 500.0, 145.0], "Hello world"); + s.execute("object.stroke", &json!({"ids": [outside.0], "swatch": "[Black]", "weight": 8.0, "align": "outside"})).unwrap(); + let o_sid = s.doc().unwrap().doc.item(outside).unwrap().text_frame().unwrap().story; + s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ref": 5, "ids": [outside.0]})).unwrap(); + let o_inner = s.doc().unwrap().doc.item(outside).unwrap().inner_bounds(); + let o_cs = s.cache.get(&s.doc().unwrap().doc, o_sid, None); + assert!(!o_cs.is_overset() && o_cs.frame(outside).unwrap().lines.len() == 1, "{o_inner:?}"); + assert!((il_b.width() - o_inner.width() - 8.0).abs() < 0.01, "inside={il_b:?} vs outside={o_inner:?}"); + } } #[cfg(test)] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e50da7b0d..ba43ed097 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -564,7 +564,7 @@ fn fitting_params(cx: &ToolContext, handle: usize) -> (&'static str, Option Option<(&'static str, usize)> { let it = cx.doc.item(id)?; let xf = cx.item_canvas_xf(id)? * it.xf; - fitting_item_params(xf, dir, corner, fallback_axis) + fitting_item_params(xf, handle, dir) }; let mut results = cx.selection.items.iter().filter_map(|id| for_item(*id)); let Some((first_axis, first_ref)) = results.next() else { @@ -574,26 +574,29 @@ fn fitting_params(cx: &ToolContext, handle: usize) -> (&'static str, Option Option<(&'static str, usize)> { +fn fitting_item_params(xf: designcraft_geom::Affine, handle: usize, dir: Point) -> Option<(&'static str, usize)> { let [a, b, c, d, _, _] = xf.as_coeffs(); let det = a * d - b * c; - if !(det.is_finite() && det.abs() > 1e-12) { + let sx = a.hypot(b); + if !(det.is_finite() && det.abs() > 1e-12 && sx.is_finite() && sx > 1e-12) { return None; } - let lx = (d * dir.x - c * dir.y) / det; - let ly = (-b * dir.x + a * dir.y) / det; - if !(lx.is_finite() && ly.is_finite()) { - return None; - } - let axis = if corner { + // Preserve the base side-handle axis rule (local width vs height follows the local X axis + // orientation) so horizontal shear does not turn a top/bottom handle into a width fit. + let axis = if handle.is_multiple_of(2) { "both" - } else if (lx.abs() - ly.abs()).abs() <= 1e-9 { - fallback_axis - } else if lx.abs() > ly.abs() { - "width" } else { - "height" + let canvas_height = matches!(handle, 1 | 5); + let local_width_is_vertical = b.abs() > a.abs(); + if canvas_height == local_width_is_vertical { "width" } else { "height" } }; + // Project the handle direction onto the orthonormal local-X / signed-perpendicular basis so + // shear and non-uniform scaling keep the opposite local edge/corner anchor intact. + let ux = (a * dir.x + b * dir.y) / sx; + let uy = ((-b * dir.x + a * dir.y) / sx) * det.signum(); + if !(ux.is_finite() && uy.is_finite()) { + return None; + } let anchor = |v: f64| { if v < -1e-6 { 2 @@ -604,9 +607,9 @@ fn fitting_item_params(xf: designcraft_geom::Affine, dir: Point, corner: bool, f } }; let (rx, ry) = match axis { - "width" => (anchor(lx), 1), - "height" => (1, anchor(ly)), - _ => (anchor(lx), anchor(ly)), + "width" => (anchor(ux), 1), + "height" => (1, anchor(uy)), + _ => (anchor(ux), anchor(uy)), }; Some((axis, ry * 3 + rx)) } diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index b62dd3f29..27ae9509f 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -1924,6 +1924,41 @@ fn double_clicking_top_and_rotated_handles_sets_opposite_ref() { ); } +#[test] +fn double_clicking_handles_on_sheared_frame_keeps_axis_and_opposite_ref() { + let mut d = Document::new(&NewDocument::default()); + let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0)); + let shear = designcraft_geom::Affine::new([1.0, 0.0, 60.0_f64.to_radians().tan(), 1.0, 0.0, 0.0]); + d.item_mut(id).unwrap().xf = shear; + let s = Selection { items: vec![id], ..Default::default() }; + let (c, l) = (Cache::new(), CanvasLayout::new(&d, false)); + let cx = ctx(&d, &s, &c, &l); + let b = cx.selection_bounds().unwrap(); + let mut t = create("selection"); + // A 60° horizontal shear keeps local X horizontal, so top/bottom still fit height and + // left/right still fit width, with each handle pinning its opposite local side. + for (handle, axis, rf) in [(1, "height", 7), (5, "height", 1), (7, "width", 5), (3, "width", 3), (0, "both", 8)] { + let p = select::handles(b)[handle]; + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y)), + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}))], + "sheared handle={handle}" + ); + } + // 90° clockwise rotation combined with 60° horizontal shear maps local X vertically. + d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate(std::f64::consts::FRAC_PI_2) * shear; + let cx = ctx(&d, &s, &c, &l); + let b = cx.selection_bounds().unwrap(); + for (handle, axis, rf) in [(1, "width", 5), (3, "height", 7)] { + let p = select::handles(b)[handle]; + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y)), + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}))], + "rotated+sheared handle={handle}" + ); + } +} + #[test] fn pen_continues_an_open_path_from_either_end_point() { let mut d = Document::new(&NewDocument::default()); From d64ce68f87d941c14c0736ba81c443268216ebda Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:17:11 +0000 Subject: [PATCH 16/17] 2880: decline ambiguous side-handle fit on mixed-orientation selections --- crates/tools/src/select.rs | 54 ++++++++++++++++++-------- crates/tools/src/tests.rs | 78 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+), 15 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index ba43ed097..df2e65682 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -540,9 +540,11 @@ fn handle_at(cx: &ToolContext, p: Point) -> Option { } /// Side handles are drawn on the canvas bounding box; fitting uses the frame's local axes and -/// keeps the opposite local edge/corner (`ref` 0..=8) fixed. When a multi-selection has differing -/// local orientations for the handle, `ref` is omitted so each frame keeps its own default. -fn fitting_params(cx: &ToolContext, handle: usize) -> (&'static str, Option) { +/// keeps the opposite local edge/corner (`ref` 0..=8) fixed. Returns `None` when a multi-selection +/// needs different local axes for the same side handle (e.g. an unrotated frame selected alongside +/// a 90°-rotated frame). When all selected items share the same local axis but have differing +/// opposite references, `ref` is omitted so each frame keeps its own default. +fn fitting_params(cx: &ToolContext, handle: usize) -> Option<(&'static str, Option)> { let dir = match handle { 0 => Point::new(-1.0, -1.0), 1 => Point::new(0.0, -1.0), @@ -561,17 +563,37 @@ fn fitting_params(cx: &ToolContext, handle: usize) -> (&'static str, Option Option<(&'static str, usize)> { - let it = cx.doc.item(id)?; - let xf = cx.item_canvas_xf(id)? * it.xf; - fitting_item_params(xf, handle, dir) - }; - let mut results = cx.selection.items.iter().filter_map(|id| for_item(*id)); - let Some((first_axis, first_ref)) = results.next() else { - return (fallback_axis, None); - }; - let all_match = results.all(|(ax, rf)| ax == first_axis && rf == first_ref); - (first_axis, all_match.then_some(first_ref)) + let mut axis: Option<&'static str> = None; + let mut ref_pt: Option = None; + let mut ref_mixed = false; + let mut seen_degenerate = false; + let mut count = 0usize; + for id in &cx.selection.items { + let Some(it) = cx.doc.item(*id) else { continue }; + count += 1; + let Some((ax, rf)) = cx.item_canvas_xf(*id).and_then(|spread_xf| fitting_item_params(spread_xf * it.xf, handle, dir)) else { + seen_degenerate = true; + ref_mixed = true; + continue; + }; + match axis { + None => { + axis = Some(ax); + ref_pt = Some(rf); + } + Some(prev) if prev != ax => return None, + Some(_) => { + if ref_pt != Some(rf) { + ref_mixed = true; + } + } + } + } + if seen_degenerate && !corner && count > 1 { + return None; + } + let axis = axis.unwrap_or(fallback_axis); + Some((axis, if ref_mixed { None } else { ref_pt })) } fn fitting_item_params(xf: designcraft_geom::Affine, handle: usize, dir: Point) -> Option<(&'static str, usize)> { @@ -1338,7 +1360,9 @@ impl Tool for SelectionTool { && let Some(h) = handle_at(cx, p) { self.drag = Drag::None; - let (axis, rf) = fitting_params(cx, h); + let Some((axis, rf)) = fitting_params(cx, h) else { + return vec![]; + }; let params = match rf { Some(rf) => json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}), None => json!({"mode": "fitFrameToContent", "axis": axis}), diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 27ae9509f..b9ae82766 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -1959,6 +1959,84 @@ fn double_clicking_handles_on_sheared_frame_keeps_axis_and_opposite_ref() { } } +#[test] +fn double_clicking_handle_on_mixed_orientation_selection_declines_ambiguous_axes() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (upright, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 300.0, 200.0), lid, "A", ParaFormat::default()).unwrap(); + let (upright2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 100.0, 520.0, 200.0), lid, "B", ParaFormat::default()).unwrap(); + let (rot90, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 250.0, 300.0, 350.0), lid, "C", ParaFormat::default()).unwrap(); + d.item_mut(rot90).unwrap().xf = designcraft_geom::Affine::rotate(std::f64::consts::FRAC_PI_2); + let (rot90_2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 250.0, 520.0, 350.0), lid, "D", ParaFormat::default()).unwrap(); + d.item_mut(rot90_2).unwrap().xf = designcraft_geom::Affine::rotate(std::f64::consts::FRAC_PI_2); + let (rot180, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 400.0, 300.0, 500.0), lid, "E", ParaFormat::default()).unwrap(); + d.item_mut(rot180).unwrap().xf = designcraft_geom::Affine::rotate(std::f64::consts::PI); + let singular = add_rect(&mut d, Rect::new(320.0, 400.0, 520.0, 500.0)); + d.item_mut(singular).unwrap().xf = designcraft_geom::Affine::scale(0.0); + + let (c, l) = (Cache::new(), CanvasLayout::new(&d, false)); + let mut t = create("selection"); + + // Mixed 0° + 90° selection: every side handle needs different local axes, so both selection + // orders decline the ambiguous fit (without falling through to text editing), while corners + // still share axis="both" and omit `ref`. + for items in [vec![upright, rot90], vec![rot90, upright]] { + let s = Selection { items: items.clone(), ..Default::default() }; + let cx = ctx(&d, &s, &c, &l); + let b = cx.selection_bounds().unwrap(); + for handle in [1, 3, 5, 7] { + let p = select::handles(b)[handle]; + assert!( + t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y)).is_empty(), + "expected decline for order={items:?} handle={handle}" + ); + assert!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y).with_clicks(2)).is_empty(), + "expected decline on second press for order={items:?} handle={handle}" + ); + } + let tl = select::handles(b)[0]; + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, tl.x, tl.y)), + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": "both"}))], + "corner handle for order={items:?}" + ); + } + + // Mixed 0° + 180° selection shares axis="height" on the top handle in both selection orders, + // omitting `ref` because opposite edges differ. + for items in [vec![upright, rot180], vec![rot180, upright]] { + let s = Selection { items: items.clone(), ..Default::default() }; + let cx = ctx(&d, &s, &c, &l); + let top = select::handles(cx.selection_bounds().unwrap())[1]; + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, top.x, top.y)), + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": "height"}))], + "0+180 order={items:?}" + ); + } + + // Matching multi-selections keep both axis and opposite `ref`. + for (items, axis, rf) in [(vec![upright, upright2], "height", 7), (vec![rot90, rot90_2], "width", 5)] { + let s = Selection { items: items.clone(), ..Default::default() }; + let cx = ctx(&d, &s, &c, &l); + let top = select::handles(cx.selection_bounds().unwrap())[1]; + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, top.x, top.y)), + vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis, "ref": rf}))], + "same-orientation multi-select {items:?}" + ); + } + + // A degenerate transform alongside a valid frame also declines side handles in both orders. + for items in [vec![upright, singular], vec![singular, upright]] { + let s = Selection { items: items.clone(), ..Default::default() }; + let cx = ctx(&d, &s, &c, &l); + let top = select::handles(cx.selection_bounds().unwrap())[1]; + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, top.x, top.y)).is_empty(), "degenerate mixed order={items:?}"); + } +} + #[test] fn pen_continues_an_open_path_from_either_end_point() { let mut d = Document::new(&NewDocument::default()); From 980666bf63fe5926bd489ee46cd51d3406ae4cce Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:28:51 +0000 Subject: [PATCH 17/17] 2880: reuse selected_with_canvas_xf in fitting_params --- crates/tools/src/lib.rs | 2 +- crates/tools/src/select.rs | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index d4a11b582..805c26374 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -317,7 +317,7 @@ impl ToolContext<'_> { /// The selected items with the transform from their own space to the canvas, found in one walk /// of the document (a search per item made a big selection quadratic). Same first match per /// id as `Document::find`, in selection order. - fn selected_with_canvas_xf(&self) -> Vec<(&Item, Affine)> { + pub(crate) fn selected_with_canvas_xf(&self) -> Vec<(&Item, Affine)> { let mut want: std::collections::HashSet = self.selection.items.iter().copied().collect(); let mut found: std::collections::HashMap = std::collections::HashMap::new(); // Pre-order with an explicit stack: a deep group tree must not exhaust the call stack. diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index df2e65682..5ab8c018b 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -567,11 +567,10 @@ fn fitting_params(cx: &ToolContext, handle: usize) -> Option<(&'static str, Opti let mut ref_pt: Option = None; let mut ref_mixed = false; let mut seen_degenerate = false; - let mut count = 0usize; - for id in &cx.selection.items { - let Some(it) = cx.doc.item(*id) else { continue }; - count += 1; - let Some((ax, rf)) = cx.item_canvas_xf(*id).and_then(|spread_xf| fitting_item_params(spread_xf * it.xf, handle, dir)) else { + let selected = cx.selected_with_canvas_xf(); + let count = selected.len(); + for (it, spread_xf) in selected { + let Some((ax, rf)) = fitting_item_params(spread_xf * it.xf, handle, dir) else { seen_degenerate = true; ref_mixed = true; continue;