DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
feat(edit): Paste vector art from other apps as editable paths
moppeeera4c2b3031cee
diff --git a/ROADMAP.md b/ROADMAP.mdindex 8a0f82071..a442600fc 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -138,6 +138,7 @@ Newest first.- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.- **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.- **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.+- **2026-10-12** · Vector art copied in Illustrator, VectorCraft, Figma or Inkscape pastes as editable paths, as InDesign pastes Illustrator art: the SVG those apps put on the clipboard becomes paths with their fills, strokes (weight, caps, joins, dashes) and opacity, groups stay groups and text comes in as outlines, centred in the view (`edit.pasteSvg`, `ui.paste`). Edit › Paste reads the system clipboard when nothing was copied in DesignCraft. No readiness percentage change.- **2026-10-12** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.- **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.- **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 31e4544f4..e9147cc2d 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -34,6 +34,7 @@ mod notes;mod object;mod overrides;mod package;+mod paste_svg;mod path_type;mod paths;mod pdflayers;@@ -154,6 +155,7 @@ pub fn command_specs() -> &'static [CommandSpec] {v.extend(interchange::specs());v.extend(export::specs());v.extend(edit::specs());+ v.extend(paste_svg::specs());v.extend(endnotes::specs());v.extend(editorial::specs());v.extend(object::specs());@@ -311,4 +313,5 @@ pub fn file_from(b: &[u8]) -> Result<designcraft_doc::Document> {pub(crate) use datamerge::sync_placeholders;pub(crate) use file::load_document_fonts;pub use file::{base64_decode, base64_encode, from_bytes, to_bytes};+pub use paste_svg::is_svg_markup;pub(crate) use place_text::autoflow as place_text_autoflow;diff --git a/crates/engine/src/cmd/paste_svg.rs b/crates/engine/src/cmd/paste_svg.rsnew file mode 100644index 000000000..6f0f36742--- /dev/null+++ b/crates/engine/src/cmd/paste_svg.rs@@ -0,0 +1,409 @@+//! 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,+ 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;+ }+ 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 (fill-opacity, else stroke-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 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.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 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 --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 077ae2944..0d3296cf6 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1379,6 +1379,14 @@ fn count_click(ui: &egui::Ui, id: egui::Id, at: Pos2, now: f64) -> u8 {n}+/// The spread at the middle of the view, and that point in spread coordinates (where Paste puts+/// art from other apps, as InDesign does).+fn view_centre(app: &DesignApp, xf: &Xf, rect: Rect) -> Option<(SpreadRef, Point)> {+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ layout.spread_at(xf.to_canvas(rect.center()))+}+fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect) {let Some(v) = app.view().copied() else { return };let xf = Xf::new(rect, &v);@@ -1493,6 +1501,19 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rlet id = if plain { "edit.pasteWithoutFormatting" } else { "edit.paste" };let _ = app.run(id, json!({"text": t}));}+ // Vector art copied in another app (Illustrator, VectorCraft, Figma) is SVG markup on+ // the system clipboard: it pastes as editable paths in the middle of the view.+ egui::Event::Paste(t) if !wants_text && designcraft_engine::cmd::is_svg_markup(&t) => {+ let at = view_centre(app, &xf, rect);+ let mut params = json!({"svg": t});+ if let Some((sr, p)) = at {+ params["spread"] = serde_json::to_value(sr).unwrap_or(serde_json::Value::Null);+ params["at"] = json!([p.x, p.y]);+ }+ if let Err(e) = app.run("edit.pasteSvg", params) {+ app.status(e);+ }+ }egui::Event::Copy | egui::Event::Cut if wants_text => {let id = if matches!(e, egui::Event::Cut) { "edit.cut" } else { "edit.copy" };if let Ok(r) = app.run(id, json!({}))@@ -1805,6 +1826,57 @@ mod tests {(s.horizontal_units, s.vertical_units)}+ const ART: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50" width="100pt" height="50pt"><path d="M0,0 C30,0 70,50 100,50" fill="none" stroke="#000" stroke-width="2"/></svg>"##;++ #[test]+ fn pasting_svg_from_another_app_places_editable_paths_in_the_middle_of_the_view() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ let undo = h.state().session.doc().unwrap().history.undo.len();+ h.event(egui::Event::Paste(ART.into()));+ h.run_steps(2);+ let app = h.state();+ let st = app.session.doc().unwrap();+ assert_eq!(st.history.undo.len(), undo + 1, "one undo step");+ let id = *st.selection.items.first().expect("the pasted path is selected");+ let it = st.doc.item(id).unwrap();+ assert_eq!(it.shape, designcraft_doc::Shape::Path);+ assert_eq!(it.path.subpaths[0].anchors.len(), 2);+ assert!((it.stroke.weight - 2.0).abs() < 1e-9);+ // Centred where the view's centre falls on the spread.+ let rect = app.canvas_rect.unwrap();+ let xf = Xf::new(rect, app.view().unwrap());+ let (_, centre) = CanvasLayout::new(&st.doc, false).spread_at(xf.to_canvas(rect.center())).unwrap();+ assert!((it.bounds().center() - centre).hypot() < 0.01, "{:?} vs {centre:?}", it.bounds());+ // Plain text pasted with no text being edited changes nothing.+ let before = st.doc.clone();+ h.event(egui::Event::Paste("just words".into()));+ h.run_steps(2);+ assert!(std::sync::Arc::ptr_eq(&before, &h.state().session.doc().unwrap().doc));+ }++ #[test]+ fn edit_paste_with_nothing_copied_here_asks_for_the_system_clipboard() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ assert!(!crate::menus::enabled(&app, "edit.paste"), "nothing copied in DesignCraft");+ assert!(crate::menus::menu_enabled(&app, "edit.paste"), "the system clipboard may hold art");+ crate::menus::activate(&mut app, "edit.paste", &Value::Null);+ assert!(app.request_system_paste);+ let ctx = egui::Context::default();+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.logic(ui.ctx()));+ out.textures_delta.clear();+ assert!(out.viewport_output[&egui::ViewportId::ROOT].commands.contains(&egui::ViewportCommand::RequestPaste));+ assert!(!app.request_system_paste);+ // With objects copied here, Edit › Paste pastes them as before.+ let r = app.run("frame.create", json!({"rect": [10, 10, 50, 50]})).unwrap();+ app.run("selection.set", json!({"ids": [r["id"]]})).unwrap();+ app.run("edit.copy", json!({})).unwrap();+ crate::menus::activate(&mut app, "edit.paste", &Value::Null);+ assert!(!app.request_system_paste);+ }+#[test]fn right_clicking_a_ruler_sets_that_rulers_units() {let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 5a4de0058..bf5aa84f4 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -173,6 +173,14 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) ->ctx.request_repaint();ok(Value::Null)}+ // What Ctrl/Cmd+V delivers from the system clipboard: text, or SVG markup copied in an+ // illustration app (pasted as editable paths when no text is being edited).+ "ui.paste" => {+ let Some(text) = s("text") else { return err("missing `text`") };+ app.synthetic.push(egui::Event::Paste(text.to_string()));+ ctx.request_repaint();+ ok(Value::Null)+ }"ui.move" => {let pos = egui::pos2(p.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32, p.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32);app.synthetic.push(egui::Event::PointerMoved(pos));diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rsindex 5252c3881..c432b5cfc 100644--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@ -57,6 +57,10 @@ const TABLE: &[(&str, [&str; 5])] = &[("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]),("Reverse Path", ["Pfadrichtung umkehren", "Inverser le tracé", "Invertir trazado", "パスの方向反転", "反转路径"]),("Set Anchor", ["Ankerpunkt festlegen", "Définir le point d’ancrage", "Definir punto de ancla", "アンカーポイントを設定", "设置锚点"]),+ (+ "Paste Vector Art",+ ["Vektorgrafik einfügen", "Coller l’illustration vectorielle", "Pegar ilustración vectorial", "ベクトルアートをペースト", "粘贴矢量图稿"],+ ),("Clear", ["Löschen", "Effacer", "Borrar", "消去", "清除"]),("Duplicate", ["Duplizieren", "Dupliquer", "Duplicar", "複製", "重复"]),("Select All", ["Alles auswählen", "Tout sélectionner", "Seleccionar todo", "すべてを選択", "全选"]),diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rsindex a182d09ec..69b80c348 100644--- a/crates/ui-egui/src/i18n/ar.rs+++ b/crates/ui-egui/src/i18n/ar.rs@@ -32,6 +32,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paste", "لصق"),("Reverse Path", "عكس المسار"),("Set Anchor", "تعيين نقطة الارتساء"),+ ("Paste Vector Art", "لصق رسم متجه"),("Clear", "مسح"),("Delete", "حذف"),("Duplicate", "تكرار"),diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rsindex 75ece03f6..472e00fd2 100644--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paste", "Incolla"),("Reverse Path", "Inverti tracciato"),("Set Anchor", "Imposta ancoraggio"),+ ("Paste Vector Art", "Incolla grafica vettoriale"),("Clear", "Cancella"),("Duplicate", "Duplica"),("Select All", "Seleziona tutto"),diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rsindex 642b4a4c0..3da530e36 100644--- a/crates/ui-egui/src/i18n/ja.rs+++ b/crates/ui-egui/src/i18n/ja.rs@@ -32,6 +32,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paste", "ペースト"),("Reverse Path", "パスの方向反転"),("Set Anchor", "アンカーポイントを設定"),+ ("Paste Vector Art", "ベクトルアートをペースト"),("Clear", "消去"),("Duplicate", "複製"),("Select All", "すべてを選択"),diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rsindex 982dfb20d..0c1421d78 100644--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@ -33,6 +33,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paste", "Colar"),("Reverse Path", "Inverter demarcador"),("Set Anchor", "Definir ponto de ancoragem"),+ ("Paste Vector Art", "Colar arte vetorial"),("Clear", "Limpar"),("Delete", "Excluir"),("Duplicate", "Duplicar"),diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rsindex f3bc8fb35..8fdea6694 100644--- a/crates/ui-egui/src/i18n/uk.rs+++ b/crates/ui-egui/src/i18n/uk.rs@@ -33,6 +33,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[("Paste", "Вставити"),("Reverse Path", "Розвернути контур"),("Set Anchor", "Задати прив’язку"),+ ("Paste Vector Art", "Вставити векторну графіку"),("Clear", "Очистити"),("Duplicate", "Дублювати"),("Select All", "Виділити все"),diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex fc7a3e634..ee5c98ed5 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -496,6 +496,9 @@ pub struct DesignApp {pub color_applied: bool,pub perf: Perf,pub synthetic: Vec<egui::Event>,+ /// Edit › Paste with nothing copied here: ask the integration for the system clipboard, whose+ /// contents come back as an `Event::Paste` (art from other apps pastes as paths).+ pub request_system_paste: bool,/// Story open in the Story Editor.pub story_editor: Option<designcraft_doc::StoryId>,control_rx: Option<Receiver<ControlRequest>>,@@ -550,6 +553,7 @@ impl DesignApp {color_applied: false,perf: Perf::default(),synthetic: vec![],+ request_system_paste: false,story_editor: None,control_rx: None,pending_shots: vec![],@@ -761,6 +765,9 @@ impl DesignApp {/// Per-frame logic before layout.pub fn logic(&mut self, ctx: &egui::Context) {+ if std::mem::take(&mut self.request_system_paste) {+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste);+ }if !self.color_applied {self.color_applied = true;if let Some(cs) = self.ui.color_settings.clone() {diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 872cb81d0..40bb23115 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -1859,7 +1859,13 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool {if ui_label(id).is_some() {return app.session.active().is_some() || id.starts_with("app.") || id.starts_with("window.");}- enabled(app, id)+ enabled(app, id) || pastes_from_system(app, id)+}++/// Edit › Paste with nothing copied in DesignCraft: the system clipboard may hold art copied in+/// another app (pasted as paths), so the item stays available and asks for it.+fn pastes_from_system(app: &DesignApp, id: &str) -> bool {+ id == "edit.paste" && app.session.active().is_some_and(|d| d.selection.text.is_none()) && !enabled(app, id)}/// Close document `index` (the active one when `None`) the way the user asks for it: with the@@ -1880,6 +1886,10 @@ pub fn close_document(app: &mut DesignApp, index: Option<usize>) {/// A menu item was chosen. An engine command whose label ends in "…" and that takes parameters/// opens a dialog built from its parameter documentation (see [`crate::dialogs::command_fields`]).pub fn activate(app: &mut DesignApp, id: &str, params: &Value) {+ if params.is_null() && pastes_from_system(app, id) {+ app.request_system_paste = true;+ return;+ }if params.is_null() && id == "file.close" {close_document(app, None);return;diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 9e5145616..506984fd6 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -39,6 +39,7 @@ so only enable it while you use it. Transport: `apps/designcraft/src/control_ser| `ui.tool.select` | `{tool}` | Select a tool (`selection`, `type`, `rectangleFrame`, …) || `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas"}], mods?}` | Drive the active tool through the same code path as the mouse || `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Synthetic keyboard input (typing into a text frame) |+| `ui.paste` | `{text}` | What Ctrl/Cmd+V delivers from the system clipboard: text into the text being edited, or SVG markup (vector art copied in Illustrator, VectorCraft or Figma) as editable paths in the middle of the view || `ui.move` / `ui.click` / `ui.drag` | screen points, `button?: left\|right\|middle` | Real egui pointer input — reaches every widget, menu and panel || `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state || `ui.dialog.open` | `{id, fields?}` | Open a dialog by id (e.g. `paragraphStyleOptions` or `characterStyleOptions` with `{name, section}`, or `{new: true}` for a new style) |