Skip to content

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

Merge pr/662: Commands: reject unknown spread values instead of falling back to page 1 (#662)

aiongg7e4c75fce955
diff --cc crates/engine/src/cmd/edit.rs
index ec2c5bec3,e7190acb4..5db99fe95
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@@ -81,73 -88,7 +81,73 @@@ fn paste_text(s: &mut Session, text: Op
});
}
let text = text.or_else(|| clip.map(|(_, p)| p)).ok_or_else(|| super::bad("edit.paste", "clipboard is empty"))?;
- s.execute("text.insert", &json!({"text": text.replace("\r\n", "\n").replace('\r', "\n"), "raw": true}))
+ let text = outside_text(&text)?;
+ s.execute("text.insert", &json!({"text": text, "raw": true}))
+}
+
+/// Text from the system clipboard as story text: Unix line ends, and none of the private-use
+/// characters (U+E000–U+E1FF) that stories use as markers for breaks, footnotes, tables and
+/// variables, since a stray one would be read as a marker without its payload.
+fn outside_text(text: &str) -> Result<String> {
+ let text: String = text.replace("\r\n", "\n").replace('\r', "\n").chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).collect();
+ if text.is_empty() { Err(super::bad("edit.paste", "the clipboard holds no text")) } else { Ok(text) }
+}
+
+/// Pasted text with no insertion point: a new text frame holding it, as wide as the first column
+/// of the page's margin area and as tall as the text (at most the margin area's height), centred
+/// on `at` (spread coordinates) or else on the margin area. The frame ends up selected. With
+/// `slice` (the text copied here), the frame's story is that formatted copy.
+fn paste_text_frame(s: &mut Session, p: &Value, text: &str, slice: Option<&designcraft_doc::Story>) -> Result<Value> {
+ use designcraft_geom::{Point, Rect, shapes};
+ const LIMIT: f64 = 1.0e5;
- let sr = super::spread_param(p, "spread");
++ let sr = super::spread_param(p, "edit.paste")?;
+ let at = super::point_param(p, "at")
+ .filter(|a| a.x.is_finite() && a.y.is_finite())
+ .map(|a| Point::new(a.x.clamp(-LIMIT, LIMIT), a.y.clamp(-LIMIT, LIMIT)));
+ let lid = s.doc()?.active_layer;
+ let cache = s.cache.clone();
+ let text = if slice.is_some() { String::new() } else { outside_text(text)? };
+ s.edit(|d, sel| {
+ let sp = d.spread(sr).ok_or_else(|| super::bad("edit.paste", "no such spread"))?;
+ let page = at.and_then(|a| sp.page_at_x(a.x)).and_then(|i| sp.pages.get(i)).or_else(|| sp.pages.first());
+ let page = page.ok_or_else(|| super::bad("edit.paste", "the spread has no pages"))?;
+ let margins = page.margin_rect();
+ let column = page.column_rects().first().copied().unwrap_or(margins);
+ let w = column.width().max(12.0);
+ let max_h = margins.height().max(12.0);
+ let c = at.unwrap_or(Point::new(column.center().x, margins.center().y));
+ let rect = |h: f64| Rect::new(c.x - w / 2.0, c.y - h / 2.0, c.x + w / 2.0, c.y + h / 2.0);
+ let para = match slice.and_then(|sl| sl.paras.first()) {
+ Some(pf) => designcraft_doc::ParaFormat { table: None, ..pf.clone() },
+ None => designcraft_doc::ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() },
+ };
+ let (id, sid) = d.add_text_frame(sr, rect(max_h), lid, &text, para)?;
+ if let Some(sl) = slice {
+ d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?.insert_story(0, sl);
+ }
+ // Shrink to the composed text unless it already fills the frame.
+ let composed = cache.get(d, sid, None);
+ if !composed.is_overset()
+ && let Some(ft) = composed.frame(id)
+ {
+ let inset = d.item(id).and_then(|i| i.text_frame()).map_or(0.0, |tf| tf.options.inset[0] + tf.options.inset[2]);
+ let h = (ft.content_height + inset + 0.5).clamp(12.0, max_h);
+ if h.is_finite()
+ && h < max_h
+ && let Some(it) = d.item_mut(id)
+ {
+ it.path = shapes::rectangle(rect(h));
+ // Keep the full height if the last line no longer fits.
+ if cache.get(d, sid, None).is_overset()
+ && let Some(it) = d.item_mut(id)
+ {
+ it.path = shapes::rectangle(rect(max_h));
+ }
+ }
+ }
+ *sel = Selection::items(vec![id]);
+ Ok(json!({"id": id.0, "story": sid.0}))
+ })
}
fn strip_objects(st: &designcraft_doc::Story) -> designcraft_doc::Story {
@@@ -313,13 -237,9 +313,13 @@@ pub fn specs() -> Vec<CommandSpec>
return Err(super::bad("edit.paste", "clipboard is empty"));
};
let off = if bool_or(p, "inPlace", false) { 0.0 } else { 12.0 };
- let to = super::spread_param(p, "spread");
++ let to = super::spread_param(p, "edit.paste")?;
+ let from = s.clipboard_origin;
let ids: Vec<ItemId> = clip.spreads.first().map(|sp| sp.items.iter().map(|i| i.id).collect()).unwrap_or_default();
s.edit(|d, sel| {
- let new = super::object::duplicate_from(d, &clip, &ids, SpreadRef::Doc(0), designcraft_geom::Vec2::new(off, off))?;
+ // The same place on another spread is the same distance from its spine or left edge.
+ let dx = d.spread(to).map_or(0.0, |sp| paste_origin(sp) - from);
+ let new = super::object::duplicate_from(d, &clip, &ids, to, designcraft_geom::Vec2::new(dx + off, off))?;
*sel = Selection::items(new.clone());
Ok(json!({"ids": new.iter().map(|i| i.0).collect::<Vec<_>>()}))
})
diff --cc crates/engine/src/cmd/file.rs
index b7bde70ad,a1919b89e..d401a22bc
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -612,13 -457,8 +612,13 @@@ fn load_cursor(s: &mut Session, mut ass
}
fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
- let (aid, (nw, nh)) = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?;
+ let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?;
+ // Undo can remove the loaded graphic's asset.
+ if !s.doc()?.doc.assets.contains_key(&aid) {
+ s.loaded = None;
+ return Err(bad("place.drop", "the loaded graphic is no longer in the document"));
+ }
- let sr = super::spread_param(p, "spread");
+ let sr = super::spread_param(p, "place.drop")?;
let lid = s.doc()?.active_layer;
let frame = super::id_param(p, "frame");
let rect = super::rect_param(p, "rect");
diff --cc crates/engine/src/cmd/guides.rs
index b5750fd23,1111cb3b0..b2bc378a5
--- a/crates/engine/src/cmd/guides.rs
+++ b/crates/engine/src/cmd/guides.rs
@@@ -111,38 -94,22 +94,38 @@@ fn page_at(d: &Document, r: SpreadRef,
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
- let r = guide_spread(p, "guide.add")?;
- let o = orientation(p)?;
- let pos = finite_number(p, "position", "guide.add")?.ok_or_else(|| bad("guide.add", "missing position"))?;
+ let r = super::spread_param(p, "guide.add")?;
let spread_guide = p.get("spreadGuide").and_then(Value::as_bool).unwrap_or(false);
+ let page = optional_usize(p, "page", "guide.add")?;
+ // (orientation, position, x used to find the page)
+ let guides: Vec<(Orientation, f64, f64)> = if str_param(p, "orientation") == Some("both") {
+ let point = p.get("point").and_then(Value::as_array).ok_or_else(|| bad("guide.add", "orientation `both` needs point: [x, y]"))?;
+ let coord = |i: usize| point.get(i).and_then(Value::as_f64).filter(|v| v.is_finite());
+ let (Some(x), Some(y), 2) = (coord(0), coord(1), point.len()) else {
+ return Err(bad("guide.add", "`point` must be two finite numbers [x, y]"));
+ };
+ vec![(Orientation::Horizontal, y, x), (Orientation::Vertical, x, x)]
+ } else {
+ let o = orientation(p)?;
+ let pos = finite_number(p, "position", "guide.add")?.ok_or_else(|| bad("guide.add", "missing position"))?;
+ let x = match o {
+ Orientation::Vertical => pos,
+ Orientation::Horizontal => finite_number(p, "at", "guide.add")?.unwrap_or(0.0),
+ };
+ vec![(o, pos, x)]
+ };
let d = &s.doc()?.doc;
- let pi = match optional_usize(p, "page", "guide.add")? {
- Some(pi) => pi,
- None if spread_guide => 0,
- None => {
- let x = match o {
- Orientation::Vertical => pos,
- Orientation::Horizontal => finite_number(p, "at", "guide.add")?.unwrap_or(0.0),
+ let placed: Vec<(Orientation, f64, usize)> = guides
+ .into_iter()
+ .map(|(o, pos, x)| {
+ let pi = match page {
+ Some(pi) => pi,
+ None if spread_guide => 0,
+ None => page_at(d, r, x),
};
- page_at(d, r, x)
- }
- };
+ (o, pos, pi)
+ })
+ .collect();
let layer = s.doc()?.active_layer;
s.edit(|d, _| {
let sp = d.spread_mut(r).ok_or_else(|| bad("guide.add", "no such spread"))?;
diff --cc crates/engine/src/cmd/object.rs
index 86ab58355,21362ef9a..59fc5e711
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@@ -3937,253 -2787,55 +3937,279 @@@ mod tint_alone_tests
use serde_json::json;
#[test]
- fn fills_and_strokes_must_name_a_swatch_and_change_nothing_otherwise() {
+ fn a_tint_alone_keeps_each_swatch_and_leaves_no_stroke_alone() {
let mut s = crate::Session::new();
s.execute("file.new", &json!({})).unwrap();
- let id = s.execute("frame.create", &json!({"rect": [0, 0, 100, 100]})).unwrap()["id"].clone();
- for (cmd, params, hint) in [
- ("object.fill", json!({"swatch": "Paper", "ids": [id]}), Some("[Paper]")),
- ("object.fill", json!({"swatch": "[black]", "ids": [id]}), Some("[Black]")),
- ("object.fill", json!({"swatch": "Missing Ink", "ids": [id]}), None),
- ("object.stroke", json!({"swatch": "#ff0000", "weight": 4, "ids": [id]}), None),
- ("object.stroke", json!({"gapSwatch": "paper", "ids": [id]}), Some("[Paper]")),
- ] {
- let before = s.doc().unwrap().doc.clone();
- let e = s.execute(cmd, &params).unwrap_err().to_string();
- assert!(e.contains("no swatch named") && e.contains("swatch.create"), "{cmd}: {e}");
- if let Some(h) = hint {
- assert!(e.contains(&format!("did you mean `{h}`")), "{cmd}: {e}");
+ let a = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();
+ let b = s.execute("frame.create", &json!({"rect": [60, 0, 110, 50]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("object.fill", &json!({"swatch": "[Black]", "ids": [a]})).unwrap();
+ s.execute("object.fill", &json!({"swatch": "C=100 M=0 Y=0 K=0", "ids": [b]})).unwrap();
+ s.execute("object.stroke", &json!({"swatch": "[None]", "ids": [a, b]})).unwrap();
+ // Fill tint on both: each keeps its swatch.
+ s.execute("object.fill", &json!({"tint": 0.25, "ids": [a, b]})).unwrap();
+ let item = |s: &crate::Session, id: u64| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone();
+ assert_eq!((item(&s, a).fill.swatch.as_str(), item(&s, a).fill.tint), ("[Black]", 0.25));
+ assert_eq!((item(&s, b).fill.swatch.as_str(), item(&s, b).fill.tint), ("C=100 M=0 Y=0 K=0", 0.25));
+ // A swatch alone is 100%.
+ s.execute("object.fill", &json!({"swatch": "[Paper]", "ids": [a]})).unwrap();
+ assert_eq!(item(&s, a).fill.tint, 1.0);
+ // A stroke tint on no stroke: still no stroke.
+ s.execute("object.stroke", &json!({"tint": 0.5, "ids": [a]})).unwrap();
+ assert!(item(&s, a).stroke.is_none(), "{:?}", item(&s, a).stroke);
+ assert!(s.execute("object.fill", &json!({"ids": [a]})).is_err(), "neither swatch nor tint");
+ }
+}
+
+#[cfg(test)]
+mod content_transform_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ /// A rotated graphic frame holding a 200 x 100 image, its content selected.
+ fn rotated_frame_with_image() -> (Session, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ let png = designcraft_render::Rendered { width: 200, height: 100, pixels: vec![200u8; 200 * 100 * 4] }.to_png();
+ s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&png), "name": "a.png", "frame": f})).unwrap();
+ s.execute("transform.rotate", &json!({"ids": [f], "angle": -45})).unwrap();
+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();
+ (s, f)
+ }
+
+ #[test]
+ fn rotating_the_content_leaves_the_frame_as_it_is() {
+ let (mut s, f) = rotated_frame_with_image();
+ let before = s.execute("transform.info", &json!({"ids": [f]})).unwrap();
+ assert!((before["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6 && (before["content"]["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6);
+ // The tutorial's step: the image straightened inside its tilted frame.
+ s.execute("transform.set", &json!({"rotation": 0})).unwrap();
+ let after = s.execute("transform.info", &json!({"ids": [f]})).unwrap();
+ assert!((after["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "the frame stays at -45: {after}");
+ assert!(after["content"]["rotation"].as_f64().unwrap().abs() < 1e-6, "the image is upright: {after}");
+ // Scale and position act on the image too.
+ s.execute("transform.set", &json!({"scaleX": 50, "scaleY": 50})).unwrap();
+ let info = s.execute("transform.info", &json!({"ids": [f]})).unwrap();
+ assert!((info["content"]["scaleX"].as_f64().unwrap() - 50.0).abs() < 1e-6, "{info}");
+ assert!((info["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6);
+ // One undo step each.
+ s.execute("edit.undo", &json!({})).unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ let undone = s.execute("transform.info", &json!({"ids": [f]})).unwrap();
+ assert!((undone["content"]["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "{undone}");
+ }
+
+ #[test]
+ fn with_the_graphic_selected_transform_info_reports_the_graphic() {
+ let (mut s, f) = rotated_frame_with_image();
+ s.execute("transform.set", &json!({"rotation": 0})).unwrap();
+ // What the Control bar and Properties read: the graphic's 0, not the frame's -45, so a
+ // spinner step from it gives 1, not -44.
+ let info = s.execute("transform.info", &json!({})).unwrap();
+ assert!(info["rotation"].as_f64().unwrap().abs() < 1e-6, "{info}");
+ let rot = info["rotation"].as_f64().unwrap() + 1.0;
+ s.execute("transform.set", &json!({"rotation": rot})).unwrap();
+ let after = s.execute("transform.info", &json!({"ids": [f]})).unwrap();
+ assert!((after["content"]["rotation"].as_f64().unwrap() - 1.0).abs() < 1e-6, "{after}");
+ assert!((after["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "the frame stays: {after}");
+ // `id` names the target explicitly, like `ids`: the frame.
+ let by_id = s.execute("transform.info", &json!({"id": f})).unwrap();
+ assert!((by_id["rotation"].as_f64().unwrap() + 45.0).abs() < 1e-6, "{by_id}");
+ }
+
+ #[test]
+ fn the_graphic_moves_to_x_and_y_from_the_rulers_zero_point() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ let png = designcraft_render::Rendered { width: 200, height: 100, pixels: vec![200u8; 200 * 100 * 4] }.to_png();
+ s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&png), "name": "a.png", "frame": f})).unwrap();
+ s.execute("view.zeroPoint", &json!({"at": [72, 36]})).unwrap();
+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();
+ s.execute("transform.set", &json!({"x": 10, "y": 20, "ref": 0})).unwrap();
+ // The graphic's top-left, measured from the zero point (what the Transform fields show).
+ let d = &s.doc().unwrap().doc;
+ let id = designcraft_doc::ItemId(f);
+ let loc = d.find(id).unwrap();
+ let it = d.item(id).unwrap();
+ let g = it.graphic().unwrap();
+ let b = (d.parent_xf(&loc) * it.xf * g.xf).transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1));
+ let o = d.ruler_origin(loc.spread, b.center().x).unwrap();
+ assert!(o.x > 0.0 && o.y > 0.0, "the zero point moved: {o:?}");
+ assert!((b.x0 - o.x - 10.0).abs() < 1e-6 && (b.y0 - o.y - 20.0).abs() < 1e-6, "{b:?} from {o:?}");
+ // The frame stays.
+ assert!((it.bounds().x0 - 100.0).abs() < 1e-6, "{:?}", it.bounds());
+ }
+
+ #[test]
+ fn a_locked_frame_records_no_undo_step() {
+ let (mut s, f) = rotated_frame_with_image();
+ s.execute("object.lock", &json!({"ids": [f]})).unwrap();
+ s.execute("selection.set", &json!({"ids": [f], "content": true})).unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ assert_eq!(s.execute("transform.set", &json!({"rotation": 0})).unwrap()["changed"], 0);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no empty undo step");
+ }
+
+ #[test]
+ fn a_frame_selection_still_transforms_the_frame_and_an_empty_frame_has_no_content() {
+ let (mut s, f) = rotated_frame_with_image();
+ // `content: false` (or a frame selection) turns frame and image together.
+ s.execute("transform.set", &json!({"rotation": 0, "content": false})).unwrap();
+ let info = s.execute("transform.info", &json!({"ids": [f]})).unwrap();
+ assert!(info["rotation"].as_f64().unwrap().abs() < 1e-6, "{info}");
+ let e = s.execute("frame.create", &json!({"rect": [400, 100, 500, 200], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ assert!(s.execute("transform.set", &json!({"ids": [e], "content": true, "rotation": 10})).is_err());
+ }
+}
+
+#[cfg(test)]
+mod fit_text_frame_tests {
+ use super::*;
+
+ fn frame(s: &mut Session, rect: [f64; 4], text: &str) -> ItemId {
+ let id = ItemId(s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap());
+ s.execute("selection.set", &json!({"ids": [id.0]})).unwrap();
+ s.execute("type.char", &json!({"attrs": {"size": 30}})).unwrap();
+ id
+ }
+
+ fn bounds(s: &Session, id: ItemId) -> Rect {
+ s.doc().unwrap().doc.item(id).unwrap().bounds()
+ }
+
+ #[test]
+ fn fit_frame_to_content_fits_a_text_frame_to_its_text() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let id = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "INDESIGN");
+ // The height only (a top or bottom handle): the width stays.
+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [id.0]})).unwrap();
+ let h = bounds(&s, id);
+ assert!(h.x1 == 500.0 && h.y0 == 100.0 && h.height() > 30.0 && h.height() < 45.0, "{h:?}");
+ // Both (a corner handle, or the menu): around the line.
+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ids": [id.0]})).unwrap();
+ let b = bounds(&s, id);
+ assert!(b.x0 == 100.0 && b.width() > 100.0 && b.width() < 250.0, "{b:?}");
+ 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(), "still fits");
+ }
+
+ #[test]
+ fn fit_frame_to_content_grows_a_frame_with_overset_text() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let id = frame(&mut s, [100.0, 100.0, 300.0, 140.0], "one two three four five six seven eight nine ten eleven twelve");
+ 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());
+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [id.0]})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ assert!(!s.cache.get(&d, sid, None).is_overset(), "{:?}", bounds(&s, id));
+ assert!(bounds(&s, id).height() > 100.0);
+ assert!(s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "diagonal", "ids": [id.0]})).is_err());
+ }
+
+ #[test]
+ fn fitting_text_keeps_columns_and_vertical_justification() {
+ use designcraft_doc::VerticalJustification::{Bottom, Center, Justify, Top};
+ for columns in [1, 2] {
+ for justification in [Top, Bottom, Center, Justify] {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let id = frame(&mut s, [100.0, 100.0, 500.0, 500.0], "one two three four five six seven eight nine ten eleven twelve");
+ let options = &mut Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().text_frame_mut().unwrap().options;
+ options.columns = columns;
+ options.vertical_justification = justification;
+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height"})).unwrap();
+ let d = &s.doc().unwrap().doc;
+ let it = d.item(id).unwrap();
+ let tf = it.text_frame().unwrap();
+ let composed = s.cache.get(d, tf.story, None);
+ assert!(!composed.is_overset(), "{columns} {justification:?}");
+ assert!(it.bounds().height() < 250.0, "{columns} {justification:?}: {:?}", it.bounds());
+ assert_eq!(tf.options.vertical_justification, justification);
+ assert_eq!(tf.options.columns, columns);
+ if columns == 2 {
+ let ft = composed.frame(id).unwrap();
+ assert!(ft.lines.iter().any(|l| l.column == 1), "both columns stay in use: {ft:?}");
+ }
}
- assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{cmd}: nothing changed");
}
- // Real names, [None] included, still work.
- for sw in ["[Paper]", "[None]", "C=100 M=0 Y=0 K=0"] {
- s.execute("object.fill", &json!({"swatch": sw, "ids": [id]})).unwrap();
- s.execute("object.stroke", &json!({"swatch": sw, "ids": [id]})).unwrap();
+ }
+
+ #[test]
+ fn graphic_fitting_obeys_each_axis_and_locked_text_and_graphics_stay_put() {
+ for graphic in [false, true] {
+ for lock_layer in [false, true] {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let id = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Fit me");
+ if graphic {
+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
+ s.execute("file.place", &json!({"base64": super::super::file::base64_encode(&png), "name": "test.png", "frame": id.0})).unwrap();
+ let it = Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap();
+ let Content::Graphic(g) = &mut it.content else { panic!("graphic") };
+ g.xf = Affine::translate((80.0, 90.0)) * Affine::scale(3.0);
+ let original = it.inner_bounds();
+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "width", "ids": [id.0]})).unwrap();
+ let fitted = s.doc().unwrap().doc.item(id).unwrap().inner_bounds();
+ assert_eq!(fitted, Rect::new(80.0, original.y0, 200.0, original.y1));
+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().path = shapes::rectangle(original);
+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "axis": "height", "ids": [id.0]})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.item(id).unwrap().inner_bounds(), Rect::new(original.x0, 90.0, original.x1, 150.0));
+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().path = shapes::rectangle(original);
+ }
+ let before = bounds(&s, id);
+ if lock_layer {
+ let layer = s.doc().unwrap().doc.item(id).unwrap().layer;
+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).layer_mut(layer).unwrap().locked = true;
+ } else {
+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(id).unwrap().locked = true;
+ }
+ s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ids": [id.0]})).unwrap();
+ assert_eq!(bounds(&s, id), before, "graphic={graphic}, layer={lock_layer}");
+ }
}
}
+
+ #[test]
+ fn an_unfittable_frame_returns_an_error_without_changing_any_target() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let a = frame(&mut s, [100.0, 100.0, 500.0, 300.0], "Fits");
+ let b = frame(&mut s, [100.0, 400.0, 500.0, 600.0], "Cannot fit");
+ Arc::make_mut(&mut s.doc_mut().unwrap().doc).item_mut(b).unwrap().text_frame_mut().unwrap().options.first_baseline_min = 30_000.0;
+ let before = [bounds(&s, a), bounds(&s, b)];
+ assert!(s.execute("object.fit", &json!({"mode": "fitFrameToContent", "ids": [a.0, b.0]})).is_err());
+ assert_eq!([bounds(&s, a), bounds(&s, b)], before);
+ }
}
+
+ #[cfg(test)]
+ mod spread_target_tests {
+ use super::*;
+
+ #[test]
+ fn creating_on_a_parent_spread_and_rejecting_unknown_spreads() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();
+ let parent = json!({"kind": "parent", "index": 0});
+ let r = s.execute("frame.create", &json!({"spread": parent, "rect": [0, 0, 100, 100]})).unwrap();
+ let id = ItemId(r["id"].as_u64().unwrap());
+ assert_eq!(s.doc().unwrap().doc.find(id).unwrap().spread, SpreadRef::Parent(0));
+ s.execute("line.create", &json!({"spread": parent, "a": [0, 0], "b": [50, 50]})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.parents[0].items.len(), 2);
+
+ // Each of these used to land on the first body page.
+ for bad in
+ [json!("A-Parent"), json!("0"), json!(-1), json!(1.5), json!({"kind": "master", "index": 0}), json!({"kind": "parent"}), json!([0])]
+ {
+ assert!(s.execute("frame.create", &json!({"spread": bad, "rect": [0, 0, 100, 100]})).is_err(), "frame.create spread {bad}");
+ assert!(s.execute("line.create", &json!({"spread": bad, "a": [0, 0], "b": [50, 50]})).is_err(), "line.create spread {bad}");
+ }
+ assert!(s.doc().unwrap().doc.spreads[0].items.is_empty());
+ }
+ }
diff --cc crates/engine/src/cmd/paste_svg.rs
index c6ec91ac1,000000000..54513be53
mode 100644,000000..100644
--- a/crates/engine/src/cmd/paste_svg.rs
+++ b/crates/engine/src/cmd/paste_svg.rs
@@@ -1,438 -1,0 +1,438 @@@
+//! Paste vector art copied in another app (Illustrator, VectorCraft, Figma, Inkscape) as editable
+//! paths, as InDesign pastes Illustrator art. Those apps put the copied objects on the system
+//! clipboard as SVG markup; each path becomes a DesignCraft path with its fill and stroke, groups
+//! stay groups, and text comes in as outlines.
+
+use designcraft_doc::{Content, Fill, Item, ItemId, Selection, Shape, Stroke, StrokeType};
+use designcraft_geom::{Affine, BezPath, PathData, Point, Rect};
+use designcraft_images::usvg;
+use serde_json::{Value, json};
+
+use super::*;
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![cmd!(
+ "edit.pasteSvg",
+ "Paste Vector Art",
+ [],
+ None,
+ "{svg: markup (what Illustrator, VectorCraft or Figma put on the clipboard), spread?, at?: [x, y] (spread coords of the art's centre; default the first page's centre)} → {ids, warnings} — paths with their fills and strokes, groups as groups, text as outlines",
+ has_doc,
+ paste_svg
+ )]
+}
+
+/// Is `text` SVG markup (rather than text to paste as text)?
+pub fn is_svg_markup(text: &str) -> bool {
+ designcraft_images::is_svg(text.as_bytes())
+}
+
+/// Nesting deeper than this is flattened into its parent (hostile input can't exhaust the stack).
+const MAX_DEPTH: usize = 64;
+
+/// A converted SVG node, in points.
+enum Art {
+ Path { path: BezPath, fill: Option<Paint>, stroke: Option<(Paint, StrokeStyle)>, opacity: f32 },
+ Group(Vec<Art>, f32),
+}
+
+impl Art {
+ /// Fold a wrapping group's opacity into this object.
+ fn fade(&mut self, by: f32) {
+ match self {
+ Art::Path { opacity, .. } | Art::Group(_, opacity) => *opacity *= by,
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+struct Paint {
+ rgb: [u8; 3],
+ opacity: f32,
+}
+
+struct StrokeStyle {
+ width: f64,
+ cap: designcraft_doc::Cap,
+ join: designcraft_doc::Join,
+ miter: f64,
+ dashes: Option<Vec<f64>>,
+}
+
+#[derive(Default)]
+struct Notes {
+ gradients: usize,
+ images: usize,
+ /// Paths whose fill-opacity and stroke-opacity differ (one object opacity holds only one).
+ mixed_opacity: usize,
+ too_deep: bool,
+}
+
+fn paint(p: &usvg::Paint, opacity: f32, notes: &mut Notes) -> Option<Paint> {
+ let rgb = match p {
+ usvg::Paint::Color(c) => [c.red, c.green, c.blue],
+ // Gradients and patterns come in as their first colour (InDesign keeps Illustrator
+ // gradients; DesignCraft's swatch gradients can't be made from SVG stops yet).
+ usvg::Paint::LinearGradient(g) => {
+ notes.gradients += 1;
+ g.stops().first().map(|s| [s.color().red, s.color().green, s.color().blue])?
+ }
+ usvg::Paint::RadialGradient(g) => {
+ notes.gradients += 1;
+ g.stops().first().map(|s| [s.color().red, s.color().green, s.color().blue])?
+ }
+ usvg::Paint::Pattern(_) => {
+ notes.gradients += 1;
+ return None;
+ }
+ };
+ Some(Paint { rgb, opacity })
+}
+
+/// To 1/10000 pt: SVG numbers are 32-bit floats (a 1 pt stroke reads as 0.99999994).
+fn round(v: f64) -> f64 {
+ (v * 10_000.0).round() / 10_000.0
+}
+
+/// `t` (SVG px space) then px → pt.
+fn to_affine(t: usvg::Transform) -> Affine {
+ let pt = designcraft_images::PT_PER_PX;
+ Affine::scale(pt) * Affine::new([f64::from(t.sx), f64::from(t.ky), f64::from(t.kx), f64::from(t.sy), f64::from(t.tx), f64::from(t.ty)])
+}
+
+fn bezpath(data: &usvg::tiny_skia_path::Path, xf: Affine) -> BezPath {
+ use usvg::tiny_skia_path::PathSegment as S;
+ let p = |q: usvg::tiny_skia_path::Point| xf * Point::new(f64::from(q.x), f64::from(q.y));
+ let mut bp = BezPath::new();
+ for seg in data.segments() {
+ match seg {
+ S::MoveTo(a) => bp.move_to(p(a)),
+ S::LineTo(a) => bp.line_to(p(a)),
+ S::QuadTo(a, b) => bp.quad_to(p(a), p(b)),
+ S::CubicTo(a, b, c) => bp.curve_to(p(a), p(b), p(c)),
+ S::Close => bp.close_path(),
+ }
+ }
+ bp
+}
+
+fn convert(g: &usvg::Group, depth: usize, notes: &mut Notes, out: &mut Vec<Art>) {
+ for node in g.children() {
+ match node {
+ usvg::Node::Path(path) => {
+ if !path.is_visible() || path.data().is_empty() {
+ continue;
+ }
+ let xf = to_affine(path.abs_transform());
+ let fill = path.fill().and_then(|f| paint(f.paint(), f.opacity().get(), notes));
+ let stroke = path.stroke().and_then(|s| {
+ let c = paint(s.paint(), s.opacity().get(), notes)?;
+ // A stroke scales with the art: its width in points.
+ let scale = xf.determinant().abs().sqrt();
+ let width = round(f64::from(s.width().get()) * scale);
+ let dashes = s.dasharray().map(|d| d.iter().map(|v| round(f64::from(*v) * scale)).collect::<Vec<_>>());
+ let style = StrokeStyle {
+ width,
+ cap: match s.linecap() {
+ usvg::LineCap::Butt => designcraft_doc::Cap::Butt,
+ usvg::LineCap::Round => designcraft_doc::Cap::Round,
+ usvg::LineCap::Square => designcraft_doc::Cap::Projecting,
+ },
+ join: match s.linejoin() {
+ usvg::LineJoin::Round => designcraft_doc::Join::Round,
+ usvg::LineJoin::Bevel => designcraft_doc::Join::Bevel,
+ _ => designcraft_doc::Join::Miter,
+ },
+ miter: f64::from(s.miterlimit().get()),
+ dashes,
+ };
+ Some((c, style))
+ });
+ if fill.is_none() && stroke.is_none() {
+ continue;
+ }
+ if let (Some(f), Some((c, _))) = (&fill, &stroke)
+ && (f.opacity - c.opacity).abs() > f32::EPSILON
+ {
+ notes.mixed_opacity += 1;
+ }
+ out.push(Art::Path { path: bezpath(path.data(), xf), fill, stroke, opacity: 1.0 });
+ }
+ usvg::Node::Group(child) => {
+ if depth >= MAX_DEPTH {
+ notes.too_deep = true;
+ continue;
+ }
+ let mut items = Vec::new();
+ convert(child, depth + 1, notes, &mut items);
+ // usvg wraps nodes in groups for transforms and opacity; only a group of several
+ // objects stays a group. Its opacity goes to what it holds.
+ let opacity = child.opacity().get();
+ if items.len() > 1 {
+ out.push(Art::Group(items, opacity));
+ } else {
+ for mut a in items {
+ a.fade(opacity);
+ out.push(a);
+ }
+ }
+ }
+ // Text arrives as outlines, as Illustrator's Create Outlines would give it.
+ usvg::Node::Text(text) => {
+ let mut items = Vec::new();
+ convert(text.flattened(), depth + 1, notes, &mut items);
+ if items.len() > 1 {
+ out.push(Art::Group(items, 1.0));
+ } else {
+ out.extend(items);
+ }
+ }
+ usvg::Node::Image(_) => notes.images += 1,
+ }
+ }
+}
+
+fn bounds(art: &[Art]) -> Option<Rect> {
+ art.iter()
+ .filter_map(|a| match a {
+ Art::Path { path, .. } => Some(designcraft_geom::Shape::bounding_box(path)),
+ Art::Group(items, _) => bounds(items),
+ })
+ .reduce(|a, b| a.union(b))
+}
+
+/// The swatch holding exactly `rgb`: an existing process colour, else a new unnamed one (hidden
+/// from the Swatches panel until Add to Swatches), as InDesign does for pasted colours.
+fn swatch_for(d: &mut designcraft_doc::Document, rgb: [u8; 3]) -> String {
+ use designcraft_color::swatch::{Swatch, SwatchValue};
+ let color = designcraft_color::Color::rgb8(rgb[0], rgb[1], rgb[2]);
+ if let Some(w) = d.swatches.iter().find(|w| matches!(&w.value, SwatchValue::Color { color: c, .. } if *c == color)) {
+ return w.name.clone();
+ }
+ let base = format!("R={} G={} B={}", rgb[0], rgb[1], rgb[2]);
+ let name = designcraft_doc::Styles::unique_name(|n| d.swatch(n).is_some(), &base);
+ d.swatches.push(Swatch {
+ name: name.clone(),
+ value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },
+ locked: false,
+ named: false,
+ hidden: true,
+ });
+ name
+}
+
+fn build(d: &mut designcraft_doc::Document, art: Vec<Art>, layer: designcraft_doc::LayerId, shift: Affine) -> Vec<Item> {
+ let mut out = Vec::new();
+ for a in art {
+ match a {
+ Art::Path { path, fill, stroke, opacity } => {
+ let data = PathData::from_bezpath(&(shift * path));
+ if data.subpaths.is_empty() {
+ continue;
+ }
+ let anchors: usize = data.subpaths.iter().map(|s| s.anchors.len()).sum();
+ // A straight two-point segment is a graphic line (Line tool); anything else a path.
+ let straight = |a: &designcraft_geom::Anchor| a.h_in == a.p && a.h_out == a.p;
+ let line = data.subpaths.len() == 1 && anchors == 2 && data.subpaths.iter().all(|s| !s.closed && s.anchors.iter().all(straight));
+ // The object's opacity: its own times the paint's. Items have no separate fill and
+ // stroke opacity, so a path with both takes the fill's (`Notes::mixed_opacity`).
+ let paint = fill.map(|f| f.opacity).or(stroke.as_ref().map(|(c, _)| c.opacity)).unwrap_or(1.0);
+ let mut it = Item::new(ItemId(d.alloc()), layer, if line { Shape::GraphicLine } else { Shape::Path }, data);
+ it.fill = match fill {
+ Some(f) => Fill::swatch(&swatch_for(d, f.rgb)),
+ None => Fill::none(),
+ };
+ it.stroke = match stroke {
+ Some((c, s)) => Stroke {
+ swatch: swatch_for(d, c.rgb),
+ weight: s.width,
+ cap: s.cap,
+ join: s.join,
+ miter_limit: s.miter,
+ kind: s.dashes.map_or(StrokeType::Solid, |pattern| StrokeType::Dashed { pattern }),
+ ..Stroke::default()
+ },
+ None => Stroke::none(),
+ };
+ it.opacity = (opacity * paint).clamp(0.0, 1.0);
+ out.push(it);
+ }
+ Art::Group(items, opacity) => {
+ let children = build(d, items, layer, shift);
+ if children.is_empty() {
+ continue;
+ }
+ let mut g = Item::new(ItemId(d.alloc()), layer, Shape::Group, PathData::default());
+ g.stroke = Stroke::none();
+ g.opacity = opacity.clamp(0.0, 1.0);
+ g.content = Content::Group { items: children.into_iter().map(std::sync::Arc::new).collect() };
+ out.push(g);
+ }
+ }
+ }
+ out
+}
+
+fn paste_svg(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "edit.pasteSvg";
+ let svg = str_param(p, "svg").ok_or_else(|| bad(ID, "missing svg"))?;
+ if !is_svg_markup(svg) {
+ return Err(bad(ID, "the clipboard doesn't hold SVG markup"));
+ }
+ let tree = designcraft_images::svg_tree(svg.as_bytes()).ok_or_else(|| bad(ID, "the SVG on the clipboard can't be read"))?;
+ let mut notes = Notes::default();
+ let mut art = Vec::new();
+ convert(tree.root(), 0, &mut notes, &mut art);
+ let b = bounds(&art).ok_or_else(|| bad(ID, "the SVG on the clipboard has no paths to paste"))?;
- let sr = spread_param(p, "spread");
++ let sr = spread_param(p, ID)?;
+ let layer = s.doc()?.active_layer;
+ let at = match super::point_param(p, "at") {
+ Some(at) => at,
+ None => {
+ let d = &s.doc()?.doc;
+ let sp = d.spread(sr).ok_or_else(|| bad(ID, "no such spread"))?;
+ sp.pages.first().map_or(Point::ZERO, |pg| pg.bounds().center())
+ }
+ };
+ if !(at.x.is_finite() && at.y.is_finite()) {
+ return Err(bad(ID, "at must be finite"));
+ }
+ let shift = Affine::translate(at - b.center());
+ let mut warnings = Vec::new();
+ if notes.gradients > 0 {
+ warnings.push(format!("{} gradient or pattern paint(s) pasted as their first colour", notes.gradients));
+ }
+ if notes.too_deep {
+ warnings.push(format!("objects nested more than {MAX_DEPTH} groups deep left out"));
+ }
+ if notes.mixed_opacity > 0 {
+ warnings.push(format!("{} object(s) with different fill and stroke opacity pasted with the fill's opacity for both", notes.mixed_opacity));
+ }
+ if notes.images > 0 {
+ warnings.push(format!("{} embedded image(s) left out (place images with File › Place)", notes.images));
+ }
+ s.edit(|d, sel| {
+ let items = build(d, art, layer, shift);
+ let mut ids = Vec::new();
+ for it in items {
+ ids.push(it.id);
+ d.insert_item(sr, it, None)?;
+ }
+ *sel = Selection::items(ids.clone());
+ Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "warnings": warnings}))
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::Session;
+ use designcraft_doc::SpreadRef;
+
+ const SPIRAL: &str = r##"<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" width="400pt" height="400pt">
+<path fill="none" stroke="#000000" stroke-width="1" d="M200,200 C200,210 210,220 220,220 C240,220 250,200 250,180 L300,100"/>
+</svg>"##;
+
+ fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s
+ }
+
+ #[test]
+ fn an_illustrator_path_pastes_as_an_editable_path_in_points() {
+ let mut s = session();
+ let undo = s.doc().unwrap().history.undo.len();
+ let r = s.execute("edit.pasteSvg", &json!({"svg": SPIRAL, "at": [300, 400]})).unwrap();
+ let ids = r["ids"].as_array().unwrap();
+ assert_eq!(ids.len(), 1, "{r}");
+ let st = s.doc().unwrap();
+ let it = st.doc.item(ItemId(ids[0].as_u64().unwrap())).unwrap();
+ assert_eq!(it.shape, Shape::Path);
+ // Five anchors: three curve ends and a line, editable with the Direct Selection tool.
+ assert_eq!(it.path.subpaths.len(), 1);
+ assert_eq!(it.path.subpaths[0].anchors.len(), 4);
+ assert!(it.fill.is_none());
+ assert_eq!(it.stroke.weight, 1.0, "a 1-unit stroke in a pt-sized SVG is 1 pt");
+ let c = st.doc.swatch(&it.stroke.swatch).unwrap();
+ assert!(matches!(&c.value, designcraft_color::swatch::SwatchValue::Color { color, .. } if color.to_rgb() == [0.0, 0.0, 0.0]));
+ // Centred on `at`, at its own size (100 × 120 user units of a 400 pt viewBox).
+ let b = it.bounds();
+ assert!((b.center().x - 300.0).abs() < 0.01 && (b.center().y - 400.0).abs() < 0.01, "{b:?}");
+ assert!((b.width() - 100.0).abs() < 0.01 && (b.height() - 120.0).abs() < 0.01, "{b:?}");
+ assert_eq!(st.selection.items, vec![it.id]);
+ assert_eq!(st.history.undo.len(), undo + 1, "one undo step");
+ }
+
+ #[test]
+ fn groups_fills_strokes_and_px_units_come_through() {
+ let mut s = session();
+ let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100">
+ <g id="logo"><rect x="0" y="0" width="100" height="100" fill="#e92819" opacity="0.5"/>
+ <circle cx="150" cy="50" r="50" fill="none" stroke="#0000ff" stroke-width="8" stroke-dasharray="4 2" stroke-linecap="round"/></g>
+ <line x1="0" y1="0" x2="200" y2="0" stroke="#000"/></svg>"##;
+ let r = s.execute("edit.pasteSvg", &json!({"svg": svg})).unwrap();
+ let st = s.doc().unwrap();
+ let ids: Vec<ItemId> = r["ids"].as_array().unwrap().iter().map(|v| ItemId(v.as_u64().unwrap())).collect();
+ assert_eq!(ids.len(), 2, "the group and the line: {r}");
+ let g = st.doc.item(ids[0]).unwrap();
+ let Content::Group { items } = &g.content else { panic!("group") };
+ assert_eq!(items.len(), 2);
+ let (rect, circle) = (&items[0], &items[1]);
+ assert_eq!(st.doc.swatch(&rect.fill.swatch).unwrap().name, "R=233 G=40 B=25");
+ assert!((rect.opacity - 0.5).abs() < 1e-3);
+ // CSS pixels: 8 px = 6 pt, the 200 px art is 150 pt wide.
+ assert!((circle.stroke.weight - 6.0).abs() < 1e-6);
+ assert_eq!(circle.stroke.cap, designcraft_doc::Cap::Round);
+ assert!(matches!(&circle.stroke.kind, StrokeType::Dashed { pattern } if (pattern[0] - 3.0).abs() < 1e-6));
+ assert_eq!(st.doc.item(ids[1]).unwrap().shape, Shape::GraphicLine);
+ let all = g.bounds().union(st.doc.item(ids[1]).unwrap().bounds());
+ assert!((all.width() - 150.0).abs() < 0.5, "{all:?}");
+ // Centred on the first page by default.
+ let page = st.doc.spread(SpreadRef::Doc(0)).unwrap().pages[0].bounds();
+ assert!((all.center().x - page.center().x).abs() < 0.5, "{all:?} {page:?}");
+ }
+
+ #[test]
+ fn differing_fill_and_stroke_opacity_takes_the_fills_and_warns() {
+ let mut s = session();
+ let svg = |stroke_opacity: &str| {
+ format!(
+ r##"<svg xmlns="http://www.w3.org/2000/svg" width="100pt" height="100pt" viewBox="0 0 100 100"><rect width="100" height="100" fill="#ff0000" fill-opacity="0.4" stroke="#000" stroke-opacity="{stroke_opacity}"/></svg>"##
+ )
+ };
+ let r = s.execute("edit.pasteSvg", &json!({"svg": svg("0.9")})).unwrap();
+ let id = ItemId(r["ids"][0].as_u64().unwrap());
+ assert!((s.doc().unwrap().doc.item(id).unwrap().opacity - 0.4).abs() < 1e-3);
+ assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("fill's opacity")), "{r}");
+ let r = s.execute("edit.pasteSvg", &json!({"svg": svg("0.4")})).unwrap();
+ let id = ItemId(r["ids"][0].as_u64().unwrap());
+ assert!((s.doc().unwrap().doc.item(id).unwrap().opacity - 0.4).abs() < 1e-3);
+ assert_eq!(r["warnings"], json!([]), "equal opacities fit the object's");
+ }
+
+ #[test]
+ fn text_and_garbage_are_refused_without_an_undo_step() {
+ let mut s = session();
+ let undo = s.doc().unwrap().history.undo.len();
+ for bad in ["just words", "<svg", "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>"] {
+ assert!(s.execute("edit.pasteSvg", &json!({"svg": bad})).is_err(), "{bad}");
+ }
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ assert!(is_svg_markup(SPIRAL) && !is_svg_markup("R=233 G=40 B=25"));
+ }
+
+ #[test]
+ fn deeply_nested_groups_do_not_exhaust_the_stack() {
+ let mut s = session();
+ let depth = 2000;
+ let svg = format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">{}<rect width="10" height="10"/>{}</svg>"#,
+ "<g opacity=\"0.99\">".repeat(depth),
+ "</g>".repeat(depth)
+ );
+ // usvg itself may refuse a document this deep; either way, no crash.
+ let _ = s.execute("edit.pasteSvg", &json!({"svg": svg}));
+ }
+}
diff --cc crates/engine/src/cmd/style.rs
index dde85b88a,4bf69ec41..287993665
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@@ -1147,115 -988,8 +1147,115 @@@ fn apply_color(s: &mut Session, p: &Val
}
}
}
+ if !caret {
+ let a = if stroke {
+ CharAttrs { stroke: Some(name.clone()), stroke_tint: Some(1.0), ..Default::default() }
+ } else {
+ CharAttrs { fill: Some(name.clone()), fill_tint: Some(1.0), ..Default::default() }
+ };
+ super::text::apply_char_attrs(d, &texts, &a, &[]);
+ }
Ok(json!({"swatch": name}))
- })
+ })?;
+ if caret && let Some(name) = r.get("swatch").cloned() {
+ let attrs = if stroke { json!({"stroke": name, "strokeTint": 1.0}) } else { json!({"fill": name, "fillTint": 1.0}) };
+ super::text::format_chars(s, &attrs)?;
+ }
+ Ok(r)
+}
+
+/// The Eyedropper on a placed image (InDesign samples the pixel under the pointer): that colour,
+/// as an unnamed colour, fills the selected text (characters), or the selected objects.
+fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "color.sample";
+ let at = super::point_param(p, "at").ok_or_else(|| bad(ID, "missing at"))?;
- let sr = super::spread_param(p, "spread");
++ let sr = super::spread_param(p, ID)?;
+ let st = s.doc()?;
+ let Some((from, color)) = image_color_at(&st.doc, sr, at) else {
+ // No opaque image pixel there (an empty part of an image frame, a transparent pixel): the
+ // Eyedropper applies the clicked object's attributes instead.
+ return match p.get("matchFrom") {
+ Some(from) => {
+ let mut params = p.clone();
+ params["from"] = from.clone();
+ super::object::match_attributes(s, &params)
+ }
+ None => Err(bad(ID, "no placed image under the point")),
+ };
+ };
+ let hex = color.to_hex();
+ let mut params = p.clone();
+ params["color"] = json!(hex);
+ let mut result = apply_color(s, &params)?;
+ result["color"] = json!(hex);
+ result["from"] = json!(from.0);
+ Ok(result)
+}
+
+/// The colour of the placed raster image at `at` on spread `sr`: the frontmost visible image whose
+/// frame shows that point (locked ones too, as sampling changes nothing). (image frame, colour);
+/// None over no image, a transparent pixel, or a graphic that is not a raster (PDF, EPS).
+pub(crate) fn image_color_at(
+ d: &designcraft_doc::Document,
+ sr: designcraft_doc::SpreadRef,
+ at: designcraft_geom::Point,
+) -> Option<(designcraft_doc::ItemId, designcraft_color::Color)> {
+ let sp = d.spread(sr)?;
+ let mut items: Vec<&designcraft_doc::Item> = sp.items.iter().map(|i| &**i).collect();
+ items.sort_by_key(|i| d.layer_rank(i.layer));
+ items
+ .into_iter()
+ .rev()
+ .filter(|it| d.layer(it.layer).is_none_or(|l| l.visible))
+ .find_map(|it| sample_item(d, it, designcraft_geom::Affine::IDENTITY, at, 0))
+}
+
+fn sample_item(
+ d: &designcraft_doc::Document,
+ it: &designcraft_doc::Item,
+ outer: designcraft_geom::Affine,
+ at: designcraft_geom::Point,
+ depth: usize,
+) -> Option<(designcraft_doc::ItemId, designcraft_color::Color)> {
+ use designcraft_doc::Content;
+ if it.hidden || depth > 64 {
+ return None;
+ }
+ let xf = outer * it.xf;
+ match &it.content {
+ // Only the active state of a multi-state object shows.
+ Content::Group { .. } => {
+ let shown: Vec<_> = it.shown_children().collect();
+ shown.into_iter().rev().find_map(|c| sample_item(d, c, xf, at, depth + 1))
+ }
+ Content::Graphic(g) => {
+ let inner = xf.inverse() * at;
+ if !designcraft_geom::hit::fill_contains(&it.path.to_bezpath(), designcraft_geom::FillRule::NonZero, inner) {
+ return None;
+ }
+ // A clipping path hides the image outside it.
+ if let Some((region, even_odd)) = g.clip_region() {
+ let rule = if even_odd { designcraft_geom::FillRule::EvenOdd } else { designcraft_geom::FillRule::NonZero };
+ if !designcraft_geom::hit::fill_contains(&region, rule, inner) {
+ return None;
+ }
+ }
+ let gp = g.xf.inverse() * inner;
+ let (w, h) = g.size;
+ // Written so that NaN (a degenerate transform) is outside too.
+ if !(w > 0.0 && h > 0.0 && gp.x >= 0.0 && gp.y >= 0.0 && gp.x < w && gp.y < h) {
+ return None;
+ }
+ let asset = d.assets.get(&g.asset).filter(|a| a.is_raster())?;
+ let img = designcraft_images::decode_rgba(&asset.data)?;
+ let (pw, ph) = img.dimensions();
+ let px = ((gp.x / w * f64::from(pw)) as u32).min(pw.checked_sub(1)?);
+ let py = ((gp.y / h * f64::from(ph)) as u32).min(ph.checked_sub(1)?);
+ let [r, gr, b, a] = img.get_pixel_checked(px, py)?.0;
+ (a > 0).then(|| (it.id, designcraft_color::Color::rgb8(r, gr, b)))
+ }
+ _ => None,
+ }
}
fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {
diff --cc crates/engine/src/cmd/thread.rs
index ac13cb2f8,000000000..8de3326f3
mode 100644,000000..100644
--- a/crates/engine/src/cmd/thread.rs
+++ b/crates/engine/src/cmd/thread.rs
@@@ -1,379 -1,0 +1,379 @@@
+//! Threading text frames: thread a frame after another (their stories merge), break a thread,
+//! take a frame out of its thread. The Selection tool's loaded text cursor runs these.
+
+use designcraft_doc::{Document, ItemId, ParaFormat, Selection, StoryId};
+use designcraft_geom::Rect;
+use serde_json::{Value, json};
+
+use super::{CommandSpec, bad, bool_or, cmd, has_doc, id_param, rect_param, spread_param, str_param};
+use crate::{Result, Session};
+
+/// Pages Shift-click autoflow may add before it gives up.
+const AUTOFLOW_MAX_PAGES: usize = 2000;
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(
+ "text.thread",
+ "Thread Text Frames",
+ [],
+ None,
+ "{from?, to?, rect?: [x0,y0,x1,y1] (spread coords), spread?, autoflow?: bool} — threads frame `to` right after frame `from` (between `from` and the frame that followed it, if any). `to` is an empty frame or a text frame nothing threads into yet; its text joins the end of the story. Give `rect` in place of `from` or `to` to thread a new text frame made there on `spread`: `{from, rect}` adds it after `from`, `{rect, to}` in front of `to`. autoflow: then add pages with threaded frames until the story fits. Selects the frame that joined the thread. → {story, from, to, overset, pagesAdded}",
+ has_doc,
+ thread
+ ),
+ cmd!(
+ "text.unthread",
+ "Break Thread",
+ [],
+ None,
+ "{frame?, side?: after|before} — breaks the thread after (or before) `frame` (default: the selected text frame). The frames from the break on stay threaded to each other but become empty; the text stays in the story, overset if the earlier frames can't hold it",
+ has_doc,
+ unthread
+ ),
+ cmd!(
+ "text.removeFromThread",
+ "Remove Frame from Thread",
+ [],
+ None,
+ "{frame?} — takes `frame` (default: the selected text frame) out of its thread: the frames before and after it join up and keep the text, `frame` stays empty",
+ has_doc,
+ remove_from_thread
+ ),
+ ]
+}
+
+/// `frame` param, or the first selected text frame.
+fn frame_param(s: &Session, p: &Value, cmd: &str) -> Result<ItemId> {
+ let st = s.doc()?;
+ let id = id_param(p, "frame")
+ .or_else(|| st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| it.is_text_frame())))
+ .ok_or_else(|| bad(cmd, "no text frame given or selected"))?;
+ if !st.doc.item(id).is_some_and(|it| it.is_text_frame()) {
+ return Err(bad(cmd, format!("{id} is not a text frame")));
+ }
+ Ok(id)
+}
+
+/// A rect param made safe for a frame: finite, ordered, at least half a point each way.
+fn frame_rect(p: &Value) -> Result<Option<Rect>> {
+ let Some(r) = rect_param(p, "rect") else { return Ok(None) };
+ if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
+ return Err(bad("text.thread", "rect must be finite"));
+ }
+ let (x0, x1) = (r.x0.min(r.x1), r.x0.max(r.x1));
+ let (y0, y1) = (r.y0.min(r.y1), r.y0.max(r.y1));
+ Ok(Some(Rect::new(x0, y0, x1.max(x0 + 0.5), y1.max(y0 + 0.5))))
+}
+
+fn thread(s: &mut Session, p: &Value) -> Result<Value> {
+ let (from, to, rect) = (id_param(p, "from"), id_param(p, "to"), frame_rect(p)?);
- let sr = spread_param(p, "spread");
++ let sr = spread_param(p, "text.thread")?;
+ let autoflow = bool_or(p, "autoflow", false);
+ let layer = s.doc()?.active_layer;
+ s.edit(|d, sel| {
+ let mut new_frame = || -> Result<ItemId> {
+ let r = rect.ok_or_else(|| bad("text.thread", "give two of from, to and rect"))?;
+ if d.layer(layer).is_none_or(|l| l.locked || !l.visible) {
+ return Err(bad("text.thread", "the active layer is locked or hidden"));
+ }
+ let para = ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() };
+ Ok(d.add_text_frame(sr, r, layer, "", para)?.0)
+ };
+ let (from, to, joined) = match (from, to) {
+ (Some(f), Some(t)) if rect.is_none() => (f, t, t),
+ (Some(f), None) => {
+ let t = new_frame()?;
+ (f, t, t)
+ }
+ (None, Some(t)) => {
+ let f = new_frame()?;
+ (f, t, f)
+ }
+ _ => return Err(bad("text.thread", "give two of from, to and rect")),
+ };
+ d.check_thread(from, to)?;
+ d.thread_keeping_story(from, to)?;
+ let sid = d.item(from).and_then(|i| i.text_frame()).map(|t| t.story).ok_or_else(|| bad("text.thread", "threading lost the story"))?;
+ let pages = if autoflow { super::place_text_autoflow(d, sid, AUTOFLOW_MAX_PAGES, "text.thread", false)? } else { 0 };
+ *sel = Selection::items(vec![joined]);
+ Ok(json!({"story": sid.0, "from": from.0, "to": to.0, "overset": overset(d, sid), "pagesAdded": pages}))
+ })
+}
+
+fn overset(d: &Document, sid: StoryId) -> bool {
+ designcraft_compose::compose_story(d, sid, &Default::default()).overset_at.is_some()
+}
+
+fn unthread(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "text.unthread";
+ let frame = frame_param(s, p, CMD)?;
+ let d0 = &s.doc()?.doc;
+ let at = match str_param(p, "side").unwrap_or("after") {
+ "after" => d0.next_frame(frame).map(|_| frame).ok_or_else(|| bad(CMD, format!("no frame follows {frame} in its thread")))?,
+ "before" => d0.prev_frame(frame).ok_or_else(|| bad(CMD, format!("no frame comes before {frame} in its thread")))?,
+ other => return Err(bad(CMD, format!("unknown side `{other}` (after, before)"))),
+ };
+ s.edit(|d, _| {
+ d.unthread_after(at)?;
+ let sid = d.item(at).and_then(|i| i.text_frame()).map(|t| t.story).ok_or_else(|| bad(CMD, "no story"))?;
+ Ok(json!({"story": sid.0, "overset": overset(d, sid)}))
+ })
+}
+
+fn remove_from_thread(s: &mut Session, p: &Value) -> Result<Value> {
+ let frame = frame_param(s, p, "text.removeFromThread")?;
+ s.edit(|d, _| {
+ d.remove_from_thread(frame)?;
+ Ok(json!({}))
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 2})).unwrap();
+ s
+ }
+
+ fn text_frame(s: &mut Session, rect: [f64; 4], text: &str) -> (u64, u64) {
+ let r = s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text, "caret": false})).unwrap();
+ (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap())
+ }
+
+ fn story(s: &mut Session, frame: u64) -> serde_json::Value {
+ s.execute("story.get", &json!({"frame": frame})).unwrap()
+ }
+
+ fn frames(s: &mut Session, frame: u64) -> Vec<u64> {
+ story(s, frame)["frames"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect()
+ }
+
+ const LONG: &str = "Threaded text keeps flowing from one frame into the next one. ";
+
+ #[test]
+ fn thread_into_an_empty_frame_and_undo() {
+ let mut s = session();
+ let (a, sid) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(10));
+ let b = s.execute("frame.create", &json!({"rect": [72, 300, 200, 400], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
+ assert!(!story(&mut s, a)["overset"].is_null(), "the first frame is overset");
+ let r = s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
+ assert_eq!(r["story"].as_u64(), Some(sid));
+ assert_eq!(frames(&mut s, a), [a, b]);
+ let d = &s.doc().unwrap().doc;
+ assert!(d.item(designcraft_doc::ItemId(b)).unwrap().is_text_frame());
+ assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(b)]);
+ // The text now reaches the second frame.
+ let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), &Default::default());
+ assert!(cs.frames.iter().any(|f| f.frame.0 == b && !f.range.is_empty()), "text flows into the new frame");
+ s.doc().unwrap().doc.check().unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(frames(&mut s, a), [a]);
+ assert!(!s.doc().unwrap().doc.item(designcraft_doc::ItemId(b)).unwrap().is_text_frame());
+ }
+
+ #[test]
+ fn thread_into_a_text_frame_merges_its_story() {
+ let mut s = session();
+ let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 200.0], "First");
+ let (b, sb) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "Second");
+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
+ let st = story(&mut s, b);
+ assert_eq!(st["id"].as_u64(), Some(sa));
+ assert_eq!(st["text"], "First\nSecond");
+ assert!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sb)).is_none());
+ s.doc().unwrap().doc.check().unwrap();
+ }
+
+ #[test]
+ fn thread_into_the_middle_of_a_thread() {
+ let mut s = session();
+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));
+ let (c, _) = text_frame(&mut s, [72.0, 500.0, 200.0, 600.0], "");
+ s.execute("text.thread", &json!({"from": a, "to": c})).unwrap();
+ let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "");
+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
+ assert_eq!(frames(&mut s, a), [a, b, c]);
+ s.doc().unwrap().doc.check().unwrap();
+ }
+
+ #[test]
+ fn bad_threads_are_errors_and_change_nothing() {
+ let mut s = session();
+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], "a");
+ let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "b");
+ let (x, _) = text_frame(&mut s, [300.0, 72.0, 400.0, 120.0], "x");
+ let (y, _) = text_frame(&mut s, [300.0, 300.0, 400.0, 400.0], "y");
+ let g = s.execute("line.create", &json!({"a": [300, 500], "b": [400, 600]})).unwrap()["id"].as_u64().unwrap();
+ let group = {
+ let p = s.execute("frame.create", &json!({"rect": [500, 500, 550, 550], "content": "unassigned"})).unwrap()["id"].clone();
+ let q = s.execute("frame.create", &json!({"rect": [560, 500, 600, 550], "content": "unassigned"})).unwrap()["id"].clone();
+ s.execute("selection.set", &json!({"ids": [p, q]})).unwrap();
+ s.execute("object.group", &json!({})).unwrap();
+ s.doc().unwrap().selection.items[0].0
+ };
+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
+ s.execute("text.thread", &json!({"from": x, "to": y})).unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ let doc = s.doc().unwrap().doc.clone();
+ for p in [
+ json!({"from": a, "to": a}),
+ json!({"from": a, "to": g}),
+ json!({"from": g, "to": a}),
+ json!({"from": a, "to": group}),
+ // Earlier in the same thread.
+ json!({"from": b, "to": a}),
+ // Text already flows into y from x.
+ json!({"from": a, "to": y}),
+ json!({"from": a, "to": 999_999}),
+ json!({"from": a}),
+ json!({"from": a, "to": b, "rect": [0, 0, 10, 10]}),
+ json!({"rect": [0, 0, 10, 10]}),
+ json!({"from": a, "rect": [0, 0, 10, 10], "spread": 99}),
+ json!({"from": "a", "to": [1]}),
+ json!([1, 2]),
+ ] {
+ assert!(s.execute("text.thread", &p).is_err(), "{p}");
+ }
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ assert_eq!(*s.doc().unwrap().doc, *doc);
+ }
+
+ #[test]
+ fn locked_frames_and_layers_refuse_threads() {
+ let mut s = session();
+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));
+ let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "");
+ let layer = s.doc().unwrap().active_layer.0;
+ let undo = s.doc().unwrap().history.undo.len();
+ s.execute("object.lock", &json!({"ids": [b]})).unwrap();
+ assert!(s.execute("text.thread", &json!({"from": a, "to": b})).is_err(), "locked frame");
+ assert!(s.execute("text.thread", &json!({"from": b, "to": a})).is_err(), "locked frame");
+ s.execute("edit.undo", &json!({})).unwrap();
+ for (set, rect) in [(json!({"locked": true}), false), (json!({"locked": true}), true), (json!({"visible": false}), true)] {
+ let mut p = json!({"id": layer});
+ p.as_object_mut().unwrap().extend(set.as_object().unwrap().clone());
+ s.execute("layer.set", &p).unwrap();
+ let t = if rect { json!({"from": a, "rect": [300, 300, 400, 400]}) } else { json!({"from": a, "to": b}) };
+ assert!(s.execute("text.thread", &t).is_err(), "{p} {t}");
+ s.execute("edit.undo", &json!({})).unwrap();
+ }
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ assert_eq!(frames(&mut s, a), [a]);
+ }
+
+ #[test]
+ fn thread_a_new_frame_after_or_in_front() {
+ let mut s = session();
+ let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));
+ let r = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 200, 400]})).unwrap();
+ let n = r["to"].as_u64().unwrap();
+ assert_eq!(frames(&mut s, a), [a, n]);
+ assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(n)]);
+ let b = s.doc().unwrap().doc.item(designcraft_doc::ItemId(n)).unwrap().bounds();
+ assert_eq!(b, Rect::new(72.0, 300.0, 200.0, 400.0));
+ // In front of the first frame: the story keeps its id and text.
+ let r = s.execute("text.thread", &json!({"rect": [300, 72, 400, 120], "to": a})).unwrap();
+ let m = r["from"].as_u64().unwrap();
+ assert_eq!(r["story"].as_u64(), Some(sa));
+ assert_eq!(frames(&mut s, a), [m, a, n]);
+ assert_eq!(story(&mut s, a)["text"], LONG.repeat(8));
+ s.doc().unwrap().doc.check().unwrap();
+ // One undo step each.
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(frames(&mut s, a), [a, n]);
+ }
+
+ use designcraft_geom::Rect;
+
+ #[test]
+ fn thread_with_autoflow_adds_pages_until_the_text_fits() {
+ let mut s = session();
+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 300.0, 200.0], &LONG.repeat(300));
+ let r = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 300, 700], "autoflow": true})).unwrap();
+ assert_eq!(r["overset"], false);
+ assert!(r["pagesAdded"].as_u64().unwrap() >= 1, "{r}");
+ assert!(frames(&mut s, a).len() >= 3);
+ s.doc().unwrap().doc.check().unwrap();
+ // One undo removes the frames and the pages.
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(frames(&mut s, a), [a]);
+ assert_eq!(s.doc().unwrap().doc.page_count(), 2);
+ }
+
+ #[test]
+ fn autoflow_from_a_parent_frame_is_an_error() {
+ let mut s = session();
+ let parent = json!({"kind": "parent", "index": 0});
+ let r = s.execute(
+ "frame.create",
+ &json!({"rect": [72, 72, 300, 200], "content": "text", "text": LONG.repeat(300), "caret": false, "spread": parent}),
+ );
+ let a = r.unwrap()["id"].as_u64().unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ let doc = s.doc().unwrap().doc.clone();
+ let e = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 300, 700], "spread": parent, "autoflow": true})).unwrap_err();
+ assert!(e.to_string().contains("text.thread"), "{e}");
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ assert_eq!(*s.doc().unwrap().doc, *doc);
+ assert_eq!(s.doc().unwrap().doc.page_count(), 2);
+ }
+
+ #[test]
+ fn unthread_after_and_before() {
+ let mut s = session();
+ let text = LONG.repeat(12);
+ let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &text);
+ let (b, _) = text_frame(&mut s, [72.0, 200.0, 200.0, 250.0], "");
+ let (c, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 350.0], "");
+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
+ s.execute("text.thread", &json!({"from": b, "to": c})).unwrap();
+ // Break after the first frame: b and c stay threaded to each other, empty.
+ let r = s.execute("text.unthread", &json!({"frame": a})).unwrap();
+ assert_eq!(r["story"].as_u64(), Some(sa));
+ assert_eq!(r["overset"], true);
+ assert_eq!(frames(&mut s, a), [a]);
+ assert_eq!(story(&mut s, a)["text"], text);
+ assert_eq!(frames(&mut s, b), [b, c]);
+ assert_eq!(story(&mut s, b)["text"], "");
+ s.doc().unwrap().doc.check().unwrap();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(frames(&mut s, a), [a, b, c]);
+ // Break before the last frame, with the frame selected.
+ s.execute("selection.set", &json!({"ids": [c]})).unwrap();
+ s.execute("text.unthread", &json!({"side": "before"})).unwrap();
+ assert_eq!(frames(&mut s, a), [a, b]);
+ assert_eq!(frames(&mut s, c), [c]);
+ // Nothing to break.
+ assert!(s.execute("text.unthread", &json!({"frame": b})).is_err());
+ assert!(s.execute("text.unthread", &json!({"frame": a, "side": "before"})).is_err());
+ assert!(s.execute("text.unthread", &json!({"frame": a, "side": "sideways"})).is_err());
+ assert!(s.execute("text.unthread", &json!({"frame": 999_999})).is_err());
+ }
+
+ #[test]
+ fn deleting_or_removing_a_threaded_frame_keeps_the_text_flowing() {
+ let mut s = session();
+ let text = LONG.repeat(12);
+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &text);
+ let (b, _) = text_frame(&mut s, [72.0, 200.0, 200.0, 250.0], "");
+ let (c, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 350.0], "");
+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();
+ s.execute("text.thread", &json!({"from": b, "to": c})).unwrap();
+ s.execute("text.removeFromThread", &json!({"frame": b})).unwrap();
+ assert_eq!(frames(&mut s, a), [a, c]);
+ assert_eq!(story(&mut s, a)["text"], text);
+ assert_eq!(story(&mut s, b)["text"], "");
+ assert!(s.execute("text.removeFromThread", &json!({"frame": b})).is_err());
+ s.execute("edit.undo", &json!({})).unwrap();
+ s.execute("edit.clear", &json!({"ids": [b]})).unwrap();
+ assert_eq!(frames(&mut s, a), [a, c]);
+ assert_eq!(story(&mut s, a)["text"], text);
+ s.doc().unwrap().doc.check().unwrap();
+ }
+}