DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge origin/main into codex/gradient-panel-layout
moppeeer2da46a8a3a72
diff --cc ROADMAP.mdindex 4007d15dc,d60a6bf49..c4907534a--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -126,9 -343,52 +343,53 @@@ list) · [roadmap.md](docs/roadmap.md)## Progress log+ - **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.+Newest first.+- **2026-10-13** · The Gradient panel follows InDesign's layout (thumbnail, Type, Location, Angle, Reverse, ramp with midpoint diamonds) and takes swatches dragged from the Swatches panel: dropped on a stop they colour it, elsewhere they add a stop. Stops keep their CMYK through panel edits; `object.gradient` stops accept a `swatch`. No readiness percentage change.+ - **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.+ - **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.+ - **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.+ - **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.+ - **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.+ - **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.+ - **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.+ - **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.+ - **2026-10-15** · Flex Layout (InDesign 2026): Object › Flex Layout (Add to, Convert to, Remove) and a Flex Layout panel laid out as InDesign's, also in Properties. A container lays out its objects by direction, wrap, justification, the alignment grid, Fixed/Auto width and height, padding and spacing, after every edit; Add detects aligned objects (direction, Auto size, Space Between at their spacing); resizing a container reflows its objects instead of scaling them; dragging an object in one reorders it. Montilla Design's tutorial replays step for step. No readiness percentage change.+ - **2026-10-14** · Layout › Margins and Columns and Layout › Create Guides are laid out as InDesign's: Margins in Top/Bottom and Inside/Outside pairs with a link button that makes all four the same, Rows and Columns side by side, Fit Guides to Margins or Page, and a Preview checkbox that shows the change on the canvas before OK. A measurement field works out arithmetic when you leave it (`0.4375 in*2` becomes `0.875 in`). No readiness percentage change.+ - **2026-10-14** · The Pathfinder panel is laid out as InDesign's: Paths (Join, Open, Close, Reverse), Pathfinder, Convert Shape and Convert Point, each a row of icon buttons. Join Path closes an open path or joins two at their nearest ends (`path.join`), and Convert Point makes the selected points plain, corner, smooth or symmetrical (`path.convertPoints`). No readiness percentage change.+ - **2026-10-12** · Linked text files (#597): placed Word, RTF and text files can stay linked; the Links panel shows them OK / Modified / Missing, and Update imports the file again into the same frames with the saved style map (the Links panel asks before replacing edits made in the layout). No readiness percentage change.+ - **2026-10-15** · IDML: the CJK leading model InDesign writes on [No paragraph style] of every document (Aki Below) only applies when the document uses a Japanese composer, as in InDesign; a Western document's paragraphs after a size change no longer sit lower than in InDesign (Montilla Design's Flex Layout file: its captions came out overset). No readiness percentage change.+ - **2026-10-14** · Type › Fill with Placeholder Text fills a frame with paragraphs of a few sentences, as InDesign does, so one paragraph can be styled on its own (it was one long paragraph, and the filler ran sentences together, "interit.Ovid"). No readiness percentage change.+ - **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.+ - **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.+ - **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.+ - **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.+ - **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.+ - **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.+ - **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.+ - **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page/Spread, New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.+ - **2026-10-14** · Pages panel: Alt-drag copies a page, a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.+ - **2026-10-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. No readiness percentage change.++ - **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.+ - **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.+ - **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.+ - **2026-10-13** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. No readiness percentage change.+ - **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.+ - **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.+ - **2026-10-14** · In a facing document, pages take their side from their section's page numbers, as InDesign shuffles them: a section that starts at 1 on a left page moves it to the right and the pages after it follow, with their objects. No readiness percentage change.+ - **2026-10-14** · The Type menu follows InDesign's order (Size, Character ⌘T, Paragraph ⌥⌘T, Glyphs, the style panels, Notes, footnotes and endnotes, then the insert submenus and Show Hidden Characters); Current Page Number has ⌥⇧⌘N. No readiness percentage change.+ - **2026-10-14** · Colour parameters: a bare `{c,m,y,k}` is always read as 0..100, so C 1 is a 1 % tint and no longer+ solid cyan; fractions take the colour's own `{model: "cmyk", …}` form (#910). No readiness percentage change.+ - **2026-10-14** · The Tools panel follows InDesign's: Gradient Swatch and Gradient Feather are tools of their own; in two columns Content Collector and Placer, Apply Color / Gradient / None and Normal / Preview each get a button; View Options holds Frame Edges, Rulers, Guides, Smart Guides, Baseline Grid and Hidden Characters; Apply Color (,) and Apply Gradient (.) reuse the last colour and gradient. No readiness percentage change.+ - **2026-10-13** · Create Outlines makes one compound path per line (and per text colour within a line), grouped, as InDesign does: Ungroup then leaves each line on its own to be spaced and made into one compound path again. A single line in one colour stays a single compound path. No readiness percentage change.+ - **2026-10-13** · Gradient swatches work on strokes: drawn across the path's box on screen and in PDF (they drew nothing), set with `object.gradient {target: stroke}` and in the Gradient panel when the Stroke box is in front; the stroke's gradient vector moves with the shape and round-trips through IDML. No readiness percentage change.+ - **2026-10-13** · Text takes gradient swatches: a gradient fill or stroke on characters spans the text frame's box (on a path: the path's), on screen and in PDF. No readiness percentage change.- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to loadthe text cursor, then click a frame to thread it, click empty space for a column-wide frame ordrag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on thediff --cc crates/engine/src/cmd/style.rsindex 04aa8cd14,1cccc7fd1..2e3ae0da7--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@@ -144,7 -145,7 +145,7 @@@ pub fn specs() -> Vec<CommandSpec>"Gradient",[],None,- "{kind?: linear|radial, stops?: [{location: 0–100, color: \"#rrggbb\"|{c,m,y,k}(0..100)|{gray: 0–100}|[r,g,b](0..255)|{model: rgb|cmyk|gray, …}(0..1) | swatch: name (its colour, as dropped on the Gradient panel), opacity?: 0–100, midpoint?: 13–87}], reverse?: bool, angle?: degrees, from?: [x,y], to?: [x,y] (spread coords: the Gradient Swatch tool's drag), ids?} → {swatch, kind, stops} — edits the fill's gradient (an unnamed gradient unless it equals a gradient swatch)",- "{kind?: linear|radial, stops?: [{location: 0–100, color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b]|{model, …}(0..1), opacity?: 0–100, midpoint?: 13–87}], reverse?: bool, angle?: degrees, from?: [x,y], to?: [x,y] (spread coords: the Gradient Swatch tool's drag), target?: fill|stroke, ids?} → {swatch, kind, stops} — edits the fill's (or the stroke's) gradient (an unnamed gradient unless it equals a gradient swatch)",++ "{kind?: linear|radial, stops?: [{location: 0–100, color: \"#rrggbb\"|{c,m,y,k}(0..100)|{gray: 0–100}|[r,g,b]|{model: rgb|cmyk|gray, …}(0..1) | swatch: name (its colour, as dropped on the Gradient panel), opacity?: 0–100, midpoint?: 13–87}], reverse?: bool, angle?: degrees, from?: [x,y], to?: [x,y] (spread coords: the Gradient Swatch tool's drag), target?: fill|stroke, ids?} → {swatch, kind, stops} — edits the fill's (or the stroke's) gradient (an unnamed gradient unless it equals a gradient swatch)",super::has_selection,apply_gradient),@@@ -756,15 -808,13 +808,19 @@@ pub fn parse_color(v: &Value) -> Optionlet scale = if v.iter().any(|&x| x > 1.0) { 255.0 } else { 1.0 };Some(Color::rgb((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32))}+ // `{model, …}` is the colour's own form (as `color.convert` takes and returns it): fractions.- Value::Object(o) if o.contains_key("model") => serde_json::from_value(v.clone()).ok(),++ // `{model, …}` is the colour's own form (as `color.convert` takes it): fractions, never guessed.++ Value::Object(o) if o.contains_key("model") => model_color(v),+ // Bare CMYK is always 0..100, as documented: C 1 % is a real tint, so values of 1 or less can't+ // mean fractions (#910).Value::Object(o) => {- let g = |k: &str| o.get(k).and_then(Value::as_f64).map(|x| (x / 100.0) as f32);- Some(Color::cmyk(g("c")?, g("m")?, g("y")?, g("k")?))+ let g = |k: &str| o.get(k).and_then(Value::as_f64);+ // {gray: 0–100} is a grey with that much black.+ if let Some(k) = g("gray") {+ return Some(Color::gray((k.clamp(0.0, 100.0) / 100.0) as f32));+ }- let v = [g("c")?, g("m")?, g("y")?, g("k")?];- let scale = if v.iter().any(|&x| x > 1.0) { 100.0 } else { 1.0 };- Some(Color::cmyk((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32, (v[3] / scale) as f32))++ let p = |k: &str| g(k).map(|x| (x / 100.0) as f32);++ Some(Color::cmyk(p("c")?, p("m")?, p("y")?, p("k")?))}_ => None,}diff --cc crates/ui-egui/src/panels/swatches.rsindex 8b7b36412,a21ffdb93..781339a5f--- a/crates/ui-egui/src/panels/swatches.rs+++ b/crates/ui-egui/src/panels/swatches.rs@@@ -125,19 -220,8 +220,20 @@@ fn swatch_rowfill_cur: Option<&str>,) {let t = Tokens::get(ui.ctx());- let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());+ // Rows can be dragged onto the Gradient panel's ramp.+ let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag());+ resp.dnd_set_drag_payload(SwatchDrag(sw.name.clone()));+ if resp.dragged()+ && let Some(p) = ui.ctx().pointer_interact_pos()+ {+ // The swatch's chip follows the pointer.+ let (c, g) = crate::widgets::swatch_colors(doc, &sw.name, 1.0);+ let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("swatch_drag")));+ let chip = egui::Rect::from_min_size(p + vec2(8.0, 8.0), vec2(16.0, 16.0));+ crate::widgets::paint_chip(&painter, chip, c, g);+ painter.rect_stroke(chip, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ }+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &sw.name));if fill_cur == Some(sw.name.as_str()) {ui.painter().rect_filled(row, 0.0, t.row_selected);} else if resp.hovered() {@@@ -402,21 -500,6 +512,21 @@@ fn spectrum(app: &mut DesignApp, ui: &m}}+/// A swatch dragged out of the Swatches panel (the Gradient panel's ramp takes it as a stop).+#[derive(Clone, Debug)]+pub struct SwatchDrag(pub String);++/// A colour in `object.gradient` form, keeping its model (CMYK stays CMYK).+fn color_json(c: &designcraft_color::Color) -> serde_json::Value {+ use designcraft_color::Color;+ match *c {- // Fractions: every component is within 0–1, so they're read back as fractions.- Color::Cmyk { c, m, y, k } => json!({"c": c, "m": m, "y": y, "k": k}),++ // The model form: fractions, read back exactly (bare CMYK is always 0–100).++ Color::Cmyk { c, m, y, k } => json!({"model": "cmyk", "c": c, "m": m, "y": y, "k": k}),+ Color::Gray { k } => json!({"model": "gray", "k": k}),+ Color::Rgb { .. } => json!(c.to_hex()),+ }+}+/// Stops in `object.gradient` form.fn stops_json(g: &designcraft_color::Gradient) -> Vec<serde_json::Value> {g.stops@@@ -425,430 -508,277 +535,523 @@@.collect()}-/// Gradient panel: type, angle, reverse, and the ramp with its stops (drag to move, click below-/// the ramp to add, drag off to remove; the selected stop's location and colour are editable).+fn color32(c: &designcraft_color::Color, alpha: f32) -> egui::Color32 {+ let [r, g, b] = c.to_rgb();+ egui::Color32::from_rgba_unmultiplied((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, (alpha * 255.0) as u8)+}++/// The panel's thumbnail: the gradient in a square, linear across or radial from the centre.+fn thumbnail(p: &egui::Painter, r: egui::Rect, g: &designcraft_color::Gradient, border: egui::Color32) {+ let n = 32;+ if g.kind == designcraft_color::GradientKind::Radial {+ // Rings from the outside in.+ for i in (0..n).rev() {+ let t = (i as f32 + 0.5) / n as f32;+ let (c, a) = g.sample(t);+ let rad = r.width() / 2.0 * std::f32::consts::SQRT_2 * (i + 1) as f32 / n as f32;+ p.with_clip_rect(r).circle_filled(r.center(), rad, color32(&c, a));+ }+ } else {+ for i in 0..n {+ let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);+ let (c, al) = g.sample((a + b) / 2.0);+ let x0 = r.left() + r.width() * a;+ p.rect_filled(egui::Rect::from_x_y_ranges(x0..=r.left() + r.width() * b + 0.5, r.y_range()), 0.0, color32(&c, al));+ }+ }+ p.rect_stroke(r, 0.0, egui::Stroke::new(1.0, border), egui::StrokeKind::Outside);+}++/// What's selected on the ramp: a stop, or the midpoint after a stop.+#[derive(Clone, Copy, PartialEq, Debug)]+enum RampSel {+ Stop(usize),+ Mid(usize),+}++/// A marker being dragged: what, where (0–1), off the panel (stops only).+type RampDrag = (RampSel, f32, bool);++/// The drag kept from the last frame, if it still names a marker of a gradient with `n` stops+/// (the selection or its gradient may have changed since).+fn live_drag(d: Option<RampDrag>, n: usize) -> Option<RampDrag> {+ d.filter(|(h, _, _)| match *h {+ RampSel::Stop(i) => i < n,+ RampSel::Mid(i) => i.saturating_add(1) < n,+ })+}++/// Sets `key` of stop `i` in `object.gradient` stops; nothing if there's no such stop.+fn set_stop(stops: &mut [serde_json::Value], i: usize, key: &str, v: serde_json::Value) {+ if let Some(o) = stops.get_mut(i).and_then(serde_json::Value::as_object_mut) {+ o.insert(key.to_string(), v);+ }+}++/// Gradient panel, laid out as InDesign's: thumbnail, Type, Location and Angle, Reverse, and the+/// ramp with midpoint diamonds above it and stops below it. Drag a stop or a diamond to move it,+/// click below the ramp to add a stop, drag a stop off to remove it, and drop a swatch from the+/// Swatches panel on a stop to colour it or elsewhere on the ramp to add a stop (or right-click a+/// stop for its colour). Until the fill is+/// a gradient the ramp shows the default White → Black, and using it gives the fill a gradient.pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());+ let lang = app.ui.language.clone();let Some(st) = app.session.active() else { return };- let Some(it) = st.selection.items.first().and_then(|i| st.doc.item(*i)) else {- ui.label(crate::rtl::widget(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Select an object to give its fill a gradient.")).color(t.text_dim),- ));- return;- };+ let item = st.selection.items.first().and_then(|i| st.doc.item(*i));+ let has_item = item.is_some();- let fill = item.map(|it| it.fill.clone()).unwrap_or_default();+ // The fill's gradient, or the stroke's when the toolbox's Stroke box is in front (as InDesign's+ // Gradient panel follows the Fill/Stroke proxy).+ let target = if app.ui.stroke_front { "stroke" } else { "fill" };- let fill = if app.ui.stroke_front { it.stroke.as_fill() } else { it.fill.clone() };- let Some(g) = designcraft_color::swatch::resolve_gradient(&st.doc.swatches, &fill.swatch).cloned() else {- crate::rtl::label(- ui,- egui::RichText::new(crate::i18n::tr(- &app.ui.language,- if app.ui.stroke_front { "The stroke isn't a gradient." } else { "The fill isn't a gradient." },- ))- .color(t.text_dim),- );- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Apply Gradient"))).clicked() {- let _ = app.run("object.gradient", json!({"target": target, "target": target}));- }- return;- };++ let fill = item.map(|it| if app.ui.stroke_front { it.stroke.as_fill() } else { it.fill.clone() }).unwrap_or_default();+ let cur = designcraft_color::swatch::resolve_gradient(&st.doc.swatches, &fill.swatch).cloned();+ let is_gradient = cur.is_some();+ let g = cur.unwrap_or_default();let radial = g.kind == designcraft_color::GradientKind::Radial;- ui.horizontal(|ui| {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Type:"));- egui::ComboBox::from_id_salt("grad_type")- .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, g.kind.label())))- .width(100.0)- .show_ui(ui, |ui| {- for (k, v) in [("Linear", "linear"), ("Radial", "radial")] {- if ui.selectable_label(g.kind.label() == k, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, k))).clicked() {- let _ = app.run("object.gradient", json!({"target": target, "kind": v}));+ let sel_id = egui::Id::new("grad_sel");+ let drag_id = egui::Id::new("grad_drag");+ let mut sel: RampSel = ui.data(|d| d.get_temp(sel_id)).unwrap_or(RampSel::Stop(0));+ let last = g.stops.len().saturating_sub(1);+ sel = match sel {+ RampSel::Stop(i) => RampSel::Stop(i.min(last)),+ RampSel::Mid(i) if i < last => RampSel::Mid(i),+ RampSel::Mid(_) => RampSel::Stop(0),+ };+ let mut send: Option<serde_json::Value> = None;+ // The ramp spans the panel, however wide the rows above are.+ let full = ui.available_width().max(60.0);+ ui.add_enabled_ui(has_item, |ui| {+ ui.horizontal(|ui| {+ let (r, resp) = ui.allocate_exact_size(vec2(34.0, 34.0), Sense::click());+ thumbnail(ui.painter(), r.shrink(1.0), &g, t.field_border);+ // Clicking the thumbnail applies the gradient shown (InDesign's way to start one).+ if resp.clicked() && !is_gradient {+ send = Some(json!({}));+ }+ ui.add_space(4.0);+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ ui.horizontal(|ui| {+ crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Type:"), 52.0);+ let shown = if is_gradient { crate::i18n::tr(&lang, g.kind.label()) } else { "" };+ egui::ComboBox::from_id_salt("grad_type").selected_text(crate::rtl::widget(ui, shown)).width(104.0).show_ui(ui, |ui| {+ for (k, v) in [("Linear", "linear"), ("Radial", "radial")] {+ if ui.selectable_label(is_gradient && g.kind.label() == k, crate::rtl::widget(ui, crate::i18n::tr(&lang, k))).clicked() {+ send = Some(json!({"kind": v}));+ }+ }+ });+ });+ ui.horizontal(|ui| {+ crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Location:"), 52.0);+ let loc = match sel {+ RampSel::Stop(i) => g.stops.get(i).map(|s| s.offset as f64 * 100.0),+ RampSel::Mid(i) => g.stops.get(i).map(|s| s.midpoint as f64 * 100.0),+ };+ if let Some(v) = crate::widgets::number(ui, "grad_loc", loc.filter(|_| is_gradient), "", 50.0, 3) {+ let mut stops = stops_json(&g);+ match sel {+ RampSel::Stop(i) => set_stop(&mut stops, i, "location", json!(v.clamp(0.0, 100.0))),+ RampSel::Mid(i) => set_stop(&mut stops, i, "midpoint", json!(v.clamp(13.0, 87.0))),+ }+ send = Some(json!({"stops": stops}));}- }+ crate::widgets::caption(ui, "%");+ ui.add_space(4.0);+ crate::widgets::caption(ui, crate::i18n::tr(&lang, "Angle:"));+ let angle =+ fill.gradient_vector.map(|[x0, y0, x1, y1]| (-(y1 - y0)).atan2(x1 - x0).to_degrees()).or(fill.gradient_angle).unwrap_or(0.0);+ ui.add_enabled_ui(is_gradient && !radial, |ui| {+ if let Some(v) = crate::widgets::number(ui, "grad_angle", is_gradient.then_some(angle), "°", 44.0, 1) {+ send = Some(json!({"angle": v}));+ }+ });+ });+ ui.horizontal(|ui| {+ crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Reverse"), 52.0);+ if icons::button(ui, "swap", 20.0, false, crate::i18n::tr(&lang, "Reverse the gradient")).clicked() && is_gradient {+ send = Some(json!({"reverse": true}));+ }+ });});- if ui- .button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Reverse")))- .on_hover_ui(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Reverse the gradient"));- })- .clicked()+ });+ ui.add_space(6.0);+ // The ramp: midpoint diamonds above, stops below.+ let w = full;+ let (area, resp) = ui.allocate_exact_size(vec2(w, 40.0), Sense::click_and_drag());+ let ramp = egui::Rect::from_min_size(area.min + vec2(6.0, 10.0), vec2(w - 12.0, 14.0));+ let painter = ui.painter();+ let n = 96;+ for i in 0..n {+ let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);+ let (c, alpha) = g.sample((a + b) / 2.0);+ let x0 = ramp.left() + ramp.width() * a;+ let x1 = ramp.left() + ramp.width() * b + 0.5;+ painter.rect_filled(egui::Rect::from_x_y_ranges(x0..=x1, ramp.y_range()), 0.0, color32(&c, alpha));+ }+ painter.rect_stroke(ramp, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ let x_of = |o: f32| ramp.left() + ramp.width() * o;+ let o_of = |x: f32| ((x - ramp.left()) / ramp.width()).clamp(0.0, 1.0);+ let mid_x = |i: usize| match (g.stops.get(i), g.stops.get(i + 1)) {+ (Some(a), Some(b)) => Some(x_of(a.offset + (b.offset - a.offset) * a.midpoint)),+ _ => None,+ };+ // The marker under the pointer: a stop below the ramp, a diamond above it.+ let hit = |p: egui::Pos2| -> Option<RampSel> {+ if p.y < ramp.top() {+ (0..last)+ .filter_map(|i| mid_x(i).map(|x| (i, (x - p.x).abs())))+ .filter(|(_, d)| *d < 6.0)+ .min_by(|a, b| a.1.total_cmp(&b.1))+ .map(|(i, _)| RampSel::Mid(i))+ } else {+ g.stops+ .iter()+ .enumerate()+ .map(|(i, s)| (i, (x_of(s.offset) - p.x).abs()))+ .filter(|(_, d)| *d < 7.0)+ .min_by(|a, b| a.1.total_cmp(&b.1))+ .map(|(i, _)| RampSel::Stop(i))+ }+ };+ let mut dragging = live_drag(ui.data(|d| d.get_temp(drag_id)), g.stops.len());+ if resp.drag_started()+ && let Some(p) = resp.interact_pointer_pos()+ && let Some(h) = hit(p)+ && let Some(o) = match h {+ RampSel::Stop(i) => g.stops.get(i).map(|s| s.offset),+ RampSel::Mid(i) => g.stops.get(i).map(|s| s.midpoint),+ }{- let _ = app.run("object.gradient", json!({"target": target, "reverse": true}));+ sel = h;+ dragging = Some((h, o, false));}- });- let sel_id = egui::Id::new("grad_sel");- let drag_id = egui::Id::new("grad_drag");- let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0).min(g.stops.len().saturating_sub(1));- ui.horizontal(|ui| {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Location:"));- let loc = g.stops.get(sel).map(|s| s.offset as f64 * 100.0);- if let Some(v) = crate::widgets::number(ui, "grad_loc", loc, " %", 54.0, 1) {+ if resp.dragged()+ && let (Some((h, _, _)), Some(p)) = (dragging, resp.interact_pointer_pos())+ {+ dragging = Some(match h {+ RampSel::Stop(_) => (h, o_of(p.x), p.y > area.bottom() + 16.0 && g.stops.len() > 2),+ RampSel::Mid(i) => {+ let m = match (g.stops.get(i), g.stops.get(i + 1)) {+ (Some(a), Some(b)) if b.offset - a.offset > 1e-6 => ((o_of(p.x) - a.offset) / (b.offset - a.offset)).clamp(0.13, 0.87),+ _ => 0.5,+ };+ (h, m, false)+ }+ });+ }+ if resp.drag_stopped()+ && let Some((h, o, off)) = dragging.take()+ {let mut stops = stops_json(&g);- stops[sel]["location"] = json!(v.clamp(0.0, 100.0));- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));- }- if !radial {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Angle:"));- let angle = fill.gradient_vector.map(|[x0, y0, x1, y1]| (-(y1 - y0)).atan2(x1 - x0).to_degrees()).or(fill.gradient_angle).unwrap_or(0.0);- if let Some(v) = crate::widgets::number(ui, "grad_angle", Some(angle), "°", 54.0, 1) {- let _ = app.run("object.gradient", json!({"target": target, "angle": v}));+ match h {+ RampSel::Stop(i) if off => {+ if i < stops.len() {+ stops.remove(i);+ }+ sel = RampSel::Stop(0);+ }+ RampSel::Stop(i) => set_stop(&mut stops, i, "location", json!(o as f64 * 100.0)),+ RampSel::Mid(i) => set_stop(&mut stops, i, "midpoint", json!(o as f64 * 100.0)),}+ send = Some(json!({"stops": stops}));}- });- ui.add_space(4.0);- // The ramp, with stop markers below it.- let w = ui.available_width().min(240.0);- let (area, resp) = ui.allocate_exact_size(vec2(w, 34.0), Sense::click_and_drag());- let ramp = egui::Rect::from_min_size(area.min + vec2(6.0, 0.0), vec2(w - 12.0, 18.0));- let painter = ui.painter();- let n = 64;- for i in 0..n {- let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);- let (c, alpha) = g.sample((a + b) / 2.0);- let [r, gg, bb] = c.to_rgb();- let col = egui::Color32::from_rgba_unmultiplied((r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8, (alpha * 255.0) as u8);- let x0 = ramp.left() + ramp.width() * a;- let x1 = ramp.left() + ramp.width() * b + 0.5;- painter.rect_filled(egui::Rect::from_x_y_ranges(x0..=x1, ramp.y_range()), 0.0, col);- }- painter.rect_stroke(ramp, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);- // A stop being dragged: (index, location 0–1, off the ramp).- let mut dragging: Option<(usize, f32, bool)> = ui.data(|d| d.get_temp(drag_id));- let x_of = |o: f32| ramp.left() + ramp.width() * o;- let o_of = |x: f32| ((x - ramp.left()) / ramp.width()).clamp(0.0, 1.0);- let near = |x: f32| {- g.stops.iter().enumerate().map(|(i, s)| (i, (x_of(s.offset) - x).abs())).filter(|(_, d)| *d < 7.0).min_by(|a, b| a.1.total_cmp(&b.1))- };- if resp.drag_started()- && let Some(p) = resp.interact_pointer_pos()- && let Some((i, _)) = near(p.x)- {- sel = i;- dragging = Some((i, g.stops[i].offset, false));- }- if resp.dragged()- && let (Some((i, _, _)), Some(p)) = (dragging, resp.interact_pointer_pos())- {- dragging = Some((i, o_of(p.x), p.y > area.bottom() + 16.0 && g.stops.len() > 2));- }- if resp.drag_stopped()- && let Some((i, o, off)) = dragging.take()- {- let mut stops = stops_json(&g);- if off {- stops.remove(i);- sel = 0;- } else {- stops[i]["location"] = json!(o as f64 * 100.0);- }- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));- }- if resp.clicked()- && let Some(p) = resp.interact_pointer_pos()- {- match near(p.x) {- Some((i, _)) => sel = i,- // Below the ramp, away from the stops: a new stop with the colour there.- None if p.y > ramp.bottom() => {- let o = o_of(p.x);- let (c, a) = g.sample(o);- let mut stops = stops_json(&g);- stops.push(json!({"location": o as f64 * 100.0, "color": c.to_hex(), "opacity": a as f64 * 100.0, "midpoint": 50.0}));- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));- sel = g.stops.iter().filter(|s| s.offset <= o).count();+ if resp.clicked()+ && let Some(p) = resp.interact_pointer_pos()+ {+ match hit(p) {+ Some(h) => sel = h,+ // Below the ramp, away from the stops: a new stop with the colour there.+ None if p.y > ramp.bottom() => {+ let o = o_of(p.x);+ let (c, a) = g.sample(o);+ let mut stops = stops_json(&g);+ stops.push(json!({"location": o as f64 * 100.0, "color": color_json(&c), "opacity": a as f64 * 100.0, "midpoint": 50.0}));+ send = Some(json!({"stops": stops}));+ sel = RampSel::Stop(g.stops.iter().filter(|s| s.offset <= o).count());+ }+ None => {}}- None => {}}- }- for (i, s) in g.stops.iter().enumerate() {- let (o, off) = match dragging {- Some((j, o, off)) if j == i => (o, off),- _ => (s.offset, false),+ // Right-click a stop: its colour (InDesign takes it from the Swatches or Color panel).+ if resp.secondary_clicked()+ && let Some(RampSel::Stop(i)) = resp.interact_pointer_pos().and_then(hit)+ {+ sel = RampSel::Stop(i);+ }+ if let (true, RampSel::Stop(i)) = (is_gradient, sel)+ && let Some(s) = g.stops.get(i)+ {+ resp.context_menu(|ui| {+ ui.horizontal(|ui| {+ crate::widgets::caption(ui, crate::i18n::tr(&lang, "Stop Color:"));+ let [r, gg, bb] = s.color.to_rgb();+ let mut rgb = [(r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8];+ if egui::color_picker::color_edit_button_srgb(ui, &mut rgb).changed() {+ let mut stops = stops_json(&g);+ set_stop(&mut stops, i, "color", json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])));+ send = Some(json!({"stops": stops}));+ }+ });+ });+ }+ // A swatch dropped from the Swatches panel: on a stop it colours that stop, elsewhere on+ // the ramp it's a new stop there.+ let drop_at = |p: egui::Pos2| match hit(egui::pos2(p.x, ramp.bottom() + 4.0)) {+ Some(RampSel::Stop(i)) => match g.stops.get(i) {+ Some(s) => (Some(i), s.offset),+ None => (None, o_of(p.x)),+ },+ _ => (None, o_of(p.x)),};- if off {- continue;- }- let x = x_of(o);- let top = ramp.bottom() + 2.0;- let [r, gg, bb] = s.color.to_rgb();- let col = egui::Color32::from_rgb((r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8);- let edge = if i == sel { t.accent } else { t.text_dim };- painter.add(egui::Shape::convex_polygon(- vec![- egui::pos2(x, top),- egui::pos2(x + 6.0, top + 7.0),- egui::pos2(x + 6.0, top + 13.0),- egui::pos2(x - 6.0, top + 13.0),- egui::pos2(x - 6.0, top + 7.0),- ],- col,- egui::Stroke::new(if i == sel { 2.0 } else { 1.0 }, edge),- ));- }- ui.data_mut(|d| {- d.insert_temp(sel_id, sel);- match dragging {- Some(v) => {- d.insert_temp(drag_id, v);+ if resp.dnd_hover_payload::<SwatchDrag>().is_some()+ && let Some(p) = ui.ctx().pointer_hover_pos()+ {+ let x = x_of(drop_at(p).1);+ painter.line_segment([egui::pos2(x, ramp.top() - 3.0), egui::pos2(x, ramp.bottom() + 14.0)], egui::Stroke::new(2.0, t.accent));+ }+ if let Some(sw) = resp.dnd_release_payload::<SwatchDrag>()+ && let Some(p) = ui.ctx().pointer_interact_pos()+ {+ let mut stops = stops_json(&g);+ match drop_at(p) {+ (Some(i), _) => {+ if let Some(o) = stops.get_mut(i).and_then(serde_json::Value::as_object_mut) {+ o.insert("swatch".to_string(), json!(sw.0));+ o.remove("color");+ }+ sel = RampSel::Stop(i);+ }+ (None, o) => {+ stops.push(json!({"location": o as f64 * 100.0, "swatch": sw.0, "midpoint": 50.0}));+ sel = RampSel::Stop(g.stops.iter().filter(|s| s.offset <= o).count());+ }}- None => d.remove::<(usize, f32, bool)>(drag_id),+ send = Some(json!({"stops": stops}));}- });- // The selected stop's colour.- if let Some(s) = g.stops.get(sel) {- ui.horizontal(|ui| {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Stop Color:"));- let [r, gg, bb] = s.color.to_rgb();- let mut rgb = [(r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8];- if egui::color_picker::color_edit_button_srgb(ui, &mut rgb).changed() {- let mut stops = stops_json(&g);- stops[sel]["color"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]));- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));+ // Diamonds.+ for i in 0..last {+ let x = match dragging {+ Some((RampSel::Mid(j), m, _)) if j == i => match (g.stops.get(i), g.stops.get(i + 1)) {+ (Some(a), Some(b)) => x_of(a.offset + (b.offset - a.offset) * m),+ _ => ramp.left(),+ },+ _ => mid_x(i).unwrap_or(ramp.left()),+ };+ let (cy, r) = (ramp.top() - 6.0, 4.0);+ let pts = vec![egui::pos2(x, cy - r), egui::pos2(x + r, cy), egui::pos2(x, cy + r), egui::pos2(x - r, cy)];+ let on = sel == RampSel::Mid(i);+ painter.add(egui::Shape::convex_polygon(pts, if on { t.text } else { egui::Color32::TRANSPARENT }, egui::Stroke::new(1.0, t.text_dim)));+ }+ // Stops: a colour square under a pointer.+ for (i, s) in g.stops.iter().enumerate() {+ let (o, off) = match dragging {+ Some((RampSel::Stop(j), o, off)) if j == i => (o, off),+ _ => (s.offset, false),+ };+ if off {+ continue;+ }+ let x = x_of(o);+ let top = ramp.bottom() + 2.0;+ let on = sel == RampSel::Stop(i);+ let edge = if on { t.text_strong } else { t.text_dim };+ painter.add(egui::Shape::convex_polygon(+ vec![egui::pos2(x, top), egui::pos2(x + 5.0, top + 5.0), egui::pos2(x - 5.0, top + 5.0)],+ if on { t.text_strong } else { t.panel },+ egui::Stroke::new(1.0, edge),+ ));+ let sq = egui::Rect::from_min_size(egui::pos2(x - 5.0, top + 5.0), vec2(10.0, 9.0));+ painter.rect_filled(sq, 0.0, color32(&s.color, 1.0));+ painter.rect_stroke(sq, 0.0, egui::Stroke::new(if on { 1.5 } else { 1.0 }, edge), egui::StrokeKind::Inside);+ }+ ui.data_mut(|d| {+ d.insert_temp(sel_id, sel);+ match dragging {+ Some(v) => {+ d.insert_temp(drag_id, v);+ }+ None => d.remove::<RampDrag>(drag_id),}});+ });- if let Some(p) = send {++ if let Some(mut p) = send {++ p["target"] = json!(target);+ let _ = app.run("object.gradient", p);}}+ #[cfg(test)]+ mod swatches_header_tests {+ use egui_kittest::{Harness, kittest::Queryable};+ use serde_json::json;++ use super::*;++ fn harness(app: DesignApp) -> Harness<'static, DesignApp> {+ Harness::builder().with_size(vec2(300.0, 520.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::new("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ show(app, ui);+ },+ app,+ )+ }++ fn items(app: &DesignApp) -> Vec<designcraft_doc::Item> {+ let st = app.session.doc().unwrap();+ st.selection.items.iter().map(|id| st.doc.item(*id).unwrap().clone()).collect()+ }++ #[test]+ fn swatches_go_to_the_fill_or_stroke_in_front_and_the_bottom_row_deletes_the_one_clicked() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "unassigned"})).unwrap();+ app.run("swatch.create", json!({"name": "Brand", "color": "#108080"})).unwrap();+ let mut h = harness(app);+ h.run_steps(3);+ // Fill in front: a swatch is the fill.+ h.get_by_label("C=0 M=100 Y=0 K=0").click();+ h.run_steps(2);+ assert_eq!(items(h.state())[0].fill.swatch, "C=0 M=100 Y=0 K=0");+ // The proxy brings the stroke to the front; the next swatch is the stroke.+ h.get_by_label("Fill").click();+ h.run_steps(2);+ assert!(h.state().ui.stroke_front);+ h.get_by_label("C=100 M=0 Y=0 K=0").click();+ h.run_steps(2);+ let it = &items(h.state())[0];+ assert_eq!((it.fill.swatch.as_str(), it.stroke.swatch.as_str()), ("C=0 M=100 Y=0 K=0", "C=100 M=0 Y=0 K=0"));+ // Formatting affects text, from the panel.+ h.get_by_label("Formatting affects text (J)").click();+ h.run_steps(2);+ assert!(h.state().ui.formatting_affects_text);+ h.get_by_label("Formatting affects container (J)").click();+ h.run_steps(2);+ assert!(!h.state().ui.formatting_affects_text);+ // Delete Swatch removes the swatch last clicked.+ h.get_by_label("Brand").click();+ h.run_steps(2);+ h.get_by_label("Delete Swatch").click();+ h.run_steps(2);+ assert!(h.state().session.doc().unwrap().doc.swatch("Brand").is_none());+ }++ #[test]+ fn the_tint_field_keeps_each_objects_own_swatch() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [136, 36, 200, 100], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ app.run("object.fill", json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();+ app.run("object.fill", json!({"ids": [b], "swatch": "C=0 M=100 Y=0 K=0"})).unwrap();+ app.run("object.stroke", json!({"ids": [a, b], "swatch": "[Black]"})).unwrap();+ app.run("selection.set", json!({"ids": [a, b]})).unwrap();+ let mut h = harness(app);+ h.run_steps(3);+ // The field shows the first selected object's fill tint.+ assert!(h.query_all_by_value("100").next().is_some());+ set_tint(h.state_mut(), 40.0).unwrap();+ h.run_steps(2);+ assert!(h.query_all_by_value("40").next().is_some(), "the field follows");+ // The stroke in front: the strokes' tints.+ h.state_mut().ui.stroke_front = true;+ set_tint(h.state_mut(), 70.0).unwrap();+ assert!(items(h.state()).iter().all(|i| i.stroke.tint == 0.7));+ let it = items(h.state());+ assert_eq!((it[0].fill.swatch.as_str(), it[0].fill.tint), ("C=100 M=0 Y=0 K=0", 0.4));+ assert_eq!((it[1].fill.swatch.as_str(), it[1].fill.tint), ("C=0 M=100 Y=0 K=0", 0.4));+ }+ }+++#[cfg(test)]+mod gradient_panel_tests {+ use designcraft_color::Color;+ use egui_kittest::{Harness, kittest::Queryable};+ use serde_json::json;++ use super::*;++ fn app_with_frame() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [100, 100, 300, 300], "content": "unassigned"})).unwrap();+ app+ }++ fn gradient(app: &DesignApp) -> Option<designcraft_color::Gradient> {+ let d = &app.session.doc().unwrap().doc;+ let id = app.session.doc().unwrap().selection.items[0];+ designcraft_color::swatch::resolve_gradient(&d.swatches, &d.item(id).unwrap().fill.swatch).cloned()+ }++ #[test]+ fn panel_edits_keep_cmyk_and_grey_stops() {+ let mut app = app_with_frame();+ app.run(+ "object.gradient",+ json!({"stops": [{"location": 0, "swatch": "C=0 M=100 Y=0 K=0"}, {"location": 50, "color": {"gray": 60}}, {"location": 100, "color": {"model": "gray", "k": 0.01}}]}),+ )+ .unwrap();+ let g = gradient(&app).unwrap();+ // What the panel sends when a stop moves: the colours come back exactly.+ let mut stops = stops_json(&g);+ stops[1]["location"] = json!(80.0);+ app.run("object.gradient", json!({"stops": stops})).unwrap();+ let g = gradient(&app).unwrap();+ assert_eq!(g.stops[0].color, Color::cmyk(0.0, 1.0, 0.0, 0.0));+ assert_eq!(g.stops[1].color, Color::gray(0.6));+ assert!((g.stops[1].offset - 0.8).abs() < 1e-6);+ assert_eq!(g.stops[2].color, Color::gray(0.01), "a 1 % grey stays 1 %");+ }++ #[test]+ fn a_drag_kept_from_a_longer_gradient_is_dropped() {+ let d = |h| Some((h, 0.5, false));+ assert_eq!(live_drag(d(RampSel::Stop(1)), 2), d(RampSel::Stop(1)));+ assert_eq!(live_drag(d(RampSel::Stop(2)), 2), None);+ assert_eq!(live_drag(d(RampSel::Mid(0)), 2), d(RampSel::Mid(0)));+ assert_eq!(live_drag(d(RampSel::Mid(1)), 2), None);+ assert_eq!(live_drag(d(RampSel::Mid(usize::MAX)), 2), None);+ let mut stops = vec![json!({"location": 0})];+ set_stop(&mut stops, 3, "location", json!(50));+ assert_eq!(stops, vec![json!({"location": 0})]);+ }++ #[test]+ fn a_swatch_dropped_on_the_ramp_is_a_new_stop() {+ let app = app_with_frame();+ let mut h = Harness::builder().with_size(vec2(280.0, 200.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::new("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ gradient_panel(app, ui);+ },+ app,+ );+ h.run_steps(3);+ assert!(gradient(h.state()).is_none(), "no gradient yet");+ // The ramp sits under the Reverse row: drop cyan at its middle.+ let row = h.get_by_label("Reverse the gradient").rect();+ let at = egui::pos2(h.ctx.content_rect().center().x, row.bottom() + 6.0 + 17.0);+ egui::DragAndDrop::set_payload(&h.ctx, SwatchDrag("C=100 M=0 Y=0 K=0".into()));+ h.event(egui::Event::PointerMoved(at));+ h.run_steps(2);+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });+ h.run_steps(3);+ let g = gradient(h.state()).expect("the drop gives the fill a gradient");+ assert_eq!(g.stops.len(), 3, "White, cyan, Black");+ assert_eq!(g.stops[1].color, Color::cmyk(1.0, 0.0, 0.0, 0.0));+ assert!((g.stops[1].offset - 0.5).abs() < 0.05, "{}", g.stops[1].offset);+ }+}diff --cc docs/target-app-parity.mdindex 6807f3d88,62ba7f08a..542239324--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@ -423,7 -428,7 +428,7 @@@ It is evidence of breadth: each item ex- View › Display Performance: Fast (grey boxes, no effects, ⌥⇧⌘Z), Typical (72 ppi proxies, ⌥⌘Z), High Quality (⌥⌘H, our default — the renderer is fast enough).- OpenType menu (Character panel): discretionary ligatures, fractions, ordinal, swash, titling, contextual alternates, slashed zero, the four figure styles and stylistic sets 1–20; `type.openType`; mapped to IDML's OTF attributes.- Add Anchor Point (=), Delete Anchor Point (-) and Convert Direction Point (⇧C) tools (click toggles smooth/corner, drag pulls out handles), with `path.addAnchor`, `path.deleteAnchor`, `path.convertAnchor`.- - Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel (InDesign's layout: thumbnail, Type, Location, Angle, Reverse) sets type, angle, reverse and edits stops and midpoints on a ramp (drag, add, drag off to remove, location; drop a swatch from the Swatches panel on a stop or the ramp; stops keep their CMYK). Edited gradients are unnamed swatches; `object.gradient`; the vector round-trips through IDML.-- Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel sets type, angle, reverse and edits stops on a ramp (drag, add, drag off to remove, location, colour). Edited gradients are unnamed swatches; `object.gradient` (`target: stroke` for a stroke's gradient, drawn across the path's box on screen and in PDF); the vector round-trips through IDML (`GradientFill…`/`GradientStroke…`). The Gradient panel follows the Fill/Stroke proxy. A radial gradient stretches with the object's box as InDesign's does (an ellipse reaching the sides of a non-square frame, on screen and in PDF). Text takes a gradient swatch as its fill or stroke, laid across its frame's box as in InDesign (screen and PDF).++- Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel (InDesign's layout: thumbnail, Type, Location, Angle, Reverse) sets type, angle, reverse and edits stops and midpoints on a ramp (drag, add, drag off to remove, location; drop a swatch from the Swatches panel on a stop or the ramp; stops keep their CMYK). Edited gradients are unnamed swatches; `object.gradient` (`target: stroke` for a stroke's gradient, drawn across the path's box on screen and in PDF); the vector round-trips through IDML (`GradientFill…`/`GradientStroke…`). The Gradient panel follows the Fill/Stroke proxy. A radial gradient stretches with the object's box as InDesign's does (an ellipse reaching the sides of a non-square frame, on screen and in PDF). Text takes a gradient swatch as its fill or stroke, laid across its frame's box as in InDesign (screen and PDF).- Document Setup (⌥⌘P): intent, number of pages, start page # (an even start begins with a left page), facing pages, size presets and orientation, bleed and slug per edge; `layout.documentSetup {}` reports the setup.- Stroke panel: cap, join, miter limit, alignment, type, Start/End arrowheads (12 kinds, drawn on screen and in PDF; the path is shortened under pointed heads) and gap colour under dashes and dots.- Preferences (⌘K: General, Type, Units & Increments, Grids, Guides & Pasteboard, Display Performance) backed by `prefs.set` (application) and `document.preferences` (units, increments, grids — undoable, saved with the document; right-click a ruler to pick its units, the horizontal and vertical rulers each have their own); scaling applies to content and scales stroke weights (Include Stroke Weight), and X/Y/W/H measure the stroke's outer edge (Dimensions Include Stroke Weight). Quick Apply (⌘Return) finds paragraph, character and object styles as well as commands.