Skip to content

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

Merge #572: Eyedropper: sample a placed image's colour into the selected text or objects

aiongg20a14d95f00e
diff --cc ROADMAP.md
index 72834d74b,02437c82d..731d43a21
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -156,45 -132,12 +156,46 @@@ Newest first
- **2026-10-12** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
- **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.
- **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.
+- **2026-10-11** · Document chapter numbering (#341): style, automatic, start at, same as previous
+ document in the book; Update Numbering resolves it in book order.
+- **2026-10-11** · Advanced workspace's object Control panel compacted into aligned two-row
+ groups (#255): spinners, fill/stroke chips, proportion links, corners, Auto-Fit, alignment.
+- **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** · 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** · 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 (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-11** · The View menu follows InDesign's: proofing first, then zoom, Rotate Spread, Screen Mode, Display Performance, rulers, Extras, Grids & Guides and Structure; the view items that sat at the end of the Type menu moved there. No readiness percentage change.
+- **2026-10-11** · Properties › Appearance's Fill and Stroke menus gain InDesign's Tint field and, for a text frame, Apply To: Frame / Text. No readiness percentage change.
+- **2026-10-11** · `story.replaceRange`, `story.setText`, notes, footnotes, endnotes, type on a path and table cells read `\r` and `\r\n` as paragraph returns, as `frame.create` and `text.insert` already did. No readiness percentage change.
+- **2026-10-11** · Corner Options keep curved sides curved and round every corner point, including where an arc meets a line (a Pathfinder quarter circle with rounded corners stayed a triangle). No readiness percentage change.
+- **2026-10-11:** Type › Justification… (Cmd+Alt+Shift+J, also in the Paragraph panel menu) sets word and letter spacing, glyph scaling and the composer on the selected paragraphs, sharing the Paragraph Style Options section (#531). 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-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-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-11** · Japanese captions now cover print ranges, imported style handling and table
+ row/column movement, including row-height distribution. Existing translation and RTL helpers
+ handle the display; command IDs, stored option values and user-defined style names are unchanged.
+- **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-11** · Live corners: the yellow widget on a selected rectangle frame shows corner
+ diamonds; dragging one rounds the corners, Alt-click steps the corner shape (#186).
+- **2026-10-11** · Optical kerning (#181): pairs are spaced from their outlines (ink gap per band,
+ pulled towards the font's stem gap, bounded) instead of silently using the font's kern pairs.
+- **2026-10-11** · New Document laid out like InDesign's (#325): Recent, Saved, Print, Web and
+ Mobile preset tabs beside the preset's details; saved document presets live in the engine
+ (`file.savePreset`, `file.deletePreset`, `file.new {preset}`); `file.new` takes intent, units,
+ start page and per-edge bleed and slug.
+- **2026-10-11** · macOS: fonts that font services and managers activate (Adobe Fonts,
+ RightFont) are listed, read from the files CoreText has available (#261, #327).
+- **2026-10-11:** Document pages take their parent page's margins and columns (left or right parent page by side) and follow its changes unless they have their own; parent ruler guides draw and snap on the pages based on it. IDML import marks a page margin preference that differs from its parent as the page's own. No readiness percentage change.
+- **2026-10-11** · Document Setup laid out like InDesign's: Page Size, Margins (new: every
+ page's, `layout.documentSetup {margins}`), Bleed and Slug with links, Adjust Layout.
+- **2026-10-11** · IDML reads and writes a spread's view rotation (Rotate Spread) as the
+ rotation part of the spread transform (#484).
+- **2026-10-11** · The document grid is drawn (View ▸ Grids & Guides ▸ Show/Hide Document Grid,
+ ⌘'), on the lines Snap to Document Grid uses, behind or in front of page items (#530).
+- **2026-10-12** · Double-clicking the Fill or Stroke box in the Tools panel opens the Color Picker with the selection's colour, as in InDesign (it opened the Swatches panel). No readiness percentage change.
+- **2026-10-11 (DC-1):** Hold Cmd+Space for the Zoom cursor and click/scrubby zoom, with Alt-click to zoom out. Releasing restores the selected tool; text editing and existing tool drags retain their input. Space remains Hand, and navigation changes neither the document nor undo history. 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.
- **2026-10-10** · Version 0.6.0; releases add a Linux riscv64 tar.gz (cross-compiled, CLI
smoke-tested under QEMU).
diff --cc crates/doc/src/lib.rs
index fdd390f58,a643cc08d..9456b5cc4
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@@ -500,81 -450,18 +500,91 @@@ pub struct Asset
/// The page shown from a multi-page PDF (0-based; Image Import Options).
#[serde(default, skip_serializing_if = "is_zero")]
pub page: u32,
+ /// Image Import Options › Crop to: the page box a placed PDF shows.
+ #[serde(default, skip_serializing_if = "PdfCrop::is_crop")]
+ pub pdf_crop: PdfCrop,
+ /// Where the `pdf_crop` box sits on the page as rendered (its visible crop box, rotated as it
+ /// displays): left, top, right, bottom as fractions of the page's width and height. Graphic
+ /// space (0,0)-(w,h) spans this box. `None`: the whole page, or a Bounding Box crop not
+ /// measured yet (`designcraft_render::shown_box` measures it when the graphic is drawn).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pdf_box: Option<[f64; 4]>,
+}
+
+impl Asset {
+ /// The part of the page a placed PDF shows, when [`Asset::pdf_box`] holds a usable box.
+ pub fn shown_box(&self) -> Option<[f64; 4]> {
+ self.shown(self.pdf_box?)
+ }
+
+ /// `b` as the part of the page this asset shows: a usable box of a placed PDF.
+ pub fn shown(&self, b: [f64; 4]) -> Option<[f64; 4]> {
+ // A box under 1/10000 of the page, or far outside it, would blow the page up to sizes
+ // nothing can draw.
+ let usable = b.iter().all(|v| v.is_finite() && v.abs() <= 1e3) && b[2] - b[0] >= 1e-4 && b[3] - b[1] >= 1e-4;
+ (usable && self.mime == "application/pdf").then_some(b)
+ }
+
+ /// A Bounding Box crop ([`PdfCrop::ContentVisible`], [`PdfCrop::ContentAll`]) whose box isn't
+ /// stored yet: finding it needs the page's drawing interpreted.
+ pub fn content_box_pending(&self) -> bool {
+ self.pdf_box.is_none() && matches!(self.pdf_crop, PdfCrop::ContentVisible | PdfCrop::ContentAll) && self.mime == "application/pdf"
+ }
+}
+
+/// Image Import Options › Crop to: which box of a PDF page a placed PDF shows.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum PdfCrop {
+ /// The crop box: the page as PDF readers show it.
+ #[default]
+ Crop,
+ Art,
+ Trim,
+ Bleed,
+ Media,
+ /// The bounds of what the page draws, with the layers the PDF shows by default.
+ ContentVisible,
+ /// The bounds of what the page draws, with every layer on.
+ ContentAll,
+}
+
+impl PdfCrop {
+ pub const ALL: [PdfCrop; 7] =
+ [PdfCrop::ContentVisible, PdfCrop::ContentAll, PdfCrop::Crop, PdfCrop::Art, PdfCrop::Trim, PdfCrop::Bleed, PdfCrop::Media];
+
+ /// The name commands and files use (`crop`, `trim`, `contentVisible`…).
+ pub fn name(self) -> &'static str {
+ match self {
+ PdfCrop::Crop => "crop",
+ PdfCrop::Art => "art",
+ PdfCrop::Trim => "trim",
+ PdfCrop::Bleed => "bleed",
+ PdfCrop::Media => "media",
+ PdfCrop::ContentVisible => "contentVisible",
+ PdfCrop::ContentAll => "contentAll",
+ }
+ }
+
+ pub fn from_name(name: &str) -> Option<PdfCrop> {
+ PdfCrop::ALL.into_iter().find(|c| c.name() == name)
+ }
+
+ fn is_crop(&self) -> bool {
+ *self == PdfCrop::Crop
+ }
}
+ impl Asset {
+ /// A raster image (PNG, JPEG, GIF, WebP, TIFF, BMP, PSD), as opposed to a PDF, EPS or SVG.
+ pub fn is_raster(&self) -> bool {
+ matches!(
+ self.mime.as_str(),
+ "image/png" | "image/jpeg" | "image/gif" | "image/webp" | "image/tiff" | "image/bmp" | "image/vnd.adobe.photoshop"
+ )
+ }
+ }
+
fn is_zero(v: &u32) -> bool {
*v == 0
}
diff --cc crates/engine/src/cmd/style.rs
index b4749fb52,b09e78503..62fefd953
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@@ -181,10 -180,19 +181,19 @@@ pub fn specs() -> Vec<CommandSpec>
"Apply Color",
[],
None,
- "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, text?: bool, ids?} — an unnamed colour on the selected text or objects; `text` also targets the text of selected frames",
- has_text_or_selection,
+ "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, text?: bool, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection; `text`: on the selected text, or the text of the selected frames (Formatting Affects Text)",
+ |s| super::has_text(s).or_else(|_| super::has_selection(s)),
apply_color
),
+ cmd!(
+ "color.sample",
+ "Sample Color (Eyedropper)",
+ [],
+ None,
+ "{at: [x,y] (spread coords), spread?, target?: fill|stroke, ids?} → {color: \"#rrggbb\", swatch, from: image id} — the Eyedropper on a placed image: the image's colour at the point (an unnamed colour) fills the selected text, else the selected objects",
- has_text_or_selection,
++ |s| super::has_text(s).or_else(|_| super::has_selection(s)),
+ sample_color
+ ),
cmd!(
"swatch.addToSwatches",
"Add to Swatches",
@@@ -1072,59 -964,165 +1081,131 @@@ fn apply_gradient(s: &mut Session, p: &
fn apply_color(s: &mut Session, p: &Value) -> Result<Value> {
let color = p.get("color").and_then(parse_color).ok_or_else(|| bad("object.color", "missing or bad color"))?;
let stroke = str_param(p, "target") == Some("stroke");
- let text = p.get("text").and_then(Value::as_bool).unwrap_or(false) || s.doc()?.selection.text.is_some();
- let named = p.get("ids").is_some() || p.get("id").is_some();
- let text = !named
- && (p.get("text").and_then(Value::as_bool).unwrap_or(false) || s.doc()?.selection.text.is_some() || s.doc()?.selection.cells.is_some());
- if text {
- let targets = super::text::format_targets(s);
- // A caret in existing text has no editable range. Refuse it before creating a swatch
- // or history; an empty story has a format run that the next insertion inherits.
- if !targets
++ let text = (p.get("text").and_then(Value::as_bool).unwrap_or(false) || s.doc()?.selection.text.is_some()) && p.get("ids").is_none() && p.get("id").is_none();
+ let (ids, texts) = if text { (vec![], super::text::format_targets_pub(s)) } else { (super::targets(s, p)?, vec![]) };
+ // A caret: the colour is for the next typing (once the swatch exists).
+ let caret = matches!(texts.as_slice(), [t] if t.range.is_empty());
+ let r = s.edit(|d, _| {
+ // Reuse a swatch holding exactly this colour, else add an unnamed one.
+ let existing = d
+ .swatches
.iter()
- .any(|t| !t.range.is_empty() || s.active().is_some_and(|d| d.doc.text_story(t.story, t.cell).is_some_and(|st| st.is_empty())))
- {
- return Err(bad("object.color", "select the text to colour"));
- }
- return s.edit(|d, _| {
- let name = color_swatch(d, color);
- for t in &targets {
- let Some(story) = d.text_story_mut(t.story, t.cell) else { continue };
- let set = |f: &mut designcraft_doc::CharFormat| {
- if stroke {
- (f.over.stroke, f.over.stroke_tint) = (Some(name.clone()), Some(1.0));
- } else {
- (f.over.fill, f.over.fill_tint) = (Some(name.clone()), Some(1.0));
- }
- };
- if t.range.is_empty() {
- if story.is_empty()
- && let Some(run) = story.chars.first_mut()
- {
- set(&mut run.format);
- story.rev = story.rev.wrapping_add(1);
- }
+ .find(|w| matches!(&w.value, SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } if *c == color))
+ .map(|w| w.name.clone());
+ let name = match existing {
+ Some(n) => n,
+ None => {
+ let name = Styles::unique_name(|n| d.swatch(n).is_some(), &value_name(color));
+ d.swatches.push(Swatch {
+ name: name.clone(),
+ value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },
+ locked: false,
+ named: false,
+ hidden: true,
+ });
+ name
+ }
+ };
+ for id in &ids {
+ if let Some(it) = d.item_mut(*id) {
+ if stroke {
+ it.stroke.swatch = name.clone();
+ it.stroke.tint = 1.0;
} else {
- story.format_chars(t.range.clone(), set);
+ it.fill.swatch = name.clone();
+ it.fill.tint = 1.0;
}
}
- Ok(json!({"swatch": name}))
- });
- }
- let ids = super::targets(s, p)?;
- s.edit(|d, _| {
- let name = color_swatch(d, color);
- color_items(d, &ids, &name, stroke);
- Ok(json!({"swatch": name}))
- })
-}
-
-/// A process swatch holding exactly `color`, else a new unnamed one (hidden from the Swatches
-/// panel until Add to Swatches).
-fn color_swatch(d: &mut designcraft_doc::Document, color: designcraft_color::Color) -> String {
- let existing = d
- .swatches
- .iter()
- .find(|w| matches!(&w.value, SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } if *c == color))
- .map(|w| w.name.clone());
- if let Some(n) = existing {
- return n;
- }
- let name = Styles::unique_name(|n| d.swatch(n).is_some(), &value_name(color));
- d.swatches.push(Swatch {
- name: name.clone(),
- value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },
- locked: false,
- named: false,
- hidden: true,
- });
- name
-}
-
-fn color_items(d: &mut designcraft_doc::Document, ids: &[designcraft_doc::ItemId], name: &str, stroke: bool) {
- for id in ids {
- if let Some(it) = d.item_mut(*id) {
- if stroke {
- it.stroke.swatch = name.to_string();
- it.stroke.tint = 1.0;
+ }
+ if !caret {
+ let a = if stroke {
+ CharAttrs { stroke: Some(name.clone()), stroke_tint: Some(1.0), ..Default::default() }
} else {
- it.fill.swatch = name.to_string();
- it.fill.tint = 1.0;
- }
+ CharAttrs { fill: Some(name.clone()), fill_tint: Some(1.0), ..Default::default() }
+ };
+ super::text::apply_char_attrs(d, &texts, &a, &[]);
}
+ Ok(json!({"swatch": name}))
+ })?;
+ if caret && let Some(name) = r.get("swatch").cloned() {
+ let attrs = if stroke { json!({"stroke": name, "strokeTint": 1.0}) } else { json!({"fill": name, "fillTint": 1.0}) };
+ super::text::format_chars(s, &attrs)?;
}
-}
-
-fn has_text_or_selection(s: &Session) -> std::result::Result<(), String> {
- has_doc(s)?;
- if s.active().is_some_and(|d| d.selection.text.is_some() || d.selection.cells.is_some()) { Ok(()) } else { super::has_selection(s) }
+ Ok(r)
}
+ /// The Eyedropper on a placed image (InDesign samples the pixel under the pointer): that colour,
+ /// as an unnamed colour, fills the selected text (characters), or the selected objects.
+ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "color.sample";
+ let at = super::point_param(p, "at").ok_or_else(|| bad(ID, "missing at"))?;
+ let sr = super::spread_param(p, "spread");
+ let st = s.doc()?;
+ let (from, color) = image_color_at(&st.doc, sr, at).ok_or_else(|| bad(ID, "no placed image under the point"))?;
+ let hex = color.to_hex();
+ let mut params = p.clone();
+ params["color"] = json!(hex);
+ let mut result = apply_color(s, &params)?;
+ result["color"] = json!(hex);
+ result["from"] = json!(from.0);
+ Ok(result)
+ }
+
+ /// The colour of the placed raster image at `at` on spread `sr`: the frontmost visible image whose
+ /// frame shows that point (locked ones too, as sampling changes nothing). (image frame, colour);
+ /// None over no image, a transparent pixel, or a graphic that is not a raster (PDF, EPS).
+ pub(crate) fn image_color_at(
+ d: &designcraft_doc::Document,
+ sr: designcraft_doc::SpreadRef,
+ at: designcraft_geom::Point,
+ ) -> Option<(designcraft_doc::ItemId, designcraft_color::Color)> {
+ let sp = d.spread(sr)?;
+ let mut items: Vec<&designcraft_doc::Item> = sp.items.iter().map(|i| &**i).collect();
+ items.sort_by_key(|i| d.layer_rank(i.layer));
+ items
+ .into_iter()
+ .rev()
+ .filter(|it| d.layer(it.layer).is_none_or(|l| l.visible))
+ .find_map(|it| sample_item(d, it, designcraft_geom::Affine::IDENTITY, at, 0))
+ }
+
+ fn sample_item(
+ d: &designcraft_doc::Document,
+ it: &designcraft_doc::Item,
+ outer: designcraft_geom::Affine,
+ at: designcraft_geom::Point,
+ depth: usize,
+ ) -> Option<(designcraft_doc::ItemId, designcraft_color::Color)> {
+ use designcraft_doc::Content;
+ if it.hidden || depth > 64 {
+ return None;
+ }
+ let xf = outer * it.xf;
+ match &it.content {
+ Content::Group { items } => items.iter().rev().find_map(|c| sample_item(d, c, xf, at, depth + 1)),
+ Content::Graphic(g) => {
+ let inner = xf.inverse() * at;
+ if !designcraft_geom::hit::fill_contains(&it.path.to_bezpath(), designcraft_geom::FillRule::NonZero, inner) {
+ return None;
+ }
+ let gp = g.xf.inverse() * inner;
+ let (w, h) = g.size;
+ // Written so that NaN (a degenerate transform) is outside too.
+ if !(w > 0.0 && h > 0.0 && gp.x >= 0.0 && gp.y >= 0.0 && gp.x < w && gp.y < h) {
+ return None;
+ }
+ let asset = d.assets.get(&g.asset).filter(|a| a.is_raster())?;
+ let img = designcraft_images::decode_rgba(&asset.data)?;
+ let (pw, ph) = img.dimensions();
+ let px = ((gp.x / w * f64::from(pw)) as u32).min(pw.checked_sub(1)?);
+ let py = ((gp.y / h * f64::from(ph)) as u32).min(ph.checked_sub(1)?);
+ let [r, gr, b, a] = img.get_pixel_checked(px, py)?.0;
+ (a > 0).then(|| (it.id, designcraft_color::Color::rgb8(r, gr, b)))
+ }
+ _ => None,
+ }
+ }
+
fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let name = match str_param(p, "swatch") {
@@@ -1825,328 -1625,110 +1906,440 @@@ mod cjk_tests
}
}
+#[cfg(test)]
+mod delete_tests {
+ use designcraft_doc::{CellStyle, ObjectStyle, StoryId, Toc, TocEntry};
+ use serde_json::json;
+
+ use crate::Session;
+
+ /// Is `name` still named anywhere in the document?
+ fn named(s: &Session, name: &str) -> bool {
+ serde_json::to_string(&*s.doc().unwrap().doc).unwrap().contains(&format!("\"{name}\""))
+ }
+
+ fn char_doc() -> (Session, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Emphasis", "basedOn": "Base", "chars": {"tracking": 20}})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Child", "basedOn": "Emphasis"})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Strong", "chars": {"size": 14}})).unwrap();
+ let refs = json!({
+ "nestedStyles": [{"style": "Emphasis", "through": true, "count": 1, "until": {"kind": "words"}}],
+ "grepStyles": [{"style": "Emphasis", "pattern": "\\d+"}],
+ "nestedLineStyles": [{"style": "Emphasis", "lines": 1}],
+ "dropCapLines": 2, "dropCapChars": 1, "dropCapStyle": "Emphasis"});
+ s.execute("style.paragraph.create", &json!({"name": "Lead", "para": refs})).unwrap();
+ s.execute("footnote.options", &json!({"refCharStyle": "Emphasis"})).unwrap();
+ let sid = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap()["story"]
+ .as_u64()
+ .unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 2})).unwrap();
+ s.execute("style.character.apply", &json!({"name": "Emphasis"})).unwrap();
+ // Local paragraph overrides name it too.
+ s.execute("type.para", &json!({"attrs": refs})).unwrap();
+ s.edit(|d, _| {
+ d.styles_mut().default_character = "Emphasis".into();
+ Ok(())
+ })
+ .unwrap();
+ assert!(named(&s, "Emphasis"));
+ (s, sid)
+ }
+
+ #[test]
+ fn deleting_a_character_style_points_every_use_at_the_replacement() {
+ let (mut s, sid) = char_doc();
+ let undo = s.doc().unwrap().history.undo.len();
+ s.execute("style.character.delete", &json!({"name": "Emphasis", "replaceWith": "Strong"})).unwrap();
+ assert!(!named(&s, "Emphasis"), "no dangling reference");
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(d.styles.char_style("Child").unwrap().based_on.as_deref(), Some("Strong"));
+ assert_eq!(d.story(StoryId(sid)).unwrap().chars[0].format.style, "Strong");
+ let lead = &d.styles.para("Lead").unwrap().para;
+ assert_eq!(lead.nested_styles.as_ref().unwrap()[0].style, "Strong");
+ assert_eq!(lead.grep_styles.as_ref().unwrap()[0].style, "Strong");
+ assert_eq!(lead.nested_line_styles.as_ref().unwrap()[0].style, "Strong");
+ assert_eq!(lead.drop_cap_style.as_deref(), Some("Strong"));
+ assert_eq!(d.footnote_options.ref_char_style, "Strong");
+ assert_eq!(d.styles.default_character, "Strong");
+ // One undo step brings the style and every use back.
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(s.doc().unwrap().doc.styles.char_style("Emphasis").is_some());
+ assert_eq!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().chars[0].format.style, "Emphasis");
+ }
+
+ #[test]
+ fn deleting_a_character_style_for_none_unsets_based_on() {
+ let (mut s, _) = char_doc();
+ s.execute("style.character.delete", &json!({"name": "Emphasis"})).unwrap();
+ assert!(!named(&s, "Emphasis"), "no dangling reference");
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(d.styles.char_style("Child").unwrap().based_on, None);
+ assert_eq!(d.footnote_options.ref_char_style, designcraft_doc::NO_CHAR_STYLE);
+ }
+
+ /// Replacing a style with its own descendant rebases the deleted style's children on its
+ /// parent, so no based-on chain becomes a cycle.
+ #[test]
+ fn replacing_a_style_with_its_child_makes_no_cycle() {
+ let (mut s, _) = char_doc();
+ s.execute("style.character.create", &json!({"name": "Grandchild", "basedOn": "Child"})).unwrap();
+ s.execute("style.character.delete", &json!({"name": "Emphasis", "replaceWith": "Grandchild"})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(d.styles.char_style("Child").unwrap().based_on.as_deref(), Some("Base"));
+ assert_eq!(d.styles.char_style("Grandchild").unwrap().based_on.as_deref(), Some("Child"));
+ assert!(!named(&s, "Emphasis"));
+ }
+
+ #[test]
+ fn bad_style_deletes_are_errors_and_change_nothing() {
+ let (mut s, _) = char_doc();
+ s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();
+ let before = s.doc().unwrap().doc.clone();
+ let undo = s.doc().unwrap().history.undo.len();
+ for (id, p) in [
+ ("style.character.delete", json!({})),
+ ("style.character.delete", json!({"name": ""})),
+ ("style.character.delete", json!({"name": "Nope"})),
+ ("style.character.delete", json!({"name": "[None]"})),
+ ("style.character.delete", json!({"name": "Emphasis", "replaceWith": "Nope"})),
+ ("style.character.delete", json!({"name": "Emphasis", "replaceWith": "Emphasis"})),
+ ("style.paragraph.delete", json!({})),
+ ("style.paragraph.delete", json!({"name": ""})),
+ ("style.paragraph.delete", json!({"name": "Nope"})),
+ ("style.paragraph.delete", json!({"name": "[Basic Paragraph]"})),
+ ("style.paragraph.delete", json!({"name": "Head", "replaceWith": "Nope"})),
+ ("style.paragraph.delete", json!({"name": "Head", "replaceWith": "Head"})),
+ ] {
+ assert!(s.execute(id, &p).is_err(), "{id} {p}");
+ }
+ assert_eq!(*s.doc().unwrap().doc, *before);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ }
+
+ #[test]
+ fn deleting_a_paragraph_style_points_every_use_at_the_replacement() {
+ let mut s = Session::new();
+ s.execute("file.newSample", &json!({})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Sub", "basedOn": "Table Body", "nextStyle": "Table Body"})).unwrap();
+ s.edit(|d, _| {
+ let story = *d.stories.keys().next().ok_or(crate::EngineError::NoDocument)?;
+ let st = d.styles_mut();
+ st.default_paragraph = "Table Body".into();
+ st.object.push(ObjectStyle { name: "Boxed".into(), paragraph_style: Some("Table Body".into()), ..Default::default() });
+ st.cell.push(CellStyle { name: "Body Cell".into(), paragraph_style: Some("Table Body".into()), ..Default::default() });
+ d.footnote_options.para_style = "Table Body".into();
+ d.endnote_options.para_style = "Table Body".into();
+ d.endnote_options.heading_style = "Table Body".into();
+ d.toc =
+ Some(Toc { story, title: "Contents".into(), entries: vec![TocEntry { style: "Table Body".into(), level: 1 }], page_numbers: false });
+ Ok(())
+ })
+ .unwrap();
+ assert!(named(&s, "Table Body"));
+ s.execute("style.paragraph.delete", &json!({"name": "Table Body", "replaceWith": "Body"})).unwrap();
+ assert!(!named(&s, "Table Body"), "no dangling reference");
+ let d = s.doc().unwrap().doc.clone();
+ let sub = d.styles.para("Sub").unwrap();
+ assert_eq!((sub.based_on.as_deref(), sub.next_style.as_deref()), (Some("Body"), Some("Body")));
+ assert_eq!(d.styles.default_paragraph, "Body");
+ assert_eq!(d.endnote_options.heading_style, "Body");
+ let after = s.execute("preflight.run", &json!({})).unwrap();
+ assert!(!after.to_string().contains("Table Body"), "{after}");
+ }
+}
+
+#[cfg(test)]
+mod swatch_options_tests {
+ use designcraft_color::SwatchValue;
+ use designcraft_doc::{ItemId, StoryId};
+ use serde_json::json;
+
+ use crate::Session;
+
+ /// A document whose frame, text, styles, tint swatch and colour group all use "Brand".
+ fn brand_doc() -> (Session, u64, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("swatch.create", &json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 100, "k": 0}})).unwrap();
+ s.execute("swatch.create", &json!({"name": "Other", "color": "#108080"})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hello"})).unwrap();
+ let (id, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());
+ s.execute("object.fill", &json!({"swatch": "Brand", "ids": [id]})).unwrap();
+ s.execute("object.stroke", &json!({"swatch": "Brand", "ids": [id]})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 3})).unwrap();
+ s.execute("type.char", &json!({"attrs": {"fill": "Brand"}})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 5, "focus": 5})).unwrap();
+ s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
+ s.execute("table.select", &json!({"what": "table"})).unwrap();
+ s.execute("table.setCell", &json!({"stroke": {"weight": 2, "type": "dashed", "gapColor": "Brand", "edges": ["all"]}})).unwrap();
+ s.execute("swatch.newColorGroup", &json!({"name": "Brand Colors", "swatches": ["Brand"]})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Accent"})).unwrap();
+ s.edit(|d, _| {
+ d.swatches.push(designcraft_color::Swatch {
+ name: "Brand 50%".into(),
+ value: SwatchValue::Tint { base: "Brand".into(), tint: 0.5 },
+ locked: false,
+ named: true,
+ hidden: false,
+ });
+ let st = d.styles_mut();
+ if let Some(p) = st.para_mut(designcraft_doc::BASIC_PARAGRAPH) {
+ p.chars.underline_color = Some("Brand".into());
+ p.para.shading_color = Some("Brand".into());
+ p.para.border_gap_color = Some("Brand".into());
+ p.chars.ruby_stroke = Some("Brand".into());
+ }
+ if let Some(c) = st.char_style_mut("Accent") {
+ c.chars.fill = Some("Brand".into());
+ c.chars.kenten_fill = Some("Brand".into());
+ }
+ Ok(())
+ })
+ .unwrap();
+ (s, id, sid)
+ }
+
+ fn uses(s: &Session, id: u64, sid: u64, name: &str) -> Vec<bool> {
+ let d = &s.doc().unwrap().doc;
+ let it = d.item(ItemId(id)).unwrap();
+ let story = d.story(StoryId(sid)).unwrap();
+ let basic = d.styles.para(designcraft_doc::BASIC_PARAGRAPH).unwrap();
+ vec![
+ it.fill.swatch == name,
+ it.stroke.swatch == name,
+ story.chars.iter().any(|r| r.format.over.fill.as_deref() == Some(name)),
+ basic.chars.underline_color.as_deref() == Some(name),
+ basic.para.shading_color.as_deref() == Some(name),
+ d.styles.char_style("Accent").unwrap().chars.fill.as_deref() == Some(name),
+ matches!(&d.swatch("Brand 50%").unwrap().value, SwatchValue::Tint { base, .. } if base == name),
+ d.color_groups[0].swatches == [name],
+ basic.para.border_gap_color.as_deref() == Some(name),
+ basic.chars.ruby_stroke.as_deref() == Some(name),
+ d.styles.char_style("Accent").unwrap().chars.kenten_fill.as_deref() == Some(name),
+ story.tables.values().any(|t| t.cells.iter().all(|c| c.strokes.iter().all(|e| e.gap_color == name))),
+ ]
+ }
+
+ #[test]
+ fn renaming_a_swatch_renames_every_use_in_one_undo_step() {
+ let (mut s, id, sid) = brand_doc();
+ assert!(uses(&s, id, sid, "Brand").iter().all(|u| *u));
+ let r = s.execute("swatch.options", &json!({"name": "Brand", "to": "Signal Orange", "spot": true})).unwrap();
+ assert_eq!(r["name"], "Signal Orange");
+ let d = &s.doc().unwrap().doc;
+ assert!(d.swatch("Brand").is_none());
+ assert!(matches!(d.swatch("Signal Orange").unwrap().value, SwatchValue::Color { color_type: designcraft_color::ColorType::Spot, .. }));
+ assert_eq!(uses(&s, id, sid, "Signal Orange"), vec![true; 12]);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(s.doc().unwrap().doc.swatch("Brand").is_some());
+ assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 12]);
+ }
+
+ #[test]
+ fn bad_swatch_renames_change_nothing() {
+ let (mut s, id, sid) = brand_doc();
+ let before = s.doc().unwrap().doc.clone();
+ for p in [
+ json!({"name": "Brand", "to": "Other"}),
+ json!({"name": "Brand", "to": " "}),
+ json!({"name": "Brand", "to": "[Paper]"}),
+ json!({"name": "[Black]", "to": "Ink"}),
+ json!({"name": "[Registration]", "to": "Reg"}),
+ json!({"name": "[None]", "to": "Nothing"}),
+ json!({"name": "[Black]", "color": "#ff0000"}),
+ json!({"name": "Brand 50%", "color": "#ff0000"}),
+ json!({"name": "Missing", "to": "X"}),
+ ] {
+ assert!(s.execute("swatch.options", &p).is_err(), "{p}");
+ }
+ assert_eq!(s.doc().unwrap().doc.swatches, before.swatches);
+ assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 12]);
+ // [Paper]'s colour can change; its name can't.
+ s.execute("swatch.options", &json!({"name": "[Paper]", "to": "[Paper]", "color": "#fff8e0"})).unwrap();
+ }
+
+ #[test]
+ fn name_with_color_value_tracks_the_colour() {
+ let (mut s, id, sid) = brand_doc();
+ let r = s.execute("swatch.options", &json!({"name": "Brand", "nameWithValue": true, "color": {"c": 10, "m": 20, "y": 30, "k": 40}})).unwrap();
+ assert_eq!(r["name"], "C=10 M=20 Y=30 K=40");
+ assert_eq!(uses(&s, id, sid, "C=10 M=20 Y=30 K=40"), vec![true; 12]);
+ // Later colour edits keep the name in step until the swatch is named by hand.
+ let r = s.execute("swatch.options", &json!({"name": "C=10 M=20 Y=30 K=40", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap();
+ assert_eq!(r["name"], "C=0 M=0 Y=0 K=50");
+ let r = s.execute("swatch.options", &json!({"name": "C=0 M=0 Y=0 K=50", "to": "Warm Gray"})).unwrap();
+ assert_eq!(r["name"], "Warm Gray");
+ assert!(s.doc().unwrap().doc.swatch("Warm Gray").unwrap().named);
+ }
+}
+
+#[cfg(test)]
+mod grep_style_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn grep_style_pattern_that_cannot_compile_is_rejected() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Keep"})).unwrap();
+ let bad = json!([{"style": "Keep", "pattern": "(\\d+"}]);
+ let e = s.execute("style.paragraph.create", &json!({"name": "Broken", "para": {"grepStyles": bad}})).unwrap_err().to_string();
+ assert!(e.contains("bad GREP") && e.contains("(\\\\d+"), "{e}");
+ assert!(s.doc().unwrap().doc.styles.para("Broken").is_none());
+
+ // The lookbehind dialect compiles.
+ let good = json!([{"style": "Keep", "pattern": "(?<=\\s)[aiouwzAIOUWZ]\\s"}]);
+ s.execute("style.paragraph.create", &json!({"name": "Polish", "para": {"grepStyles": good}})).unwrap();
+ let e = s.execute("style.paragraph.edit", &json!({"name": "Polish", "para": {"grepStyles": bad, "spaceAfter": 6}})).unwrap_err().to_string();
+ assert!(e.contains("bad GREP"), "{e}");
+ let st = s.doc().unwrap().doc.styles.para("Polish").unwrap().clone();
+ assert_eq!(st.para.grep_styles.unwrap()[0].pattern, "(?<=\\s)[aiouwzAIOUWZ]\\s");
+ assert_eq!(st.para.space_after, None, "nothing changes");
+
+ // A paragraph override too.
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Ala i kot"})).unwrap();
+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
+ let e = s.execute("type.para", &json!({"grepStyles": bad})).unwrap_err().to_string();
+ assert!(e.contains("bad GREP"), "{e}");
+ }
+
+ #[test]
+ fn idml_import_keeps_a_broken_grep_style_and_warns() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Keep"})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Broken"})).unwrap();
+ // Written past the command, as another application could.
+ s.edit(|d, _| {
+ if let Some(st) = d.styles_mut().para_mut("Broken") {
+ st.para.grep_styles = Some(vec![designcraft_doc::GrepStyle { style: "Keep".into(), pattern: "[a-".into() }]);
+ }
+ Ok(())
+ })
+ .unwrap();
+ let b64 = s.execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
+ let r = s.execute("file.openIdml", &json!({"base64": b64})).unwrap();
+ let warnings = r["warnings"].to_string();
+ assert!(warnings.contains("Broken") && warnings.contains("[a-") && warnings.contains("bad GREP"), "{warnings}");
+ let st = s.doc().unwrap().doc.styles.para("Broken").unwrap().clone();
+ assert_eq!(st.para.grep_styles.unwrap()[0].pattern, "[a-", "the style opens with its pattern");
+ }
+}
++
+ #[cfg(test)]
+ mod sample_color_tests {
+ use designcraft_color::{Color, SwatchValue};
+ use designcraft_doc::ItemId;
+ use serde_json::json;
+
+ use crate::Session;
+
+ /// A 2×1 image, red then blue, placed 144 pt wide at (72, 72): each pixel is 72 pt.
+ fn session_with_image() -> (Session, u64) {
+ let png = designcraft_render::Rendered { width: 2, height: 1, pixels: vec![255, 0, 0, 255, 0, 0, 255, 255] }.to_png();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let b64 = super::super::file::base64_encode(&png);
+ let r = s.execute("file.place", &json!({"base64": b64, "name": "rb.png", "x": 72, "y": 72, "width": 144})).unwrap();
+ (s, r["id"].as_u64().unwrap())
+ }
+
+ fn swatch_color(s: &Session, name: &str) -> Color {
+ match &s.doc().unwrap().doc.swatch(name).unwrap().value {
+ SwatchValue::Color { color, .. } => *color,
+ other => panic!("{other:?}"),
+ }
+ }
+
+ #[test]
+ fn the_eyedropper_colours_selected_text_with_the_image_under_it() {
+ let (mut s, image) = session_with_image();
+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 500, 360], "content": "text", "text": "Elevate."})).unwrap();
+ let fid = ItemId(f["id"].as_u64().unwrap());
+ let story = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;
+ s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 7})).unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ let r = s.execute("color.sample", &json!({"at": [180, 100]})).unwrap();
+ assert_eq!((r["color"].as_str(), r["from"].as_u64()), (Some("#0000ff"), Some(image)), "{r}");
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
+ let name = r["swatch"].as_str().unwrap().to_string();
+ assert_eq!(swatch_color(&s, &name), Color::rgb8(0, 0, 255));
+ assert!(s.doc().unwrap().doc.swatch(&name).unwrap().hidden, "an unnamed colour");
+ let st = s.doc().unwrap().doc.story(story).unwrap().clone();
+ assert_eq!(st.format_after(0).over.fill.as_deref(), Some(name.as_str()));
+ assert_eq!(st.format_after(7).over.fill, None, "the full stop keeps its colour");
+ // The frame itself is not coloured.
+ assert!(s.doc().unwrap().doc.item(fid).unwrap().fill.is_none());
+ }
+
+ #[test]
+ fn the_eyedropper_fills_selected_objects_and_samples_locked_images() {
+ let (mut s, _) = session_with_image();
+ let lid = s.doc().unwrap().doc.layers[0].id.0;
+ s.execute("layer.set", &json!({"id": lid, "locked": true})).unwrap();
+ s.execute("layer.new", &json!({"name": "TEXT"})).unwrap();
+ let rect = s.execute("frame.create", &json!({"rect": [300, 300, 400, 400]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("selection.set", &json!({"ids": [rect]})).unwrap();
+ let r = s.execute("color.sample", &json!({"at": [100, 100], "target": "stroke"})).unwrap();
+ assert_eq!(r["color"], "#ff0000", "{r}");
+ let it = s.doc().unwrap().doc.item(ItemId(rect)).unwrap().clone();
+ assert_eq!(swatch_color(&s, &it.stroke.swatch), Color::rgb8(255, 0, 0));
+ // Sampling the same colour again reuses its swatch.
+ let again = s.execute("color.sample", &json!({"at": [90, 90]})).unwrap();
+ assert_eq!(again["swatch"], r["swatch"]);
+ }
+
+ #[test]
- fn nothing_to_sample_or_nothing_to_colour_is_refused_without_an_edit() {
++ fn a_caret_takes_the_sample_for_typing_and_nothing_to_sample_is_refused() {
+ let (mut s, _) = session_with_image();
+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 500, 360], "content": "text", "text": "Hi"})).unwrap();
+ let fid = ItemId(f["id"].as_u64().unwrap());
+ let story = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;
+ s.execute("text.select", &json!({"story": story.0, "anchor": 1, "focus": 1})).unwrap();
++ // A caret: the sampled colour is for the next typing.
++ let r = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap();
++ s.execute("text.insert", &json!({"text": "X"})).unwrap();
++ let st = s.doc().unwrap().doc.story(story).unwrap().clone();
++ assert_eq!(st.format_after(1).over.fill.as_deref(), r["swatch"].as_str(), "{r}");
++ assert_eq!(st.format_after(0).over.fill, None, "the text before the caret keeps its colour");
+ let undo = s.doc().unwrap().history.undo.len();
- let caret = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap_err().to_string();
- assert!(caret.contains("select the text"), "{caret}");
+ s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 2})).unwrap();
+ let none = s.execute("color.sample", &json!({"at": [600, 600]})).unwrap_err().to_string();
+ assert!(none.contains("no placed image"), "{none}");
+ // Just past the image's right edge.
+ assert!(s.execute("color.sample", &json!({"at": [216.5, 100]})).is_err());
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ }
+
+ #[test]
+ fn sampling_and_explicit_colour_use_the_same_text_application_path() {
+ for command in ["color.sample", "object.color"] {
+ let (mut s, _) = session_with_image();
+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 500, 360], "content": "text"})).unwrap();
+ let story = designcraft_doc::StoryId(f["story"].as_u64().unwrap());
+ s.execute("text.select", &json!({"story": story.0, "anchor": 0})).unwrap();
+ let undo = s.doc().unwrap().history.undo.len();
+ let r = s.execute(command, &json!({"at": [100, 100], "color": "#ff0000"})).unwrap();
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{command}");
+ s.execute("text.insert", &json!({"text": "Hi"})).unwrap();
+ let text = s.doc().unwrap().doc.story(story).unwrap();
+ assert_eq!(text.format_after(0).over.fill.as_deref(), r["swatch"].as_str(), "empty-story typing: {command}");
+ // Explicit ids override text targeting, including with a text selection active.
+ let fid = ItemId(f["id"].as_u64().unwrap());
+ s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 2})).unwrap();
+ let r = s.execute(command, &json!({"at": [180, 100], "color": "#0000ff", "id": fid.0})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.item(fid).unwrap().fill.swatch, r["swatch"].as_str().unwrap());
+ let text = s.doc().unwrap().doc.story(story).unwrap();
+ assert_ne!(text.format_after(0).over.fill.as_deref(), r["swatch"].as_str(), "text unchanged: {command}");
+ let r = s.execute(command, &json!({"at": [180, 100], "color": "#0000ff", "target": "stroke"})).unwrap();
+ let text = s.doc().unwrap().doc.story(story).unwrap();
+ assert_eq!(text.format_after(0).over.stroke.as_deref(), r["swatch"].as_str(), "selected text stroke: {command}");
+ }
+ }
+ }
diff --cc crates/tools/src/tests.rs
index 6aaa12ce6,0d3981904..6f070ee67
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@@ -742,646 -706,66 +742,714 @@@ fn pen_click_snaps_to_a_guide()
assert!((x - 100.0).abs() < 1e-6, "anchor x {x}");
}
+/// A text frame with overset text (selected), an empty frame and a threaded pair x → y, on page 1.
+struct ThreadDoc {
+ d: Document,
+ l: CanvasLayout,
+ s: Selection,
+ c: Cache,
+ /// The selected text frame.
+ a: ItemId,
+ /// An empty (unassigned) frame.
+ e: ItemId,
+ x: ItemId,
+ y: ItemId,
+}
+
+fn thread_doc() -> ThreadDoc {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let lid = d.default_layer();
+ let (a, _) = d
+ .add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 250.0, 160.0), lid, &"Words flow on. ".repeat(40), ParaFormat::default())
+ .unwrap();
+ let e = ItemId(d.alloc());
+ d.insert_item(SpreadRef::Doc(0), Item::new(e, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 400.0, 250.0, 500.0))), None).unwrap();
+ let (x, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 100.0, 450.0, 160.0), lid, "x", ParaFormat::default()).unwrap();
+ let (y, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 400.0, 450.0, 500.0), lid, "", ParaFormat::default()).unwrap();
+ d.thread(x, y).unwrap();
+ let l = CanvasLayout::new(&d, false);
+ ThreadDoc { s: Selection::items(vec![a]), c: Cache::new(), l, d, a, e, x, y }
+}
+
+impl ThreadDoc {
+ fn cx(&self) -> ToolContext<'_> {
+ ctx(&self.d, &self.s, &self.c, &self.l)
+ }
+ /// Canvas point of a spread-0 point.
+ fn at(&self, x: f64, y: f64) -> Point {
+ self.l.to_canvas(SpreadRef::Doc(0), Point::new(x, y))
+ }
+ fn port(&self, id: ItemId, out: bool) -> Point {
+ thread::port_center(&self.d, &self.l, id, out, 1.0).unwrap()
+ }
+}
+
+fn click(t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point, mods: Mods) -> Vec<Action> {
+ let mut v = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods));
+ v.extend(t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y).with_mods(mods)));
+ v
+}
+
+fn thread_exec(p: serde_json::Value) -> Vec<Action> {
+ vec![Action::Exec("text.thread".into(), p)]
+}
+
+#[test]
+fn out_port_loads_text_and_a_click_threads_an_empty_frame() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ let port = td.port(td.a, true);
+ // The out port sits on the right edge, 12 px above the bottom-right corner.
+ assert!((port - td.at(250.0, 148.0)).hypot() < 1e-9, "{port:?}");
+ // A press just off the port's centre still loads (any zoom: tolerance is in pixels).
+ assert!(click(&mut t, &cx, port + designcraft_geom::Vec2::new(3.0, -3.0), Mods::default()).is_empty());
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);
+ let over_e = td.at(175.0, 450.0);
+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::ThreadLink);
+ // A frame something already threads into can't join; neither can the loaded frame itself.
+ assert_eq!(t.cursor(&cx, td.at(375.0, 450.0), Mods::default()), Cursor::NotAllowed);
+ assert_eq!(t.cursor(&cx, td.at(175.0, 130.0), Mods::default()), Cursor::LoadedText);
+ assert_eq!(click(&mut t, &cx, over_e, Mods::default()), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));
+ // Unloaded again: the cursor and clicks are back to normal.
+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::Arrow);
+}
+
+#[test]
+fn ports_hit_at_any_zoom() {
+ let td = thread_doc();
+ let mut cx = td.cx();
+ cx.zoom = 4.0;
+ let port = thread::port_center(&td.d, &td.l, td.a, false, 4.0).unwrap();
+ assert!((port - td.at(100.0, 100.0 + 14.5 / 4.0)).hypot() < 1e-9);
+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(1.5, 1.5)), Some((td.a, false)));
+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(4.0, 0.0)), None, "8 screen px away at 4×");
+}
+
+#[test]
+fn loaded_click_on_empty_page_makes_a_column_frame() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ let a = click(&mut t, &cx, td.at(200.0, 600.0), Mods::default());
+ assert_eq!(a, thread_exec(serde_json::json!({"from": td.a.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}})));
+}
+
+#[test]
+fn loaded_drag_makes_a_frame_of_that_size_and_shift_autoflows() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let (p0, p1) = (td.at(320.0, 560.0), td.at(470.0, 700.0));
+ let shift = Mods { shift: true, ..Default::default() };
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y).with_mods(shift)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y).with_mods(shift)).is_empty());
+ assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::from_points(p0, p1))]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y).with_mods(shift));
+ assert_eq!(
+ a,
+ thread_exec(
+ serde_json::json!({"from": td.a.0, "rect": [320.0, 560.0, 470.0, 700.0], "spread": {"kind": "doc", "index": 0}, "autoflow": true})
+ )
+ );
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow, "autoflow unloads");
+}
+
+#[test]
+fn loaded_drag_snaps_like_frame_drawing() {
+ let td = thread_doc();
+ let cx = ToolContext { snap: SnapView::FACTORY, ..td.cx() };
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ // Press and release a point or two inside the column's edges: both sides snap to them.
+ let (p0, p1) = (td.at(col.x0 + 1.5, 560.0), td.at(col.x1 - 2.0, 650.0));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y));
+ let Some(Overlay::Marquee(m)) = t.overlays(&cx).first().cloned() else { panic!("no marquee") };
+ assert!((m.x0 - td.at(col.x0, 0.0).x).abs() < 1e-9 && (m.x1 - td.at(col.x1, 0.0).x).abs() < 1e-9, "{m:?}");
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y));
+ let [Action::Exec(id, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!(id, "text.thread");
+ let r: Vec<f64> = p["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ assert_eq!((r[0], r[2]), (col.x0, col.x1), "{p}");
+}
+
+#[test]
+fn alt_click_stays_loaded() {
+ let mut td = thread_doc();
+ let original = td.d.clone();
+ let mut t = create("selection");
+ let alt = Mods { alt: true, ..Default::default() };
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ let empty = td.at(200.0, 600.0);
+ let new_frame_from =
+ |f: ItemId| thread_exec(serde_json::json!({"from": f.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}}));
+ {
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);
+ // The thread failed (the document is unchanged): still loaded from a.
+ assert_eq!(click(&mut t, &cx, empty, alt), new_frame_from(td.a));
+ }
+ // That click's command ran: the next click threads after the frame it added.
+ let (n, _) =
+ td.d.add_text_frame(SpreadRef::Doc(0), Rect::new(col.x0, 600.0, col.x1, col.y1), td.d.default_layer(), "", ParaFormat::default()).unwrap();
+ td.d.thread(td.a, n).unwrap();
+ {
+ let cx = td.cx();
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": n.0, "to": td.e.0})));
+ }
+ // Undone: back on a, not on a's old neighbour or the frame the undo removed.
+ td.d = original;
+ {
+ let cx = td.cx();
+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.a));
+ }
+ // From x, which threads into y: when threading e in between fails, x stays loaded, not y.
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.x, true), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.x.0, "to": td.e.0})));
+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.x));
+}
+
+#[test]
+fn escape_unloads_and_keeps_the_selection() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);
+ // An ordinary click on empty space deselects again.
+ let p = td.at(500.0, 700.0);
+ assert_eq!(
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y)),
+ vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]
+ );
+}
+
+#[test]
+fn loaded_click_on_the_linked_frame_unthreads() {
+ // x is selected; its out port links to y.
+ let td = thread_doc();
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.x, true), Mods::default());
+ let over_y = td.at(375.0, 450.0);
+ assert_eq!(t.cursor(&cx, over_y, Mods::default()), Cursor::Unthread);
+ assert_eq!(
+ click(&mut t, &cx, over_y, Mods::default()),
+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))]
+ );
+ // From y's in port, x is the frame before.
+ let td = ThreadDoc { s: Selection::items(vec![td.y]), ..td };
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.y, false), Mods::default());
+ assert_eq!(
+ click(&mut t, &cx, td.at(375.0, 130.0), Mods::default()),
+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.y.0, "side": "before"}))]
+ );
+}
+
+#[test]
+fn in_port_threads_in_front() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, false), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), Mods::default()), thread_exec(serde_json::json!({"from": td.e.0, "to": td.a.0})));
+}
+
+#[test]
+fn double_click_on_a_port_breaks_its_link() {
+ let td = thread_doc();
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ // A double click sent as such (control channel), and the canvas's second press.
+ let second = |p: Point| [PointerEvent::new(PointerKind::DoubleClick, p.x, p.y), PointerEvent::new(PointerKind::Down, p.x, p.y).with_clicks(2)];
+ let p = td.port(td.x, true);
+ for ev in second(p) {
+ let mut t = create("selection");
+ click(&mut t, &cx, p, Mods::default());
+ let a = t.pointer(&cx, &ev);
+ assert_eq!(a, vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))], "{ev:?}");
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p.x, p.y)).is_empty());
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);
+ // The in port of the first frame has no link: nothing to break.
+ let q = td.port(td.x, false);
+ for ev in second(q) {
+ assert!(t.pointer(&cx, &ev).is_empty(), "{ev:?}");
+ }
+ }
+}
+
+#[test]
+fn clicks_in_a_row_edit_and_select_text() {
+ 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, 300.0, 200.0), lid, "Two words", ParaFormat::default()).unwrap();
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let (x, y) = (150.0 + off.x, 110.0 + off.y);
+ let press = |n: u8| PointerEvent::new(PointerKind::Down, x, y).with_clicks(n);
+ // Selection tool: the second press of a double click edits the text there.
+ let mut t = create("selection");
+ let a = t.pointer(&cx, &press(1));
+ assert!(matches!(&a[0], Action::Exec(id, _) if id == "selection.set"), "{a:?}");
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y));
+ let a = t.pointer(&cx, &press(2));
+ assert_eq!(a.first(), Some(&Action::SwitchTool("type".into())));
+ assert!(matches!(&a[1], Action::Exec(id, p) if id == "text.placeCaret" && p["frame"] == fid.0), "{a:?}");
+ // Type tool: word, line, paragraph, then the story.
+ let mut t = create("type");
+ let unit = |a: Vec<Action>| match a.as_slice() {
+ [Action::Exec(id, p)] if id == "text.selectAt" => p["unit"].as_str().map(str::to_string),
+ [Action::Exec(id, _)] if id == "text.placeCaret" => None,
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(unit(t.pointer(&cx, &press(1))), None);
+ for (n, want) in [(2, "word"), (3, "line"), (4, "paragraph"), (5, "story"), (9, "story")] {
+ assert_eq!(unit(t.pointer(&cx, &press(n))).as_deref(), Some(want), "{n} clicks");
+ }
+ // A double click sent as such (control channel) selects a word too.
+ assert_eq!(unit(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x, y))).as_deref(), Some("word"));
+ // Moving a little while pressed keeps the unit selected.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 2.0, y)).is_empty());
+}
+
+/// 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)),
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ });
+ 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 frame = Selection::items(vec![f]);
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let set = |content: bool| vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": content}))];
+ // The canvas's presses in a row: the first selects the frame, the second its content.
+ let a = t.pointer(&ctx(&d, &Selection::default(), &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": false}))]);
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));
+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(true));
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y)).is_empty());
+ // With the content selected, the first press keeps it and the second selects the frame.
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty());
+ t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(false));
+ // A double click sent as such (control channel) toggles too.
+ let dbl = PointerEvent::new(PointerKind::DoubleClick, at.x, at.y);
+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &dbl), set(true));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &dbl), set(false));
+}
+
+/// A 200 × 150 pt rectangle frame, selected.
+fn live_corner_doc() -> (Document, ItemId) {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0));
+ (d, id)
+}
+
+fn corner_preview(a: &[Action]) -> Vec<(String, f64)> {
+ let p = match a {
+ [Action::Preview(cmd, p)] | [Action::Exec(cmd, p)] if cmd == "object.cornerOptions" => p,
+ other => panic!("{other:?}"),
+ };
+ p["corners"].as_array().unwrap().iter().map(|c| (c["shape"].as_str().unwrap().to_string(), c["size"].as_f64().unwrap())).collect()
+}
+
+fn diamonds(o: &[Overlay]) -> Vec<Point> {
+ o.iter().filter_map(|o| if let Overlay::LiveCornerDiamond(p) = o { Some(*p) } else { None }).collect()
+}
+
+#[test]
+fn live_corners_click_widget_then_drag_rounds_all_corners() {
+ let (d, id) = live_corner_doc();
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let at = |x, y| spread_pt(&l, x, y);
+ let mut t = create("selection");
+ // The widget sits on the right edge, a little below the top-right corner.
+ let w = at(300.0, 111.5);
+ assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(p) if near(*p, w))));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y)), vec![Action::Handled]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y)).is_empty());
+ // Without corner sizes the diamonds sit 12 px along the top and bottom edges.
+ let want = [at(112.0, 100.0), at(288.0, 100.0), at(288.0, 250.0), at(112.0, 250.0)];
+ let got = diamonds(&t.overlays(&cx));
+ assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| near(*g, w)), "{got:?}");
+ assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));
+ // Drag the top-left diamond 20 pt toward the centre.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, want[0].x, want[0].y));
+ assert_eq!(a, vec![Action::Begin("Corner Options".into())]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 20.0, want[0].y + 3.0));
+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 20.0); 4]);
+ // The size stops at half the shorter side.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 500.0, want[0].y));
+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 75.0); 4]);
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, want[0].x + 500.0, want[0].y)), vec![Action::Commit]);
+}
+
+#[test]
+fn live_corners_shift_drag_and_alt_click_change_one_corner() {
+ let (mut d, id) = live_corner_doc();
+ d.item_mut(id).unwrap().corners = designcraft_geom::corners::CornerOptions::uniform(designcraft_geom::corners::CornerShape::Rounded, 30.0);
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let at = |x, y| spread_pt(&l, x, y);
+ let mut t = create("selection");
+ let w = at(300.0, 111.5);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ // With 30 pt corners the diamonds sit 30 pt along the edges.
+ let tr = at(270.0, 100.0);
+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tr)));
+ let shift = Mods { shift: true, ..Default::default() };
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tr.x, tr.y).with_mods(shift));
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, tr.x - 10.0, tr.y).with_mods(shift));
+ let r = |n: f64| ("rounded".to_string(), n);
+ assert_eq!(corner_preview(&a), vec![r(30.0), r(40.0), r(30.0), r(30.0)]);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, tr.x - 10.0, tr.y));
+ // Alt-click steps the bottom-right corner's shape; Shift+Alt steps every corner.
+ let br = at(270.0, 250.0);
+ let alt = Mods { alt: true, ..Default::default() };
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(alt));
+ assert_eq!(corner_preview(&a), vec![r(30.0), r(30.0), ("inverseRounded".to_string(), 30.0), r(30.0)]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, br.x - 30.0, br.y).with_mods(alt)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, br.x - 30.0, br.y)).is_empty());
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(Mods { alt: true, shift: true, ..Default::default() }));
+ assert_eq!(corner_preview(&a), vec![("inverseRounded".to_string(), 30.0); 4]);
+}
+
+#[test]
+fn live_corners_end_on_escape_empty_click_and_other_selection() {
+ let (mut d, id) = live_corner_doc();
+ let other = add_rect(&mut d, Rect::new(400.0, 100.0, 500.0, 200.0));
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let w = spread_pt(&l, 300.0, 111.5);
+ let mut t = create("selection");
+ let enter = |t: &mut Box<dyn Tool>| {
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ assert_eq!(diamonds(&t.overlays(&cx)).len(), 4);
+ };
+ // Escape leaves corner editing and keeps the selection; the next Escape deselects.
+ enter(&mut t);
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Handled]);
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]);
+ // A click on empty canvas.
+ enter(&mut t);
+ let e = spread_pt(&l, 350.0, 400.0);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, e.x, e.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, e.x, e.y));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ // Another selection.
+ enter(&mut t);
+ let s2 = Selection { items: vec![other], ..Default::default() };
+ let cx2 = ctx(&d, &s2, &c, &l);
+ assert!(diamonds(&t.overlays(&cx2)).is_empty());
+ t.pointer(&cx2, &PointerEvent::new(PointerKind::Move, 0.0, 0.0));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ // A frame too small on screen has no widget.
+ let mut far = ctx(&d, &s, &c, &l);
+ far.zoom = 0.1;
+ assert!(!t.overlays(&far).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));
+}
+
+#[test]
+fn live_corner_diamonds_follow_a_rotated_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rotated(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0), 30.0);
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let m = l.xf(SpreadRef::Doc(0)) * d.item(id).unwrap().xf;
+ let mut t = create("selection");
+ // The widget: 11.5 pt from the top-right corner along the turned right edge.
+ let w = m * Point::new(300.0, 111.5);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ let tl = m * Point::new(112.0, 100.0);
+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tl)), "{:?}", t.overlays(&cx));
+ // Dragging along the turned top edge sets the size.
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tl.x, tl.y));
+ let to = m * Point::new(137.0, 100.0);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.x, to.y));
+ let got = corner_preview(&a);
+ assert!(got.iter().all(|(shape, size)| shape == "rounded" && (size - 25.0).abs() < 1e-6), "{got:?}");
+}
+
+#[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);
+}
+
+/// A text frame holding a 3×3 table of 80 pt columns, optionally rotated about its centre.
+fn table_frame(degrees: f64) -> (Document, ItemId) {
+ let mut d = Document::new(&NewDocument::default());
+ let layer = d.default_layer();
+ let (id, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 400.0), layer, "", ParaFormat::default()).unwrap();
+ let tid = d.alloc();
+ d.story_mut(sid).unwrap().insert_table(0, designcraft_doc::Table::new(tid, 3, 3, 0, 0, 240.0));
+ d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate_about(degrees.to_radians(), Point::new(250.0, 250.0));
+ (d, id)
+}
+
+#[test]
+fn type_tool_drags_a_table_column_border() {
+ for degrees in [0.0, 90.0] {
+ let (d, id) = table_frame(degrees);
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let it = d.item(id).unwrap();
+ let sid = it.text_frame().unwrap().story;
+ let cs = c.get(&d, sid, None);
+ let cell = cs.frames[0].tables[0].cell(1, 0).unwrap();
+ let xf = cx.item_canvas_xf(id).unwrap() * d.text_xf(it);
+ let on_border = xf * Point::new(cell.rect.x1 + 1.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let dragged = xf * Point::new(cell.rect.x1 + 21.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let mut t = create("type");
+ let expected = if degrees == 0.0 { Cursor::ResizeH } else { Cursor::ResizeV };
+ assert_eq!(t.cursor(&cx, on_border, Mods::default()), expected);
+ // A click with a 1 px wobble on the border changes nothing.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, on_border.x + 1.0, on_border.y)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, on_border.x + 1.0, on_border.y)).is_empty());
+ // A press on the border starts a resize, not a text selection.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));
+ assert_eq!(a[0], Action::Begin("Resize Column".into()));
+ let Action::Preview(cmd, p) = &a[1] else { panic!("{a:?}") };
+ assert_eq!(
+ (cmd.as_str(), &p["axis"], &p["index"], &p["frame"]),
+ ("table.resizeBorder", &serde_json::json!("column"), &serde_json::json!(0), &serde_json::json!(id.0))
+ );
+ assert!((p["delta"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}");
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)), vec![Action::Commit]);
+ // Esc cancels a drag in progress.
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)).is_empty());
+ // Inside the cell the Type tool places the caret as usual.
+ let inside = xf * Point::new(cell.rect.x0 + 20.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, inside.x, inside.y));
+ assert!(matches!(&a[..], [Action::Exec(cmd, _)] if cmd == "text.placeCaret"), "{a:?}");
+ }
+}
++
+ #[test]
+ fn eyedropper_samples_a_placed_image_and_matches_other_objects() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let photo = ItemId(d.alloc());
+ let mut it = Item::new(photo, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (100.0, 100.0),
+ xf: designcraft_geom::Affine::translate((0.0, 0.0)),
++ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
++ wrap: Default::default(),
+ });
+ d.assets.insert(
+ designcraft_doc::AssetId(1),
+ std::sync::Arc::new(designcraft_doc::Asset {
+ id: designcraft_doc::AssetId(1),
+ name: "photo.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: std::sync::Arc::new(vec![]),
+ pixels: Some((100, 100)),
+ page: 0,
++ pdf_crop: Default::default(),
++ pdf_box: None,
+ }),
+ );
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ // An unfilled text frame over part of the photo lets it show through.
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(150.0, 150.0, 250.0, 250.0), lid, "x", ParaFormat::default()).unwrap();
+ let swatch = add_rect(&mut d, Rect::new(300.0, 100.0, 350.0, 150.0));
+ d.item_mut(swatch).unwrap().fill.swatch = "[Black]".into();
+ let target = add_rect(&mut d, Rect::new(400.0, 100.0, 450.0, 150.0));
+ // The photo's layer is locked: sampling it still works.
+ d.layers.iter_mut().for_each(|l| l.locked = true);
+ let s = Selection { items: vec![target], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("eyedropper");
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ let sample = |x: f64, y: f64| Action::Exec("color.sample".into(), serde_json::json!({"at": [x, y], "spread": {"kind": "doc", "index": 0}}));
+ assert_eq!(a, vec![sample(120.0, 130.0)]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 180.0 + off.x, 180.0 + off.y));
+ assert_eq!(a, vec![sample(180.0, 180.0)], "through the text frame");
+ // A filled object is matched as before (here on a locked layer: not reachable, so nothing).
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y)).is_empty());
+ let mut d2 = d.clone();
+ d2.layers.iter_mut().for_each(|l| l.locked = false);
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": swatch.0}))]);
+ // Vector graphics and missing assets must retain the ordinary attribute-matching path.
+ for mime in ["application/pdf", "application/postscript", "image/svg+xml", "application/octet-stream"] {
+ std::sync::Arc::make_mut(d2.assets.get_mut(&designcraft_doc::AssetId(1)).unwrap()).mime = mime.into();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))], "{mime}");
+ }
+ d2.assets.clear();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))]);
+ }
diff --cc crates/ui-egui/src/i18n.rs
index cd5cd5901,29e5eca8e..4d661a2eb
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@@ -1101,17 -739,10 +1101,21 @@@ const TABLE: &[(&str, [&str; 5])] = &
),
("Apply Cell Style", ["Apply Cell Style", "Apply Cell Style", "Apply Cell Style", "Apply Cell Style", "应用单元格样式"]),
("Apply Color", ["Apply Color", "Apply Color", "Apply Color", "Apply Color", "应用颜色"]),
+ ("Repeat", ["Wiederholen", "Répéter", "Repetir", "繰り返し", "重复"]),
+ ("Count:", ["Anzahl:", "Nombre :", "Recuento:", "繰り返し数:", "计数:"]),
+ ("Create as a grid", ["Als Raster erstellen", "Créer en tant que grille", "Crear como cuadrícula", "グリッドとして作成", "创建为网格"]),
+ ("Rows:", ["Zeilen:", "Rangées :", "Filas:", "行:", "行:"]),
+ ("Vertical:", ["Vertikal:", "Vertical :", "Vertical:", "垂直方向:", "垂直:"]),
+ ("Horizontal:", ["Horizontal:", "Horizontal :", "Horizontal:", "水平方向:", "水平:"]),
+ ("Invalid value", ["Ungültiger Wert", "Valeur non valide", "Valor no válido", "無効な値", "无效值"]),
+ ("Isolate Blending", ["Füllmethode isolieren", "Isoler le mode de fusion", "Aislar fusión", "描画モードを分離", "分离混合"]),
+ ("Knockout Group", ["Aussparungsgruppe", "Groupe de masquage", "Grupo de exclusión", "グループの抜き", "挖空组"]),
+ ("Object:", ["Objekt:", "Objet :", "Objeto:", "オブジェクト:", "对象:"]),
+ ("Group:", ["Gruppe:", "Groupe :", "Grupo:", "グループ:", "编组:"]),
+ (
+ "Sample Color (Eyedropper)",
+ ["Farbe aufnehmen (Pipette)", "Prélever la couleur (Pipette)", "Tomar color (Cuentagotas)", "カラーを抽出 (スポイト)", "取样颜色 (吸管)"],
+ ),
("Apply Condition", ["Apply Condition", "Apply Condition", "Apply Condition", "Apply Condition", "应用条件"]),
(
"Apply Parent to Pages…",
diff --cc crates/ui-egui/src/i18n/ar.rs
index eb77c55e7,fb3b7731d..6d9a23c12
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@@ -1063,17 -1041,7 +1063,18 @@@ pub(super) const TABLE: &[(&str, &str)
("Formatting affects container (J)", "تطبيق التنسيق على الحاوية (J)"),
("Formatting affects text (J)", "تطبيق التنسيق على النص (J)"),
("Apply Color", "تطبيق اللون"),
+ ("Repeat", "تكرار"),
+ ("Count:", "العدد:"),
+ ("Create as a grid", "إنشاء كشبكة"),
+ ("Rows:", "الصفوف:"),
+ ("Vertical:", "رأسي:"),
+ ("Horizontal:", "أفقي:"),
+ ("Invalid value", "قيمة غير صالحة"),
+ ("Isolate Blending", "عزل المزج"),
+ ("Knockout Group", "مجموعة مفرغة"),
+ ("Object:", "الكائن:"),
+ ("Group:", "المجموعة:"),
+ ("Sample Color (Eyedropper)", "أخذ عينة من اللون (القطارة)"),
("Apply None", "إزالة اللون"),
("Height Only", "الارتفاع فقط"),
("Width Only", "العرض فقط"),
diff --cc crates/ui-egui/src/i18n/it.rs
index 2302dd0db,95fbcb44d..5f20fb0d2
--- a/crates/ui-egui/src/i18n/it.rs
+++ b/crates/ui-egui/src/i18n/it.rs
@@@ -417,17 -412,7 +417,18 @@@ pub(super) const TABLE: &[(&str, &str)
("Apply Attributes (Eyedropper)", "Applica attributi (Contagocce)"),
("Apply Cell Style", "Applica stile di cella"),
("Apply Color", "Applica colore"),
+ ("Repeat", "Ripeti"),
+ ("Count:", "Conteggio:"),
+ ("Create as a grid", "Crea come griglia"),
+ ("Rows:", "Righe:"),
+ ("Vertical:", "Verticale:"),
+ ("Horizontal:", "Orizzontale:"),
+ ("Invalid value", "Valore non valido"),
+ ("Isolate Blending", "Isola fusione"),
+ ("Knockout Group", "Gruppo di foratura"),
+ ("Object:", "Oggetto:"),
+ ("Group:", "Gruppo:"),
+ ("Sample Color (Eyedropper)", "Campiona colore (Contagocce)"),
("Apply Condition", "Applica condizione"),
("Apply Parent to Pages…", "Applica pagina mastro alle pagine…"),
("ArtCraft App Page…", "Pagina dell'app ArtCraft…"),
diff --cc crates/ui-egui/src/i18n/ja.rs
index 568fda587,935174345..4643c2166
--- a/crates/ui-egui/src/i18n/ja.rs
+++ b/crates/ui-egui/src/i18n/ja.rs
@@@ -535,15 -414,7 +535,16 @@@ pub(super) const TABLE: &[(&str, &str)
("Apply Attributes (Eyedropper)", "属性を適用 (スポイト)"),
("Apply Cell Style", "セルスタイルを適用"),
("Apply Color", "カラーを適用"),
+ ("Repeat", "繰り返し"),
+ ("Count:", "繰り返し数:"),
+ ("Create as a grid", "グリッドとして作成"),
+ ("Rows:", "行:"),
+ ("Invalid value", "無効な値"),
+ ("Isolate Blending", "描画モードを分離"),
+ ("Knockout Group", "グループの抜き"),
+ ("Object:", "オブジェクト:"),
+ ("Group:", "グループ:"),
+ ("Sample Color (Eyedropper)", "カラーを抽出 (スポイト)"),
("Apply Condition", "条件を適用"),
("Apply Parent to Pages…", "ページに親ページを適用…"),
("ArtCraft App Page…", "ArtCraft アプリページ…"),
diff --cc crates/ui-egui/src/i18n/pt_br.rs
index c284ffcf5,6c383cc8c..11bb4dfeb
--- a/crates/ui-egui/src/i18n/pt_br.rs
+++ b/crates/ui-egui/src/i18n/pt_br.rs
@@@ -1060,17 -1045,7 +1060,18 @@@ pub(super) const TABLE: &[(&str, &str)
("Formatting affects container (J)", "Formatação afeta o contêiner (J)"),
("Formatting affects text (J)", "Formatação afeta o texto (J)"),
("Apply Color", "Aplicar cor"),
+ ("Repeat", "Repetir"),
+ ("Count:", "Contagem:"),
+ ("Create as a grid", "Criar como grade"),
+ ("Rows:", "Linhas:"),
+ ("Vertical:", "Vertical:"),
+ ("Horizontal:", "Horizontal:"),
+ ("Invalid value", "Valor inválido"),
+ ("Isolate Blending", "Isolar mesclagem"),
+ ("Knockout Group", "Grupo de vazamento"),
+ ("Object:", "Objeto:"),
+ ("Group:", "Grupo:"),
+ ("Sample Color (Eyedropper)", "Amostrar cor (Conta-gotas)"),
("Apply None", "Aplicar nenhum"),
("Height Only", "Somente altura"),
("Width Only", "Somente largura"),
diff --cc crates/ui-egui/src/i18n/uk.rs
index 1f9a8309f,6ea43f398..456a719ba
--- a/crates/ui-egui/src/i18n/uk.rs
+++ b/crates/ui-egui/src/i18n/uk.rs
@@@ -418,17 -415,7 +418,18 @@@ pub(super) const TABLE: &[(&str, &str)
("Apply Attributes (Eyedropper)", "Застосувати атрибути (піпетка)"),
("Apply Cell Style", "Застосувати стиль клітинки"),
("Apply Color", "Застосувати колір"),
+ ("Repeat", "Повторення"),
+ ("Count:", "Кількість:"),
+ ("Create as a grid", "Створити як сітку"),
+ ("Rows:", "Рядки:"),
+ ("Vertical:", "Вертикально:"),
+ ("Horizontal:", "Горизонтально:"),
+ ("Invalid value", "Неприпустиме значення"),
+ ("Isolate Blending", "Ізолювати змішування"),
+ ("Knockout Group", "Група вибивання"),
+ ("Object:", "Об’єкт:"),
+ ("Group:", "Група:"),
+ ("Sample Color (Eyedropper)", "Узяти колір (піпетка)"),
("Apply Condition", "Застосувати умову"),
("Apply Parent to Pages…", "Застосувати шаблон до сторінок…"),
("ArtCraft App Page…", "Сторінка програми ArtCraft…"),