Skip to content

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

M5: loaded place cursor (place gun): click = actual size, drag = fit, click frame = place into

Brandon Thomas51045daf3616
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 2a9fb2245..cbfa3ea76 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -31,6 +31,16 @@ pub fn specs() -> Vec<CommandSpec> {
s.set_active(p.get("index").and_then(Value::as_u64).unwrap_or(0) as usize);
ok()
}),
+ cmd!(
+ "place.load",
+ "Load Place Cursor",
+ [],
+ None,
+ "{path | base64, name?} — load a graphic into the place cursor (then click/drag with the placeGun tool)",
+ has_doc,
+ place_load
+ ),
+ cmd!("place.drop", "Place Loaded Graphic", [], None, "{spread?, x, y, rect?: [x0,y0,x1,y1], frame?: id}", has_doc, place_drop),
cmd!(
"file.place",
"Place…",
@@ -239,3 +249,82 @@ pub fn base64_decode(s: &str) -> Vec<u8> {
}
out
}
+
+fn read_source(p: &Value) -> Result<(Vec<u8>, String, Option<String>)> {
+ if let Some(b) = str_param(p, "base64") {
+ return Ok((base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None));
+ }
+ let path = str_param(p, "path").ok_or_else(|| bad("place", "missing `path` or `base64`"))?;
+ #[cfg(not(target_arch = "wasm32"))]
+ let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ #[cfg(target_arch = "wasm32")]
+ let b: Vec<u8> = vec![];
+ let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.into());
+ Ok((b, name, Some(path.to_string())))
+}
+
+fn place_load(s: &mut Session, p: &Value) -> Result<Value> {
+ let (bytes, name, link) = read_source(p)?;
+ let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?;
+ let aid = s.edit(|d, _| {
+ let aid = AssetId(d.alloc());
+ let mime = designcraft_render::image_mime(&bytes).to_string();
+ d.assets
+ .insert(aid, Arc::new(Asset { id: aid, name: name.clone(), mime, link: link.clone(), data: Arc::new(bytes), pixels: Some((pw, ph)) }));
+ Ok(aid)
+ })?;
+ s.loaded = Some((aid, (pw as f64, ph as f64)));
+ s.set_tool("placeGun");
+ Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph}))
+}
+
+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 sr = super::spread_param(p, "spread");
+ let lid = s.doc()?.active_layer;
+ let frame = super::id_param(p, "frame");
+ let rect = super::rect_param(p, "rect");
+ let (x, y) = (super::f64_or(p, "x", 0.0), super::f64_or(p, "y", 0.0));
+ let r = s.edit(|d, sel| {
+ let id = match frame {
+ Some(fid) => {
+ let it = d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?;
+ let r = it.inner_bounds();
+ let k = (r.width() / nw).max(r.height() / nh);
+ it.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (nw, nh),
+ xf: Affine::translate((r.x0 + (r.width() - nw * k) / 2.0, r.y0 + (r.height() - nh * k) / 2.0)) * Affine::scale(k),
+ auto_fit: designcraft_doc::Fitting::FillProportionally,
+ });
+ fid
+ }
+ None => {
+ // Drag: fit proportionally into the dragged rect; click: actual size at the point.
+ let (frame_r, k) = match rect {
+ Some(r) if r.width() > 2.0 && r.height() > 2.0 => {
+ let k = (r.width() / nw).min(r.height() / nh);
+ (Rect::new(r.x0, r.y0, r.x0 + nw * k, r.y0 + nh * k), k)
+ }
+ _ => (Rect::new(x, y, x + nw, y + nh), 1.0),
+ };
+ let id = ItemId(d.alloc());
+ let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(frame_r));
+ it.object_style = d.styles.default_graphic_frame.clone();
+ it.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (nw, nh),
+ xf: Affine::translate((frame_r.x0, frame_r.y0)) * Affine::scale(k),
+ auto_fit: Default::default(),
+ });
+ d.insert_item(sr, it, None)?;
+ id
+ }
+ };
+ *sel = Selection::items(vec![id]);
+ Ok(json!({"id": id.0}))
+ })?;
+ s.loaded = None;
+ s.set_tool("selection");
+ Ok(r)
+}
diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs
index f208ce2c0..fbaad2b48 100644
--- a/crates/engine/src/cmd/inspect.rs
+++ b/crates/engine/src/cmd/inspect.rs
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!(noundo "tool.select", "Select Tool", [], None, "{tool: selection|directSelection|type|rectangleFrame|…}", always, |s, p| {
let t = p.get("tool").and_then(Value::as_str).unwrap_or("selection");
- if designcraft_tools::tool_info(t).is_none() {
+ if designcraft_tools::tool_info(t).is_none() && t != "placeGun" {
return Err(super::bad("tool.select", format!("unknown tool `{t}`")));
}
s.set_tool(t);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 88c923a6e..43965944a 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -140,6 +140,8 @@ pub struct Session {
pub clipboard: Option<Arc<Document>>,
/// Requests for the UI (dialogs, view changes) produced by tools/commands.
pub ui_requests: Vec<UiRequest>,
+ /// Graphic loaded in the place cursor: (asset, natural size in points).
+ pub loaded: Option<(designcraft_doc::AssetId, (f64, f64))>,
pub(crate) untitled: u32,
}
@@ -160,6 +162,7 @@ impl Session {
journal: vec![],
clipboard: None,
ui_requests: vec![],
+ loaded: None,
untitled: 0,
}
}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 9c73b2b60..d6ff24685 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -181,6 +181,30 @@ fn rotate_scale_shear_and_eyedropper() {
s.execute("transform.shear", &json!({"ids": [b], "angle": 20})).unwrap();
}
+#[test]
+fn place_gun_click_drag_and_into_frame() {
+ use designcraft_tools::{PointerEvent, PointerKind};
+ let mut s = session();
+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
+ let b64 = cmd::base64_encode(&png);
+ s.execute("place.load", &json!({"base64": b64, "name": "a.png"})).unwrap();
+ assert_eq!(s.tool_id(), "placeGun");
+ let v = ViewInfo { zoom: 1.0 };
+ s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 300.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 300.0), v).unwrap();
+ let st = s.doc().unwrap();
+ let it = st.doc.spreads[0].items.last().unwrap();
+ // Dragged 80×200 → fit proportionally: 80×40.
+ assert_eq!(it.bounds(), designcraft_geom::Rect::new(100.0, 100.0, 180.0, 140.0));
+ assert_eq!(s.tool_id(), "selection");
+ // Into an empty frame.
+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 400, 400], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("place.load", &json!({"base64": b64})).unwrap();
+ s.execute("place.drop", &json!({"frame": f})).unwrap();
+ assert!(matches!(s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().content, designcraft_doc::Content::Graphic(_)));
+}
+
/// Unicode text per page, through hayro's interpreter (ToUnicode / ActualText).
fn pdf_text(bytes: &[u8]) -> Vec<String> {
use hayro_interpret::font::Glyph;
diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs
index c602f0608..29f616a36 100644
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@ -243,6 +243,7 @@ pub fn create(id: &str) -> Box<dyn Tool> {
"shear" => Box::new(xform::XformTool::new("shear")),
"eyedropper" => Box::new(xform::EyedropperTool),
"hand" => Box::new(nav::HandTool::default()),
+ "placeGun" => Box::new(nav::PlaceGun::default()),
"zoom" => Box::new(nav::ZoomTool),
other => Box::new(NoopTool(tool_info(other).map(|t| t.id).unwrap_or("selection"))),
}
diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs
index b0cc9590c..6d84e091d 100644
--- a/crates/tools/src/nav.rs
+++ b/crates/tools/src/nav.rs
@@ -59,3 +59,60 @@ impl Tool for ZoomTool {
if m.alt { Cursor::ZoomOut } else { Cursor::ZoomIn }
}
}
+
+/// The loaded place cursor: click places at actual size, drag draws the frame, click on an empty
+/// frame places into it.
+#[derive(Default)]
+pub struct PlaceGun {
+ start: Option<Point>,
+ cur: Point,
+}
+
+impl Tool for PlaceGun {
+ fn id(&self) -> &'static str {
+ "placeGun"
+ }
+ fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
+ match ev.kind {
+ PointerKind::Down => {
+ self.start = Some(ev.pos);
+ self.cur = ev.pos;
+ vec![]
+ }
+ PointerKind::Drag => {
+ self.cur = ev.pos;
+ vec![]
+ }
+ PointerKind::Up => {
+ let Some(a) = self.start.take() else { return vec![] };
+ let Some((sr, sa)) = cx.layout.spread_at(a) else { return vec![] };
+ let off = cx.layout.offset(sr);
+ let b = ev.pos - off;
+ if (ev.pos - a).hypot() < cx.tol(3.0)
+ && let Some((_, id)) = cx.hit(a)
+ && cx
+ .doc
+ .item(id)
+ .is_some_and(|i| matches!(i.content, designcraft_doc::Content::Unassigned | designcraft_doc::Content::Graphic(_)))
+ {
+ return vec![Action::Exec("place.drop".into(), json!({"frame": id.0}))];
+ }
+ let r = designcraft_geom::Rect::from_points(sa, b);
+ vec![Action::Exec(
+ "place.drop".into(),
+ json!({"spread": crate::spread_json(sr), "x": sa.x, "y": sa.y, "rect": [r.x0, r.y0, r.x1, r.y1]}),
+ )]
+ }
+ _ => vec![],
+ }
+ }
+ fn overlays(&self, _cx: &ToolContext) -> Vec<crate::Overlay> {
+ match self.start {
+ Some(a) => vec![crate::Overlay::Marquee(designcraft_geom::Rect::from_points(a, self.cur))],
+ None => vec![],
+ }
+ }
+ fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
+ Cursor::LoadedGraphic
+ }
+}