DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge pr/689: Ungroup leaves frames with pasted-in content whole; name them by their shape (#689)
aiongg3f489a12739b
diff --cc ROADMAP.mdindex 0e89d3db4,524baa166..d171df3c4--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -128,57 -129,9 +128,58 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+ - **2026-10-13** · Ungroup only takes groups apart: a frame with pasted-in content stays whole (and selected), is named by its shape in the Layers and Properties panels, and offers Convert Shape rather than Ungroup. Non-groups stay selected. 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** · Backspace between two consecutive tables, pasting a table next to a table anchor, and pasting several paragraphs right before one keep every table on its own anchor paragraph. Previously a table was dropped or left without its anchor, and the saved file failed to reopen. No readiness percentage change.+- **2026-10-12** · The engine's atomic writer, used by saves and exports (documents, snippets, books, libraries, swatches, XML, interchange, MCP, desktop and CLI writes), delegates to craft-libs/craft-atomic. Failed writes retain the original; new files follow the umask and replaced files keep their permissions. Recovery checkpoints and package output keep their own no-follow writers. No readiness percentage change.+- **2026-10-13** · New Document has Preview (off by default, kept for the session): a document with the window's settings shows in the workspace and follows them once typing pauses. Create keeps it with a clean undo history and refuses invalid fields; Close removes it and shows the previous document again. The preview takes no Untitled number and writes no recovery data; one edited by a menu or script stays open as a document. No readiness percentage change.+- **2026-10-13** · Object styles carry effects (drop shadow, feather, inner and outer shadows and glows, bevel, satin, gradient and directional feather). New styles from a selection keep its effects, `style.object.edit` changes a style's effects and every item that follows them, `style.object.clearOverrides` returns items to their style, and new frames take their default style's effects. IDML carries only the drop shadow and feather, for ObjectStyles (with their effects category and BasedOn chain) as for items (#653). No readiness percentage change.+- **2026-10-13** · A parent can be based on another parent (`layout.parents.options`). Pages draw the base parent's items, then the parent's, then their own, on screen and in PDF and image export; chains work, cycles are refused, overrides reach base items, `document.inspect` reports `basedOn`, and IDML round-trips it. No readiness percentage change.+- **2026-10-12** · The Effects dialog, as in InDesign: Object › Effects (Transparency…, Drop Shadow… and the rest, and their shortcuts) and the Effects panel's fx button open it on the chosen effect, turned on. Transparency and every effect in one window, in the document's units, with X/Y offsets, Preview on the page, Cancel putting things back, and OK as one undo step (`object.effects`). Shadows default to InDesign's 120° light angle. 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** · 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** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). 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-12** · Text in oval, polygon and other non-rectangular text frames follows the frame's outline: each line is set in the part of its band inside the shape, one inset away from the outline, in every column and in vertical frames; text wrap still applies on top (#646). No readiness percentage change.+- **2026-10-12** · Colour entry: the Color Picker's hex, R/G/B and C/M/Y/K fields and the Color panel's number fields keep typed text until it is complete; panel and picker values are applied on a fixed scale (`{model, …}` colours in 0..1), so M 1 is 1 %. Picking keeps a CMYK colour CMYK; dialogs leave the page behind them undimmed; colours that round to the same swatch name share one swatch (#323). No readiness percentage change.+- **2026-10-12** · Placed photos show in their own colours: embedded ICC profiles (Adobe RGB, ProPhoto, P3, grey) are converted to sRGB on screen, and CMYK JPEGs (including YCCK), CMYK TIFFs and CMYK PSDs go through their embedded CMYK profile or the working CMYK space with the colour settings' intent and black-point compensation, instead of the profile-free formula. Unreadable profiles are ignored. No readiness percentage change.+- **2026-10-12** · Placed Word documents keep their bullets and numbering (#626): `numbering.xml` levels become bullet or numbered paragraphs with Word's number formats, label text, start numbers, restarts and list indents, also when a paragraph style carries the list. No readiness percentage change.+- **2026-10-12** · Text strokes can sit behind the fill: the stroke lies wholly outside the letters at its full weight on screen, in PNG and in PDF, set from the Properties panel or Character Style Options. IDML `StrokeAlignment` on text imports and exports as this setting, so imported text with outside-aligned strokes keeps its letter shapes (#619). No readiness percentage change.+- **2026-10-12** · Type tool: Option/Alt+Left/Right kerns the pair at the caret (manual kerning) or tracks a selection by the Kerning/Tracking increment (Preferences › Units & Increments, 20/1000 em), five times with Cmd/Ctrl; moving by words is Cmd+Left/Right on macOS and Ctrl+Left/Right elsewhere, and Option/Alt+Shift+Left/Right still selects by words (#621). No readiness percentage change.+- **2026-10-12** · Autoflow on Place threads one frame per page column (right to left in a right-to-left story), so text no longer runs across the gutter; pages Smart Text Reflow adds get a primary frame with the page's columns (#625). 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** · Pages panel: double-clicking a parent shows that parent and selects only its row; parent rows show rendered thumbnails. Commands name parents by id, full name, or a prefix only one parent has; an unknown or ambiguous name is an error instead of clearing the page's parent (#624). No readiness percentage change.+- **2026-10-12** · With the Type tool, dragging a table's column or row border resizes it (the double-arrow cursor shows over a border): later columns and rows move along, Shift keeps the table size, and Shift on the right or bottom edge scales every column or row. A dragged row becomes At Least; one undo step per drag, Esc cancels; works in rotated frames and turned spreads. Scripts use `table.resizeBorder`. No readiness percentage change.+- **2026-10-12** · The Tools panel's Fill/Stroke keys work: D (default fill and stroke), X (fill or stroke in front), Shift+X (swap per object, tints included) and / (Apply None), as `color.*` commands; swap and default are one undo step (`object.swapFillStroke`, `object.defaultFillStroke`); the Color panel follows the proxy's fill/stroke choice. 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-11** · Font menu laid out like InDesign's: filters (classification, favourites,+ recently added), families opening to their styles, the selected text as the sample in three+ sizes, Recently Used fonts, Show Similar Fonts and each font's format.+- **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-12** · Edit › Step and Repeat has its InDesign dialog: Repeat (Count, or Rows and Columns with Create as a grid), Offset (Vertical, Horizontal, in ruler units) and Preview, which shows the copies while the dialog is open; Cancel takes them away and OK makes them as one undo step. No readiness percentage change.+- **2026-10-12** · Load Styles: the Paragraph Styles and Character Styles panels load styles from another DesignCraft document or an IDML file, with the styles, swatches and lists they name; a dialog picks the styles and what happens to one the document defines differently (`style.load`). 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** · 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+ frame just added; click the linked frame or double-click a port to break the thread.+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No+ readiness percentage change.+- **2026-10-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.+- **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. 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** · IDML import keeps a font family name exactly as written, trailing spaces included, and font lookup falls back to the name without surrounding spaces; `FontStyle="Nothing"` leaves the style to the paragraph (#558). No readiness percentage change.+- **2026-10-12** · Clipping paths saved with images in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path, inverted or not) clip the image on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (#450). No readiness percentage change.+- **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). No readiness percentage change.+- **2026-10-12** · Hyphenation Zone applies to the Single-line Composer only, as in InDesign. With the default Paragraph Composer, ragged text hyphenates where InDesign does (aper-natem), giving the same line breaks. No readiness percentage change.+- **2026-10-12** · Text frame auto-size: Height Only, Width Only, Height and Width (also keeping proportions) frames grow and shrink to fit their text after edits and IDML import, around their reference point, with minimum sizes and No Line Breaks, in the same undo step (#180). No readiness percentage change.+- **2026-10-12** · Text Frame Options › Balance Columns (`object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`) evens out the columns of the frame a story ends in, from its last column break on; frames the text runs on from fill normally (#609). No readiness percentage change.- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.+- **2026-10-12** · Windows: dragging the window across monitors with different display scales keeps its size instead of growing until it crashes (winit pinned to its 0.30.x backport of the fix). The GPU surface may be as large as the adapter's largest texture (16384 px on DirectX 12, Vulkan and Metal hardware) instead of 8192, and a wgpu error is logged instead of closing the app. No readiness percentage change.- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.- **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.diff --cc crates/engine/src/cmd/object.rsindex 0c8d8d821,c2ca37f2b..1861f9217--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@@ -1549,514 -1419,71 +1549,520 @@@ fn arrange(s: &mut Session, p: &Value)})}-fn group(s: &mut Session, p: &Value) -> Result<Value> {- let ids = targets(s, p)?;- if ids.len() < 2 {- return Err(bad("object.group", "select at least two objects"));+/// An optional non-negative integer parameter; any other value is an error.+fn opt_u64(p: &Value, cmd: &str, key: &str) -> Result<Option<u64>> {+ match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("{key} must be a non-negative integer"))),}- s.edit(|d, sel| {- let sr = d.find(ids[0]).map(|l| l.spread).ok_or(designcraft_doc::DocError::NoItem(ids[0]))?;- // Keep stacking order: collect in z-order.- let order: Vec<ItemId> = d.spread(sr).map(|sp| sp.items.iter().map(|i| i.id).filter(|i| ids.contains(i)).collect()).unwrap_or_default();- let front = d.spread(sr).and_then(|sp| sp.items.iter().position(|i| Some(&i.id) == order.last())).unwrap_or(0);- let layer = d.item(order[0]).map(|i| i.layer).unwrap_or_default();- let mut kids = Vec::new();- for id in &order {- kids.push(d.remove_item_keep_story(*id)?);- }- let gid = ItemId(d.alloc());- let mut g = Item::new(gid, layer, Shape::Group, designcraft_geom::PathData::default());- g.content = Content::Group { items: kids.into_iter().map(Arc::new).collect() };- let at = front + 1 - order.len();- d.insert_item(sr, g, Some(at))?;- *sel = Selection::items(vec![gid]);- Ok(json!({"id": gid.0}))- })}-fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {- let ids = targets(s, p)?;- s.edit(|d, sel| {- let mut out = Vec::new();+/// The sibling list under the group at `parent` (the spread's top level when empty).+fn siblings_mut<'a>(d: &'a mut Document, r: SpreadRef, parent: &[usize]) -> Option<&'a mut Vec<Arc<Item>>> {+ let mut items = &mut d.spread_mut(r)?.items;+ for &i in parent {+ items = Arc::make_mut(items.get_mut(i)?).children_mut()?;+ }+ Some(items)+}++fn reorder(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "object.reorder";+ let mut ids = targets(s, p)?;+ let mut seen = HashSet::new();+ ids.retain(|i| seen.insert(*i));+ let Some(&first) = ids.first() else { return Err(bad(C, "no objects")) };+ let above = opt_u64(p, C, "above")?.map(ItemId);+ let below = opt_u64(p, C, "below")?.map(ItemId);+ let index = opt_u64(p, C, "index")?;+ let layer = opt_u64(p, C, "layer")?.map(designcraft_doc::LayerId);+ if [above.is_some(), below.is_some(), index.is_some()].into_iter().filter(|b| *b).count() > 1 {+ return Err(bad(C, "give only one of above, below and index"));+ }+ let target = above.map(|t| (t, true)).or(below.map(|t| (t, false)));+ let d = s.doc()?.doc.clone();+ let (spread, parent, new_items) = {+ let no_object = |id: ItemId| bad(C, format!("no object {}", id.0));+ let loc = d.find(first).ok_or_else(|| no_object(first))?;+ let Some((_, parent)) = loc.path.split_last() else { return Err(no_object(first)) };+ let parent = parent.to_vec();+ let sibling = |id: ItemId| d.find(id).is_some_and(|l| l.spread == loc.spread && l.path.split_last().is_some_and(|(_, pp)| pp == parent));for id in &ids {- let Some(loc) = d.find(*id) else { continue };- let Some(g) = d.item(*id).cloned() else { continue };- // Only groups come apart: a frame holding pasted-into items stays whole, and objects- // that aren't groups stay selected (as in InDesign).- let Content::Group { items } = &g.content else {- out.push(*id);- continue;- };- if !g.is_group() || loc.path.len() != 1 {- out.push(*id);- continue;+ if d.find(*id).is_none() {+ return Err(no_object(*id));}- let Some(sp) = d.spread_mut(loc.spread) else { continue };- sp.items.remove(loc.path[0]);- for (k, c) in items.iter().enumerate() {- let mut c = (**c).clone();- c.xf = g.xf * c.xf;- out.push(c.id);- sp.items.insert(loc.path[0] + k, Arc::new(c));+ if !sibling(*id) {+ return Err(bad(C, "the objects must be on one spread and in one group"));}}- *sel = Selection::items(out);- ok()- })-}--fn set_flag(s: &mut Session, p: &Value, f: impl Fn(&mut Item), deselect: bool) -> Result<Value> {- let ids = targets(s, p)?;- s.edit(|d, sel| {- for id in &ids {- if let Some(it) = d.item_mut(*id) {- f(it);+ let in_group = !parent.is_empty();+ let group_layer = if in_group {+ let g = d.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: parent.clone() }).ok_or_else(|| no_object(first))?;+ if !g.states.is_empty() {+ return Err(bad(C, "the states of a multi-state object are reordered in the Object States panel"));+ }+ Some(g.layer)+ } else {+ None+ };+ let own_layer = d.item(first).map(|i| i.layer).ok_or_else(|| no_object(first))?;+ let target_layer = match target {+ Some((t, _)) => {+ if ids.contains(&t) {+ return Err(bad(C, "an object can't move next to itself"));+ }+ if d.find(t).is_none() {+ return Err(no_object(t));+ }+ if !sibling(t) {+ return Err(bad(C, "the target must be on the same spread and in the same group"));+ }+ let tl = d.item(t).map(|i| i.layer).ok_or_else(|| no_object(t))?;+ if layer.is_some_and(|l| l != tl) {+ return Err(bad(C, "layer differs from the target's layer"));+ }+ if in_group { own_layer } else { tl }}+ None => layer.unwrap_or(own_layer),+ };+ if d.layer(target_layer).is_none() {+ return Err(bad(C, "no such layer"));}- if deselect {+ if let Some(gl) = group_layer+ && layer.is_some_and(|l| l != gl)+ {+ return Err(bad(C, "group members stay on their group's layer"));+ }+ let items = d.spread(loc.spread).map(|sp| sp.items.clone()).ok_or_else(|| no_object(first))?;+ let items = parent.iter().try_fold(items, |items, &i| items.get(i).map(|g| g.children().to_vec())).ok_or_else(|| no_object(first))?;+ // Moved objects keep their relative stacking order.+ let moved: Vec<Arc<Item>> = items.iter().filter(|i| ids.contains(&i.id)).cloned().collect();+ let rest: Vec<Arc<Item>> = items.iter().filter(|i| !ids.contains(&i.id)).cloned().collect();+ let at = match target {+ Some((t, front)) => {+ let i = rest.iter().position(|x| x.id == t).ok_or_else(|| no_object(t))?;+ if front { i + 1 } else { i }+ }+ None => {+ let k = usize::try_from(index.unwrap_or(0)).map_err(|_| bad(C, "index out of range"))?;+ // Positions of the layer's objects (all siblings in a group), topmost first.+ let stack: Vec<usize> = rest.iter().enumerate().filter(|(_, x)| in_group || x.layer == target_layer).map(|(i, _)| i).rev().collect();+ if k > stack.len() {+ return Err(bad(C, format!("index {k} out of range (0..={})", stack.len())));+ }+ match (stack.get(k), stack.last()) {+ (Some(&i), _) => i + 1,+ (None, Some(&backmost)) => backmost,+ (None, None) => rest.len(),+ }+ }+ };+ let (back, front) = rest.split_at(at.min(rest.len()));+ let moved = moved.into_iter().map(|mut it| {+ if !in_group && it.layer != target_layer {+ set_layer_deep(Arc::make_mut(&mut it), target_layer, 0);+ }+ it+ });+ let new_items: Vec<Arc<Item>> = back.iter().cloned().chain(moved).chain(front.iter().cloned()).collect();+ if new_items.iter().zip(items.iter()).all(|(a, b)| a.id == b.id && a.layer == b.layer) {+ return ok();+ }+ (loc.spread, parent, new_items)+ };+ s.edit(|d, _| {+ let items = siblings_mut(d, spread, &parent).ok_or_else(|| bad(C, "the objects moved"))?;+ *items = new_items;+ ok()+ })+}++/// Sets the layer of `it` and its group members (nesting is bounded).+fn set_layer_deep(it: &mut Item, l: designcraft_doc::LayerId, depth: usize) {+ it.layer = l;+ if depth < 64+ && let Some(kids) = it.children_mut()+ {+ for k in kids {+ set_layer_deep(Arc::make_mut(k), l, depth + 1);+ }+ }+}++/// `object.setLayer`: moves the objects, or the top-level groups of group members, to a layer.+fn set_layer(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "object.setLayer";+ let l = designcraft_doc::LayerId(p.get("layer").and_then(Value::as_u64).ok_or_else(|| bad(C, "missing layer"))?);+ let ids = targets(s, p)?;+ s.edit(|d, _| {+ if d.layer(l).is_none() {+ return Err(bad(C, "no such layer"));+ }+ let mut tops: Vec<ItemId> = Vec::new();+ for id in &ids {+ if let Some(t) = d.top_level_of(*id)+ && !tops.contains(&t)+ {+ tops.push(t);+ }+ }+ for t in &tops {+ if let Some(it) = d.item_mut(*t) {+ set_layer_deep(it, l, 0);+ }+ }+ Ok(json!({"changed": tops.len()}))+ })+}++/// Where a group of `ids` goes: their spread, the path of the group holding them (empty at top+/// level), and their indices in that list, back to front.+struct GroupPlan {+ spread: SpreadRef,+ parent: Vec<usize>,+ indices: Vec<usize>,+}++/// Objects can be grouped when they share a spread and a parent: all top-level, or all in the+/// same group (which then holds the new group). A multi-state object keeps one state per child,+/// so objects inside one stay as they are.+fn group_plan(d: &Document, ids: &[ItemId]) -> std::result::Result<GroupPlan, String> {+ let mut seen = HashSet::new();+ let mut locs = Vec::new();+ for id in ids {+ if seen.insert(*id) {+ locs.push(d.find(*id).ok_or_else(|| format!("no object with id {}", id.0))?);+ }+ }+ if locs.len() < 2 {+ return Err("select at least two objects".into());+ }+ let mut plan: Option<GroupPlan> = None;+ for loc in locs {+ let Some((&i, parent)) = loc.path.split_last() else { return Err("object not found".into()) };+ match &mut plan {+ None => plan = Some(GroupPlan { spread: loc.spread, parent: parent.to_vec(), indices: vec![i] }),+ Some(p) if p.spread == loc.spread && p.parent == parent => p.indices.push(i),+ Some(_) => return Err(GROUP_SAME_LEVEL.into()),+ }+ }+ let Some(mut plan) = plan else { return Err("select at least two objects".into()) };+ if !plan.parent.is_empty() && d.item_at(&ItemLoc { spread: plan.spread, path: plan.parent.clone() }).is_some_and(|g| !g.states.is_empty()) {+ return Err("objects inside a multi-state object can't be grouped".into());+ }+ plan.indices.sort_unstable();+ Ok(plan)+}++const GROUP_SAME_LEVEL: &str = "objects to group must be on the same spread and at the same level (all top-level, or all in the same group)";++/// Menu state of Object › Group: the selection must be groupable.+fn can_group(s: &Session) -> std::result::Result<(), String> {+ has_selection(s)?;+ let st = s.active().ok_or_else(|| "no document open".to_string())?;+ group_plan(&st.doc, &st.selection.items).map(|_| ()).map_err(|_| super::CANT_GROUP_SELECTION.into())+}++fn group(s: &mut Session, p: &Value) -> Result<Value> {+ let ids = targets(s, p)?;+ s.edit(|d, sel| {+ let plan = group_plan(d, &ids).map_err(|e| bad("object.group", e))?;+ let missing = || bad("object.group", "the objects to group are gone");+ let siblings = siblings_mut(d, plan.spread, &plan.parent).ok_or_else(missing)?;+ let (Some(&back), Some(&front)) = (plan.indices.first(), plan.indices.last()) else { return Err(missing()) };+ let layer = siblings.get(back).ok_or_else(missing)?.layer;+ // Keep stacking order: remove front to back, then restore back-to-front order.+ let mut kids = Vec::with_capacity(plan.indices.len());+ for &i in plan.indices.iter().rev() {+ if i >= siblings.len() {+ return Err(missing());+ }+ kids.push(siblings.remove(i));+ }+ kids.reverse();+ let gid = ItemId(d.alloc());+ let mut g = Item::new(gid, layer, Shape::Group, designcraft_geom::PathData::default());+ let at = (front + 1).saturating_sub(kids.len());+ g.content = Content::Group { items: kids };+ let siblings = siblings_mut(d, plan.spread, &plan.parent).ok_or_else(missing)?;+ siblings.insert(at.min(siblings.len()), Arc::new(g));+ *sel = Selection::items(vec![gid]);+ Ok(json!({"id": gid.0}))+ })+}++fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {+ let ids = targets(s, p)?;+ s.edit(|d, sel| {+ let mut out = Vec::new();+ for id in &ids {+ let Some(loc) = d.find(*id) else { continue };+ let Some(g) = d.item(*id).cloned() else { continue };- let Content::Group { items } = &g.content else { continue };- if loc.path.len() != 1 {++ // Only groups come apart: a frame holding pasted-into items stays whole, and objects++ // that aren't groups stay selected (as in InDesign).++ let Content::Group { items } = &g.content else {++ out.push(*id);++ continue;++ };++ if !g.is_group() || loc.path.len() != 1 {++ out.push(*id);+ continue;+ }+ let Some(sp) = d.spread_mut(loc.spread) else { continue };+ sp.items.remove(loc.path[0]);+ for (k, c) in items.iter().enumerate() {+ let mut c = (**c).clone();+ c.xf = g.xf * c.xf;+ out.push(c.id);+ sp.items.insert(loc.path[0] + k, Arc::new(c));+ }+ }+ *sel = Selection::items(out);+ ok()+ })+}++fn text_wrap(s: &mut Session, p: &Value) -> Result<Value> {+ use designcraft_doc::{ContourType, WrapMode, WrapSide};+ let side: Option<WrapSide> = match p.get("side") {+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown side"))?),+ None => None,+ };+ // Detected edges, alpha channels and image paths need the image's pixels or paths, which+ // composition doesn't read; those types aren't offered.+ let contour = match p.get("contour").map(|v| serde_json::from_value::<ContourType>(v.clone())) {+ Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping))) => Some(c),+ Some(_) => return Err(bad("object.textWrap", "unsupported contour type")),+ None => None,+ };+ let mode: Option<WrapMode> = match p.get("mode") {+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown mode"))?),+ None if side.is_some() || contour.is_some() => None,+ None => Some(WrapMode::BoundingBox),+ };+ let off = match p.get("offset") {+ Some(Value::Number(n)) => Some([n.as_f64().unwrap_or(0.0); 4]),+ Some(v) => serde_json::from_value(v.clone()).ok(),+ None => None,+ };+ let invert = p.get("invert").and_then(Value::as_bool);+ let content = match p.get("content").and_then(Value::as_bool) {+ Some(c) => c,+ None => p.get("ids").is_none() && p.get("id").is_none() && s.doc()?.selection.content,+ };+ set_flag(+ s,+ p,+ move |i| {+ let w = match &mut i.content {+ Content::Graphic(g) if content => &mut g.wrap,+ _ => &mut i.wrap,+ };+ if let Some(m) = mode {+ w.mode = m;+ }+ if let Some(o) = off {+ w.offsets = o;+ }+ if let Some(v) = invert {+ w.invert = v;+ }+ if let Some(v) = side {+ w.side = v;+ }+ if let Some(c) = contour {+ w.contour = c;+ }+ // A custom boundary has the offsets built in and replaces the contour, so setting+ // either one rebuilds the wrap from the frame.+ if off.is_some() || contour.is_some() {+ w.path = None;+ }+ },+ false,+ )+}++fn corner_options(s: &mut Session, p: &Value) -> Result<Value> {+ use designcraft_geom::corners::{Corner, CornerOptions, CornerShape};+ let opts = match p.get("corners") {+ Some(v) => {+ let corners: [Corner; 4] =+ serde_json::from_value(v.clone()).map_err(|e| bad("object.cornerOptions", format!("corners: four {{shape, size}} entries ({e})")))?;+ if corners.iter().any(|c| !c.size.is_finite() || c.size < 0.0) {+ return Err(bad("object.cornerOptions", "corner sizes must be finite and not negative"));+ }+ CornerOptions { corners }+ }+ None => {+ let shape = p.get("shape").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or(CornerShape::Rounded);+ CornerOptions::uniform(shape, f64_or(p, "size", 12.0))+ }+ };+ set_flag(s, p, move |i| i.corners = opts, false)+}++/// `object.matchAttributes`: the selected objects (or `ids`) take `from`'s appearance.+pub(super) fn match_attributes(s: &mut Session, p: &Value) -> Result<Value> {+ let from = super::id_param(p, "from").ok_or_else(|| bad("object.matchAttributes", "missing from"))?;+ let src = s.doc()?.doc.item(from).cloned().ok_or(designcraft_doc::DocError::NoItem(from))?;+ set_flag(+ s,+ p,+ move |i| {+ if i.id == src.id {+ return;+ }+ i.fill = src.fill.clone();+ i.stroke = src.stroke.clone();+ i.corners = src.corners;+ i.opacity = src.opacity;+ i.blend = src.blend;+ i.effects = src.effects.clone();+ },+ false,+ )+}++/// `patch` merged into `base`: objects field by field (recursively), anything else replaced.+fn merge_json(base: &mut Value, patch: &Value) {+ match (base, patch) {+ (Value::Object(b), Value::Object(p)) => {+ for (k, v) in p {+ merge_json(b.entry(k.clone()).or_insert(Value::Null), v);+ }+ }+ (b, p) => *b = p.clone(),+ }+}++/// Keep effect values in their ranges: opacities 0–1, sizes and distances ≥ 0, percentages 0–100.+fn sanitize_effects(e: &mut designcraft_doc::Effects) -> Result<()> {+ const ID: &str = "object.effects";+ let len = |v: &mut f64| -> Result<()> {+ if !v.is_finite() {+ return Err(bad(ID, "values must be finite"));+ }+ *v = v.clamp(0.0, 10_000.0);+ Ok(())+ };+ let pct = |v: &mut f64| -> Result<()> {+ if !v.is_finite() {+ return Err(bad(ID, "values must be finite"));+ }+ *v = v.clamp(0.0, 100.0);+ Ok(())+ };+ let ang = |v: &mut f64| -> Result<()> {+ if !v.is_finite() {+ return Err(bad(ID, "values must be finite"));+ }+ *v = (*v + 180.0).rem_euclid(360.0) - 180.0;+ Ok(())+ };+ let op = |v: &mut f32| -> Result<()> {+ if !v.is_finite() {+ return Err(bad(ID, "values must be finite"));+ }+ *v = v.clamp(0.0, 1.0);+ Ok(())+ };+ let ds = &mut e.drop_shadow;+ op(&mut ds.opacity)?;+ ang(&mut ds.angle)?;+ len(&mut ds.distance)?;+ len(&mut ds.size)?;+ pct(&mut ds.spread)?;+ let is = &mut e.inner_shadow;+ op(&mut is.opacity)?;+ ang(&mut is.angle)?;+ len(&mut is.distance)?;+ len(&mut is.size)?;+ pct(&mut is.choke)?;+ let og = &mut e.outer_glow;+ op(&mut og.opacity)?;+ len(&mut og.size)?;+ pct(&mut og.spread)?;+ let ig = &mut e.inner_glow;+ op(&mut ig.opacity)?;+ len(&mut ig.size)?;+ pct(&mut ig.choke)?;+ let bv = &mut e.bevel;+ len(&mut bv.size)?;+ len(&mut bv.depth)?;+ ang(&mut bv.angle)?;+ op(&mut bv.highlight_opacity)?;+ op(&mut bv.shadow_opacity)?;+ let sa = &mut e.satin;+ op(&mut sa.opacity)?;+ ang(&mut sa.angle)?;+ len(&mut sa.distance)?;+ len(&mut sa.size)?;+ len(&mut e.feather)?;+ for w in &mut e.directional_feather.widths {+ len(w)?;+ }+ let gf = &mut e.gradient_feather;+ ang(&mut gf.angle)?;+ op(&mut gf.start)?;+ op(&mut gf.end)?;+ Ok(())+}++fn effects_all(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "object.effects";+ let patch = match p.get("effects") {+ None | Some(Value::Null) => None,+ Some(v @ Value::Object(_)) => Some(v.clone()),+ Some(_) => return Err(bad(ID, "effects must be an object")),+ };+ let opacity = match p.get("opacity") {+ None | Some(Value::Null) => None,+ Some(v) => Some(v.as_f64().filter(|o| o.is_finite()).ok_or_else(|| bad(ID, "opacity must be a number"))?.clamp(0.0, 1.0) as f32),+ };+ let blend = match p.get("blend") {+ None | Some(Value::Null) => None,+ Some(v) => {+ let raw = v.as_str().ok_or_else(|| bad(ID, "blend must be a string"))?;+ Some(BlendMode::parse(raw).ok_or_else(|| bad(ID, format!("unknown blend mode `{raw}`")))?)+ }+ };+ let ids = targets(s, p)?;+ s.edit(|d, _| {+ let mut changed = 0;+ for id in &ids {+ let Some(it) = d.item_mut(*id) else { continue };+ if it.locked {+ continue;+ }+ if let Some(patch) = &patch {+ let mut cur = serde_json::to_value(&it.effects).map_err(|e| bad(ID, e.to_string()))?;+ merge_json(&mut cur, patch);+ let mut fx: designcraft_doc::Effects = serde_json::from_value(cur).map_err(|e| bad(ID, format!("effects: {e}")))?;+ sanitize_effects(&mut fx)?;+ it.effects = fx;+ }+ if let Some(o) = opacity {+ it.opacity = o;+ }+ if let Some(b) = blend {+ it.blend = b;+ }+ changed += 1;+ }+ Ok(json!({"changed": changed}))+ })+}++fn set_flag(s: &mut Session, p: &Value, f: impl Fn(&mut Item), deselect: bool) -> Result<Value> {+ let ids = targets(s, p)?;+ s.edit(|d, sel| {+ for id in &ids {+ if let Some(it) = d.item_mut(*id) {+ f(it);+ }+ }+ if deselect {*sel = Selection::default();}Ok(json!({"changed": ids.len()}))@@@ -4724,43 -3309,64 +4730,80 @@@ mod path_edit_tests}#[cfg(test)]-mod spread_target_tests {- use super::*;+mod effects_command_tests {+ use designcraft_doc::ItemId;+ use serde_json::json;#[test]- fn creating_on_a_parent_spread_and_rejecting_unknown_spreads() {- let mut s = Session::new();- s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();- let parent = json!({"kind": "parent", "index": 0});- let r = s.execute("frame.create", &json!({"spread": parent, "rect": [0, 0, 100, 100]})).unwrap();- let id = ItemId(r["id"].as_u64().unwrap());- assert_eq!(s.doc().unwrap().doc.find(id).unwrap().spread, SpreadRef::Parent(0));- s.execute("line.create", &json!({"spread": parent, "a": [0, 0], "b": [50, 50]})).unwrap();- assert_eq!(s.doc().unwrap().doc.parents[0].items.len(), 2);-- // Each of these used to land on the first body page.- for bad in- [json!("A-Parent"), json!("0"), json!(-1), json!(1.5), json!({"kind": "master", "index": 0}), json!({"kind": "parent"}), json!([0])]+ fn effects_set_together_in_one_undo_step_and_keep_what_is_not_given() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300]})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.dropShadow", &json!({"on": true, "distance": 10, "ids": [id]})).unwrap();+ let undo = s.doc().unwrap().history.undo.len();+ let r = s+ .execute(+ "object.effects",+ &json!({"ids": [id], "opacity": 0.5, "blend": "multiply",+ "effects": {"innerShadow": {"on": true, "angle": 120, "distance": 7, "size": 7}, "dropShadow": {"size": 9}, "feather": 4}}),+ )+ .unwrap();+ assert_eq!(r["changed"], 1);+ let st = s.doc().unwrap();+ assert_eq!(st.history.undo.len(), undo + 1, "one undo step");+ let it = st.doc.item(ItemId(id)).unwrap();+ let e = &it.effects;+ assert!(e.inner_shadow.on && e.inner_shadow.angle == 120.0 && e.inner_shadow.size == 7.0);+ assert!(e.drop_shadow.on && e.drop_shadow.distance == 10.0 && e.drop_shadow.size == 9.0, "untouched fields stay");+ assert_eq!((e.feather, it.opacity, it.blend), (4.0, 0.5, designcraft_color::BlendMode::Multiply));+ // Out of range values are kept in range; garbage changes nothing.+ s.execute("object.effects", &json!({"ids": [id], "effects": {"outerGlow": {"on": true, "opacity": 3, "spread": 400, "size": -5}}})).unwrap();+ let og = s.doc().unwrap().doc.item(ItemId(id)).unwrap().effects.outer_glow.clone();+ assert_eq!((og.opacity, og.spread, og.size), (1.0, 100.0, 0.0));+ let before = s.doc().unwrap().doc.clone();+ for bad in [json!({"effects": {"dropShadow": {"distance": "far"}}}), json!({"effects": 5}), json!({"blend": "loud"}), json!({"opacity": "x"})]{- assert!(s.execute("frame.create", &json!({"spread": bad, "rect": [0, 0, 100, 100]})).is_err(), "frame.create spread {bad}");- assert!(s.execute("line.create", &json!({"spread": bad, "a": [0, 0], "b": [50, 50]})).is_err(), "line.create spread {bad}");+ let mut p = bad.clone();+ p["ids"] = json!([id]);+ assert!(s.execute("object.effects", &p).is_err(), "{bad}");}- assert!(s.doc().unwrap().doc.spreads[0].items.is_empty());+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));}}++ #[cfg(test)]+ mod ungroup_tests {+ use super::*;++ #[test]+ fn ungroup_leaves_frames_with_pasted_in_items_whole() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = |r: Value| ItemId(r["id"].as_u64().unwrap());+ let sq = id(s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap());+ let ell = id(s.execute("frame.create", &json!({"rect": [90, 90, 210, 210], "shape": "ellipse"})).unwrap());+ s.execute("selection.set", &json!({"ids": [sq.0]})).unwrap();+ s.execute("edit.cut", &json!({})).unwrap();+ s.execute("selection.set", &json!({"ids": [ell.0]})).unwrap();+ s.execute("edit.pasteInto", &json!({})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert_eq!(d.item(ell).unwrap().default_label(), "<ellipse>", "named by its shape, not <group>");+ // Ungroup: the frame keeps its content and stays selected.+ s.execute("object.ungroup", &json!({})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!(d.item(ell).unwrap().has_nested_items());+ assert_eq!(d.spreads[0].items.len(), 1);+ assert_eq!(s.doc().unwrap().selection.items, vec![ell]);+ // A real group with the frame in it still comes apart, the frame whole.+ let other = id(s.execute("frame.create", &json!({"rect": [300, 100, 400, 200]})).unwrap());+ s.execute("selection.set", &json!({"ids": [ell.0, other.0]})).unwrap();+ let g = id(s.execute("object.group", &json!({})).unwrap());+ assert_eq!(s.doc().unwrap().doc.item(g).unwrap().default_label(), "<group>");+ s.execute("object.ungroup", &json!({})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!(d.item(g).is_none());+ assert!(d.item(ell).unwrap().has_nested_items());+ assert_eq!(s.doc().unwrap().selection.items.len(), 2);+ d.check().unwrap();+ }+ }