Skip to content

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

Merge origin/main into codex/content-handles

moppeeerb3fb92a97ff9
diff --cc ROADMAP.md
index c3d0a6a84,d60a6bf49..efbb90e02
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -126,9 -343,52 +343,53 @@@ list) · [roadmap.md](docs/roadmap.md)
## Progress log
+ - **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.
+
Newest first.
+- **2026-10-13** · A selected placed graphic shows its own brown bounding box with handles: dragging one resizes the graphic inside its frame (Shift keeps proportions, Alt from the centre) and leaves the frame as it is; `transform.set` takes the graphic's new spread `bounds`. Builds on #415 and #550. No readiness percentage change.
+ - **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
+ - **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
+ - **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
+ - **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.
+ - **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.
+ - **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.
+ - **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.
+ - **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.
+ - **2026-10-15** · Flex Layout (InDesign 2026): Object › Flex Layout (Add to, Convert to, Remove) and a Flex Layout panel laid out as InDesign's, also in Properties. A container lays out its objects by direction, wrap, justification, the alignment grid, Fixed/Auto width and height, padding and spacing, after every edit; Add detects aligned objects (direction, Auto size, Space Between at their spacing); resizing a container reflows its objects instead of scaling them; dragging an object in one reorders it. Montilla Design's tutorial replays step for step. No readiness percentage change.
+ - **2026-10-14** · Layout › Margins and Columns and Layout › Create Guides are laid out as InDesign's: Margins in Top/Bottom and Inside/Outside pairs with a link button that makes all four the same, Rows and Columns side by side, Fit Guides to Margins or Page, and a Preview checkbox that shows the change on the canvas before OK. A measurement field works out arithmetic when you leave it (`0.4375 in*2` becomes `0.875 in`). No readiness percentage change.
+ - **2026-10-14** · The Pathfinder panel is laid out as InDesign's: Paths (Join, Open, Close, Reverse), Pathfinder, Convert Shape and Convert Point, each a row of icon buttons. Join Path closes an open path or joins two at their nearest ends (`path.join`), and Convert Point makes the selected points plain, corner, smooth or symmetrical (`path.convertPoints`). No readiness percentage change.
+ - **2026-10-12** · Linked text files (#597): placed Word, RTF and text files can stay linked; the Links panel shows them OK / Modified / Missing, and Update imports the file again into the same frames with the saved style map (the Links panel asks before replacing edits made in the layout). No readiness percentage change.
+ - **2026-10-15** · IDML: the CJK leading model InDesign writes on [No paragraph style] of every document (Aki Below) only applies when the document uses a Japanese composer, as in InDesign; a Western document's paragraphs after a size change no longer sit lower than in InDesign (Montilla Design's Flex Layout file: its captions came out overset). No readiness percentage change.
+ - **2026-10-14** · Type › Fill with Placeholder Text fills a frame with paragraphs of a few sentences, as InDesign does, so one paragraph can be styled on its own (it was one long paragraph, and the filler ran sentences together, "interit.Ovid"). No readiness percentage change.
+ - **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.
+ - **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.
+ - **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+ - **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.
+ - **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+ - **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.
+ - **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page/Spread, New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.
+ - **2026-10-14** · Pages panel: Alt-drag copies a page, a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.
+ - **2026-10-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. No readiness percentage change.
+
+ - **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.
+ - **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.
+ - **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.
+ - **2026-10-13** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. No readiness percentage change.
+ - **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.
+ - **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.
+ - **2026-10-14** · In a facing document, pages take their side from their section's page numbers, as InDesign shuffles them: a section that starts at 1 on a left page moves it to the right and the pages after it follow, with their objects. No readiness percentage change.
+ - **2026-10-14** · The Type menu follows InDesign's order (Size, Character ⌘T, Paragraph ⌥⌘T, Glyphs, the style panels, Notes, footnotes and endnotes, then the insert submenus and Show Hidden Characters); Current Page Number has ⌥⇧⌘N. No readiness percentage change.
+ - **2026-10-14** · Colour parameters: a bare `{c,m,y,k}` is always read as 0..100, so C 1 is a 1 % tint and no longer
+ solid cyan; fractions take the colour's own `{model: "cmyk", …}` form (#910). No readiness percentage change.
+ - **2026-10-14** · The Tools panel follows InDesign's: Gradient Swatch and Gradient Feather are tools of their own; in two columns Content Collector and Placer, Apply Color / Gradient / None and Normal / Preview each get a button; View Options holds Frame Edges, Rulers, Guides, Smart Guides, Baseline Grid and Hidden Characters; Apply Color (,) and Apply Gradient (.) reuse the last colour and gradient. No readiness percentage change.
+ - **2026-10-13** · Create Outlines makes one compound path per line (and per text colour within a line), grouped, as InDesign does: Ungroup then leaves each line on its own to be spaced and made into one compound path again. A single line in one colour stays a single compound path. No readiness percentage change.
+ - **2026-10-13** · Gradient swatches work on strokes: drawn across the path's box on screen and in PDF (they drew nothing), set with `object.gradient {target: stroke}` and in the Gradient panel when the Stroke box is in front; the stroke's gradient vector moves with the shape and round-trips through IDML. No readiness percentage change.
+ - **2026-10-13** · Text takes gradient swatches: a gradient fill or stroke on characters spans the text frame's box (on a path: the path's), on screen and in PDF. No readiness percentage change.
- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load
the text cursor, then click a frame to thread it, click empty space for a column-wide frame or
drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the
@@@ -161,10 -438,16 +439,17 @@@
- **2026-10-12** · The Effects panel shows the level its settings apply to ("Group: Color Dodge 100%") and, as in InDesign, Isolate Blending and Knockout Group for a selected group. No readiness percentage change.
- **2026-10-11** · Properties gains InDesign's Pathfinder section (Add, Subtract, Intersect, Exclude Overlap, Minus Back) with several objects selected; section titles and icon buttons have accessible names. No readiness percentage change.
- **2026-10-12** · The Eyedropper samples a placed image: clicking the photo with text (or objects) selected fills them with the image's colour under the pointer, as an unnamed colour (`color.sample`), as in InDesign. Images on locked layers can be sampled. No readiness percentage change.
+- **2026-10-12** · With a placed graphic selected (Direct Selection), the Transform values act on the graphic inside its frame, as in InDesign: a tilted frame's image can be straightened to 0°. No readiness percentage change.
+ - **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.
+ - **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. No readiness percentage change.
+ - **2026-10-12** · A gradient feather on a group fades the group as one, on screen and in PDF. Before, the screen ignored it, and PDF masked the group with a box of zero size because a group has no path of its own. No readiness percentage change.
+ - **2026-10-12** · In a CMYK transparency blend space (print documents), blend modes blend in CMYK on screen as in InDesign. Color Dodge with 100% K text turns coloured areas under it white and leaves the paper alone, where RGB blending changed almost nothing. PDF export already did this. No readiness percentage change.
+ - **2026-10-11** · Moving a sheared and rotated text frame no longer leaves trails of text behind: canvas repaints cover the frame's whole text box, not just its outline. No readiness percentage change.
- **2026-10-12** · Words in capitals hyphenate like capitalized words (FERRUM COM-MODI), as in InDesign; Hyphenate Capitalized Words off keeps them whole. No readiness percentage change.
+ - **2026-10-12** · Load Swatches refuses an `.ase` file with more than 100,000 colors, and `swatch.load` merges a file of 100,000 colors in under 0.1 s (it took 9.6 s of CPU in a test build). No readiness percentage change.
- **2026-10-11** · `transform.move {copy}`, Edit › Duplicate and Step and Repeat return the copies' ids, so a script can go on with them. No readiness percentage change.
- **2026-10-11** · `object.fill` and `object.stroke` refuse a swatch name the document doesn't have (it painted nothing) and suggest the name meant (`Paper` → `[Paper]`). No readiness percentage change.
+ - **2026-10-13** · Dropping an `.ase` file on the window loads its swatches, as Load Swatches does (the drop failed with "Can't Place the File"). No readiness percentage change.
- **2026-10-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.
- **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change.
diff --cc crates/engine/src/cmd/object.rs
index e732e0186,bbc0a36a1..e658694b5
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@@ -1056,8 -1085,14 +1093,14 @@@ fn transform_move(s: &mut Session, p: &
if it.locked {
continue;
}
- it.xf = Affine::translate((dx, dy)) * it.xf;
+ it.xf = Affine::translate(v) * it.xf;
}
+ // An object dragged inside a Flex Layout takes the place it was dropped on.
+ if !copy {
+ for id in &ids {
+ super::flex::drop_in_container(d, *id);
+ }
+ }
Ok(json!({"moved": ids.len(), "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
})
}
@@@ -3494,181 -3461,35 +3627,214 @@@ mod spread_target_tests
}
}
+#[cfg(test)]
+mod content_move_tests {
+ use super::*;
+
+ /// A session with a 40×20 image placed in a frame at (100, 100)–(300, 300).
+ fn placed() -> (Session, ItemId) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("place.load", &json!({"base64": super::super::base64_encode(&png)})).unwrap();
+ s.execute("place.drop", &json!({"frame": f})).unwrap();
+ (s, ItemId(f))
+ }
+
+ /// Spread bounds of the frame and of its graphic.
+ fn boxes(s: &Session, id: ItemId) -> (Rect, Rect) {
+ let it = s.doc().unwrap().doc.item(id).unwrap().clone();
+ let g = it.graphic().unwrap();
+ (it.bounds(), (it.xf * g.xf).transform_rect_bbox(Rect::new(0.0, 0.0, g.size.0, g.size.1)))
+ }
+
+ fn near(a: Rect, b: Rect) -> bool {
+ [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6)
+ }
+
+ #[test]
+ fn content_moves_inside_the_frame_in_one_undo_step() {
+ let (mut s, f) = placed();
+ let (frame0, g0) = boxes(&s, f);
+ s.execute("selection.set", &json!({"ids": [f.0], "content": true})).unwrap();
+ s.execute("transform.move", &json!({"dx": 10, "dy": -5})).unwrap();
+ let (frame1, g1) = boxes(&s, f);
+ assert!(near(frame1, frame0), "the frame stays");
+ assert!(near(g1, g0 + Vec2::new(10.0, -5.0)), "{g1:?}");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(near(boxes(&s, f).1, g0));
+ // Explicit ids with `content` act on the content whatever the selection is.
+ s.execute("selection.set", &json!({"ids": [f.0]})).unwrap();
+ s.execute("transform.move", &json!({"ids": [f.0], "content": true, "dx": 3})).unwrap();
+ assert!(near(boxes(&s, f).0, frame0) && near(boxes(&s, f).1, g0 + Vec2::new(3.0, 0.0)));
+ // A frame selection moves frame and content together.
+ s.execute("transform.move", &json!({"dx": 4})).unwrap();
+ assert!(near(boxes(&s, f).0, frame0 + Vec2::new(4.0, 0.0)) && near(boxes(&s, f).1, g0 + Vec2::new(7.0, 0.0)));
+ }
+
+ #[test]
+ fn content_moves_on_the_page_axes_in_a_rotated_frame_and_pasted_items_move_too() {
+ let (mut s, f) = placed();
+ s.execute("transform.rotate", &json!({"ids": [f.0], "angle": 90})).unwrap();
+ let (frame0, g0) = boxes(&s, f);
+ s.execute("transform.move", &json!({"ids": [f.0], "content": true, "dx": 10})).unwrap();
+ let (frame1, g1) = boxes(&s, f);
+ assert!(near(frame1, frame0) && near(g1, g0 + Vec2::new(10.0, 0.0)), "{g0:?} → {g1:?}");
+ // Items pasted into a frame are its content.
+ let a = s.execute("frame.create", &json!({"rect": [400, 100, 420, 120], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("selection.set", &json!({"ids": [a]})).unwrap();
+ s.execute("edit.copy", &json!({})).unwrap();
+ let b = s.execute("frame.create", &json!({"rect": [400, 300, 500, 400], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("selection.set", &json!({"ids": [b]})).unwrap();
+ s.execute("edit.pasteInto", &json!({})).unwrap();
+ let kids = |s: &Session| {
+ let it = s.doc().unwrap().doc.item(ItemId(b)).unwrap().clone();
+ (it.bounds(), it.children().iter().map(|c| it.xf.transform_rect_bbox(c.bounds())).collect::<Vec<_>>())
+ };
+ let (fb0, k0) = kids(&s);
+ s.execute("transform.move", &json!({"ids": [b], "content": true, "dx": 5, "dy": 6})).unwrap();
+ let (fb1, k1) = kids(&s);
+ assert!(near(fb1, fb0) && near(k1[0], k0[0] + Vec2::new(5.0, 6.0)), "{k0:?} → {k1:?}");
+ }
+}
+
+#[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 content_bounds_resize_the_graphic_and_leave_the_frame() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200], "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();
+ let bounds = |s: &Session| {
+ let it = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone();
+ let g = it.graphic().unwrap().clone();
+ (it.bounds(), (it.xf * g.xf).transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1)))
+ };
+ let (frame0, _) = bounds(&s);
+ // The handles' drag: the image to (20, 40)–(420, 240), one undo step; the frame stays.
+ s.execute("transform.set", &json!({"ids": [f], "content": true, "bounds": [20, 40, 420, 240]})).unwrap();
+ let (frame1, g1) = bounds(&s);
+ assert_eq!(frame1, frame0);
+ let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
+ assert!(near(g1.x0, 20.0) && near(g1.y0, 40.0) && near(g1.x1, 420.0) && near(g1.y1, 240.0), "{g1:?}");
+ // Dragged past the opposite edge: normalized, never empty.
+ s.execute("transform.set", &json!({"ids": [f], "content": true, "bounds": [300, 300, 300, 100]})).unwrap();
+ let (_, g2) = bounds(&s);
+ assert!(g2.width() > 0.0 && near(g2.y0, 100.0) && near(g2.y1, 300.0), "{g2:?}");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(near(bounds(&s).1.x1, 420.0));
+ }
+
+ #[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 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 fill_tint_tests {
+ use super::*;
+
+ #[test]
+ fn a_tint_alone_keeps_each_objects_own_swatch() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let a = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap();
+ let b = s.execute("frame.create", &json!({"rect": [136, 36, 200, 100]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("object.fill", &json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();
+ s.execute("object.fill", &json!({"ids": [b], "swatch": "C=0 M=100 Y=0 K=0"})).unwrap();
+ s.execute("object.fill", &json!({"ids": [a, b], "tint": 0.4})).unwrap();
+ let fill_of = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().fill.clone();
+ assert_eq!((fill_of(&s, a).swatch.as_str(), fill_of(&s, a).tint), ("C=100 M=0 Y=0 K=0", 0.4));
+ assert_eq!((fill_of(&s, b).swatch.as_str(), fill_of(&s, b).tint), ("C=0 M=100 Y=0 K=0", 0.4));
+ // A swatch without a tint is at 100 %, as before.
+ s.execute("object.fill", &json!({"ids": [a], "swatch": "[Black]"})).unwrap();
+ assert_eq!(fill_of(&s, a).tint, 1.0);
+ // Neither, or a tint out of range: refused.
+ assert!(s.execute("object.fill", &json!({"ids": [a]})).is_err());
+ assert!(s.execute("object.fill", &json!({"ids": [a], "tint": 2})).is_err());
+ assert!(s.execute("object.fill", &json!({"ids": [a], "tint": "x"})).is_err());
+ // A stroke tint alone: stroked objects take it, an object without a stroke keeps none.
+ s.execute("object.stroke", &json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0", "weight": 2})).unwrap();
+ s.execute("object.stroke", &json!({"ids": [b], "swatch": "[None]"})).unwrap();
+ s.execute("object.stroke", &json!({"ids": [a, b], "tint": 0.5})).unwrap();
+ let stroke_of = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().stroke.clone();
+ assert_eq!((stroke_of(&s, a).swatch.as_str(), stroke_of(&s, a).tint, stroke_of(&s, a).weight), ("C=100 M=0 Y=0 K=0", 0.5, 2.0));
+ assert!(stroke_of(&s, b).is_none());
+ }
+ }
diff --cc crates/engine/src/tests.rs
index 6a3005758,616a86398..a56e0fece
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -570,41 -570,364 +570,399 @@@ fn commands_take_non_object_params_with
}
}
+#[test]
+fn direct_selection_drag_and_arrow_keys_move_placed_content() {
+ use designcraft_tools::{Mods, PointerEvent, PointerKind, SnapView, ToolKey};
+ let mut s = session();
+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("place.load", &json!({"base64": cmd::base64_encode(&png)})).unwrap();
+ s.execute("place.drop", &json!({"frame": f})).unwrap();
+ let xfs = |s: &Session| {
+ let it = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone();
+ (it.xf, it.graphic().unwrap().xf.translation())
+ };
+ let (frame0, g0) = xfs(&s);
+ let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) };
+ let at = s.layout().to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(150.0, 150.0));
+ s.set_tool("directSelection");
+ s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 20.0, at.y + 10.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 30.0, at.y + 10.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, at.x + 30.0, at.y + 10.0), v).unwrap();
+ assert!(s.doc().unwrap().selection.content);
+ let (frame1, g1) = xfs(&s);
+ assert_eq!(frame1, frame0, "the frame stays");
+ assert_eq!(g1 - g0, designcraft_geom::Vec2::new(30.0, 10.0));
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(xfs(&s).1, g0, "one undo step");
+ // Arrow keys nudge the selected content; Shift nudges ten times as far.
+ s.set_tool("selection");
+ s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
+ s.tool_key(ToolKey::Down, Mods { shift: true, ..Default::default() }, v).unwrap();
+ let (frame2, g2) = xfs(&s);
+ assert_eq!(frame2, frame0);
+ assert_eq!(g2 - g0, designcraft_geom::Vec2::new(1.0, 10.0));
+}
+
+ #[test]
+ fn paragraph_style_edit_persists_attrs_and_rename() {
+ let mut s = session();
+ let name =
+ s.execute("style.paragraph.create", &json!({"name": "Body Copy", "para": {"align": "left"}})).unwrap()["name"].as_str().unwrap().to_string();
+ s.execute("style.paragraph.edit", &json!({"name": name, "para": {"align": "center"}})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let style = st.doc.styles.para(&name).expect("style still exists");
+ assert_eq!(style.para.align, Some(designcraft_doc::Align::Center), "edited attribute persisted");
+ }
+ // Renaming updates the style definition itself, and every place it's referenced.
+ s.execute("style.paragraph.edit", &json!({"name": name, "rename": "Body Text"})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.para("Body Text").is_some(), "renamed style exists under the new name");
+ assert!(st.doc.styles.para(&name).is_none(), "old name is gone");
+ }
+
+ #[test]
+ fn paragraph_style_edit_rejects_based_on_cycle() {
+ let mut s = session();
+ let a = s.execute("style.paragraph.create", &json!({"name": "A"})).unwrap()["name"].as_str().unwrap().to_string();
+ let b = s.execute("style.paragraph.create", &json!({"name": "B", "basedOn": a})).unwrap()["name"].as_str().unwrap().to_string();
+ let r = s.execute("style.paragraph.edit", &json!({"name": a, "basedOn": b}));
+ assert!(r.is_err(), "A based on B based on A must be rejected");
+ }
+
+ #[test]
+ fn paragraph_style_delete_reassigns_affected_text() {
+ let mut s = session();
+ let name = s.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();
+ let sid = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();
+ s.execute("text.insert", &json!({"text": "Hello, world"})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name": name})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.paras[0].style, name, "style applied before delete");
+ }
+ s.execute("style.paragraph.delete", &json!({"name": name, "replaceWith": designcraft_doc::BASIC_PARAGRAPH})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.para(&name).is_none(), "deleted style is gone");
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.paras[0].style, designcraft_doc::BASIC_PARAGRAPH, "affected paragraph reassigned to the replacement style");
+ }
+
+ #[test]
+ fn paragraph_style_delete_rejects_builtin_styles() {
+ let mut s = session();
+ let r = s.execute("style.paragraph.delete", &json!({"name": designcraft_doc::BASIC_PARAGRAPH}));
+ assert!(r.is_err(), "built-in styles can't be deleted");
+ }
+
+ #[test]
+ fn character_style_edit_persists_attrs_and_rename() {
+ let mut s = session();
+ let name = s.execute("style.character.create", &json!({"name": "Key Term", "chars": {"fontStyle": "Bold"}})).unwrap()["name"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ s.execute("style.character.edit", &json!({"name": name, "chars": {"tracking": 20.0}})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let style = st.doc.styles.char_style(&name).expect("style still exists");
+ assert_eq!(style.chars.tracking, Some(20.0), "edited attribute persisted");
+ }
+ // Renaming updates the style definition itself, and every place it's referenced.
+ s.execute("style.character.edit", &json!({"name": name, "rename": "Emphasis"})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.char_style("Emphasis").is_some(), "renamed style exists under the new name");
+ assert!(st.doc.styles.char_style(&name).is_none(), "old name is gone");
+ }
+
+ #[test]
+ fn character_style_edit_rejects_based_on_cycle() {
+ let mut s = session();
+ let a = s.execute("style.character.create", &json!({"name": "A"})).unwrap()["name"].as_str().unwrap().to_string();
+ let b = s.execute("style.character.create", &json!({"name": "B", "basedOn": a})).unwrap()["name"].as_str().unwrap().to_string();
+ let r = s.execute("style.character.edit", &json!({"name": a, "basedOn": b}));
+ assert!(r.is_err(), "A based on B based on A must be rejected");
+ }
+
+ #[test]
+ fn character_style_delete_reassigns_affected_text() {
+ let mut s = session();
+ let name = s.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();
+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.execute("text.insert", &json!({"text": "Hello, world"})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap();
+ s.execute("style.character.apply", &json!({"name": name})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.chars[0].format.style, name, "style applied before delete");
+ }
+ s.execute("style.character.delete", &json!({"name": name, "replaceWith": designcraft_doc::NO_CHAR_STYLE})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.char_style(&name).is_none(), "deleted style is gone");
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.chars[0].format.style, designcraft_doc::NO_CHAR_STYLE, "affected run reassigned to the replacement style");
+ }
+
+ #[test]
+ fn character_style_delete_rejects_builtin_styles() {
+ let mut s = session();
+ let r = s.execute("style.character.delete", &json!({"name": designcraft_doc::NO_CHAR_STYLE}));
+ assert!(r.is_err(), "built-in styles can't be deleted");
+ }
+
+ #[test]
+ fn character_style_delete_rejects_missing_unknown_and_self_replacement() {
+ let mut s = session();
+ let name = s.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();
+ assert!(s.execute("style.character.delete", &json!({"name": ""})).is_err(), "empty name is rejected");
+ assert!(s.execute("style.character.delete", &json!({"name": "No Such Style"})).is_err(), "unknown name is rejected");
+ assert!(s.execute("style.character.delete", &json!({"name": name, "replaceWith": "No Such Style"})).is_err(), "unknown replaceWith is rejected");
+ assert!(s.execute("style.character.delete", &json!({"name": name, "replaceWith": name})).is_err(), "replaceWith can't be the deleted style");
+ }
+
+ #[test]
+ fn paragraph_style_delete_rejects_missing_unknown_and_self_replacement() {
+ let mut s = session();
+ let name = s.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();
+ assert!(s.execute("style.paragraph.delete", &json!({"name": ""})).is_err(), "empty name is rejected");
+ assert!(s.execute("style.paragraph.delete", &json!({"name": "No Such Style"})).is_err(), "unknown name is rejected");
+ assert!(s.execute("style.paragraph.delete", &json!({"name": name, "replaceWith": "No Such Style"})).is_err(), "unknown replaceWith is rejected");
+ assert!(s.execute("style.paragraph.delete", &json!({"name": name, "replaceWith": name})).is_err(), "replaceWith can't be the deleted style");
+ }
+
+ #[test]
+ fn deleting_a_style_never_leaves_its_replacement_based_on_itself() {
+ let mut s = session();
+ let para = |s: &Session, n: &str| s.doc().unwrap().doc.styles.para(n).unwrap().based_on.clone();
+ s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Sub", "basedOn": "Head"})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Minor", "basedOn": "Sub"})).unwrap();
+ // Minor is based on Sub; deleting Sub in favour of Minor gives Minor Sub's parent.
+ s.execute("style.paragraph.delete", &json!({"name": "Sub", "replaceWith": "Minor"})).unwrap();
+ assert_eq!(para(&s, "Minor").as_deref(), Some("Head"));
+ s.execute("style.character.create", &json!({"name": "Strong"})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Stronger", "basedOn": "Strong"})).unwrap();
+ s.execute("style.character.delete", &json!({"name": "Strong", "replaceWith": "Stronger"})).unwrap();
+ let based = s.doc().unwrap().doc.styles.character.iter().find(|c| c.name == "Stronger").unwrap().based_on.clone();
+ assert_ne!(based.as_deref(), Some("Stronger"));
+ }
+
+ #[test]
+ fn character_style_delete_reassigns_every_kind_of_reference() {
+ let mut s = session();
+ let name = s.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();
+ let repl = s.execute("style.character.create", &json!({"name": "Emphasis"})).unwrap()["name"].as_str().unwrap().to_string();
+ // Another character style's basedOn.
+ let based = s.execute("style.character.create", &json!({"name": "Strong", "basedOn": name})).unwrap()["name"].as_str().unwrap().to_string();
+ // A paragraph style's nested, nested line, GREP and drop cap styles, and the footnote reference style.
+ s.execute(
+ "style.paragraph.create",
+ &json!({"name": "Body", "para": {
+ "nestedStyles": [{"style": name, "through": true, "count": 1, "until": {"kind": "words"}}],
+ "grepStyles": [{"style": name, "pattern": "x"}],
+ "nestedLineStyles": [{"style": name, "lines": 1}],
+ "dropCapStyle": name}}),
+ )
+ .unwrap();
+ s.execute("footnote.options", &json!({"refCharStyle": name})).unwrap();
+ s.execute("style.character.delete", &json!({"name": name, "replaceWith": repl})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.char_style(&name).is_none(), "deleted style is gone");
+ assert_eq!(st.doc.styles.char_style(&based).unwrap().based_on.as_deref(), Some(repl.as_str()), "basedOn redirected");
+ let body = st.doc.styles.para("Body").unwrap();
+ assert_eq!(body.para.nested_styles.as_ref().unwrap()[0].style, repl, "nested style redirected");
+ assert_eq!(body.para.nested_line_styles.as_ref().unwrap()[0].style, repl, "nested line style redirected");
+ assert_eq!(body.para.grep_styles.as_ref().unwrap()[0].style, repl, "grep style redirected");
+ assert_eq!(body.para.drop_cap_style.as_deref(), Some(repl.as_str()), "drop cap style redirected");
+ assert_eq!(st.doc.footnote_options.ref_char_style, repl, "footnote reference style redirected");
+ }
+
+ #[test]
+ fn page_tool_selects_a_page_and_its_handles_preview_or_resize_it() {
+ use designcraft_tools::{CanvasLayout, Mods, PointerEvent, PointerKind};
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap();
+ let id = s.execute("frame.create", &json!({"rect": [400, 100, 500, 200]})).unwrap()["id"].as_u64().unwrap();
+ let frame = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds();
+ let width = |s: &Session| s.doc().unwrap().doc.spreads[0].pages[0].width;
+ // The page on the canvas (a single page is centred on the spine).
+ let page = |s: &Session| {
+ let d = &s.doc().unwrap().doc;
+ CanvasLayout::new(d, false).page_rect(d, 0).unwrap()
+ };
+ s.set_tool("page");
+ let v = ViewInfo::at_zoom(1.0);
+ let ev = |kind, x: f64, y: f64, alt: bool| PointerEvent { mods: Mods { alt, ..Default::default() }, ..PointerEvent::new(kind, x, y) };
+ let drag = |s: &mut Session, from: (f64, f64), by: f64, alt: bool, check: &dyn Fn(&Session)| {
+ s.pointer(&ev(PointerKind::Down, from.0, from.1, alt), v).unwrap();
+ s.pointer(&ev(PointerKind::Drag, from.0 + by, from.1, alt), v).unwrap();
+ check(s);
+ s.pointer(&ev(PointerKind::Up, from.0 + by, from.1, alt), v).unwrap();
+ };
+ // A click selects the page.
+ let c = page(&s).center();
+ s.pointer(&ev(PointerKind::Down, c.x, c.y, false), v).unwrap();
+ s.pointer(&ev(PointerKind::Up, c.x, c.y, false), v).unwrap();
+ assert_eq!(s.doc().unwrap().selection.page, Some(0));
+ // A plain drag of the right handle previews the page's liquid rule and springs back.
+ s.execute("liquid.pageRule", &json!({"rule": "scale"})).unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ let r = page(&s);
+ drag(&mut s, (r.x1, r.center().y), 612.0, false, &|s| {
+ assert_eq!(width(s), 1224.0, "previewed");
+ // Scale keeps proportions: only wider, so the frame is centred on the wider page.
+ assert_eq!(frame(s).x0, 706.0, "the Scale rule in the preview: {:?}", frame(s));
+ });
+ assert_eq!((width(&s), frame(&s)), (612.0, designcraft_geom::Rect::new(400.0, 100.0, 500.0, 200.0)), "sprung back");
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing to undo");
+ // Alt-drag resizes; with the rule off the frame stays where it is.
+ s.execute("liquid.pageRule", &json!({"rule": "off"})).unwrap();
+ let r = page(&s);
+ drag(&mut s, (r.x1, r.center().y), 100.0, true, &|_| {});
+ assert_eq!(width(&s), 712.0);
+ assert_eq!(frame(&s).x0, 400.0);
+ // The left handle grows the page to the left: the frame keeps its place by the right edge.
+ let r = page(&s);
+ drag(&mut s, (r.x0, r.center().y), -100.0, true, &|_| {});
+ let pg = s.doc().unwrap().doc.spreads[0].pages[0].clone();
+ assert_eq!(pg.width, 812.0);
+ assert_eq!(frame(&s).x0 - pg.x, 500.0, "100 pt further from the page's left edge");
+ // A click on the pasteboard deselects the page.
+ let r = page(&s);
+ s.pointer(&ev(PointerKind::Down, r.x0 - 200.0, r.center().y, false), v).unwrap();
+ assert_eq!(s.doc().unwrap().selection.page, None);
+ }
+
+ #[test]
+ fn page_size_keeps_objects_by_its_anchor() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400, "facingPages": false})).unwrap();
+ let id = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap();
+ let frame = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds();
+ // Bottom-right stays put: 100 wider and 50 taller moves the frame 100 right and 50 down.
+ s.execute("layout.pageSize", &json!({"pages": [1], "width": 500, "height": 450, "anchor": 8})).unwrap();
+ assert_eq!(frame(&s), designcraft_geom::Rect::new(200.0, 150.0, 300.0, 250.0));
+ // The centre: half of it.
+ s.execute("layout.pageSize", &json!({"pages": [1], "width": 700, "height": 450, "anchor": 4})).unwrap();
+ assert_eq!(frame(&s).x0, 300.0);
+ assert!(s.execute("layout.pageSize", &json!({"pages": [1], "width": 700, "anchor": 9})).is_err());
+ assert!(s.execute("layout.selectPage", &json!({"page": 2})).is_err());
+ assert_eq!(s.execute("layout.selectPage", &json!({"page": 1})).unwrap()["page"], 1);
+ }
+
+ #[test]
+ fn controlled_by_parent_takes_the_parent_pages_rule() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400, "facingPages": false})).unwrap();
+ let id = s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap();
+ let frame = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds();
+ // The page follows its parent; the parent page re-centres.
+ s.execute("liquid.pageRule", &json!({"rule": "controlledByParent", "pages": [1]})).unwrap();
+ s.edit(|d, _| {
+ std::sync::Arc::make_mut(&mut d.parents[0]).pages[0].liquid = designcraft_doc::LiquidRule::ReCenter;
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layout.pageSize", &json!({"pages": [1], "width": 600})).unwrap();
+ assert_eq!(frame(&s).x0, 200.0, "re-centred: {:?}", frame(&s));
+ // Without a parent (or a parent that's also controlled by its parent) nothing moves.
+ s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": null})).unwrap();
+ s.execute("layout.pageSize", &json!({"pages": [1], "width": 800})).unwrap();
+ assert_eq!(frame(&s).x0, 200.0);
+ // Show Parent Page Overlay is a page option.
+ s.execute("layout.pageOptions", &json!({"pages": [1], "showParentOverlay": true})).unwrap();
+ assert!(s.doc().unwrap().doc.spreads[0].pages[0].show_parent_overlay);
+ assert!(s.execute("layout.pageOptions", &json!({"pages": [2], "showParentOverlay": true})).is_err());
+ }
+
+ #[test]
+ fn page_tool_pins_and_locks_objects_on_object_based_pages() {
+ use designcraft_tools::{CanvasLayout, Mods, PointerEvent, PointerKind};
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap();
+ let id = s.execute("frame.create", &json!({"rect": [256, 72, 356, 132]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("liquid.pageRule", &json!({"rule": "objectBased"})).unwrap();
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ s.set_tool("page");
+ let v = ViewInfo::at_zoom(1.0);
+ let ev =
+ |kind, p: designcraft_geom::Point, alt: bool| PointerEvent { mods: Mods { alt, ..Default::default() }, ..PointerEvent::new(kind, p.x, p.y) };
+ let canvas = |s: &Session| {
+ let d = &s.doc().unwrap().doc;
+ let l = CanvasLayout::new(d, false);
+ (
+ l.page_rect(d, 0).unwrap(),
+ l.xf(designcraft_doc::SpreadRef::Doc(0)).transform_rect_bbox(d.item(designcraft_doc::ItemId(id)).unwrap().bounds()),
+ )
+ };
+ let click = |s: &mut Session, p: designcraft_geom::Point| {
+ s.pointer(&ev(PointerKind::Down, p, false), v).unwrap();
+ s.pointer(&ev(PointerKind::Up, p, false), v).unwrap();
+ };
+ let liquid = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().liquid;
+ // A click on the object selects it with its page; its pins and locks show.
+ let (_, o) = canvas(&s);
+ click(&mut s, o.center());
+ let sel = s.doc().unwrap().selection.clone();
+ assert_eq!((sel.page, sel.items.clone()), (Some(0), vec![designcraft_doc::ItemId(id)]));
+ assert!(
+ s.overlays(v)
+ .iter()
+ .any(|o| matches!(o, designcraft_tools::Overlay::LiquidPins { pins: [false, false, false, false], resize: [true, true], .. }))
+ );
+ // The right pin (14 px outside the right edge) and the width lock (10 px right of the centre).
+ click(&mut s, designcraft_geom::Point::new(o.x1 + 14.0, o.center().y));
+ click(&mut s, designcraft_geom::Point::new(o.center().x + 10.0, o.center().y));
+ let l = liquid(&s).unwrap();
+ assert!(l.pin_right && !l.resize_width && l.resize_height && !l.pin_left, "{l:?}");
+ // Alt-drag the page 100 pt wider: the pinned, width-locked frame keeps its size by the right edge.
+ let (p, _) = canvas(&s);
+ let right = designcraft_geom::Point::new(p.x1, p.center().y);
+ s.pointer(&ev(PointerKind::Down, right, true), v).unwrap();
+ s.pointer(&ev(PointerKind::Drag, right + designcraft_geom::Vec2::new(100.0, 0.0), true), v).unwrap();
+ s.pointer(&ev(PointerKind::Up, right + designcraft_geom::Vec2::new(100.0, 0.0), true), v).unwrap();
+ let d = &s.doc().unwrap().doc;
+ let (pg, b) = (&d.spreads[0].pages[0], d.item(designcraft_doc::ItemId(id)).unwrap().bounds());
+ assert_eq!(pg.width, 712.0);
+ assert!((b.width() - 100.0).abs() < 1e-6 && (pg.x + pg.width - b.x1 - 256.0).abs() < 1e-6, "{b:?}");
+ // Hovering a pin shows its tooltip.
+ let (_, o) = canvas(&s);
+ s.pointer(&ev(PointerKind::Move, designcraft_geom::Point::new(o.x1 + 14.0, o.center().y), false), v).unwrap();
+ assert!(s.overlays(v).iter().any(|o| matches!(o, designcraft_tools::Overlay::Tip { text, .. } if text.starts_with("Object is pinned"))));
+ }
+
+ #[test]
+ fn duplicating_a_page_keeps_its_own_size_rule_guides_and_objects() {
+ // Chris Cicchino's Page Tool video (2:06): the letterhead page is duplicated, then resized.
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 252, "height": 144, "facingPages": false})).unwrap();
+ s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();
+ s.execute("layout.pageSize", &json!({"pages": [2], "width": 612, "height": 792})).unwrap();
+ s.execute("liquid.pageRule", &json!({"rule": "scale", "pages": [2]})).unwrap();
+ s.execute("guide.add", &json!({"spread": 1, "page": 0, "orientation": "vertical", "position": 300})).unwrap();
+ s.execute("frame.create", &json!({"spread": 1, "rect": [100, 100, 200, 200]})).unwrap();
+ let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 1})).unwrap();
+ assert_eq!(r["page"], 2);
+ let d = s.doc().unwrap().doc.clone();
+ let (si, pi) = d.page_loc(2).unwrap();
+ let pg = &d.spreads[si].pages[pi];
+ assert_eq!((pg.width, pg.height, pg.liquid), (612.0, 792.0, designcraft_doc::LiquidRule::Scale));
+ assert_eq!(pg.guides.len(), 1);
+ assert_eq!(d.spreads[si].items.len(), 1);
+ // At the end of the document (the New Page button): the business card, not the last page's size.
+ let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 0, "atEnd": true})).unwrap();
+ assert_eq!(r["page"], 3);
+ let d = s.doc().unwrap().doc.clone();
+ let (si, pi) = d.page_loc(3).unwrap();
+ assert_eq!((d.spreads[si].pages[pi].width, d.spreads[si].pages[pi].height), (252.0, 144.0));
+ }
+
/// Load the text from a frame's out port with the Selection tool and click on the pasteboard:
/// a new frame is threaded there and the overset text flows into it.
#[test]
diff --cc crates/tools/src/lib.rs
index 13cf0e24e,3f042d4a0..bec49d25c
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@@ -322,9 -325,28 +325,31 @@@ pub enum Overlay
b: Point,
label: String,
},
+ /// The whole content of this frame drawn faintly, the part outside the frame included (while
+ /// the content moves inside it).
+ ContentGhost(ItemId),
+ /// A page selected with the Page tool (canvas rect): its outline and eight handles.
+ PageHandles(Rect),
+ /// A small tag whose bottom-left is at `p` (the Page tool's liquid page rule; English, the UI
+ /// translates it).
+ Tag {
+ p: Point,
+ text: String,
+ },
+ /// A tooltip near the pointer (English; the UI translates it).
+ Tip {
+ p: Point,
+ text: String,
+ },
+ /// An object's liquid pins and resize locks on an object-based page (Page tool), canvas
+ /// coordinates: pinned sides (top, right, bottom, left) and whether width and height follow the
+ /// page.
+ LiquidPins {
+ object: Rect,
+ page: Rect,
+ pins: [bool; 4],
+ resize: [bool; 2],
+ },
}
/// Correction from a snap, in spread coordinates for `delta`.
diff --cc crates/tools/src/tests.rs
index 06b6f1b3e,aacfb8d3f..e8220dc66
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@@ -1160,143 -1214,103 +1214,244 @@@ fn eyedropper_samples_a_placed_image_an
assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))]);
}
+/// A 100×100 frame at (100, 100) holding a 200×100 graphic that overhangs it.
+fn graphic_frame(doc: &mut Document) -> ItemId {
+ let id = ItemId(doc.alloc());
+ let mut item = Item::new(id, doc.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));
+ item.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (200.0, 100.0),
+ xf: designcraft_geom::Affine::translate((50.0, 100.0)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ id
+}
+
+fn preview_params(a: &[Action]) -> serde_json::Value {
+ match a.last() {
+ Some(Action::Preview(cmd, p)) if cmd == "transform.move" => p.clone(),
+ other => panic!("{other:?}"),
+ }
+}
+
+#[test]
+fn direct_selection_drags_content_inside_its_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let none = Selection::default();
+ let mut t = create("directSelection");
+ let at = spread_pt(&l, 120.0, 130.0);
+ let a = t.pointer(&ctx(&d, &none, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);
+ let sel = Selection { content: true, ..Selection::items(vec![f]) };
+ let cx = ctx(&d, &sel, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 15.0, at.y - 4.0));
+ assert_eq!(a.first(), Some(&Action::Begin("Move Content".into())));
+ let p = preview_params(&a);
+ assert_eq!(
+ (p["dx"].as_f64(), p["dy"].as_f64(), &p["content"], &p["ids"]),
+ (Some(15.0), Some(-4.0), &serde_json::json!(true), &serde_json::json!([f.0]))
+ );
+ assert_eq!(t.cursor(&cx, at, Mods::default()), Cursor::HandGrab);
+ assert!(t.overlays(&cx).contains(&Overlay::ContentGhost(f)));
+ // Shift keeps the drag on one axis.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 15.0, at.y - 4.0).with_mods(Mods { shift: true, ..Default::default() }));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p["dy"].as_f64()), (Some(15.0), Some(0.0)));
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x + 15.0, at.y)), vec![Action::Commit]);
+}
+
+#[test]
+fn selection_tool_grabber_moves_content_elsewhere_moves_the_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let frame = Selection::items(vec![f]);
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let centre = spread_pt(&l, 150.0, 150.0);
+ let mut t = create("selection");
+ // Hovering the grabber shows the hand; it is there on hover before any click, too.
+ assert_eq!(t.cursor(&ctx(&d, &Selection::default(), &c, &l), centre, Mods::default()), Cursor::Hand);
+ let g = select::grabbers(&ctx(&d, &Selection::default(), &c, &l), Some(centre));
+ assert!(matches!(g.as_slice(), [(id, p)] if *id == f && near(*p, centre)), "{g:?}");
+ // Press on the grabber: the content is selected; the drag moves it.
+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, centre.x, centre.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Drag, centre.x - 20.0, centre.y + 10.0));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p["dy"].as_f64(), &p["content"]), (Some(-20.0), Some(10.0), &serde_json::json!(true)));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, centre.x - 20.0, centre.y + 10.0)), vec![Action::Commit]);
+ // A press elsewhere in the frame keeps the content selection; dragging selects and moves the frame.
+ let edge = spread_pt(&l, 115.0, 185.0);
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y)).is_empty());
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x + 30.0, edge.y));
+ assert_eq!(a[0], Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0]})));
+ assert_eq!(a[1], Action::Begin("Move".into()));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p.get("content"), p.get("ids")), (Some(30.0), None, None));
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Up, edge.x + 30.0, edge.y));
+ // With the frame selected, a drag away from the grabber moves the frame.
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y));
+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x, edge.y + 30.0));
+ assert_eq!(a[0], Action::Begin("Move".into()));
+ assert_eq!(preview_params(&a).get("content"), None);
+}
+
+#[test]
+fn double_click_toggles_frame_and_content() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let at = spread_pt(&l, 120.0, 180.0);
+ let mut t = create("selection");
+ let dbl = PointerEvent::new(PointerKind::DoubleClick, at.x, at.y);
+ let frame = Selection::items(vec![f]);
+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &dbl);
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &dbl);
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": false}))]);
+}
+
+#[test]
+fn a_selected_graphics_own_handles_resize_it_and_leave_the_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let set_params = |a: &[Action]| match a.last() {
+ Some(Action::Preview(cmd, p)) if cmd == "transform.set" => p.clone(),
+ other => panic!("{other:?}"),
+ };
+ for tool in ["selection", "directSelection"] {
+ let mut t = create(tool);
+ let cx = ctx(&d, &content, &c, &l);
+ // The graphic's bottom-right corner, (250, 200), outside the frame's (200, 200).
+ let corner = spread_pt(&l, 250.0, 200.0);
+ assert_ne!(t.cursor(&cx, corner, Mods::default()), Cursor::Arrow, "{tool}");
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, corner.x, corner.y)), vec![Action::Begin("Resize Content".into())], "{tool}");
+ let to = spread_pt(&l, 300.0, 250.0);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.x, to.y));
+ let p = set_params(&a);
+ assert_eq!(
+ (&p["ids"], &p["content"], &p["bounds"]),
+ (&serde_json::json!([f.0]), &serde_json::json!(true), &serde_json::json!([50.0, 100.0, 300.0, 250.0]))
+ );
+ assert!(t.overlays(&cx).contains(&Overlay::ContentGhost(f)));
+ // Shift keeps the graphic's proportions (2:1).
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, ..Default::default() }));
+ let b = set_params(&a)["bounds"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
+ assert!(((b[2] - b[0]) / (b[3] - b[1]) - 2.0).abs() < 1e-6, "{b:?}");
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.x, to.y)), vec![Action::Commit]);
+ }
+ // The frame's own handles don't resize the frame while its graphic is selected.
+ let mut t = create("selection");
+ let frame_corner = spread_pt(&l, 200.0, 200.0);
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, frame_corner.x, frame_corner.y));
+ assert!(!a.contains(&Action::Begin("Resize".into())), "{a:?}");
+}
++
+ #[test]
+ fn eyedropper_ignores_inactive_states_of_a_multi_state_object() {
+ use designcraft_doc::{Asset, AssetId, Content, Graphic};
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ d.assets.insert(
+ AssetId(1),
+ std::sync::Arc::new(Asset {
+ id: AssetId(1),
+ name: "photo.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: std::sync::Arc::new(vec![]),
+ pixels: Some((100, 100)),
+ page: 0,
+ }),
+ );
+ let area = Rect::new(100.0, 100.0, 200.0, 200.0);
+ let raster = {
+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(area));
+ it.content = Content::Graphic(Graphic {
+ asset: AssetId(1),
+ size: (100.0, 100.0),
+ xf: designcraft_geom::Affine::translate((0.0, 0.0)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ it
+ };
+ let mut vector = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(area));
+ vector.fill.swatch = "[Black]".into();
+ let target = add_rect(&mut d, Rect::new(400.0, 100.0, 450.0, 150.0));
+ let s = Selection { items: vec![target], ..Default::default() };
+ let sample = Action::Exec("color.sample".into(), serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}}));
+ // Children [vector, raster] with the raster on top: it samples only while it is the active state.
+ for (active, samples) in [(1, true), (0, false)] {
+ let mut group = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(area));
+ group.content = Content::Group { items: vec![std::sync::Arc::new(vector.clone()), std::sync::Arc::new(raster.clone())] };
+ group.states = vec!["a".into(), "b".into()];
+ group.active_state = active;
+ let mut d2 = d.clone();
+ d2.insert_item(SpreadRef::Doc(0), group, None).unwrap();
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d2, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = create("eyedropper").pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a.contains(&sample), samples, "active state {active}: {a:?}");
+ }
+ }
+
+ #[test]
+ fn pen_cursor_shows_add_delete_and_close() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 200.0), lid, "", ParaFormat::default()).unwrap();
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let selected = Selection::items(vec![fid]);
+ let none = Selection::default();
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let at = |x: f64, y: f64| Point::new(x + off.x, y + off.y);
+ let mut t = create("pen");
+ let m = Mods::default();
+
+ let cx = ctx(&d, &selected, &c, &l);
+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::PenDelete, "on a selected path's anchor");
+ assert_eq!(t.cursor(&cx, at(150.0, 101.0), m), Cursor::PenAdd, "on a selected path's outline");
+ assert_eq!(t.cursor(&cx, at(150.0, 150.0), m), Cursor::Pen, "inside, away from the outline");
+ let click = |t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point| {
+ let down = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y));
+ let up = t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y));
+ (down, up)
+ };
+ let (down, up) = click(&mut t, &cx, at(200.0, 100.0));
+ assert_eq!(down, vec![Action::Exec("path.deleteAnchor".into(), serde_json::json!({"id": fid.0, "subpath": 0, "anchor": 1}))]);
+ assert!(up.is_empty() && !t.busy(), "deleting starts no path");
+ let (down, _) = click(&mut t, &cx, at(150.0, 101.0));
+ assert!(matches!(&down[..], [Action::Exec(cmd, p)] if cmd == "path.addAnchor" && p["id"] == fid.0), "{down:?}");
+
+ // Unselected paths are drawn over; the first anchor of the path being drawn closes it.
+ let cx = ctx(&d, &none, &c, &l);
+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::Pen, "unselected path");
+ click(&mut t, &cx, at(300.0, 300.0));
+ assert_eq!(t.cursor(&cx, at(300.0, 300.0), m), Cursor::Pen, "one anchor cannot close yet");
+ click(&mut t, &cx, at(400.0, 300.0));
+ assert_eq!(t.cursor(&cx, at(301.0, 301.0), m), Cursor::PenClose, "on the first anchor");
+ assert_eq!(t.cursor(&cx, at(350.0, 350.0), m), Cursor::Pen, "elsewhere while drawing");
+ }
+
+ #[test]
+ fn anchor_tools_show_pen_state_cursors() {
+ let d = Document::new(&NewDocument::default());
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let p = Point::new(10.0, 10.0);
+ let cursor = |id: &str| create(id).cursor(&cx, p, Mods::default());
+ assert_eq!(cursor("addAnchor"), Cursor::PenAdd);
+ assert_eq!(cursor("deleteAnchor"), Cursor::PenDelete);
+ assert_eq!(cursor("convertDirection"), Cursor::PenConvert);
+ }
diff --cc crates/ui-egui/src/canvas.rs
index af9e4c005,40b146f56..73670b587
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -1317,67 -1415,84 +1437,140 @@@ fn draw_tool_overlays(app: &mut DesignA
painter.rect_filled(r, 3.0, tok.measure_bg);
painter.galley(r.min + vec2(5.0, 3.0), g, tok.measure_text);
}
+ Overlay::PageHandles(r) => {
+ // The Page tool's selected page: outline and eight handles, as InDesign draws them.
+ let r = xf.rect(r);
+ let col = Color32::from_rgb(79, 153, 255);
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, col), StrokeKind::Middle);
+ for i in (0..9).filter(|i| *i != 4) {
+ let c = pos2(r.min.x + r.width() * (i % 3) as f32 / 2.0, r.min.y + r.height() * (i / 3) as f32 / 2.0);
+ let h = Rect::from_center_size(c, vec2(7.0, 7.0));
+ painter.rect_filled(h, 0.0, Color32::WHITE);
+ painter.rect_stroke(h, 0.0, Stroke::new(1.0, col), StrokeKind::Inside);
+ }
+ }
+ Overlay::Tag { p, text } => {
+ let text = crate::i18n::tr(&app.ui.language, &text).to_owned();
+ let s = xf.to_screen(p);
+ let g = painter.layout_no_wrap(text, egui::FontId::proportional(10.0), tok.measure_text);
+ let r = Rect::from_min_size(s - vec2(0.0, g.size().y + 4.0), g.size() + vec2(8.0, 4.0));
+ painter.rect_filled(r, 2.0, tok.measure_bg);
+ painter.rect_stroke(r, 2.0, Stroke::new(1.0, Color32::from_rgb(79, 153, 255)), StrokeKind::Inside);
+ painter.galley(r.min + vec2(4.0, 2.0), g, tok.measure_text);
+ }
+ Overlay::Tip { p, text } => {
+ let text = crate::i18n::tr(&app.ui.language, &text).to_owned();
+ let s = xf.to_screen(p) + vec2(14.0, 14.0);
+ let g = painter.layout(text, egui::FontId::proportional(11.0), tok.measure_text, 260.0);
+ let r = Rect::from_min_size(s, g.size() + vec2(10.0, 6.0));
+ painter.rect_filled(r, 3.0, tok.measure_bg);
+ painter.galley(r.min + vec2(5.0, 3.0), g, tok.measure_text);
+ }
+ Overlay::LiquidPins { object, page, pins, resize } => draw_liquid_pins(painter, xf.rect(object), xf.rect(page), pins, resize),
Overlay::Path { .. } => {}
+ Overlay::ContentGhost(id) => {
+ if let Some(doc) = &doc {
+ draw_content_ghost(painter, xf, doc, &layout, id);
+ }
+ }
}
}
}
+/// A frame's whole content drawn faintly over the canvas, the part outside the frame included,
+/// with its bounds outlined (while the content moves inside the frame).
+fn draw_content_ghost(painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout, id: designcraft_doc::ItemId) {
+ let Some(it) = doc.item(id) else { return };
+ let Some((a, _)) = item_canvas_xf(doc, layout, id) else { return };
+ let outline = Stroke::new(1.0, Color32::from_rgb(196, 111, 43));
+ let Content::Graphic(g) = &it.content else {
+ for c in it.children() {
+ let r = xf.rect((a * it.xf).transform_rect_bbox(c.bounds()));
+ painter.rect_stroke(r, 0.0, outline, StrokeKind::Middle);
+ }
+ return;
+ };
+ let m = a * it.xf * g.xf;
+ let (w, h) = g.size;
+ let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| xf.to_screen(m * p));
+ if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
+ return;
+ }
+ if let Some(tex) = ghost_texture(painter.ctx(), doc, g) {
+ let mut mesh = egui::Mesh::with_texture(tex.id());
+ let tint = Color32::from_white_alpha(90);
+ for (p, uv) in corners.iter().zip([pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]) {
+ mesh.vertices.push(egui::epaint::Vertex { pos: *p, uv, color: tint });
+ }
+ mesh.indices.extend([0, 1, 2, 0, 2, 3]);
+ painter.add(egui::Shape::mesh(mesh));
+ }
+ painter.add(egui::Shape::closed_line(corners.to_vec(), outline));
+}
+
+/// A screen-resolution proxy of a placed graphic for the ghost, cached per asset.
+fn ghost_texture(ctx: &egui::Context, doc: &Document, g: &designcraft_doc::Graphic) -> Option<egui::TextureHandle> {
+ let asset = doc.assets.get(&g.asset)?;
+ let key = egui::Id::new(("content_ghost", std::sync::Arc::as_ptr(&asset.data) as usize, asset.data.len(), asset.page));
+ if let Some(t) = ctx.data(|d| d.get_temp::<egui::TextureHandle>(key)) {
+ return Some(t);
+ }
+ // A 72 ppi proxy is enough for a faint preview.
+ let pm = designcraft_render::images::mip(&asset.data, asset.page, g.size.0, 1.0)?;
+ let (pw, ph) = (pm.width() as usize, pm.height() as usize);
+ let max = ctx.input(|i| i.max_texture_side).min(4096);
+ if pw == 0 || ph == 0 || pw > max || ph > max {
+ return None;
+ }
+ let ci = egui::ColorImage::from_rgba_premultiplied([pw, ph], pm.data_as_u8_slice());
+ let t = ctx.load_texture("content_ghost", ci, egui::TextureOptions::LINEAR);
+ ctx.data_mut(|d| d.insert_temp(key, t.clone()));
+ Some(t)
+}
+
+ /// An object's liquid controls on an object-based page, as InDesign draws them in orange: a
+ /// dashed line across the object for width and height with a padlock (closed: locked), and a pin
+ /// outside each edge (pinned: a line to the page edge).
+ fn draw_liquid_pins(painter: &egui::Painter, o: Rect, page: Rect, pins: [bool; 4], resize: [bool; 2]) {
+ let col = Color32::from_rgb(178, 88, 18);
+ let st = Stroke::new(1.5, col);
+ let c = o.center();
+ let mids = [pos2(c.x, o.min.y), pos2(o.max.x, c.y), pos2(c.x, o.max.y), pos2(o.min.x, c.y)];
+ // The width and height lines between the edges' middles.
+ for (a, b) in [(mids[3], mids[1]), (mids[0], mids[2])] {
+ dashed(painter, a, b, Stroke::new(1.0, col), 3.0, 3.0);
+ }
+ for m in mids {
+ painter.circle_filled(m, 3.5, col);
+ }
+ let (po, lo) = (designcraft_tools::PIN_OFFSET_PX as f32, designcraft_tools::LOCK_OFFSET_PX as f32);
+ let outward = [vec2(0.0, -1.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(-1.0, 0.0)];
+ let edge = [pos2(c.x, page.min.y), pos2(page.max.x, c.y), pos2(c.x, page.max.y), pos2(page.min.x, c.y)];
+ for i in 0..4 {
+ if pins[i] {
+ painter.line_segment([mids[i], edge[i]], st);
+ painter.circle_filled(edge[i], 4.0, col);
+ } else {
+ painter.circle_stroke(mids[i] + outward[i] * po, 4.0, st);
+ }
+ }
+ // Padlocks: the width lock right of the centre, the height lock above it.
+ for (at, locked) in [(c + vec2(lo, 0.0), !resize[0]), (c + vec2(0.0, -lo), !resize[1])] {
+ let body = Rect::from_center_size(at + vec2(0.0, 2.0), vec2(8.0, 6.0));
+ painter.rect_filled(body.expand(1.0), 1.0, Color32::WHITE);
+ painter.rect_filled(body, 1.0, col);
+ // The shackle: over the body when locked, swung open when not.
+ let base = if locked { body.center().x } else { body.center().x + 3.0 };
+ let pts: Vec<_> = (0..=8)
+ .map(|k| {
+ let a = std::f32::consts::PI * k as f32 / 8.0;
+ pos2(base - 2.6 * a.cos(), body.min.y - 3.0 * a.sin())
+ })
+ .collect();
+ painter.add(egui::Shape::line(pts, Stroke::new(1.3, col)));
+ }
+ }
+
#[allow(clippy::too_many_arguments)]
fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens) {
let painter = ui.painter_at(full);
diff --cc crates/ui-egui/src/panels/mod.rs
index 8f6f8dc6d,c88ae30a3..b84aa883d
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -745,31 -787,88 +795,117 @@@ mod font_menu_ui_tests
}
}
+#[cfg(test)]
+mod content_selection_tests {
+ use serde_json::json;
+
+ /// With a placed graphic selected (Direct Selection), X/Y/W/H are the graphic's: what the
+ /// Transform fields then set.
+ #[test]
+ fn a_selected_graphic_shows_its_own_bounds() {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let f = app.run("frame.create", json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].clone();
+ let png = designcraft_render::Rendered { width: 400, height: 400, pixels: vec![200u8; 400 * 400 * 4] }.to_png();
+ let b64 = designcraft_engine::cmd::base64_encode(&png);
+ app.run("file.place", json!({"base64": b64, "name": "a.png", "frame": f})).unwrap();
+ app.run("selection.set", json!({"ids": [f]})).unwrap();
+ let frame = super::sel_info(&app).unwrap().page_rect;
+ assert!((frame.width() - 200.0).abs() < 1e-6, "{frame:?}");
+ app.run("selection.set", json!({"ids": [f], "content": true})).unwrap();
+ // Placing fitted it to 50%: back to its own 400 pt.
+ app.run("transform.set", json!({"scaleX": 100, "scaleY": 100})).unwrap();
+ let g = super::sel_info(&app).unwrap().page_rect;
+ assert!((g.width() - 400.0).abs() < 1e-6, "the graphic's width, not the frame's: {g:?}");
+ // So a width typed from it scales the graphic by that ratio, not by half.
+ app.run("transform.set", json!({"width": 401})).unwrap();
+ let after = super::sel_info(&app).unwrap().page_rect;
+ assert!((after.width() - 401.0).abs() < 1e-6, "{after:?}");
+ }
+}
++
+ #[cfg(test)]
+ mod swatch_list_tests {
+ use super::*;
+
+ fn rects(shapes: &[egui::epaint::ClippedShape]) -> Vec<(egui::Rect, egui::Color32)> {
+ fn walk(s: &egui::Shape, out: &mut Vec<(egui::Rect, egui::Color32)>) {
+ match s {
+ egui::Shape::Rect(r) => out.push((r.rect, r.fill)),
+ egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
+ _ => {}
+ }
+ }
+ let mut out = vec![];
+ shapes.iter().for_each(|s| walk(&s.shape, &mut out));
+ out
+ }
+
+ fn texts(shapes: &[egui::epaint::ClippedShape]) -> Vec<(String, egui::Rect)> {
+ fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
+ match s {
+ egui::Shape::Text(t) => out.push((t.galley.job.text.clone(), t.visual_bounding_rect())),
+ egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
+ _ => {}
+ }
+ }
+ let mut out = vec![];
+ shapes.iter().for_each(|s| walk(&s.shape, &mut out));
+ out
+ }
+
+ #[test]
+ fn the_swatch_under_the_pointer_is_highlighted_and_names_clear_the_scroll_bar() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", serde_json::json!({})).unwrap();
+ // A long name, as process swatches have.
+ app.run("swatch.create", serde_json::json!({"name": "C=15 M=100 Y=100 K=0 Long Name", "color": {"c": 15, "m": 100, "y": 100, "k": 0}}))
+ .unwrap();
+ let long = "C=15 M=100 Y=100 K=0 Long Name";
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx, "");
+ let tokens = Tokens::for_brightness(crate::theme::Brightness::MediumDark);
+ crate::theme::apply(&ctx, &tokens);
+ let mut time = 0.0;
+ let mut frame = |app: &mut DesignApp, events: Vec<egui::Event>| {
+ time += 0.1;
+ let raw = egui::RawInput {
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 700.0))),
+ time: Some(time),
+ events,
+ ..Default::default()
+ };
+ let mut out = ctx.run_ui(raw, |ui| swatch_picker(app, ui, "list", Some("[Black]".into()), |_, _| {}));
+ out.textures_delta.clear();
+ out.shapes
+ };
+ frame(&mut app, vec![]);
+ let chip = egui::pos2(17.0, 17.0);
+ for pressed in [true, false] {
+ frame(
+ &mut app,
+ vec![
+ egui::Event::PointerMoved(chip),
+ egui::Event::PointerButton { pos: chip, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
+ ],
+ );
+ }
+ let shapes = frame(&mut app, vec![]);
+ let (_, name) = texts(&shapes).into_iter().find(|(t, _)| t == "[Registration]").expect("the list is open");
+ let pointer = name.center();
+ frame(&mut app, vec![egui::Event::PointerMoved(pointer)]);
+ let shapes = frame(&mut app, vec![]);
+ let all = rects(&shapes);
+ let (row, _) = *all.iter().find(|(r, c)| *c == tokens.accent_strong && r.contains(pointer)).expect("the hovered row is highlighted");
+ let (list, _) = *all
+ .iter()
+ .filter(|(r, c)| *c == tokens.panel && r.contains_rect(row))
+ .min_by(|a, b| a.0.area().total_cmp(&b.0.area()))
+ .expect("the popup");
+ let scroll = ctx.global_style().spacing.scroll;
+ assert!(row.right() + scroll.bar_width <= list.right(), "rows {row:?} stop short of the scroll bar in {list:?}");
+ let (_, long_rect) = texts(&shapes).into_iter().find(|(t, _)| t == long).unwrap();
+ assert!(long_rect.right() <= row.right(), "the longest name {long_rect:?} fits its row {row:?}");
+ assert!(texts(&shapes).iter().any(|(t, r)| t == "[Black]" && r.right() <= row.right()));
+ }
+ }