diff --git a/ASSETS.md b/ASSETS.md index 03f33d9a6e..a74a9a29a4 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -83,11 +83,18 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/cursors/cursor-mark-ring.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-mark-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-mark-star.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-move.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-not-allowed.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-convert.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-curvature.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-new.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-reshape-segment.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-h.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-nesw.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-nwse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-v.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-type-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | | `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | | `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | diff --git a/assets/cursors/cursor-move.svg b/assets/cursors/cursor-move.svg new file mode 100644 index 0000000000..ee3c16ed90 --- /dev/null +++ b/assets/cursors/cursor-move.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-not-allowed.svg b/assets/cursors/cursor-not-allowed.svg new file mode 100644 index 0000000000..83a8556cd0 --- /dev/null +++ b/assets/cursors/cursor-not-allowed.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-h.svg b/assets/cursors/cursor-resize-h.svg new file mode 100644 index 0000000000..361da7e098 --- /dev/null +++ b/assets/cursors/cursor-resize-h.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-nesw.svg b/assets/cursors/cursor-resize-nesw.svg new file mode 100644 index 0000000000..0f37741f94 --- /dev/null +++ b/assets/cursors/cursor-resize-nesw.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-nwse.svg b/assets/cursors/cursor-resize-nwse.svg new file mode 100644 index 0000000000..d143d581da --- /dev/null +++ b/assets/cursors/cursor-resize-nwse.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-v.svg b/assets/cursors/cursor-resize-v.svg new file mode 100644 index 0000000000..095be8455d --- /dev/null +++ b/assets/cursors/cursor-resize-v.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-type-vertical.svg b/assets/cursors/cursor-type-vertical.svg new file mode 100644 index 0000000000..62b0d50f65 --- /dev/null +++ b/assets/cursors/cursor-type-vertical.svg @@ -0,0 +1 @@ + diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 39b39fc294..78927ef970 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -227,6 +227,16 @@ impl Node { } } + /// The path whose anchors the anchor tools edit, in document space: a path's, or the path of + /// type on a path outside perspective (Add, Delete and Anchor Point tools, Pen + Alt). + pub fn anchor_path(&self) -> Option> { + match &self.kind { + NodeKind::Path { path, .. } => Some(std::borrow::Cow::Borrowed(path)), + NodeKind::Text(t) if self.extras().perspective.is_none() => t.type_path().map(std::borrow::Cow::Owned), + _ => None, + } + } + pub fn path_data_mut(&mut self) -> Option<&mut PathData> { match &mut self.kind { NodeKind::Path { path, .. } => Some(path), diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5b213f3b08..c4d3cd6bb4 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -487,6 +487,16 @@ impl TextObject { true }) } + /// Replace type on a path's path with `path`, given in document space; the brackets keep their + /// fractions of the path. False, changing nothing, for other type, a degenerate `xf` or a path + /// that would not be finite. + pub fn set_type_path(&mut self, path: &PathData) -> bool { + matches!(self.kind, TextKind::OnPath { .. }) + && self.reshape_local(|frame, to_text| { + *frame = path.transformed(to_text); + true + }) + } /// Edit a copy of the area frame with `f` (given the document → text space map) and keep it /// when `f` succeeds and the result is finite. fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 934151589b..be8155274e 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -174,7 +174,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill); type with a style's look also takes the style's opacity and blend mode and is linked to it (in the document the style was picked in; elsewhere it is not linked), and its placed gradients fit the frame text wrap gives it", has_doc, text_create ), @@ -255,6 +255,7 @@ fn insert_look_turned( } n.name = name; n.bbox_angle = bbox_angle; + let pre = wrap_snapshot(d, &n, &look); let mut into = None; match (mode, inside) { (crate::DrawMode::Inside, Some(target)) if d.node(target).is_some() => { @@ -274,6 +275,7 @@ fn insert_look_turned( d.insert(parent, usize::MAX, n)?; } } + place_after_wrap(d, pre, id, &look); if select { sel.set([id]); } @@ -988,20 +990,42 @@ fn text_parent(s: &Session, p: &Value) -> Result> { } /// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected. -fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result { +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, look: NewArt, bbox_angle: f64) -> Result { let id = s.edit("Type", |d, sel| { let id = d.alloc_id(); let mut n = Node::new(id, kind); - NewArt::plain(Appearance::default()).apply(d, &mut n); + look.apply(d, &mut n); super::object::align_new_object(d, &mut n); n.bbox_angle = bbox_angle; + let pre = wrap_snapshot(d, &n, &look); d.insert(Some(parent), usize::MAX, n)?; + place_after_wrap(d, pre, id, &look); sel.set([id]); Ok(id) })?; Ok(json!({ "id": id.0 })) } +/// The document before new type `n` goes in, when `look` places gradients on it: text wrap can +/// reflow the type once it is in ([`place_after_wrap`]). +fn wrap_snapshot(d: &vectorcraft_doc::Document, n: &Node, look: &NewArt) -> Option { + (matches!(n.kind, NodeKind::Text(_)) && look.places_gradients()).then(|| d.clone()) +} + +/// New type `id` just inserted into `d` (`pre`: `d` before, from [`wrap_snapshot`]): text wrap +/// reflows it now, and when that changes its bounds (an Auto Size frame below a wrap object grows), +/// `look`'s gradients are placed on the bounds it ends with. +fn place_after_wrap(d: &mut vectorcraft_doc::Document, pre: Option, id: NodeId, look: &NewArt) { + let Some(pre) = pre else { return }; + let placed_on = d.node(id).and_then(Node::geometric_bounds); + super::textwrap::refresh(&pre, d); + if let Some(n) = d.node_mut(id) + && n.geometric_bounds() != placed_on + { + look.place(n); + } +} + fn text_create(s: &mut Session, p: &Value) -> Result { let parent = text_parent(s, p)?; let x = f64_req(p, "x", "text.create")?; @@ -1040,11 +1064,16 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } + // New art's fills, strokes and effects (New Art Has Basic Appearance off, or a graphic style + // picked with nothing selected), with the characters' paint under Override Character Color as + // graphicStyle.apply gives type; a `color` given keeps the characters' fill. + let look = s.new_type_look(); + if s.prefs.override_char_color { + super::style::override_text_chars(&mut t, &look.appearance, p.get("color").and_then(color_value).is_none()); + } let made = match parent { - Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?, - None => { - insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)? - } + Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), look, bbox_turn(rotation))?, + None => insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), look, None, true, bbox_turn(rotation), true)?, }; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 1054ca3ddc..13291b5307 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -33,6 +33,6 @@ mod smooth; pub(super) use anchors::{following_anchors, remove_anchors_of}; pub use commands::specs; -pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; +pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path}; pub(super) use cut::{components, erase_outline}; pub(super) use freehand::freehand_brushed; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 8068418edd..a1271a39a9 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -1,4 +1,4 @@ -use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound}; +use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, with_anchor_path, within_input_bound}; use super::{ Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2, add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or, @@ -111,6 +111,24 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result { let ai = usize_req(p, "anchor", C)?; let curvature = switch_or(p, "curvature", false, C)?; let removed = s.edit("Delete Anchor Point", |d, sel| { + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + // Type on a path keeps its path: the anchor goes only while two or more stay. + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if ai >= sp.anchors.len() { + return Err(EngineError::Other("no such anchor".into())); + } + if curvature { + vectorcraft_tools::draw2::curvature_remove(sp, ai); + } else { + po::remove_anchors(sp, &[ai]); + } + Ok(()) + })?; + sel.anchors.remove(&id); + sel.segments.remove(&id); + return Ok(false); + } let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; if ai >= sp.anchors.len() { return Err(EngineError::Other("no such anchor".into())); @@ -254,23 +272,24 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "x and y must be finite")); } s.edit("Convert Anchor Point", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if smooth && target.is_none() { - if ai >= sp.anchors.len() { - return Err(EngineError::Other("no such anchor".into())); + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if smooth && target.is_none() { + if ai >= sp.anchors.len() { + return Err(EngineError::Other("no such anchor".into())); + } + // Without a handle position the anchor curves as the Curvature tool curves a point; one + // with no direction to take stays as it is. + vectorcraft_tools::draw2::curvature_smooth(sp, ai); + return Ok(()); } - // Without a handle position the anchor curves as the Curvature tool curves a point; one - // with no direction to take stays as it is. - vectorcraft_tools::draw2::curvature_smooth(sp, ai); - return Ok(()); - } - let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - match target { - Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), - _ => a.retract(), - } - Ok(()) + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + match target { + Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), + _ => a.retract(), + } + Ok(()) + }) })?; ok() } @@ -287,13 +306,14 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result { } let perpendicular = switch_or(p, "perpendicular", false, C)?; s.edit("Reshape", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; - if !bent { - return Err(EngineError::Other("no such segment".into())); - } - Ok(()) + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; + if !bent { + return Err(EngineError::Other("no such segment".into())); + } + Ok(()) + }) })?; ok() } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 08404a3092..eda5d19d23 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Delete Anchor Point", [], None, - "{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points)", + "{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least", has_doc, remove_anchor ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Convert Anchor Point", [], None, - "{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", + "{id (a path, or type on a path), subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", has_doc, convert_anchor ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Reshape Segment", [], None, - "{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", + "{id (a path, or type on a path), subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", has_doc, reshape_segment ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index f69ac40822..999953eb52 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -308,6 +308,29 @@ pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> { } } +/// Run `f` on the anchors the anchor tools edit on `id` ([`Node::anchor_path`]): a path's, as +/// [`path_mut`] gives them, or type on a path's path in document space. The type keeps the edited +/// path and lays out again; an edit that leaves a subpath with fewer than two anchors, or a path +/// that is not finite or reaches past the canvas, is an error and changes nothing. +pub(in super::super) fn with_anchor_path(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result) -> Result { + if !matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + return f(path_mut(d, id)?); + } + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let mut path = n.anchor_path().map(std::borrow::Cow::into_owned).ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?; + let r = f(&mut path)?; + let within = path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)); + if path.subpaths.is_empty() || path.subpaths.iter().any(|sp| sp.anchors.len() < 2) || !within { + return Err(EngineError::Other(format!("type on a path keeps at least two anchors on its path, within the canvas (object {id})"))); + } + let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::NoNode(id)) }; + if !t.set_type_path(&path) { + return Err(EngineError::Other(format!("the path of object {id} would not be finite"))); + } + crate::cmd::typecmd::refresh_bounds(t); + Ok(r) +} + pub(super) fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> { match d.node(id).map(|n| &n.kind) { Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)), diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index d719434f28..54eb05b312 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -273,6 +273,12 @@ fn unplace_all(mut ap: Appearance) -> Appearance { ap } +/// The fills, strokes and effects new art takes from graphic style `g`, placed gradients relative +/// to the unit box. +fn style_look(g: &GraphicStyle) -> Appearance { + if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) } +} + /// How a new object looks ([`Session::new_art_look`]): its appearance and transparency and the /// graphic style it is linked to. pub(crate) struct NewArt { @@ -280,6 +286,8 @@ pub(crate) struct NewArt { opacity: f32, blend: BlendMode, style: Option, + /// Taken from a graphic style, linked to it or not (a style from another document is not). + styled: bool, /// From the template: placed gradients are relative to the unit box. unit_box: bool, } @@ -287,24 +295,47 @@ pub(crate) struct NewArt { impl NewArt { /// A plain look: `appearance`, full opacity, no link. pub(crate) fn plain(appearance: Appearance) -> Self { - Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, unit_box: false } + Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, styled: false, unit_box: false } } /// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and - /// it links to the style (type keeps its own transparency). + /// it links to the style, taking its isolate and knockout too (type keeps its own transparency + /// unless the look is a graphic style's). A look that no longer matches the style's definition + /// (the style was redefined after it was picked) is given unlinked ([`NewArt::linked_style`]). pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) { + self.place(n); + if matches!(n.kind, NodeKind::Text(_)) && !self.styled { + return; + } + (n.opacity, n.blend) = (self.opacity, self.blend); + let style = self.linked_style(d); + if let Some(g) = style.and_then(|i| d.graphic_styles.get(i)) { + (n.isolate, n.knockout) = (g.isolate, g.knockout); + } + n.extras_mut().graphic_style = style.map(|i| d.graphic_style_id(i)); + } + + /// The index in `d` of the graphic style this look links to: its style, while the style's + /// fills, strokes, effects, opacity and blend mode are still the ones this look has. + pub(crate) fn linked_style(&self, d: &Document) -> Option { + let i = d.graphic_style_index(self.style.as_deref()?)?; + let g = d.graphic_styles.get(i)?; + ((g.opacity, g.blend) == (self.opacity, self.blend) && style_look(g).approx_eq(&self.appearance)).then_some(i) + } + + /// Give `n` this look's appearance, its placed gradients relative to `n`'s bounds now. + pub(crate) fn place(&self, n: &mut Node) { n.appearance = self.appearance.clone().into(); - if self.unit_box - && n.appearance.has_placed_gradient() + if self.places_gradients() && let Some(b) = n.geometric_bounds() { n.appearance.rebase_gradients(GraphicStyle::UNIT_BOX, b); } - if matches!(n.kind, NodeKind::Text(_)) { - return; - } - (n.opacity, n.blend) = (self.opacity, self.blend); - n.extras_mut().graphic_style = self.style.as_deref().and_then(|name| d.graphic_style_index(name)).map(|i| d.graphic_style_id(i)); + } + + /// Does this look place gradients on the bounds of the object it is given to? + pub(crate) fn places_gradients(&self) -> bool { + self.unit_box && self.appearance.has_placed_gradient() } } @@ -332,7 +363,32 @@ impl Session { st.width = width; } let (opacity, blend, style) = self.new_art_transparency(); - NewArt { appearance, opacity, blend, style: style.map(str::to_string), unit_box: true } + NewArt { appearance, opacity, blend, style: style.map(str::to_string), styled: self.new_art_styled(), unit_box: true } + } + + /// The look of new type (`text.create`): the template's fills, strokes and effects when it is + /// more than one plain fill and stroke or comes from a graphic style (of this document or + /// another), else none of its own, so the characters' fill and stroke show. The document's own + /// default look (its redefined Default Graphic Style, which [`reset`] gives new art) leaves type + /// plain as the shipped default does; the same look taken from the selection does not. The + /// template is not repainted with the fill and stroke proxies. + pub(crate) fn new_type_look(&self) -> NewArt { + let plain = || NewArt::plain(Appearance::default()); + let Some(t) = self.template() else { return plain() }; + let styled = self.new_art_styled(); + let default_look = + || !self.paint.inherited && self.active().and_then(|st| redefined_default_style(&st.doc)).is_some_and(|g| style_look(g).approx_eq(&t)); + if !styled && (t.is_basic() || default_look()) { + return plain(); + } + let (opacity, blend, style) = self.new_art_transparency(); + NewArt { appearance: t.into_owned(), opacity, blend, style: style.map(str::to_string), styled, unit_box: true } + } + + /// Does the next object drawn take its look from a graphic style, in this document or the one + /// the style was taken from? + fn new_art_styled(&self) -> bool { + !self.basic_only() && self.paint.style.is_some() } /// The appearance of the next object drawn (the Appearance panel shows it with nothing @@ -341,9 +397,16 @@ impl Session { self.new_art_look(self.paint.fill.clone(), self.paint.stroke.clone(), self.paint.stroke_width).appearance } - /// The opacity, blend mode and graphic style (name) of the next object drawn. + /// The opacity, blend mode and graphic style (name) of the next object drawn. The style is + /// left out in a document other than the one it was taken from, so new art there is not + /// linked to a style of the same name. pub fn new_art_transparency(&self) -> (f32, BlendMode, Option<&str>) { - if self.basic_only() { (1.0, BlendMode::Normal, None) } else { (self.paint.opacity, self.paint.blend, self.paint.style.as_deref()) } + if self.basic_only() { + return (1.0, BlendMode::Normal, None); + } + let here = self.active().map(|st| st.uid); + let style = self.paint.style.as_deref().filter(|_| self.paint.style_doc.is_some() && self.paint.style_doc == here); + (self.paint.opacity, self.paint.blend, style) } /// The stroke of the next object drawn (the Stroke panel shows it with nothing selected). @@ -378,7 +441,7 @@ impl Session { /// A graphic style clicked with nothing selected: new art takes it (`add`: its fills, strokes /// and effects on top of the template's, unlinked). pub(crate) fn new_art_style(&mut self, g: &GraphicStyle, add: bool) { - let ap = if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) }; + let ap = style_look(g); if add { let t = self.new_art_template_mut(); t.items.extend(ap.items); @@ -390,14 +453,16 @@ impl Session { } /// Make `ap` (placed gradients relative to the unit box) and this transparency the template, - /// and its top fill, stroke and weight the proxies. + /// and its top fill, stroke and weight the proxies. `style` is a graphic style of the + /// document in front. fn take_new_art(&mut self, ap: Appearance, opacity: f32, blend: BlendMode, style: Option, inherited: bool) { + let style_doc = style.as_ref().and_then(|_| self.active().map(|st| st.uid)); let p = &mut self.paint; (p.fill, p.stroke) = (unplaced(&ap.fill_paint()), unplaced(&ap.stroke_paint())); if let Some(st) = ap.stroke() { p.stroke_width = st.width; } - (p.appearance, p.opacity, p.blend, p.style, p.inherited) = (Some(ap), opacity, blend, style, inherited); + (p.appearance, p.opacity, p.blend, p.style, p.style_doc, p.inherited) = (Some(ap), opacity, blend, style, style_doc, inherited); } /// After each command: with New Art Has Basic Appearance off, new art takes the appearance of @@ -522,7 +587,9 @@ fn set_basic(s: &mut Session, p: &Value) -> Result { } fn describe(s: &mut Session, _: &Value) -> Result { - let (opacity, blend, style) = s.new_art_transparency(); + let (opacity, blend, _) = s.new_art_transparency(); + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let style = s.doc().ok().and_then(|st| look.linked_style(&st.doc)).and_then(|i| s.doc().ok()?.doc.graphic_styles.get(i)).map(|g| g.name.clone()); Ok(json!({ "basic": s.prefs.new_art_basic, "appearance": s.new_art(), @@ -540,8 +607,7 @@ pub(crate) fn reset(s: &mut Session) { s.paint = PaintDefaults::default(); let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned(); if let Some(g) = style { - let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) }; - s.take_new_art(ap, 1.0, BlendMode::Normal, None, false); + s.take_new_art(style_look(&g), 1.0, BlendMode::Normal, None, false); } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index de0013036c..62d6f27e27 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", + "{id (a path, or type on a path), subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", has_doc, set_handle ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Move Anchor Point", [], None, - "{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again", + "{id (a path, or type on a path), subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again", has_doc, move_anchor ), @@ -149,7 +149,7 @@ pub fn specs() -> Vec { "Add Anchor Point", [], None, - "{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected", + "{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection)", has_doc, insert_anchor ), @@ -719,39 +719,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Reshape", |d, _| { - let path = path_mut(d, id)?; - let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - let old_point = a.p; - let old_handle = if out { a.h_out } else { a.h_in }; - if let Some(to) = at { - a.translate(to - a.p); - } - let handle = if out { a.h_out } else { a.h_in }; - let kind_changes = independent && a.kind != AnchorKind::Corner; - // Ordinary decimal moves can round `at - old_point` differently from the handle's - // translation. Within that calculation's roundoff, place the selected point exactly - // without realigning the other stored Smooth handle. Real edits still use set_handle. - let translation_roundoff = at.is_some_and(|to| { - let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| { - let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0); - (actual - requested).abs() <= 4.0 * f64::EPSILON * scale - }; - to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y) - }); - if !kind_changes && (handle == pos || translation_roundoff) { - if out { - a.h_out = pos; - } else { - a.h_in = pos; + super::draw2::with_anchor_path(d, id, |path| { + let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + let old_point = a.p; + let old_handle = if out { a.h_out } else { a.h_in }; + if let Some(to) = at { + a.translate(to - a.p); } - } else { - a.set_handle(out, pos, independent); - } - if symmetric { - let opposite = a.p - (pos - a.p); - if out { a.h_in = opposite } else { a.h_out = opposite } - } - Ok(()) + let handle = if out { a.h_out } else { a.h_in }; + let kind_changes = independent && a.kind != AnchorKind::Corner; + // Ordinary decimal moves can round `at - old_point` differently from the handle's + // translation. Within that calculation's roundoff, place the selected point exactly + // without realigning the other stored Smooth handle. Real edits still use set_handle. + let translation_roundoff = at.is_some_and(|to| { + let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| { + let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0); + (actual - requested).abs() <= 4.0 * f64::EPSILON * scale + }; + to != old_point + && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) + && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y) + }); + if !kind_changes && (handle == pos || translation_roundoff) { + if out { + a.h_out = pos; + } else { + a.h_in = pos; + } + } else { + a.set_handle(out, pos, independent); + } + if symmetric { + let opposite = a.p - (pos - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } + Ok(()) + }) })?; ok() } @@ -852,22 +855,26 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out if s.script_running() { return Err(EngineError::Busy); } - let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| { - sp.anchors.get(ai).is_some_and(|a| { - let mut linked = *a; - linked.link_handle(out, pos, sp.has_segment(ai, !out)); - linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos)) + let unchanged = s.doc()?.doc.node(id).and_then(Node::anchor_path).is_some_and(|pd| { + pd.subpaths.get(si).is_some_and(|sp| { + sp.anchors.get(ai).is_some_and(|a| { + let mut linked = *a; + linked.link_handle(out, pos, sp.has_segment(ai, !out)); + linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos)) + }) }) }); if unchanged { return ok(); } s.edit("Reshape", |d, _| { - let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - let pull_out = sp.has_segment(ai, !out); - let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - a.link_handle(out, pos, pull_out); - Ok(()) + super::draw2::with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + let pull_out = sp.has_segment(ai, !out); + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + a.link_handle(out, pos, pull_out); + Ok(()) + }) })?; ok() } @@ -958,6 +965,13 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Move", |d, sel| { + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + return super::draw2::with_anchor_path(d, id, |path| { + let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + *a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p)); + Ok(()) + }); + } let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p); let before = corner_sources(d, id); let moved = BTreeSet::from([(si, ai)]); @@ -975,24 +989,25 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result { ok() } -/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path that has it. -/// Busy while a script runs, as [`Session::edit`] is. +/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path, or type +/// on a path ([`Node::anchor_path`], in document space), that has it. Busy while a script runs, as +/// [`Session::edit`] is. fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result> { if s.script_running() { return Err(EngineError::Busy); } let d = &s.doc()?.doc; - Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied()) + Ok(d.node(id).and_then(Node::anchor_path).and_then(|path| path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).copied())) } -/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or -/// incoming side; false when the path, subpath or anchor is not there. +/// Whether anchor `ai` of subpath `si` of path `id` (or of type on a path's path) has a segment on +/// its outgoing (`out`) or incoming side; false when the path, subpath or anchor is not there. fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result { if s.script_running() { return Err(EngineError::Busy); } let d = &s.doc()?.doc; - Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out))) + Ok(d.node(id).and_then(Node::anchor_path).is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, out)))) } fn set_anchors(s: &mut Session, p: &Value) -> Result { @@ -2610,12 +2625,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0); let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?; let idx = s.edit("Add Anchor Point", |d, sel| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if seg >= sp.segment_count() { - return Err(EngineError::Other("no such segment".into())); + let idx = super::draw2::with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if seg >= sp.segment_count() { + return Err(EngineError::Other("no such segment".into())); + } + Ok(sp.insert_anchor(seg, t)) + })?; + // Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor` + // leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only. + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + if select_anchor || !sel.contains(id) { + sel.clear(); + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + if sel.key_anchor.is_some_and(|(k, _)| k == id) { + sel.key_anchor = None; + } + sel.add(id); + return Ok(idx); } - let idx = sp.insert_anchor(seg, t); renumber_after_insert(sel, id, si, idx); // A path that wasn't selected becomes the selection, its new anchor direct-selected, so // the point added shows and can be edited at once (#4237). `selectAnchor` does the same diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 05fa6ce85f..699f3cdec7 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -257,7 +257,12 @@ pub(crate) fn captured(n: &Node) -> Appearance { /// fills, and their stroke when it has strokes. fn override_chars(n: &mut Node, ap: &Appearance) { let NodeKind::Text(t) = &mut n.kind else { return }; - let (fills, strokes) = (ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill())); + override_text_chars(t, ap, true); +} + +/// [`override_chars`] for type `t`; with `fill` false its characters keep their fill. +pub(crate) fn override_text_chars(t: &mut vectorcraft_doc::TextObject, ap: &Appearance, fill: bool) { + let (fills, strokes) = (fill && ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill())); for r in &mut t.runs { if fills { r.style.fill = Paint::None; diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 21ba56347c..9ae0db2902 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -442,7 +442,7 @@ impl Session { // parts it left alone keep the interaction's. The pattern lists every field, so a field // added to `PaintDefaults` does not compile until it is handled here. The paints a preview // took its new-art paints over from take the change as well. - let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint; + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = &self.paint; for start in std::iter::once(&mut it.paint).chain(it.inherited_preview_paint.as_mut()) { if *fill != paint.fill { start.fill.clone_from(fill); @@ -462,8 +462,9 @@ impl Session { if *blend != paint.blend { start.blend = *blend; } - if *style != paint.style { + if *style != paint.style || *style_doc != paint.style_doc { start.style.clone_from(style); + start.style_doc = *style_doc; } if *inherited != paint.inherited { start.inherited = *inherited; @@ -974,7 +975,7 @@ fn take_changed_paints( left: &vectorcraft_tools::PaintDefaults, now: &vectorcraft_tools::PaintDefaults, ) { - let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = now; + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = now; if left.fill != *fill { target.fill.clone_from(fill); } @@ -993,8 +994,9 @@ fn take_changed_paints( if left.blend != *blend { target.blend = *blend; } - if left.style != *style { + if left.style != *style || left.style_doc != *style_doc { target.style.clone_from(style); + target.style_doc = *style_doc; } if left.inherited != *inherited { target.inherited = *inherited; diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 6737666046..3d9bd36473 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -474,3 +474,249 @@ fn set_new_art_refuses_while_new_art_takes_the_selected_look() { assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true})); assert_eq!(s.new_art().stroke().unwrap().width, 7.0); } + +fn new_type(s: &mut Session, p: Value) -> Node { + let id = NodeId(run(s, "text.create", p)["id"].as_u64().unwrap()); + node(s, id) +} + +/// The fill of `n`'s first run of characters. +fn char_fill(n: &Node) -> Paint { + match &n.kind { + vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.fill.clone(), + _ => panic!("{} is not type", n.id.0), + } +} + +/// Type with a second fill and a drop shadow on the object, selected. +fn styled_type(s: &mut Session) -> NodeId { + let id = NodeId(run(s, "text.create", json!({"x": 20, "y": 60, "text": "RIP", "size": 30}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({})); + run(s, "paint.setFill", json!({"color": "#ff0000"})); + run(s, "effect.apply", json!({"effect": "stylize.dropShadow"})); + id +} + +#[test] +fn with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects() { + let mut s = session(); + let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.none", json!({})); + let src = styled_type(&mut s); + let from = node(&s, src).appearance; + assert_eq!(from.effects.len(), 1); + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.set", json!({"ids": [src.0]})); + run(&mut s, "select.none", json!({})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "new"})); + assert_eq!(n.appearance.effects.len(), 1, "the drop shadow"); + assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), from.items.iter().filter(|i| i.is_fill()).count()); + assert_eq!(n.appearance.fill_paint(), from.fill_paint(), "the template keeps its own fill"); + // Override Character Color: the object's fill shows instead of the characters' own. + assert_eq!(char_fill(&n), Paint::None); + // Type placed in a group takes it too, and a color given keeps the characters' fill. + run(&mut s, "select.set", json!({"ids": [src.0]})); + run(&mut s, "select.none", json!({})); + let g = new_type(&mut s, json!({"x": 200, "y": 250, "text": "in", "parent": group, "color": "#00ff00"})); + assert_eq!(g.appearance.effects.len(), 1); + assert_ne!(char_fill(&g), Paint::None); +} + +#[test] +fn new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke() { + let mut s = session(); + let plain = new_type(&mut s, json!({"x": 20, "y": 60, "text": "a"})); + assert!(plain.appearance.items.is_empty() && plain.appearance.effects.is_empty()); + // Option on: a styled selection gives new type only its basic paints, so it stays plain. + let src = styled_type(&mut s); + run(&mut s, "select.none", json!({})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "b"})); + assert_eq!((n.appearance.items.len(), n.appearance.effects.len(), char_fill(&n)), (0, 0, char_fill(&plain))); + // Option off with plain type last selected: its characters' basic look, no fills of the object. + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.set", json!({"ids": [n.id.0]})); + run(&mut s, "select.none", json!({})); + let m = new_type(&mut s, json!({"x": 200, "y": 250, "text": "c"})); + assert_eq!((m.appearance.items.len(), char_fill(&m)), (0, char_fill(&plain))); + assert!(node(&s, src).appearance.effects.len() == 1, "the source keeps its look"); +} + +#[test] +fn a_graphic_style_clicked_with_nothing_selected_styles_the_next_type() { + let mut s = session(); + fancy(&mut s); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Fancy"}))["name"].as_str().unwrap().to_string(); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "styled"})); + assert_eq!((n.appearance.items.iter().filter(|i| i.is_fill()).count(), n.appearance.effects.len()), (2, 1)); + assert_eq!(char_fill(&n), Paint::None); + // With Override Character Color off the characters keep their fill under the style's. + run(&mut s, "graphicStyle.setOptions", json!({"overrideCharColor": false})); + run(&mut s, "select.none", json!({})); + let kept = new_type(&mut s, json!({"x": 200, "y": 250, "text": "kept"})); + assert_eq!(kept.appearance.effects.len(), 1); + assert_ne!(char_fill(&kept), Paint::None); +} + +#[test] +fn new_art_and_type_from_a_knockout_style_stay_linked_to_it() { + let mut s = session(); + rect(&mut s, 20.0); + run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true})); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Knockout"}))["name"].as_str().unwrap().to_string(); + for (make, p) in + [("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))] + { + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + run(&mut s, make, p); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{make}"); + } +} + +#[test] +fn a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type() { + let mut s = session(); + let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0); + let red = node(&s, src).appearance.fill_paint(); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Plain"}))["name"].as_str().unwrap().to_string(); + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + // The first type is linked to the style, so the next one, taking its look, gets it too. + for (y, text) in [(200, "one"), (250, "two")] { + let n = new_type(&mut s, json!({"x": 200, "y": y, "text": text})); + assert_eq!(n.appearance.fill_paint(), red, "{text}"); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{text}"); + run(&mut s, "select.none", json!({})); + } +} + +#[test] +fn new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with() { + let mut s = session(); + let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 80})); + // A placed vertical gradient, top to bottom of the rectangle. + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]); + run(&mut s, "paint.setFill", json!({"gradient": {"stops": stops, "start": [50, 0], "end": [50, 80]}})); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Vertical"}))["name"].as_str().unwrap().to_string(); + run(&mut s, "object.textWrap.make", json!({"offset": 0})); + let style = s.doc().unwrap().doc.graphic_styles.iter().find(|g| g.name == name).unwrap().clone(); + assert!(style.unit_box && style.appearance.has_placed_gradient()); + let area = json!({"width": 100, "height": 20, "fit": "autoHeight"}); + // Drawn behind the wrap object, and placed into a group below it. + for p in [ + json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area}), + json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area, "parent": group}), + ] { + run(&mut s, "select.none", json!({})); + run(&mut s, "view.drawMode", json!({"mode": if p.get("parent").is_some() { "normal" } else { "behind" }})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + let n = new_type(&mut s, p.clone()); + let b = n.geometric_bounds().unwrap(); + assert!(b.height() > 80.0, "the frame grows below the wrap object: {b:?} ({p})"); + let mut placed = style.appearance.clone(); + placed.rebase_gradients(vectorcraft_doc::GraphicStyle::UNIT_BOX, b); + assert_eq!(*n.appearance, placed, "{p}"); + } +} + +#[test] +fn new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name() { + let mut s = session(); + fancy(&mut s); + run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true})); + run(&mut s, "graphicStyle.new", json!({"name": "Shared"})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": "Shared"})); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + rect(&mut s, 20.0); + run(&mut s, "graphicStyle.new", json!({"name": "Shared"})); + for (make, p) in + [("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))] + { + run(&mut s, "select.none", json!({})); + let id = NodeId(run(&mut s, make, p)["id"].as_u64().unwrap()); + let n = node(&s, id); + assert_eq!((n.extras().graphic_style, n.isolate), (None, false), "{make}"); + assert_eq!(n.appearance.effects.len(), 1, "{make} keeps the template's look"); + } + // Back in the document the style came from, new art is linked to it again. + s.set_active(0); + run(&mut s, "select.none", json!({})); + run(&mut s, "text.create", json!({"x": 200, "y": 200, "text": "k"})); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Shared".to_string(), true))); +} + +#[test] +fn new_type_in_another_document_takes_a_basic_styles_look_and_transparency() { + let mut s = session(); + let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0); + let red = node(&s, src).appearance.fill_paint(); + run(&mut s, "transparency.set", json!({"opacity": 50, "blend": "multiply"})); + run(&mut s, "graphicStyle.new", json!({"name": "Red"})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": "Red"})); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "k"})); + assert_eq!(n.appearance.fill_paint(), red, "the style's fill"); + assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply), "the style's transparency"); + assert_eq!(n.extras().graphic_style, None, "no link to a style of another document"); +} + +#[test] +fn new_art_and_type_from_a_style_redefined_after_it_was_picked_keep_the_picked_look_unlinked() { + let mut s = session(); + fancy(&mut s); + run(&mut s, "graphicStyle.new", json!({"name": "Picked"})); + let other = painted(&mut s, 120.0, "#00ff00", "#000000", 3.0); + run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": "Picked"})); + let picked = s.new_art(); + let redefine = |s: &mut Session| run(s, "graphicStyle.redefine", json!({"name": "Picked", "id": other.0})); + let linked = |s: &mut Session| run(s, "appearance.newArt", json!({}))["graphicStyle"].clone(); + let make = + [("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))]; + redefine(&mut s); + assert_eq!(linked(&mut s), Value::Null); + // Undone, the style has the picked look again, and new art links to it. + run(&mut s, "edit.undo", json!({})); + assert_eq!(linked(&mut s), json!("Picked")); + for (cmd, p) in &make { + run(&mut s, "select.none", json!({})); + run(&mut s, cmd, p.clone()); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Picked".to_string(), true)), "{cmd}"); + } + redefine(&mut s); + assert_eq!(linked(&mut s), Value::Null); + for (cmd, p) in &make { + run(&mut s, "select.none", json!({})); + let id = NodeId(run(&mut s, cmd, p.clone())["id"].as_u64().unwrap()); + let n = node(&s, id); + assert_eq!((n.extras().graphic_style, n.isolate, n.opacity), (None, false, 0.5), "{cmd}: the picked transparency, unlinked"); + assert_eq!((n.appearance.effects.len(), n.appearance.fill_paint()), (1, picked.fill_paint()), "{cmd}: the picked look"); + } +} + +#[test] +fn new_type_takes_a_selected_look_that_matches_the_redefined_default_style() { + let mut s = session(); + let src = fancy(&mut s); + run(&mut s, "graphicStyle.redefine", json!({"name": "Default Graphic Style", "id": src.0})); + run(&mut s, "graphicStyle.breakLink", json!({"ids": [src.0]})); + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.set", json!({"ids": [src.0]})); + run(&mut s, "select.none", json!({})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "in"})); + assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), 2, "both fills from the selection"); + assert_eq!(n.appearance.effects.len(), 1, "the drop shadow from the selection"); + // The same look from paint.default is the document's default, so new type stays plain. + run(&mut s, "select.none", json!({})); + run(&mut s, "paint.default", json!({})); + let d = new_type(&mut s, json!({"x": 200, "y": 260, "text": "df"})); + assert!(d.appearance.items.is_empty() && d.appearance.effects.is_empty(), "plain type"); + assert_ne!(char_fill(&d), Paint::None); +} diff --git a/crates/engine/src/tests/pathtype.rs b/crates/engine/src/tests/pathtype.rs index 5ceba16c10..5209950383 100644 --- a/crates/engine/src/tests/pathtype.rs +++ b/crates/engine/src/tests/pathtype.rs @@ -519,3 +519,138 @@ fn type_on_a_path_made_with_the_type_tool_has_brackets_at_once() { assert!(ink(&s, id).y0 > 299.0, "{tool}: below the path"); } } + +/// Press and release `tool` at `p`. +fn click(s: &mut Session, tool: &str, p: Point) { + let v = ViewInfo::default(); + s.select_tool(tool, v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap(); + } + assert!(!s.in_interaction()); +} + +/// Type along "M100 300 L300 300 L500 300" turned a quarter turn, so a document-space edit isn't +/// the path's own, and selected; with its path in document space. +fn turned_path_type(s: &mut Session) -> NodeId { + let id = path_type(s, "M100 300 L300 300 L500 300", [100.0, 310.0], "Reshaped type"); + s.execute("object.transform", &json!({"ids": [id.0], "matrix": [0, 1, -1, 0, 600, 0]})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + id +} + +fn type_path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData { + text(s, id).type_path().unwrap() +} + +fn close(a: Point, b: Point) -> bool { + near(a.x, b.x) && near(a.y, b.y) +} + +/// #10862: the Anchor Point tool drags handles out of an anchor of selected type on a path's path, +/// in document space through the type's transform, as one undo step, and the type reflows. +#[test] +fn anchor_point_tool_pulls_handles_out_of_type_on_a_path() { + let mut s = session(); + let id = turned_path_type(&mut s); + let middle = type_path(&s, id).subpaths[0].anchors[1].p; + let (glyphs, n) = (origins(&s, id), undo_len(&s)); + let to = middle + vectorcraft_geom::Vec2::new(40.0, 0.0); + drag(&mut s, "anchorPoint", middle, to, Mods::default()); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(close(a.p, middle) && close(a.h_out, to) && close(a.h_in, middle - (to - middle)), "{a:?}"); + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth); + assert_ne!(origins(&s, id), glyphs, "the type reflows along the curved path"); + assert_eq!(undo_len(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!type_path(&s, id).subpaths[0].anchors[1].has_out()); +} + +/// #10862: the rest of the Anchor Point tool's gestures on type on a path's path: a click makes a +/// smooth anchor a corner, a handle drag moves that handle alone, Shift at the press moves the +/// anchor, and a segment drag bends the segment. +#[test] +fn anchor_point_tool_reshapes_type_on_a_path() { + let mut s = session(); + let id = turned_path_type(&mut s); + let [first, middle, last] = [0, 1, 2].map(|i| type_path(&s, id).subpaths[0].anchors[i].p); + let up = vectorcraft_geom::Vec2::new(40.0, 0.0); + drag(&mut s, "anchorPoint", middle, middle + up, Mods::default()); + // A handle end, dragged, moves alone and makes the anchor a corner. + let handle = middle + vectorcraft_geom::Vec2::new(40.0, 30.0); + drag(&mut s, "anchorPoint", middle + up, handle, Mods::default()); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(close(a.h_out, handle) && close(a.h_in, middle - up) && a.kind == vectorcraft_geom::AnchorKind::Corner, "{a:?}"); + // A click on the anchor takes its handles back. + click(&mut s, "anchorPoint", middle); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(!a.has_in() && !a.has_out(), "{a:?}"); + // Shift at the press moves the anchor. + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut s, "anchorPoint", middle, middle + up, shift); + assert!(close(type_path(&s, id).subpaths[0].anchors[1].p, middle + up)); + // A drag on the first segment bends it; its anchors stay. + let on_segment = first.midpoint(middle + up); + drag(&mut s, "anchorPoint", on_segment, on_segment + vectorcraft_geom::Vec2::new(0.0, 30.0), Mods::default()); + let sp = &type_path(&s, id).subpaths[0]; + assert!(close(sp.anchors[0].p, first) && close(sp.anchors[2].p, last)); + assert!(sp.anchors[0].has_out() && sp.anchors[1].has_in(), "the segment curves: {sp:?}"); +} + +/// #10862: the Add and Delete Anchor Point tools add an anchor to type on a path's path and delete +/// one, and Pen + Alt pulls handles out of one; Delete leaves the path two anchors at least, and +/// Scissors does not cut the type. +#[test] +fn add_delete_and_pen_alt_edit_type_on_a_path() { + let mut s = session(); + let id = turned_path_type(&mut s); + let [first, middle] = [0, 1].map(|i| type_path(&s, id).subpaths[0].anchors[i].p); + let quarter = first.midpoint(middle); + click(&mut s, "addAnchor", quarter); + let sp = type_path(&s, id).subpaths[0].clone(); + assert_eq!(sp.anchors.len(), 4); + assert!(close(sp.anchors[1].p, quarter), "{sp:?}"); + let alt = Mods { alt: true, ..Mods::default() }; + let to = quarter + vectorcraft_geom::Vec2::new(0.0, 25.0); + drag(&mut s, "pen", quarter, to, alt); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(close(a.p, quarter) && close(a.h_out, to) && a.kind == vectorcraft_geom::AnchorKind::Smooth, "{a:?}"); + // The Pen's Auto Add/Delete adds an anchor on a segment and deletes it again. + let last = type_path(&s, id).subpaths[0].anchors[3].p; + let three_quarters = middle.midpoint(last); + click(&mut s, "pen", three_quarters); + assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 5); + click(&mut s, "pen", three_quarters); + assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 4); + click(&mut s, "deleteAnchor", quarter); + click(&mut s, "deleteAnchor", middle); + assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 2); + let n = undo_len(&s); + let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": 0})); + assert!(r.is_err(), "type on a path keeps two anchors: {r:?}"); + assert_eq!((type_path(&s, id).subpaths[0].anchors.len(), undo_len(&s)), (2, n)); + let end = type_path(&s, id).subpaths[0].anchors[1].p; + click(&mut s, "scissors", first.midpoint(end)); + assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. })); + assert_eq!(undo_len(&s), n, "Scissors leaves the type whole"); +} + +/// #10862: `path.insertAnchor` on type on a path, unselected or with `selectAnchor`, leaves the type +/// selected whole with no direct-selected anchors, so `path.moveAnchors` (the arrow keys) moves +/// the type instead of failing on an anchor that is not a path's. +#[test] +fn an_anchor_added_to_type_on_a_path_leaves_it_selected_whole() { + let mut s = session(); + let id = turned_path_type(&mut s); + for select_anchor in [false, true] { + if !select_anchor { + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5, "selectAnchor": select_anchor})).unwrap(); + let sel = &s.doc().unwrap().selection; + assert!(sel.contains(id) && sel.partial(id).is_none() && !sel.anchors.contains_key(&id), "selectAnchor {select_anchor}"); + let before = type_path(&s, id).subpaths[0].anchors[0].p; + s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 0})).unwrap(); + assert!(close(type_path(&s, id).subpaths[0].anchors[0].p, before + vectorcraft_geom::Vec2::new(10.0, 0.0))); + } +} diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index 29417779df..4eedb1355f 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -42,8 +42,8 @@ pub(crate) use cid::replacement; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; pub use entry::{ - INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, - holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, + CONFLICTING_GLYPHS_NOTE, INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, + UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(test)] pub(crate) use entry::{TEST_MAX_OBJECTS, import_with_reader_options, read}; diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index cd248a7689..32090ca177 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -1,7 +1,7 @@ use super::cid::{CidText, FontInfo, comparable, font_chars, identify_glyph, matching_face, replacement, unify_radical}; use super::entry::{ - MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, RESHAPED_TEXT_NOTE, TEXT_OUTLINES, TOO_MANY_OBJECTS, UNMATCHED_GLYPHS_NOTE, - UNNAMED_CHARACTERS_NOTE, max_objects, + CONFLICTING_GLYPHS_NOTE, MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, RESHAPED_TEXT_NOTE, TEXT_OUTLINES, TOO_MANY_OBJECTS, + UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, max_objects, }; use super::reshaped; use super::state::{ @@ -819,7 +819,13 @@ impl<'p> Builder<'p> { // A line with a glyph the file's font can't keep (another glyph for the same character) // is kept as outlines too, so each glyph draws as the file does. let conflict = line_conflict && !glyphs.is_empty() && !line_type3; - if conflict || (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)) { + // The warning names why: the glyph conflict, else type that reshapes as it is set. + let note = if conflict { + Some(CONFLICTING_GLYPHS_NOTE) + } else { + (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)).then_some(RESHAPED_TEXT_NOTE) + }; + if let Some(note) = note { outlined = true; if self.mask.is_some() { self.flush_glyphs(); @@ -852,7 +858,7 @@ impl<'p> Builder<'p> { self.flush_masked(); } } - self.warn(RESHAPED_TEXT_NOTE); + self.warn(note); } else { let mut n = Node::new(self.id(), NodeKind::Text(Box::new(t))); n.opacity = opacity; diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index fbc9e1aef5..b36072488a 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -180,16 +180,24 @@ pub const UNMATCHED_GLYPHS_NOTE: &str = "text whose glyphs differ from the insta pub const RESHAPED_TEXT_NOTE: &str = "text that would not look as it does in the file if set as type (a script whose letters join) was kept as outlines"; +/// Warning: type in a font the file carries that draws a character with a different glyph than +/// the rest of the file does in that font (an alternate letter) was kept as outlines: the font kept +/// with the document has one glyph per character ([`crate::import_fonts`]). +pub const CONFLICTING_GLYPHS_NOTE: &str = + "text that uses a different glyph for a character than the rest of its font (such as an alternate letter) was kept as outlines"; + /// The end of the warning that glyphs whose characters the file doesn't name were kept as /// outlines, after "text in" and the font's name. pub const UNNAMED_CHARACTERS_NOTE: &str = "whose characters the file doesn't name (U+FFFD) was kept as outlines"; /// Is `note` one of the warnings that glyphs were kept as outlines ([`OUTLINED_TEXT_NOTE`], -/// [`UNMATCHED_GLYPHS_NOTE`], [`RESHAPED_TEXT_NOTE`], [`UNNAMED_CHARACTERS_NOTE`])? +/// [`UNMATCHED_GLYPHS_NOTE`], [`RESHAPED_TEXT_NOTE`], [`CONFLICTING_GLYPHS_NOTE`], +/// [`UNNAMED_CHARACTERS_NOTE`])? pub fn is_outlines_note(note: &str) -> bool { note == OUTLINED_TEXT_NOTE || note == UNMATCHED_GLYPHS_NOTE || note == RESHAPED_TEXT_NOTE + || note == CONFLICTING_GLYPHS_NOTE || note.starts_with("text in ") && note.ends_with(UNNAMED_CHARACTERS_NOTE) } diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index a7118fd37a..3f244112ab 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -79,8 +79,8 @@ pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_w pub use export::{check_page_sizes, export, export_with_report, page_areas}; pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; pub use import::{ - INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, - holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, + CONFLICTING_GLYPHS_NOTE, INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, + UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(any(test, feature = "read-count"))] pub use import::{form_content_of, function_evaluations_of, imports_of}; diff --git a/crates/pdf/src/tests/file_fonts.rs b/crates/pdf/src/tests/file_fonts.rs index b27dac4f0d..ab4a88f541 100644 --- a/crates/pdf/src/tests/file_fonts.rs +++ b/crates/pdf/src/tests/file_fonts.rs @@ -275,6 +275,16 @@ fn two_glyphs_for_one_character_both_survive_import() { close(&glyph_ink(db, &imported), "imported"); } +/// The line kept as outlines for its other glyph of `a` is Latin type: the warning names the glyph +/// conflict, not a script whose letters join, and is one of the warnings on outlines (which a `.ai` +/// read from its layers drops when no outlines are left). +#[test] +fn a_line_kept_as_outlines_for_another_glyph_names_the_glyph_conflict() { + let warnings = import(&two_glyphs_pdf()).warnings; + assert!(warnings.iter().any(|w| w == CONFLICTING_GLYPHS_NOTE && is_outlines_note(w)), "{warnings:?}"); + assert!(warnings.iter().all(|w| !is_outlines_note(w) || w == CONFLICTING_GLYPHS_NOTE), "{warnings:?}"); +} + /// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps: /// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that /// type as outlines with the license warning instead of embedding the font again. diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 2ac3c90086..acc45b4338 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -25,6 +25,8 @@ pub struct PaintDefaults { pub blend: vectorcraft_color::BlendMode, /// The graphic style the template came from (by name): new art is linked to it. pub style: Option, + /// The document `style` is in (its session id): new art in another document is not linked. + pub style_doc: Option, /// The template is the last selection's appearance (New Art Has Basic Appearance off): with /// the option on again, new art takes only its basic fill and stroke. pub inherited: bool, @@ -41,6 +43,7 @@ impl Default for PaintDefaults { opacity: 1.0, blend: Default::default(), style: None, + style_doc: None, inherited: false, } } diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 5528b7cd97..5e34518138 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -483,7 +483,7 @@ shown_when = [ "The Smooth tool, and the Pencil or Blob Brush where Alt gives the Smooth tool, when no path is selected that the Smooth tool can act on: a drag changes nothing.", ] hotspot = "The centre." -designer = false +look = "A ring crossed by a diagonal bar." [[cursor]] id = "Busy" diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index cf3551fc19..1e748eab11 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -834,6 +834,23 @@ fn type_path_handles(cx: &ToolContext) -> Vec { out } +/// The anchors and direction handles of selected, editable type on a path's path, for the tools +/// that edit them besides Direct Selection (the Anchor Point, Add and Delete Anchor Point tools and +/// the Pen, #10862): the canvas draws only a path's own. +pub(crate) fn type_path_overlays(cx: &ToolContext) -> Vec { + let editable = cx.doc.editable(); + let mut out = vec![]; + for &id in &cx.selection.objects { + let Some(path) = cx.doc.node(id).filter(|n| is_path_type(n) && editable(id)).and_then(editable_path) else { continue }; + let color = cx.doc.layer_color(id); + out.extend(path.anchors().map(|(_, _, a)| Overlay::Anchor { p: a.p, color, filled: false, size: 5.0 })); + } + if !out.is_empty() { + out.extend(type_path_handles(cx)); + } + out +} + /// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and /// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path, /// subpath, anchor, is_out). diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 7e334ce31f..3b5cd4b4b9 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -377,7 +377,18 @@ pub(crate) fn walk_pickable<'a>(cx: &ToolContext<'a>, mut f: impl FnMut(&'a vect /// Editable path nodes, selected ones first, then the rest top-most first ([`walk_pickable`]). pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec { - let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(|n| n.path_data().is_some())).collect(); + candidates(cx, false) +} + +/// [`candidate_paths`], with selected type on a path outside perspective among the selected ones: +/// the objects whose anchors the Add, Delete and Anchor Point tools edit (#10862). +pub(crate) fn anchor_owners(cx: &ToolContext) -> Vec { + candidates(cx, true) +} + +fn candidates(cx: &ToolContext, path_type: bool) -> Vec { + let picks = |n: &vectorcraft_doc::Node| n.path_data().is_some() || (path_type && crate::select::is_path_type(n)); + let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(picks)).collect(); let mut rest = vec![]; walk_pickable(cx, |n| { if let NodeKind::Path { guide: false, .. } = &n.kind { @@ -407,9 +418,28 @@ pub(crate) fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator(cx: &'a ToolContext) -> impl Iterator + 'a { + let editable = cx.doc.editable(); + cx.selection.objects.iter().copied().filter(move |&id| { + editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. }) || crate::select::is_path_type(n)) + }) +} + /// The paths whose anchors show with the Pen: the selected ones, and those inside selected groups -/// and compound paths (not guides, nor locked or hidden ones). Pen + Alt converts their anchors. +/// and compound paths (not guides, nor locked or hidden ones). pub(crate) fn shown_paths(cx: &ToolContext) -> Vec { + shown(cx, false) +} + +/// [`shown_paths`] with selected type on a path outside perspective, as the Anchor Point tool the +/// Pen lends takes it ([`anchor_owners`]): the objects whose anchors Pen + Alt converts (#10862). +pub(crate) fn shown_anchor_owners(cx: &ToolContext) -> Vec { + shown(cx, true) +} + +fn shown(cx: &ToolContext, path_type: bool) -> Vec { fn inside(n: &vectorcraft_doc::Node, v: &mut Vec) { match &n.kind { NodeKind::Path { guide: false, .. } => v.push(n.id), @@ -424,7 +454,11 @@ pub(crate) fn shown_paths(cx: &ToolContext) -> Vec { } let mut v = vec![]; for n in cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)) { - inside(n, &mut v); + if path_type && crate::select::is_path_type(n) { + v.push(n.id); + } else { + inside(n, &mut v); + } } let editable = cx.doc.editable(); v.retain(|id| editable(*id)); @@ -436,11 +470,17 @@ pub(crate) fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId anchor_in(cx, candidate_paths(cx), p, tol) } -/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor). +/// [`hit_anchor`] on the [`anchor_owners`], selected type on a path's path included. +pub(crate) fn hit_owner_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> { + anchor_in(cx, anchor_owners(cx), p, tol) +} + +/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor). Type on +/// a path among `ids` offers its path's anchors ([`vectorcraft_doc::Node::anchor_path`]). pub(crate) fn anchor_in(cx: &ToolContext, ids: impl IntoIterator, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> { let mut best: Option<((NodeId, usize, usize), f64)> = None; for id in ids { - let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue }; for (si, ai, a) in pd.anchors() { let d = a.p.distance(p); if d <= tol && best.is_none_or(|b| d < b.1 - 1e-9) { @@ -459,11 +499,16 @@ pub(crate) fn hit_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeI segment_in(cx, candidate_paths(cx), p, tol) } +/// [`hit_segment`] on the [`anchor_owners`], selected type on a path's path included. +pub(crate) fn hit_owner_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> { + segment_in(cx, anchor_owners(cx), p, tol) +} + /// Nearest point within `tol` on a segment of the first of `ids` that passes there: (path, -/// subpath, segment, t). +/// subpath, segment, t). Type on a path among `ids` offers its path's segments. pub(crate) fn segment_in(cx: &ToolContext, ids: impl IntoIterator, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> { for id in ids { - let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue }; if let Some((si, seg, t, _, d)) = pd.nearest(p) && d <= tol { diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 5a92f70faa..5d6e7ec8e7 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -14,12 +14,14 @@ //! follow the same conversions (#2544). //! Scissors: hover and click snap as the Pen does; click a path to split it there (Alt = add, //! as the Add Anchor Point tool does). +//! Add, Delete and Anchor Point edit the path of selected type on a path outside perspective as +//! they edit a path's (#10862); Delete leaves it two anchors at least, and Scissors does not cut it. use serde_json::json; use vectorcraft_doc::NodeId; use vectorcraft_geom::{ParamCurve, Point}; -use super::{FEEDBACK, hit_anchor, hit_segment, insert_anchor, remove_anchor}; +use super::{FEEDBACK, hit_anchor, hit_owner_anchor, hit_owner_segment, hit_segment, insert_anchor, remove_anchor}; use crate::direct::hit_handle; use crate::guides::{DrawSnap, HandleSnap}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -276,14 +278,14 @@ impl AnchorTool { } fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option { - cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) + cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) } /// Where anchor `ai` is in the document a preview edits: the document as the interaction /// began, since each preview runs on that, otherwise the document `cx` shows. fn began_anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option { let d = cx.interaction_doc.unwrap_or(cx.doc); - d.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) + d.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) } /// Where a blend's spine point `ai` is in the spine a spine edit changes: the spine pinned @@ -342,9 +344,9 @@ impl AnchorTool { let (point, tol) = (cx.point_tol(), cx.pick_tol()); let mut target = if let Some((id, si, ai, out)) = hit_handle(cx, p, point) { State::Handle { id, si, ai, out, start: p, began: false } - } else if let Some((id, si, ai)) = hit_anchor(cx, p, point) { + } else if let Some((id, si, ai)) = hit_owner_anchor(cx, p, point) { State::Convert { id, si, ai, start: p, began: false } - } else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) { + } else if let Some((id, si, seg, t)) = hit_owner_segment(cx, p, tol) { State::Reshape { id, si, seg, t, start: p, began: false, spine: false } } else { State::Idle @@ -402,12 +404,10 @@ impl AnchorTool { /// instead of converting it. Any other press is kept. fn moving(cx: &ToolContext, st: State) -> State { match st { - State::Convert { id, si, ai, start, .. } => { - match cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) { - Some(from) => State::Move { id, si, ai, from, start, began: false }, - None => st, - } - } + State::Convert { id, si, ai, start, .. } => match Self::anchor_pos(cx, id, si, ai) { + Some(from) => State::Move { id, si, ai, from, start, began: false }, + None => st, + }, State::SpineConvert { id, ai, start, .. } => { match crate::direct::spines(cx) .into_iter() @@ -471,11 +471,11 @@ impl AnchorTool { } fn add(cx: &ToolContext, p: Point) -> Vec { - hit_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect() + hit_owner_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect() } fn delete(cx: &ToolContext, p: Point) -> Vec { - hit_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect() + hit_owner_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect() } } @@ -708,8 +708,8 @@ impl Tool for AnchorTool { let has_handles = cx .doc .node(id) - .and_then(|n| n.path_data()) - .and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) + .and_then(|n| n.anchor_path()) + .and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied()) .is_some_and(|a| a.has_in() || a.has_out()); if has_handles { vec![Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": "corner"}))] @@ -743,7 +743,8 @@ impl Tool for AnchorTool { )] } State::Handle { id, si, ai, out, began: false, .. } => { - let Some(a) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) else { + let Some(a) = cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied()) + else { return vec![]; }; vec![Action::Exec( @@ -780,6 +781,10 @@ impl Tool for AnchorTool { } fn overlays(&self, cx: &ToolContext) -> Vec { let mut out = if self.id == "anchorPoint" { Self::spine_overlays(cx) } else { vec![] }; + if self.id != "scissors" { + // These tools edit selected type on a path's path, whose anchors the canvas leaves out. + out.extend(crate::direct::type_path_overlays(cx)); + } if matches!(self.state, State::Handle { .. }) { out.extend(self.guides.iter().cloned()); } diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index 9f66d7162c..44bc68cbe1 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -672,6 +672,62 @@ fn anchor_tools_leave_out_shaper_sources_and_art_outside_isolation() { assert_eq!(picked(Some(rect), "deleteAnchor", 100.0, 100.0), Some(rect)); } +/// #10862: selected type on a path's path takes the Anchor Point, Add and Delete Anchor Point tools +/// as a path does; Scissors leaves it alone, and type that is not selected is not picked. +#[test] +fn anchor_tools_edit_selected_type_on_a_path() { + let (d, text) = doc_with_path_type(); + let p = paint(); + let mut s = Selection::default(); + s.add(text); + let names = |a: &[Action]| -> Vec<(String, u64)> { + a.iter() + .filter_map(|x| match x { + Action::Preview(c, v) | Action::Exec(c, v) => Some((c.clone(), v["id"].as_u64()?)), + _ => None, + }) + .collect() + }; + let gesture = |sel: &Selection, tool: &str, from: (f64, f64), to: (f64, f64)| { + let cx = cx(&d, sel, &p); + let mut t = AnchorTool::new(tool); + let mut out = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1)); + if from != to { + out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1))); + } + out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1))); + names(&out) + }; + let convert = gesture(&s, "anchorPoint", (400.0, 300.0), (420.0, 260.0)); + assert!(convert.contains(&("path.convertAnchor".into(), text.0)), "{convert:?}"); + assert_eq!(gesture(&s, "addAnchor", (250.0, 300.0), (250.0, 300.0)), vec![("path.insertAnchor".to_string(), text.0)]); + assert_eq!(gesture(&s, "deleteAnchor", (400.0, 300.0), (400.0, 300.0)), vec![("path.removeAnchor".to_string(), text.0)]); + assert!(gesture(&s, "scissors", (250.0, 300.0), (250.0, 300.0)).is_empty(), "Scissors does not cut type"); + let none = Selection::default(); + assert!(gesture(&none, "anchorPoint", (400.0, 300.0), (420.0, 260.0)).is_empty(), "type that is not selected"); +} + +/// #10862: the anchors of selected type on a path's path show with the tools that edit them (the +/// canvas draws only a path's own), not with Scissors, and not when the type is not selected. +#[test] +fn anchor_tools_show_the_anchors_of_selected_type_on_a_path() { + let (d, text) = doc_with_path_type(); + let p = paint(); + let mut s = Selection::default(); + s.add(text); + let anchors = + |o: Vec| -> Vec { o.into_iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(p) } else { None }).collect() }; + let ends = [Point::new(100.0, 300.0), Point::new(400.0, 300.0)]; + let selected = cx(&d, &s, &p); + for tool in ["anchorPoint", "addAnchor", "deleteAnchor"] { + assert_eq!(anchors(AnchorTool::new(tool).overlays(&selected)), ends, "{tool}"); + } + assert_eq!(anchors(crate::pen::PenTool::default().overlays(&selected)), ends, "pen"); + assert!(anchors(AnchorTool::new("scissors").overlays(&selected)).is_empty()); + let none = Selection::default(); + assert!(anchors(AnchorTool::new("anchorPoint").overlays(&cx(&d, &none, &p))).is_empty()); +} + #[test] fn anchor_point_drag_pulls_handles_click_converts() { let (d, id) = doc_with_rect(); diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 3fd145868c..07ba0a3161 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -36,7 +36,7 @@ use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{Anchor, BezPath, Point, Vec2}; use crate::direct::hit_handle; -use crate::draw2::{AnchorTool, editable_paths, shown_paths}; +use crate::draw2::{AnchorTool, editable_anchor_owners, shown_anchor_owners, shown_paths}; use crate::guides::{DrawSnap, Leave}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -225,21 +225,21 @@ fn pick_endpoint(first: Option, last: Point, p: Point, tol: f64, tie: End (None, None) => None, } } -/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's -/// gesture, within its tolerance. +/// Alt held over a handle end, an anchor or a segment of a selected path, or of selected type on a +/// path's path: the Anchor Point tool's gesture, within its tolerance. fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool { let point = cx.point_tol(); m.alt && (hit_handle(cx, p, point).is_some() - || crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some() - || crate::draw2::segment_in(cx, crate::draw2::shown_paths(cx), p, cx.pick_tol()).is_some()) + || crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some() + || crate::draw2::segment_in(cx, shown_anchor_owners(cx), p, cx.pick_tol()).is_some()) } /// The cursor where [`alt_converts`]: Alt lends the Anchor Point tool, so its caret over a handle /// end or an anchor, the Reshape Segment cursor over a segment. fn alt_cursor(cx: &ToolContext, p: Point) -> Cursor { let point = cx.point_tol(); - if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some() { + if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some() { Cursor::AnchorPoint } else { Cursor::ReshapeSegment @@ -526,7 +526,8 @@ impl Tool for PenTool { if let Some(t) = &self.convert { return t.overlays(cx); } - let mut o = vec![]; + // Pen + Alt and Auto Add/Delete edit selected type on a path's path, so its anchors show. + let mut o = crate::direct::type_path_overlays(cx); // The rubber band preference hides only the preview segment; Measurement Labels decides the readout. if self.drag.is_none() && self.handle.is_none() @@ -752,15 +753,16 @@ pub(crate) fn continue_from(cx: &ToolContext, id: NodeId, si: usize, at_first: b out } -/// Auto Add/Delete: what a click at `p` does to a selected path. On one of its anchors it deletes -/// it; else, where one of its segments passes within `tol`, it adds an anchor. None when the -/// preference turns it off, Shift is held, or no selected path is there. +/// Auto Add/Delete: what a click at `p` does to a selected path, or to selected type on a path's +/// path. On one of its anchors it deletes it; else, where one of its segments passes within `tol`, +/// it adds an anchor. None when the preference turns it off, Shift is held, or no selected path is +/// there. fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option { if !cx.auto_add_delete || m.shift { return None; } - let anchor = crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).map(crate::draw2::remove_anchor); - anchor.or_else(|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).map(crate::draw2::insert_anchor)) + let anchor = crate::draw2::anchor_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::remove_anchor); + anchor.or_else(|| crate::draw2::segment_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::insert_anchor)) } /// A click on a selected blend's spine: delete the point under `p` when no key object sits on it diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index b2eeb4170e..536c45472d 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -149,7 +149,15 @@ pub(crate) fn open_with( previewing: bool, ) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, spec.command, fields, build); + // Each add-on dialog previews on the canvas, so the scrim leaves the canvas undimmed (#10706). + let canvas = crate::dialogs::host::preview_canvas(app); + let dialog = HostedParamDialog::new(&ctx, spec.command, fields, move |fields| { + let dialog = build(fields); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } + }); let dialog = if previewing { dialog } else { dialog.preview_off() }; let host = app.dialogs().ok_or("no window")?; close_open(app); diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index 92ad231a96..79faf1802d 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -16,7 +16,7 @@ use vectorcraft_tools::addons::tangent_circle; use crate::VectorcraftApp; use crate::canvas::rulers::general_lengths; -use crate::dialogs::host::{HeldOptions, open_held_with}; +use crate::dialogs::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas}; use crate::dialogs::preview::LivePreview; /// The dialog's kind. @@ -64,9 +64,10 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { let lengths = general_lengths(app); let fields = DialogFields::from_pairs([("radius", FieldValue::Number(radius))]); // The field has no bounds: a radius typed outside the tool's range is kept as typed and shows [`RADIUS_RANGE`]. + let canvas = preview_canvas(app); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { let rows = vec![Param::number("radius", tl!("Radius:"), radius, 1.0, 2).length(lengths)]; - ParamDialog::new(KIND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true) + ParamDialog::new(KIND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews_on(true, canvas) }); let cancel: Box = Box::new(|app| { if let Some(mut open) = app.addon_dialogs.tangent_radius.take() { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 538e681765..12cc42686c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -11,6 +11,7 @@ use craft::ui::docking::IconGroupSeparator; use craft::ui::list::{CommandHighlight, ThumbRows}; use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; +use craft::ui::runtime::drag::{self, OsFiles}; use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; use craft::ui::runtime::toast::{self, Toast}; @@ -149,7 +150,6 @@ impl VectorcraftApp { spelling: Default::default(), text_nodes: Default::default(), momentary: None, - momentary_keys: vec![], hand: None, zoom_tool: None, selection_box: None, @@ -368,18 +368,26 @@ impl VectorcraftApp { } /// The folders this pass may read and write: the automation roots while the pass carries - /// input the control channel injected, or delivers files the OS dropped in such a pass; - /// anywhere otherwise. + /// input the control channel injected, or while the drag session still holds files the OS + /// dropped in such a pass; anywhere otherwise. fn automation_scope(&self, ctx: &egui::Context) -> Option> { - let delivers = self.confined_drop.is_some_and(|last| ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT) <= last); - (WindowHost::of(ctx).injected_pass() || delivers).then(|| self.automation_roots.clone()).flatten() + (WindowHost::of(ctx).injected_pass() || self.confined_drop.is_some()).then(|| self.automation_roots.clone()).flatten() } - /// Notes files the OS dropped in a pass that carries injected input: the drag session delivers - /// them in the next root frame, which [`Self::automation_scope`] confines too. + /// Keeps the files the OS dropped in a pass that carries injected input until the drag session + /// lets them go: it delivers them in a later pass, after their target is resolved, and + /// [`Self::automation_scope`] confines every pass until then. fn note_confined_drop(&mut self, ctx: &egui::Context) { + if self.automation_roots.is_none() { + return; + } + let held = || drag::active::(ctx); if WindowHost::of(ctx).injected_pass() && ctx.input(|i| !i.raw.dropped_files.is_empty()) { - self.confined_drop = Some(ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT) + 1); + self.confined_drop = held(); + } else if let Some(dropped) = &self.confined_drop + && !held().is_some_and(|now| Arc::ptr_eq(&now, dropped)) + { + self.confined_drop = None; } } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index b98eeb4606..ff93fc733c 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -81,9 +81,6 @@ pub struct CanvasCache { /// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between /// passes; the tool adapter takes it out for its call and puts it back. pub momentary: Option, - /// The keys down when the held momentary command started; empty while none is held or when none started it. - /// Temporary, with `tool_adapter::end_missed_momentary` (craft-libs#5056). - pub momentary_keys: Vec, pub hand: Option, /// The selected Zoom tool keeps its press and drag rectangle between canvas passes. pub zoom_tool: Option, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 73b97bce0f..facbde7d15 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -146,6 +146,8 @@ struct Body { edited: Option, /// The Quick Pen tool took this pass's wheel for its arc size ([`quick_pen_wheel::arc_size`]). arc_view: Option, + /// What this pass's pan by whole device pixels left ([`pan_on_device_pixels`]). + pan: Option, } /// Window `win`'s document in the framework canvas, filling the rest of `ui`. True when the canvas @@ -184,6 +186,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin if refit && queued.is_empty() { queued.push(ViewRequest::Place(ViewCommands::FitArtboard)); } + // A view the app asks for this pass (a fit, a zoom command) keeps its exact center. + let requested = !queued.is_empty(); let mut cv = view.canvas(scaling, area); let given = cv; // A zoom percentage (Actual Size) counts from the density of the display that shows this @@ -265,8 +269,16 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pass.view = Some(arc_view); } } + // The canvas's own pans (the wheel, a middle-button drag, keys) move the view by a step from where it was. + let pan = (!measuring).then(|| { + let rest = doc_windows::view(app, win) + .filter(|_| !requested) + .and_then(|v| v.pan_rest.filter(|rest| rest.kept == Some((v.center, v.zoom, v.rotation)))); + pan_on_device_pixels(rest, ui.ctx().input(|i| i.max_texture_side), &mut space, pass.as_mut()) + }); body = with_canvas_space(ui, space, |ui| show_body(app, ui, &space, pass.as_ref(), win, kind, bar_shapes)); body.arc_view = arc_turn.then_some(arc_view); + body.pan = pan; } }); let output = shown.output; @@ -279,7 +291,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, context_key, edited, arc_view } = body; + let Body { reply, context_at, context_key, edited, arc_view, pan } = body; let request = reply .as_ref() .and_then(|r| r.context.as_ref()) @@ -288,13 +300,17 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin let jumped = edited.is_some(); // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own, and a // wheel turn the Quick Pen tool takes for its arc size leaves other view requests in place. - let view_now = if presenting && ui.input(|i| i.pointer.middle_down()) { - given - } else { - edited.or(reply.and_then(|r| r.view)).or(arc_view).or(output.view).unwrap_or(cv) - }; + let keeps_given = presenting && ui.input(|i| i.pointer.middle_down()); + let pan = pan.filter(|_| !keeps_given); + let view_now = + if keeps_given { given } else { edited.or(reply.and_then(|r| r.view)).or(arc_view).or(pan.map(|p| p.view)).or(output.view).unwrap_or(cv) }; + // Pointer drags of the Hand, compass and scroll bars request absolute views without carrying a rounding remainder. + let absolute_drag = (edited.is_some() || app.session.tool_id() == "hand" || tool_adapter::view_tool_held(app)) + && ui.input(|i| i.pointer.any_down() || i.pointer.any_released()); + let (view_now, pan) = settled_on_device_pixels(pan, view_now, !absolute_drag); if let Some(view) = doc_windows::view_mut(app, win) { view.set_canvas(&view_now, scaling); + view.pan_rest = pan.map(|rest| PanRest { kept: Some((view.center, view.zoom, view.rotation)), ..rest }); // Fitted once, the view stays where it is moved. view.fitted |= refit; // An edit of the compass or a scroll bar reaches the next pass, which stops a running ease. @@ -318,6 +334,100 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } +/// What a canvas pan by whole device pixels ([`pan_step`]) left: the view the canvas settled on, the device pixels a +/// point it was shown at, and the part of a device pixel along each screen axis the pan has not moved yet (at most half +/// a pixel each way). +/// +/// Temporary: storytold/craft-libs#5411 moves the canvas's pans and wheel steps by whole device pixels. Remove this, +/// [`crate::state::View::pan_rest`] and their callers with the craft-libs pin bump that brings it in. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct PanRest { + view: CanvasView, + pixels_per_point: f32, + owed: (f64, f64), + /// The app's center, zoom and rotation after keeping the settled view. + kept: Option<(vectorcraft_geom::Point, f64, f64)>, +} + +impl PanRest { + /// A rest of nothing after `view`, shown at `pixels_per_point`. + fn none(view: CanvasView, pixels_per_point: f32) -> Self { + Self { view, pixels_per_point, owed: (0.0, 0.0), kept: None } + } +} + +/// `view`, when it differs from `from` only in its center: the view that moves the document from where `from` draws it +/// by a whole number of device pixels at `pixels_per_point` along each screen axis, the number nearest to how far +/// `view` moves it plus `owed` device pixels, with what is left of a pixel. Exactly half a pixel left stays owed. None +/// when `view` differs from `from` in more than its center, or `pixels_per_point` or the views are not usable. +pub(crate) fn pan_step(from: CanvasView, view: CanvasView, owed: (f64, f64), pixels_per_point: f32) -> Option<(CanvasView, (f64, f64))> { + let ppp = f64::from(pixels_per_point); + let mut moved = from; + moved.center = view.center; + if moved != view || !(ppp.is_finite() && ppp > 0.0 && view.zoom.is_finite() && view.zoom > 0.0) { + return None; + } + let (a, b) = (from.affine() * vectorcraft_geom::Point::ZERO, view.affine() * vectorcraft_geom::Point::ZERO); + let total = ((b.x - a.x) * ppp + owed.0, (b.y - a.y) * ppp + owed.1); + let nearest = |t: f64| t.signum() * (t.abs() - 0.5).ceil().max(0.0); + let whole = (nearest(total.0), nearest(total.1)); + let shift = egui::vec2((a.x + whole.0 / ppp - b.x) as f32, (a.y + whole.1 / ppp - b.y) as f32); + if !(shift.x.is_finite() && shift.y.is_finite()) { + return None; + } + let mut shown = view; + if shift != egui::Vec2::ZERO { + shown.center = view.center - view.unmap_vec(shift); + } + (shown.center.x.is_finite() && shown.center.y.is_finite()).then_some((shown, (total.0 - whole.0, total.1 - whole.1))) +} + +/// Moves the view the canvas settled on in this pass (`space`'s target) from `rest.view` by whole pixels of the art's +/// frame ([`pan_step`], [`raster::frame_ppp`] with the display's largest texture side `max_side`), adding the part of a +/// pixel `rest` owes, and gives the tool host the same view in `pass`. The render worker then moves the frame it kept +/// ([`raster::render_job`]) instead of rendering the whole canvas for a pan by part of a pixel. Nothing is rounded while +/// a zoom eases, when the app changed the view since `rest`, or when the app asks for a view this pass (`rest` is None). +/// Returns the rest to keep. +fn pan_on_device_pixels(rest: Option, max_side: usize, space: &mut CanvasSpace, pass: Option<&mut ToolPass>) -> PanRest { + let target = space.target(); + // The pixels of the art's frame, which are fewer than the device's when the frame would be wider than `max_side`. + let ppp = raster::frame_ppp(target.rect.size(), space.pixels_per_point, max_side); + let step = rest.filter(|rest| !space.easing() && rest.pixels_per_point == ppp).and_then(|rest| { + let mut from = rest.view; + // Match zooms separated only by the UI scaling round trip. + if (from.zoom - target.zoom).abs() <= 1e-12 * from.zoom.abs().max(target.zoom.abs()) { + from.zoom = target.zoom; + } + pan_step(from, target, rest.owed, ppp) + }); + let Some((view, owed)) = step else { + return PanRest::none(target, ppp); + }; + if view != target { + space.set_view(view); + if let Some(pass) = pass { + pass.space = Some(*space); + pass.view = Some(view); + } + } + PanRest { view, pixels_per_point: ppp, owed, kept: None } +} + +/// `view`, the view the app keeps after this pass, moved from the view of `rest` by whole device pixels when it differs +/// from it in its center alone (a tool, a scroll bar or the compass panned it after [`pan_on_device_pixels`]), and the +/// rest to keep. Without `carry` (an absolute drag) the rest neither adds nor keeps a part of a pixel. +fn settled_on_device_pixels(rest: Option, view: CanvasView, carry: bool) -> (CanvasView, Option) { + let Some(rest) = rest else { return (view, None) }; + if rest.view == view { + return (view, Some(PanRest { owed: if carry { rest.owed } else { (0.0, 0.0) }, ..rest })); + } + let ppp = rest.pixels_per_point; + match pan_step(rest.view, view, if carry { rest.owed } else { (0.0, 0.0) }, ppp) { + Some((view, owed)) => (view, Some(PanRest { view, owed: if carry { owed } else { (0.0, 0.0) }, ..rest })), + None => (view, Some(PanRest::none(view, ppp))), + } +} + /// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks and the /// display-only widgets over it, the picture last. fn show_body( diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d0d753082f..9a0c681a4c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6268,6 +6268,309 @@ fn a_whole_pixel_pan() { } } +/// Wheel steps of part of a device pixel, at a zoom and center that put the document's origin between device pixels, +/// move the frame the render worker kept: every frame that may copy from the last one does. +#[test] +fn wheel_steps_of_part_of_a_pixel_move_the_kept_frame() { + keeping_color_settings(|| { + for rulers in [false, true] { + for scaling in [1.0, 1.75] { + wheel_steps_of_part_of_a_pixel(rulers, scaling); + } + } + }); +} + +fn wheel_steps_of_part_of_a_pixel(rulers: bool, scaling: f64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.ui_scaling = scaling; + app.ui.view.rulers = rulers; + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for x in [20, 160, 300] { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 40, "width": 80, "height": 200})).unwrap(); + } + app.canvas.worker_started = true; + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + { + let v = app.view_mut().unwrap(); + let zoom = 1.37; + let scale = f64::from(scaling as f32); + if scaling != 1.0 { + assert_ne!((zoom * scale) / scale, zoom, "the UI scaling round trip changes the canvas zoom"); + } + v.zoom = zoom * scale; + v.center = Point::new(200.3, 150.7); + } + app_step(&mut app, &ctx, vec![]); + let (worker, jobs, done) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + app.canvas.last_ms = 50.0; + let at = app.canvas_view().unwrap().rect.center(); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.3, -0.4), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + let start = app.canvas_view().unwrap().center; + let mut r = vectorcraft_render::Renderer::new(); + let (mut kept, mut copying) = (None, 0); + for _ in 0..10 { + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), wheel.clone()]); + while let Ok(job) = jobs.try_recv() { + let may = job.may_copy && kept.is_some(); + let frame = render_job(&mut r, &mut kept, &job); + copying += usize::from(may); + if may { + assert!(frame.reused, "each new frame of the pan copies the kept frame's pixels, rulers: {rulers}, UI scaling: {scaling}"); + } + let (img, reused) = (frame.img, frame.reused); + done.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused, view_sized: false }) + .unwrap(); + } + } + assert_ne!(app.canvas_view().unwrap().center, start, "the wheel pans the view"); + assert!(copying >= 3, "the pan asks for new frames: {copying}"); +} + +/// Pans by part of a device pixel, each from the view the last one settled on, move the document by whole device pixels +/// at the view's zoom and rotation, and the parts left over add up: after each step the document is within half a device +/// pixel of where the pans together put it. A change of more than the center is not a pan. +#[test] +fn pans_by_part_of_a_pixel_move_by_whole_device_pixels_and_add_up() { + let rect = egui::Rect::from_min_size(pos2(10.5, 7.25), vec2(640.0, 480.0)); + for (zoom, rotation, ppp) in [(1.37, 0.0, 1.0), (0.613, 30.0, 2.0), (7.9, -75.0, 1.25)] { + let start = CanvasView::new(rect, Point::new(203.17, -48.6), zoom).rotation(rotation); + let origin = |v: &CanvasView| v.affine() * Point::ZERO; + let (mut view, mut owed) = (start, (0.0, 0.0)); + // Each step moves the document 0.3 points right and 0.45 points up on screen. + let step = vec2(0.3, -0.45); + for n in 1..=12 { + let mut next = view; + next.center = view.center - view.unmap_vec(step); + let (shown, left) = super::pan_step(view, next, owed, ppp).expect("a pan"); + let ppp = f64::from(ppp); + let (a, b) = (origin(&view), origin(&shown)); + let wanted = origin(&start) + vectorcraft_geom::Vec2::new(f64::from(step.x), f64::from(step.y)) * f64::from(n); + for (from, to, want) in [(a.x, b.x, wanted.x), (a.y, b.y, wanted.y)] { + let moved = (to - from) * ppp; + assert!((moved - moved.round()).abs() < 1e-6, "{zoom} {rotation}° step {n}: moved {moved} device pixels"); + assert!(((to - want) * ppp).abs() <= 0.5 + 1e-6, "{zoom} {rotation}° step {n}: {} device pixels short", (want - to) * ppp); + } + assert_eq!((shown.zoom, shown.rotation, shown.rect), (start.zoom, start.rotation, start.rect)); + (view, owed) = (shown, left); + } + let mut zoomed = view; + zoomed.zoom = zoom * 1.1; + assert_eq!(super::pan_step(view, zoomed, owed, ppp), None, "a zoom is not a pan"); + } +} + +/// A drag (a button held) sets where the view goes: each pass's view stays within half a device pixel of the view the +/// drag asked for, however many passes it lasts, and moves by whole device pixels from the last one. +#[test] +fn a_drag_s_views_stay_within_half_a_pixel_of_the_pointer() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.37); + let mut rest = Some(super::PanRest::none(start, 1.0)); + for n in 1..=20 { + // The drag asks for the view at its press moved 0.35 points a pass. + let mut asked = start; + asked.center = start.center - start.unmap_vec(vec2(0.35, 0.35) * n as f32); + let last = rest.unwrap().view; + let (view, next) = super::settled_on_device_pixels(rest, asked, false); + let [a, b, c] = [last, view, asked].map(|v| v.affine() * Point::ZERO); + for (from, to, want) in [(a.x, b.x, c.x), (a.y, b.y, c.y)] { + assert!(((to - from) - (to - from).round()).abs() < 1e-6, "pass {n}: whole pixels from the last view"); + assert!((to - want).abs() <= 0.5 + 1e-6, "pass {n}: {} device pixels from the drag", want - to); + } + rest = next; + } +} + +/// A drag's rounding is not owed to the pans after it: a drag by 0.4 device pixels leaves the view where it was and +/// nothing owed, so a later step of 0.2 device pixels does not move the view either. +#[test] +fn a_drag_leaves_nothing_owed_to_later_pans() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.0); + let mut asked = start; + asked.center = start.center - start.unmap_vec(vec2(0.4, 0.0)); + let (view, rest) = super::settled_on_device_pixels(Some(super::PanRest::none(start, 1.0)), asked, false); + assert_eq!(view.center, start.center, "a drag by 0.4 device pixels rounds to no move"); + assert_eq!(rest.map(|rest| rest.owed), Some((0.0, 0.0)), "the drag leaves nothing owed"); + let mut stepped = view; + stepped.center = view.center - view.unmap_vec(vec2(0.2, 0.0)); + let (after, _) = super::settled_on_device_pixels(rest, stepped, true); + assert_eq!(after.center, view.center, "a step of 0.2 device pixels alone does not move the view"); +} + +/// A drag pass that leaves the view where it was clears what earlier pans left owed, so a later step of 0.2 device +/// pixels after 0.4 owed does not move the view by a whole pixel. +#[test] +fn a_drag_that_leaves_the_view_in_place_clears_what_is_owed() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.0); + let owing = super::PanRest { owed: (0.4, 0.0), ..super::PanRest::none(start, 1.0) }; + let (view, rest) = super::settled_on_device_pixels(Some(owing), start, false); + assert_eq!(view, start, "the drag keeps the view"); + assert_eq!(rest.map(|rest| rest.owed), Some((0.0, 0.0)), "the drag leaves nothing owed"); + let mut stepped = view; + stepped.center = view.center - view.unmap_vec(vec2(0.2, 0.0)); + let (after, _) = super::settled_on_device_pixels(rest, stepped, true); + assert_eq!(after.center, view.center, "a step of 0.2 device pixels alone does not move the view"); + // A pass that carries the rest keeps what is owed when the view stays where it was. + let (_, kept) = super::settled_on_device_pixels(Some(owing), start, true); + assert_eq!(kept.map(|rest| rest.owed), Some((0.4, 0.0)), "a carrying pass keeps what is owed"); +} + +/// Steps a tool takes from where the view was (a drag's autoscroll, the Hand's glide) keep the parts of a pixel they +/// leave: after each pass the view is within half a device pixel of all the steps together. +#[test] +fn a_tool_s_steps_keep_the_parts_of_a_pixel_they_leave() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.37); + let mut rest = Some(super::PanRest::none(start, 1.25)); + for n in 1..=12 { + let last = rest.unwrap().view; + // Each pass the tool moves the view it was given 2.4 device pixels left. + let mut asked = last; + asked.center = last.center - last.unmap_vec(vec2(-2.4 / 1.25, 0.0)); + let (view, next) = super::settled_on_device_pixels(rest, asked, true); + let moved = (view.affine() * Point::ZERO).x - (start.affine() * Point::ZERO).x; + assert!((moved * 1.25 + 2.4 * f64::from(n)).abs() <= 0.5 + 1e-5, "pass {n}: moved {} device pixels", moved * 1.25); + rest = next; + } +} + +/// A Hand drag by parts of a device pixel, at a zoom and center that put the document's origin between device pixels, +/// ends where the pointer let go: the document is within half a device pixel of where the drag puts it, after the +/// release too. +#[test] +fn a_hand_drag_by_parts_of_a_pixel_ends_where_the_pointer_lets_go() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("hand"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + { + let v = app.view_mut().unwrap(); + v.zoom = 1.37; + v.center = Point::new(200.3, 150.7); + } + app_step(&mut app, &ctx, vec![]); + let start = app.canvas_view().unwrap(); + let at = start.rect.center(); + let end = at + vec2(17.7, 12.35); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press(at, true)]); + for to in [at + vec2(13.7, 9.35), end] { + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + } + let origin = |v: &CanvasView| v.affine() * Point::ZERO; + let wanted = origin(&start) + vectorcraft_geom::Vec2::new(f64::from(end.x - at.x), f64::from(end.y - at.y)); + let near = |app: &VectorcraftApp, when: &str| { + let got = origin(&app.canvas_view().unwrap()); + assert!((got.x - wanted.x).abs() <= 0.5 + 1e-6 && (got.y - wanted.y).abs() <= 0.5 + 1e-6, "{when}: {got:?}, the drag puts it at {wanted:?}"); + }; + near(&app, "dragging"); + app_step(&mut app, &ctx, vec![press(end, false)]); + app_step(&mut app, &ctx, vec![]); + near(&app, "released"); +} + +/// A middle-button drag at 1.25 device pixels a point moves the view by whole device pixels and keeps the parts of a +/// pixel each move leaves: after moves of one point each the document is within half a device pixel of the pointer. +#[test] +fn a_middle_button_drag_keeps_the_parts_of_a_pixel_it_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = crate::testing::ui_context(); + let step = |app: &mut VectorcraftApp, events: Vec| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + let mut raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + raw.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(1.25); + crate::testing::app_frame(app, &ctx, raw); + }; + for _ in 0..3 { + step(&mut app, vec![]); + } + { + let v = app.view_mut().unwrap(); + v.zoom = 1.37; + v.center = Point::new(200.3, 150.7); + } + step(&mut app, vec![]); + assert_eq!(ctx.pixels_per_point(), 1.25); + let start = app.canvas_view().unwrap(); + let at = start.rect.center(); + let middle = + |at: Pos2, pressed: bool| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() }; + step(&mut app, vec![egui::Event::PointerMoved(at), middle(at, true)]); + let mut to = at; + for _ in 0..8 { + to += vec2(1.0, 0.0); + step(&mut app, vec![egui::Event::PointerMoved(to)]); + } + let origin = |v: &CanvasView| v.affine() * Point::ZERO; + let (got, from) = (origin(&app.canvas_view().unwrap()), origin(&start)); + let moved = (got.x - from.x) * 1.25; + assert!((moved - f64::from(to.x - at.x) * 1.25).abs() <= 0.5 + 1e-6, "moved {moved} device pixels for {} points", to.x - at.x); + assert!(((got.y - from.y) * 1.25).abs() <= 0.5 + 1e-6, "no move down"); + step(&mut app, vec![middle(to, false)]); +} + +/// A fit the app asks for after a pan by parts of a device pixel, at the zoom the pan kept, puts the view at the fitted +/// center exactly: the pan's leftover part of a pixel does not round it. +#[test] +fn a_fit_after_a_pan_by_part_of_a_pixel_keeps_its_exact_center() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = crate::testing::ui_context(); + let step = |app: &mut VectorcraftApp, events: Vec| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + let mut raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + raw.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(1.25); + crate::testing::app_frame(app, &ctx, raw); + }; + for _ in 0..3 { + step(&mut app, vec![]); + } + let fitted = app.canvas_view().unwrap(); + let at = fitted.rect.center(); + // The pans start from a view whose document origin is between device pixels of the fitted one. + { + let v = app.view_mut().unwrap(); + v.center = Point::new(v.center.x + 0.37, v.center.y + 0.21); + } + step(&mut app, vec![]); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.3, -0.45), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..3 { + step(&mut app, vec![egui::Event::PointerMoved(at), wheel.clone()]); + } + let panned = app.canvas_view().unwrap(); + assert_ne!(panned.center, fitted.center, "the wheel pans the view"); + assert_eq!(panned.zoom, fitted.zoom, "the pan keeps the zoom"); + assert!(app.view().unwrap().pan_rest.is_some(), "the pan keeps a rest"); + app.view_mut().unwrap().fitted = false; + step(&mut app, vec![]); + let refit = app.canvas_view().unwrap(); + assert_eq!(refit.zoom, fitted.zoom, "the fit gives the same zoom"); + let (got, want) = (refit.affine() * Point::ZERO, fitted.affine() * Point::ZERO); + assert!((got.x - want.x).abs() < 1e-6 && (got.y - want.y).abs() < 1e-6, "the fit is not rounded: {got:?}, fitted at {want:?}"); +} + /// Installing, replacing or removing a plug-in draws a document with a plug-in effect again, and a /// pan from the frame drawn before the change renders whole instead of copying its pixels. The key /// of a document without a plug-in effect does not follow the plug-ins. The other tests share the diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 4edaa65945..67b2b51db8 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -9,8 +9,8 @@ use craft::behavior::{CancelReason, CanvasView, Cursor, PointerKind as Device, P use craft::keymap::{Chord, Key}; use craft::ui::canvas::ToolPath; use craft::ui::canvas::{ - Autoscroll, CanvasTool, Momentary, MomentaryCommands, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, - ToolPass, ToolPointer, + Autoscroll, CanvasTool, Momentary, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, ToolPass, + ToolPointer, }; use craft::ui::contract::DragPreview; use craft::ui::runtime::drag; @@ -656,37 +656,6 @@ impl CanvasTool for SessionTool<'_> { } } -/// Ends the held momentary command (Space's Hand, Cmd+Space's Zoom...) once none of the keys that were down when it -/// started is down, and returns the command still held. The shortcut board drops a queued release when the canvas -/// does not run on the frame the key goes up (a dialog or another tab in front). A hold that started with no key down -/// (automation) lasts until its release. -/// -/// Temporary: craft-libs#5056 ends the hold inside the tool host. Remove this function, [`note_momentary_keys`], -/// their calls and `CanvasCache::momentary_keys` once the craft-libs pin includes that change. -fn end_missed_momentary(ctx: &egui::Context, momentary: &mut Momentary, keys: &mut Vec) -> Option { - let held = momentary.held()?; - if keys.is_empty() { - return Some(held); - } - let down = craft::ui::runtime::keys::held(ctx); - if keys.iter().any(|key| down.contains(key)) { - return Some(held); - } - momentary.fired(held, craft::ui::runtime::commands::FirePhase::Release); - keys.clear(); - None -} - -/// Notes the keys down when a momentary command starts (or changes), for [`end_missed_momentary`]; `before` is the -/// command held before the tool host's pass. -fn note_momentary_keys(ctx: &egui::Context, before: Option, momentary: &Momentary, keys: &mut Vec) { - match momentary.held() { - None => keys.clear(), - Some(held) if before != Some(held) => *keys = craft::ui::runtime::keys::held(ctx), - Some(_) => {} - } -} - /// Runs the tool host on `tool` with the app's momentary set, which the app keeps across passes. A finger, once a pen /// has been seen, only navigates (palm rejection). fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn CanvasTool) -> ToolHostResponse { @@ -694,9 +663,7 @@ fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn C let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); - let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut app.canvas.momentary_keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); - note_momentary_keys(ui.ctx(), before, &momentary, &mut app.canvas.momentary_keys); app.canvas.momentary = Some(momentary); response } @@ -855,14 +822,9 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); - let mut keys = std::mem::take(&mut app.canvas.momentary_keys); drop(app); - let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); - note_momentary_keys(ui.ctx(), before, &momentary, &mut keys); - let mut app = tool.app(); - app.canvas.momentary = Some(momentary); - app.canvas.momentary_keys = keys; + tool.app().canvas.momentary = Some(momentary); response } diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index b120d35c4a..436d8306e0 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -29,11 +29,18 @@ pub static CURSOR_ICONS: AppIcons = AppIcons::new( ("cursor-mark-ring", include_bytes!("../../../assets/cursors/cursor-mark-ring.svg")), ("cursor-mark-square", include_bytes!("../../../assets/cursors/cursor-mark-square.svg")), ("cursor-mark-star", include_bytes!("../../../assets/cursors/cursor-mark-star.svg")), + ("cursor-move", include_bytes!("../../../assets/cursors/cursor-move.svg")), + ("cursor-not-allowed", include_bytes!("../../../assets/cursors/cursor-not-allowed.svg")), ("cursor-pen-convert", include_bytes!("../../../assets/cursors/cursor-pen-convert.svg")), ("cursor-pen-curvature", include_bytes!("../../../assets/cursors/cursor-pen-curvature.svg")), ("cursor-pen-join", include_bytes!("../../../assets/cursors/cursor-pen-join.svg")), ("cursor-pen-new", include_bytes!("../../../assets/cursors/cursor-pen-new.svg")), ("cursor-reshape-segment", include_bytes!("../../../assets/cursors/cursor-reshape-segment.svg")), + ("cursor-resize-h", include_bytes!("../../../assets/cursors/cursor-resize-h.svg")), + ("cursor-resize-nesw", include_bytes!("../../../assets/cursors/cursor-resize-nesw.svg")), + ("cursor-resize-nwse", include_bytes!("../../../assets/cursors/cursor-resize-nwse.svg")), + ("cursor-resize-v", include_bytes!("../../../assets/cursors/cursor-resize-v.svg")), + ("cursor-type-vertical", include_bytes!("../../../assets/cursors/cursor-type-vertical.svg")), ], ); @@ -45,6 +52,8 @@ const PIPETTE_TIP: Vec2 = Vec2::new(2.0, 22.0); const CARET: Vec2 = Vec2::new(12.0, 6.0); /// The blade's point of the knife, at the box's upper right. const BLADE_POINT: Vec2 = Vec2::new(20.0, 4.0); +/// The middle of the box: the crossing of the move, resize and not-allowed glyphs and the vertical I-beam's center. +const CENTER: Vec2 = Vec2::new(12.0, 12.0); /// The bottom of the drop below the paint bucket. const BUCKET_DROP: Vec2 = Vec2::new(20.0, 22.0); /// The bottom of the drop beside the Live Paint diamond. @@ -91,12 +100,12 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::GroupSelection => badged(CursorBadge::Add), Cursor::SelectionMove => badged(CursorBadge::Move), Cursor::SelectionCopy => badged(CursorBadge::Copy), - Cursor::Move => system(CursorIcon::Move), + Cursor::Move => tool("cursor-move", CENTER, None), Cursor::Crosshair => PaintedCursor::Crosshair.into(), - Cursor::ResizeH => system(CursorIcon::ResizeHorizontal), - Cursor::ResizeV => system(CursorIcon::ResizeVertical), - Cursor::ResizeNwSe => system(CursorIcon::ResizeNwSe), - Cursor::ResizeNeSw => system(CursorIcon::ResizeNeSw), + Cursor::ResizeH => tool("cursor-resize-h", CENTER, None), + Cursor::ResizeV => tool("cursor-resize-v", CENTER, None), + Cursor::ResizeNwSe => tool("cursor-resize-nwse", CENTER, None), + Cursor::ResizeNeSw => tool("cursor-resize-nesw", CENTER, None), Cursor::ShearH => PaintedCursor::skew(Vec2::new(1.0, 0.0)).into(), Cursor::ShearV => PaintedCursor::skew(Vec2::new(0.0, -1.0)).into(), Cursor::Rotate => turn_toward(0), @@ -112,16 +121,18 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::PenConvert => tool("cursor-pen-convert", TIP, None), Cursor::Curvature => tool("cursor-pen-curvature", TIP, None), Cursor::AnchorPoint => tool("cursor-anchor-point", CARET, None), - Cursor::Text => system(CursorIcon::Text), - Cursor::TypeVertical | Cursor::TypeAreaVertical | Cursor::TypeOnPathVertical => system(CursorIcon::VerticalText), + Cursor::Text => PaintedCursor::IBeam.into(), + Cursor::TypeVertical | Cursor::TypeAreaVertical | Cursor::TypeOnPathVertical => tool("cursor-type-vertical", CENTER, None), Cursor::TypeArea => PaintedCursor::type_on(false).into(), Cursor::TypeOnPath => PaintedCursor::type_on(true).into(), Cursor::Hand => PaintedCursor::Hand.into(), - Cursor::HandGrab => system(CursorIcon::Grabbing), + // The framework draws the hand closed while the primary button is down. + Cursor::HandGrab => PaintedCursor::Hand.into(), Cursor::ZoomIn => PaintedCursor::zoom(false).into(), Cursor::ZoomOut => PaintedCursor::zoom(true).into(), Cursor::Eyedropper => tool("pipette", PIPETTE_TIP, None), - Cursor::NotAllowed => system(CursorIcon::NotAllowed), + Cursor::NotAllowed => tool("cursor-not-allowed", CENTER, None), + // The window-wide wait pointer of a long operation, not a canvas tool's cursor. Cursor::Busy => system(CursorIcon::Progress), Cursor::AddStop => badged(CursorBadge::Add), Cursor::RemoveStop => badged(CursorBadge::Subtract), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index a0554f26bb..c83bd7fd1c 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -35,6 +35,42 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() { assert!(missed.is_empty(), "hotspots off their glyphs: {missed:?}"); } +/// One tool switches between these looks as the pointer moves (the Curvature pen over an anchor, the +/// Selection arrow over a corner handle, the Hand while it pans, a tool that has nothing to act on, the +/// type tools). The app draws all of them at its own cursor size, so none comes from the desktop's +/// cursor theme at another size; only the window-wide wait pointer of a long operation does. +#[test] +fn a_tools_move_resize_grab_and_not_allowed_cursors_are_drawn_like_its_own() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + crate::icons::register(); + register_app_icons(&CURSOR_ICONS); + let pairs = [ + (Cursor::Curvature, Cursor::Move), + (Cursor::Arrow, Cursor::ResizeNwSe), + (Cursor::Arrow, Cursor::ResizeH), + (Cursor::Hand, Cursor::HandGrab), + (Cursor::Smooth, Cursor::NotAllowed), + (Cursor::TypeArea, Cursor::Text), + (Cursor::TypeArea, Cursor::TypeVertical), + ]; + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + for (own, other) in pairs { + for c in [own, other] { + let cb::Cursor::Painted(painted) = tool_cursor(c) else { panic!("{c:?} beside {own:?} comes from the desktop's cursor theme") }; + let (one, two) = (painted_image(&env, &painted, 1.0), painted_image(&env, &painted, 2.0)); + let (Some(one), Some(two)) = (one, two) else { panic!("{c:?} has no image") }; + assert!(two.size[0] > one.size[0] && two.size[1] > one.size[1], "{c:?} grows with the cursor scale"); + } + } + }) + .textures_delta + .clear(); + assert!(matches!(tool_cursor(Cursor::Busy), cb::Cursor::System(_)), "the wait pointer stays the system's"); +} + /// A `cursor-` icon name a cursor uses must be in the set the host registers. #[test] fn every_cursor_icon_the_app_names_is_in_its_set() { diff --git a/crates/ui-egui/src/dialogs/blend_options.rs b/crates/ui-egui/src/dialogs/blend_options.rs index 86c105c021..6a69222d73 100644 --- a/crates/ui-egui/src/dialogs/blend_options.rs +++ b/crates/ui-egui/src/dialogs/blend_options.rs @@ -19,7 +19,7 @@ use craft::ui::runtime::env::LengthUnits; use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, Selection}; -use super::host::{HeldOptions, open_held_with}; +use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas}; use super::preview::LivePreview; // PLAN: assumed path of wg.A20's `LivePreview` use crate::VectorcraftApp; use crate::canvas::general_lengths; @@ -119,7 +119,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let opening = Arc::new(()); let cancelled = Arc::clone(&opening); let document = app.session.active().map(|st| (st.uid, st.reverts)); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(on_blend, lengths).values(Bind::bound(fields))); + let canvas = preview_canvas(app); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(on_blend, lengths, canvas).values(Bind::bound(fields))); let cancel: Box = Box::new(move |app| { if app.object_dialogs.blend.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) && let Some(open) = app.object_dialogs.blend.take() @@ -138,7 +139,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result { } /// The dialog over its rows; Steps shows (disabled for Smooth Color) with the two modes that have a count of steps. -fn dialog<'a>(on_blend: bool, lengths: LengthUnits) -> ParamDialog<'a> { +/// It previews a blend on `canvas`. +fn dialog<'a>(on_blend: bool, lengths: LengthUnits, canvas: Option) -> ParamDialog<'a> { let spacing = SPACING.iter().map(|(value, label)| ((*value).to_owned(), tl!(label).into())).collect(); let params = vec![ Param::new("spacing", tl!("Spacing:"), ParamKind::choice(spacing, None)), @@ -148,7 +150,7 @@ fn dialog<'a>(on_blend: bool, lengths: LengthUnits) -> ParamDialog<'a> { Param::number("distance", tl!("Distance"), 10.0, 1.0, 3).length(lengths).bounds(Some(0.001), None).visible_when("spacing", "distance"), Param::custom("orientation", tl!("Orientation:"), orientation_row), ]; - ParamDialog::new(KIND, tl!("Blend Options"), params).previews(on_blend) + ParamDialog::new(KIND, tl!("Blend Options"), params).previews_on(on_blend, canvas) } /// The orientation the fields hold: `page` unless it is `path`. diff --git a/crates/ui-egui/src/dialogs/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs index 45798466fb..1250a459d9 100644 --- a/crates/ui-egui/src/dialogs/color_group_options.rs +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -47,7 +47,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { fields.set("name", g.name.as_str()); let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; let rows = vec![Param::new("name", field_label(tl!("Name:")), ParamKind::text(""))]; - let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false); + let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false, None); let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { // A different document, a revert, or a different group closes the draft without renaming. if !same_group(app, &identity) { diff --git a/crates/ui-egui/src/dialogs/color_guide_options.rs b/crates/ui-egui/src/dialogs/color_guide_options.rs index 721064005b..85304706b7 100644 --- a/crates/ui-egui/src/dialogs/color_guide_options.rs +++ b/crates/ui-egui/src/dialogs/color_guide_options.rs @@ -54,7 +54,7 @@ pub fn open(app: &mut VectorcraftApp) { }) .response }); - let dialog = hosted(&ctx, KIND, tl!("Color Guide Options"), fields, vec![steps, variations], false); + let dialog = hosted(&ctx, KIND, tl!("Color Guide Options"), fields, vec![steps, variations], false, None); let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { app.ui.color_guide = options(app.ui.color_guide, &answer.fields); Ok(()) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 938237f5fc..9d6c1af6fc 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -424,12 +424,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let row_swatch = super::recolor::row_swatch_of(&dialogs, parent, &key) .and_then(|(name, lib, to)| view_place(app, &view, &name, &lib, &to)) .filter(|p| picked_row_swatch(app, &view, *p).flatten().is_some()); - let child = ColorPickerDialog::from_request(request) + let mut child = ColorPickerDialog::from_request(request) .eyedropper(true) .add_to_swatches(false) .gamut(gamut(app)) .working_rgb(WorkingRgb) .swatch_view(swatches); + // As for the picker opened on its own, the canvas stays undimmed, so the parent's live preview shows the true + // color; presses on it stay blocked. + if let Some(canvas) = crate::doc_windows::current(app).map(crate::canvas::canvas_id) { + child = child.canvas(canvas).canvas_samples(false); + } let row = super::recolor::row_identity(&dialogs, parent, &key); let id = dialogs.with(|h| h.open_child(child, parent)); // Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to. diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index f385161dda..6b4a082c7a 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -10,7 +10,7 @@ use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use serde_json::{Map, Value}; use super::form; -use super::host::{HeldOptions, open_held_with}; +use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas}; use super::preview::LivePreview; use crate::VectorcraftApp; @@ -119,11 +119,12 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par let setting = Setting::of(app); let fields = form::fields_of(&command_params(command, ¶ms, setting), ¶ms); let token = Arc::new(()); + let canvas = preview_canvas(app); let dialog = { let (key, heading, opening) = (command.to_string(), heading_label(label), params.clone()); HostedParamDialog::command(&ctx, command, fields, move |fields| { ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting)) - .previews(previews) + .previews_on(previews, canvas) .values(craft::ui::contract::Bind::bound(fields)) }) // The Preview box starts off, as production's dialogs did (#5360). diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index 7b28dc305d..9dcfa02d92 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -36,7 +36,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{EnvelopeKind, NodeKind}; use super::form::{fields_of, json_of}; -use super::host::{HeldOptions, open_held_with}; +use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas}; use super::preview::LivePreview; use super::warp_effect::{percent_param, row_label, static_style, style_entries, style_param}; use crate::VectorcraftApp; @@ -195,9 +195,12 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map) -> Value { } }); let held = HeldOptions { parent: None, cancel: Some(cancel) }; + let canvas = preview_canvas(app); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { - ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone()) + ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)) + .values(Bind::bound(fields)) + .previews_on(previews, canvas) + .reset_to(defaults.clone()) }); let document = app.session.active().map(|st| (st.uid, st.reverts)); match open_held_with(app, dialog, ok, held) { diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs index 82987ab202..20375548a7 100644 --- a/crates/ui-egui/src/dialogs/host.rs +++ b/crates/ui-egui/src/dialogs/host.rs @@ -2,6 +2,7 @@ //! module and every held dialog. use craft::ui::dialog::{DialogId, DialogResult, HoldsOk}; +use craft::ui::patterns::form_dialogs::ParamDialog; use craft::ui::runtime::env::WindowKey; use craft::ui::shell::WindowDialogs; use serde_json::Value; @@ -140,6 +141,28 @@ pub(crate) fn open_held_with( Some(id) } +/// The canvas of the window that shows the active document, for a dialog that previews on it. +pub(crate) fn preview_canvas(app: &VectorcraftApp) -> Option { + crate::doc_windows::current(app).map(crate::canvas::canvas_id) +} + +/// A parameter dialog's Preview box over a document canvas. +pub(crate) trait PreviewsOn { + /// Shows the Preview box when `on`, and then registers `canvas` (from [`preview_canvas`]): the modal layer's + /// scrim leaves that canvas undimmed, so the preview shows its true colors, and the wheel still moves the view. + fn previews_on(self, on: bool, canvas: Option) -> Self; +} + +impl PreviewsOn for ParamDialog<'_> { + fn previews_on(self, on: bool, canvas: Option) -> Self { + let dialog = self.previews(on); + match canvas.filter(|_| on) { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } + } +} + /// The dialog on top of the stack. pub(crate) fn top_dialog(app: &VectorcraftApp) -> Option { // `open_dialogs` lists in opening order, the top one last. diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index d29451406b..56816f67bc 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -24,6 +24,7 @@ use craft::ui::runtime::env::UnitKind; use serde_json::{Map, Value, json}; use vectorcraft_doc::{JustificationOptions, SingleWordJustify}; +use super::host::{PreviewsOn as _, preview_canvas}; use super::preview::LivePreview; use super::warichu::set_shared; use crate::VectorcraftApp; @@ -92,8 +93,8 @@ fn problem(fields: &DialogFields) -> Option<&'static str> { } /// The dialog over its values: three titled groups of Minimum, Desired and Maximum, Auto Leading and -/// Single Word Justification. Preview starts off ([`HostedParamDialog::preview_off`]). -fn form(fields: &mut DialogFields) -> ParamDialog<'_> { +/// Single Word Justification. Preview starts off ([`HostedParamDialog::preview_off`]) and shows on `canvas`. +fn form(fields: &mut DialogFields, canvas: Option) -> ParamDialog<'_> { let titles = [tl!("Word Spacing"), tl!("Letter Spacing"), tl!("Glyph Scaling")]; let columns = [tl!("Minimum"), tl!("Desired"), tl!("Maximum")]; let mut rows = Vec::new(); @@ -108,7 +109,7 @@ fn form(fields: &mut DialogFields) -> ParamDialog<'_> { let options = single_word_choices().into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect(); rows.push(Param::new("singleWord", tl!("Single Word Justification:"), ParamKind::choice(options, Some("fullJustify".to_owned())))); let reason = problem(fields); - let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true).values(Bind::bound(fields)); + let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews_on(true, canvas).values(Bind::bound(fields)); match reason { Some(why) => dialog.ok_enabled(false).ok_reason(why.into()), None => dialog, @@ -145,7 +146,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result { set_shared(&mut fields, "autoLeading", crate::panels::paragraph::shared_justification_f64(app, |j| j.auto_leading)); set_shared(&mut fields, "singleWord", crate::panels::paragraph::shared_single_word_justify(app).map(single_word_name)); let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), form).preview_off(); + let canvas = preview_canvas(app); + let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), move |fields| form(fields, canvas)).preview_off(); let id = super::host::open_held(app, dialog, |app, result| { let Some(open) = app.justification.take() else { return Ok(()) }; if !open.in_opening_document(app) { diff --git a/crates/ui-egui/src/dialogs/new_color_group.rs b/crates/ui-egui/src/dialogs/new_color_group.rs index 56073beaf9..3f2e00b9b2 100644 --- a/crates/ui-egui/src/dialogs/new_color_group.rs +++ b/crates/ui-egui/src/dialogs/new_color_group.rs @@ -36,7 +36,7 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec) -> Result Result<(), String> { let Some(source) = app.session.active().filter(|active| active.uid == document) else { return Err(tl!("Create this color group in the document that opened the dialog.").to_owned()); diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 6d73024ec8..ca2b4d623c 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -49,7 +49,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s other => (vec![name_row()], Some(crate::panels::swatch_paint_params(other))), }; let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; - let dialog = hosted(&ctx, KIND, tl!("New Swatch"), fields, rows, false); + let dialog = hosted(&ctx, KIND, tl!("New Swatch"), fields, rows, false, None); let group = group.unwrap_or_default().to_owned(); let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { let active = diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 5c2260f526..3e6af7f088 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -26,7 +26,7 @@ use vectorcraft_geom::PathData; use super::form; // PLAN: assumed `LivePreview` is exported by `dialogs::form` (wg.A20, widgets-w11). -use super::host::{HeldOptions, open_held, open_held_with}; +use super::host::{HeldOptions, PreviewsOn as _, open_held, open_held_with, preview_canvas}; use super::preview::LivePreview; use crate::VectorcraftApp; @@ -445,13 +445,14 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem let lengths = crate::canvas::general_lengths(app); let opening = op.opening(); let key = op.key(); + let canvas = preview_canvas(app); let dialog = HostedParamDialog::new(&ctx, key, fields, move |f| { let mut d = ParamDialog::new(key, op.title(), rows(op, &opening, lengths)).values(Bind::bound(f)); if let Some(k) = remember.clone() { d = d.remember(k); } if op.previews() { - d = d.previews(true); + d = d.previews_on(true, canvas); } if op == PathOp::Simplify { d.below(counts_row) } else { d } }); @@ -531,8 +532,9 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) { let reverts = state.reverts; let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height())); let lengths = crate::canvas::general_lengths(app); + let canvas = preview_canvas(app); let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| { - ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews(true) + ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews_on(true, canvas) }); let ok = |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| { let Some(mut record) = app.object_dialogs.split.take() else { return Err(tl!("The Split Into Grid dialog is closed.").to_owned()) }; diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index 3338d9b7bb..e21f80a4e1 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -30,7 +30,7 @@ use vectorcraft_color::cms::{self, Intent, ProfileKind, ProofTarget}; use vectorcraft_engine::cmd::colormgmt::proof_file::{self, EXT}; use vectorcraft_render::proof; -use super::host::{HeldOptions, open_held_with}; +use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas}; use crate::VectorcraftApp; use crate::file_asks::{Owner, ask, ask_while}; use crate::menus::Node; @@ -88,7 +88,8 @@ pub fn open(app: &mut VectorcraftApp) { ("simulatePaper", FieldValue::Bool(s.simulate_paper)), ("simulateBlack", FieldValue::Bool(s.simulate_black)), ]); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, build); + let canvas = preview_canvas(app); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| build(fields, canvas)); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; match open_held_with(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields), options) { Some(id) => app.ui.proof_setup = Some(Open { id, opening: Arc::new(()), before, shown: None, sent: None }), @@ -114,13 +115,13 @@ fn rgb_device(device: &str) -> bool { device.starts_with("rgb:") } -/// The dialog over the host's values, made again every pass. -fn build(fields: &mut DialogFields) -> ParamDialog<'_> { +/// The dialog over the host's values, made again every pass, previewing on `canvas`. +fn build(fields: &mut DialogFields, canvas: Option) -> ParamDialog<'_> { let footer = vec![ (SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other).stays_open(true)), (LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other).stays_open(true)), ]; - ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer) + ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews_on(true, canvas).extra_buttons(footer) } /// The rows for the values `fields` hold now. diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index f270e3227d..f471af1c08 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -132,7 +132,8 @@ use craft::ui::buttons::{IconButton, ToggleButton}; use craft::ui::choice::{Checkbox, Swatch}; use craft::ui::contract::overlay::Anchor; use craft::ui::contract::{ - Bind, CollectionEvent, ColumnSpec, EditResponse, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Trigger, + Bind, CanvasGesture, CollectionEvent, ColumnSpec, EditResponse, Entry, Props as _, Sampler as _, SelectMode, Show as _, ShowCollection as _, + ShowContainer as _, Trigger, }; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; use craft::ui::display::{Shade, Text}; @@ -143,7 +144,7 @@ use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{FormDialog, ResetFooter, ResetPick}; use craft::ui::pickers::Select; use craft::ui::runtime::env::Label; -use craft::ui::runtime::overlay::CloseReason; +use craft::ui::runtime::overlay::{Backdrop, CloseReason}; use craft::ui::runtime::requests::ColorRequest; use craft::ui::sections::{FooterAction, FooterBar}; use craft::ui::table::Table; @@ -1999,11 +2000,15 @@ pub(crate) struct RecolorDialog { picked_row: Option, /// The Color Theme Picker's canvas tool, which the canvas runs while the picker is on. theme_tool: edit_tab::ThemePickTool, + /// The canvas of the window the dialog opened in, which its modal layer leaves undimmed so the preview shows + /// the true colors. + canvas: Option, } impl RecolorDialog { fn new(app: &VectorcraftApp, fields: Fields) -> Self { RecolorDialog { + canvas: crate::doc_windows::current(app).map(crate::canvas::canvas_id), id: dialog_id(KIND), opening: Arc::new(()), feed: Feed::of(app, &fields), @@ -2071,7 +2076,8 @@ impl RecolorDialog { Ok(()) } - fn shown(&mut self, ui: &mut Ui) -> Option> { + /// `covered`: a dialog opened from this one (a row's Color Picker) is open over it. + fn shown(&mut self, ui: &mut Ui, covered: bool) -> Option> { let measuring = craft::ui::runtime::measure::active(ui.ctx()); let finish = self.held.is_accepted(); // The refusal of OK shows until a value changes. @@ -2084,17 +2090,32 @@ impl RecolorDialog { let art = self.fields.bool("__art"); let mut preview = self.fields.bool("preview"); let footer = ResetFooter::new(ui, None, true); + let canvas = self.canvas.filter(|_| !covered); + let theme_pick = self.fields.bool(THEME_PICKER); let RecolorDialog { fields, feed, filed, ends, row_menu, .. } = self; let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).ok_enabled(!waiting); if art { form = form.preview(Some(Bind::bound(&mut preview))); } + // The dialog opened over this one dims the window around the canvas; a scrim of this one under it would dim + // the canvas again. + if covered { + form = form.shaped(|dialog| dialog.backdrop(Backdrop::None)); + } let mut running = false; let out = form.show(ui, |ui, cx, d| { // A measuring run closes nothing: the real run of the same pass makes the close. if finish && !measuring { cx.request_close_as(CloseReason::Activated); } + // The canvas stays undimmed under the modal layer, and the wheel and a middle drag still scroll it. + if let Some(canvas) = canvas { + cx.keep_view_open(canvas); + // The Color Theme Picker's clicks and Shift-drags on the art reach its canvas tool. + if theme_pick { + cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY); + } + } let ctx = ui.ctx().clone(); let ((), gesture) = craft::ui::runtime::edit::watch_gestures(&ctx, || body(ui, d, feed, filed, ends, row_menu, can)); if !measuring { @@ -2136,8 +2157,9 @@ impl StackDialog for RecolorDialog { Some(KIND) } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { - self.shown(ui) + fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option> { + let covered = stack.has_child(self.id); + self.shown(ui, covered) } /// OK as its button gives it: the fields are filed for the app, which answers none until it has diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs index 47e0f722d6..394336039c 100644 --- a/crates/ui-egui/src/dialogs/recolor/fixture.rs +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -59,6 +59,114 @@ fn preserve_grays_can_be_clicked_in_a_narrow_localized_dialog() { } } +/// The whole app in a window with Recolor Artwork open over a red square, and a frame driver. +fn open_over_app() -> (VectorcraftApp, impl FnMut(&mut VectorcraftApp, Vec) -> egui::FullOutput) { + use egui::{RawInput, vec2}; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + let mut time = 0.0; + let mut draw = move |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + app.run("ui.recolorDialog", json!({})).unwrap(); + for _ in 0..8 { + draw(&mut app, vec![]); + } + (app, draw) +} + +/// The rects of the modal scrim that the frame `out` painted over the canvas of `app`, at a point of the canvas that +/// no dialog covers. The frame must also paint the scrim somewhere, so the search can find it. +fn scrims_over_canvas(app: &VectorcraftApp, out: &egui::FullOutput) -> usize { + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + let mut scrim = egui::Color32::TRANSPARENT; + let mut theme = crate::testing::ui_context().run_ui(Default::default(), |ui| scrim = rgba_color(Env::of(ui).tokens.tokens().color.surface.scrim)); + theme.textures_delta.clear(); + let at = app.canvas_view().expect("a canvas").rect.left_top() + egui::vec2(20.0, 20.0); + let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default(); + for bounds in nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Dialog).filter_map(|(_, n)| n.bounds()) { + let covers = (bounds.x0..=bounds.x1).contains(&f64::from(at.x)) && (bounds.y0..=bounds.y1).contains(&f64::from(at.y)); + assert!(!covers, "the probe {at:?} lies on the canvas outside every dialog, not in {bounds:?}"); + } + let shapes = crate::tests_labels::flat_painted_shapes(&out.shapes); + let scrims: Vec = shapes + .iter() + .filter_map(|shape| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None }) + .filter(|rect| rect.fill.a() > 0 && rect.fill.to_opaque() == scrim.to_opaque()) + .map(|rect| rect.rect) + .collect(); + assert!(!scrims.is_empty(), "the modal layer still dims the window around the canvas"); + scrims.iter().filter(|rect| rect.contains(at)).count() +} + +/// Recolor Artwork previews its colors on the art, so its modal layer leaves the canvas undimmed (#10590). +#[test] +fn recolor_artwork_leaves_the_canvas_undimmed() { + let (mut app, mut draw) = open_over_app(); + assert!(app.dialogs().unwrap().with(|host| host.is_open::()), "Recolor Artwork is open"); + let out = draw(&mut app, vec![]); + assert_eq!(scrims_over_canvas(&app, &out), 0, "no scrim over the canvas while Recolor Artwork previews"); + // A click on the canvas stays blocked: it does not reach the tool and clear the selection. + let at = app.canvas_view().unwrap().rect.left_top() + egui::vec2(20.0, 20.0); + let selected = app.session.doc().unwrap().selection.clone(); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + draw(&mut app, vec![Event::PointerMoved(at), press(true)]); + draw(&mut app, vec![press(false)]); + draw(&mut app, vec![]); + assert_eq!(app.session.doc().unwrap().selection, selected, "the click under the dialog leaves the selection"); +} + +/// With the Color Theme Picker on, a click on the art reaches the picker's canvas tool through the dialog's modal +/// layer and becomes a pick. +#[test] +fn a_theme_picker_click_on_the_canvas_is_a_pick() { + let (mut app, mut draw) = open_over_app(); + app.dialogs().unwrap().with(|host| host.get_mut::().map(|d| d.fields.fields.insert(super::THEME_PICKER.into(), json!(true)))); + for _ in 0..3 { + draw(&mut app, vec![]); + } + let at = app.canvas_view().unwrap().to_screen(craft::behavior::kurbo::Point::new(20.0, 20.0)); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + draw(&mut app, vec![Event::PointerMoved(at)]); + draw(&mut app, vec![press(true)]); + draw(&mut app, vec![press(false)]); + for _ in 0..3 { + draw(&mut app, vec![]); + } + let picks = app.dialogs().unwrap().with(|host| host.get::().and_then(|d| d.fields.fields.get(super::THEME_PICKS).cloned())); + let picks = picks.and_then(|p| p.as_array().cloned()).unwrap_or_default(); + assert_eq!(picks.len(), 1, "the click is one pick: {picks:?}"); + let at: Vec = picks[0]["at"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); + assert!(at.len() == 2 && (at[0] - 20.0).abs() < 0.5 && (at[1] - 20.0).abs() < 0.5, "at the point clicked: {at:?}"); +} + +/// A Color Picker opened from a row of Recolor Artwork leaves the canvas undimmed too: neither its own scrim nor the +/// one of the dialog below it covers the canvas (#10590). +#[test] +fn a_row_color_picker_leaves_the_canvas_undimmed() { + use craft::color_ui::ui::ColorPickerDialog; + use craft::ui::runtime::requests::ColorRequest; + let (mut app, mut draw) = open_over_app(); + let red = crate::panels::srgba(&vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.get_mut::().map(|d| d.color_request = Some(ColorRequest::new("0", red)))); + for _ in 0..8 { + draw(&mut app, vec![]); + } + assert!(dialogs.with(|host| host.get::().is_some()), "the row's Color Picker is open"); + assert!(dialogs.with(|host| host.is_open::()), "over Recolor Artwork"); + let out = draw(&mut app, vec![]); + assert_eq!(scrims_over_canvas(&app, &out), 0, "no scrim over the canvas while the row's picker is open"); +} + /// Recolor Artwork over an app, in a window-sized fixture. pub(crate) struct Recolor { fixture: Fixture, diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs index 37e2d113d5..5d4e3b8a01 100644 --- a/crates/ui-egui/src/dialogs/recolor_preset.rs +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -39,7 +39,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { fields.set("limitTo", limit.clone()); fields.set(OPENING, FieldValue::Json(json!({"uid": document, "reverts": reverts, "colors": colors}))); let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))]; - let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false); + let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false, None); // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { let Some(FieldValue::Json(opening)) = answer.fields.get(OPENING) else { return Err("the Recolor with Preset target is missing".into()) }; diff --git a/crates/ui-egui/src/dialogs/spot_colors.rs b/crates/ui-egui/src/dialogs/spot_colors.rs index 4c04501352..7d43a684b9 100644 --- a/crates/ui-egui/src/dialogs/spot_colors.rs +++ b/crates/ui-egui/src/dialogs/spot_colors.rs @@ -31,7 +31,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.set("values", id(use_lab)); let options = CHOICES.iter().map(|(lab, text, help)| (id(*lab).to_owned(), tl!(text).to_owned().into(), tl!(help).to_owned().into())).collect(); let rows = vec![Param::new("values", field_label(tl!("Lab Spot Colors:")), ParamKind::radio_with_details(options, Some(id(true).to_owned())))]; - let dialog = hosted(&ctx, KIND, tl!("Spot Colors"), fields, rows, false); + let dialog = hosted(&ctx, KIND, tl!("Spot Colors"), fields, rows, false, None); let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { let use_lab = answer.fields.text("values") == Some(id(true)); app.run("swatch.spotOptions", json!({ "useLab": use_lab })).map(|_| ()) diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index b0e91b5ba1..427ff07693 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -31,7 +31,7 @@ use serde_json::{Value, json}; use vectorcraft_color::cms::Model; use vectorcraft_color::{Color, GradientPaint, Paint}; -use super::host::{HeldOptions, open_held_with}; +use super::host::{HeldOptions, PreviewsOn as _, open_held_with, preview_canvas}; use crate::VectorcraftApp; use crate::panels::color::{color_of_values, gamut, model_values}; @@ -179,7 +179,8 @@ pub(super) fn name_row() -> Param { Param::new("name", field_label(tl!("Swatch Name:")), ParamKind::text("")) } -/// A hosted dialog for the command `key`, whose rows are `rows`: the one way the colour dialogs build theirs. +/// A hosted dialog for the command `key`, whose rows are `rows`: the one way the colour dialogs build theirs. One +/// that `previews` does so on `canvas`. pub(super) fn hosted( ctx: &egui::Context, key: &'static str, @@ -187,10 +188,11 @@ pub(super) fn hosted( fields: DialogFields, rows: Vec, previews: bool, + canvas: Option, ) -> HostedParamDialog { let title = title.to_owned(); HostedParamDialog::new(ctx, key, fields, move |values| { - ParamDialog::new(key, title.clone(), rows.clone()).values(Bind::bound(values)).previews(previews) + ParamDialog::new(key, title.clone(), rows.clone()).values(Bind::bound(values)).previews_on(previews, canvas) }) } @@ -294,7 +296,7 @@ fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Ve let active = app.session.active().ok_or("no drawing")?; let document = (active.uid, active.reverts); let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; - let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true); + let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true, preview_canvas(app)); if owns_preview(app) { let _ = app.session.cancel_interaction(); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 333d22209d..6c41d58e2d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -356,9 +356,10 @@ pub struct VectorcraftApp { /// (`--automation-read-root`, `--automation-write-root`); `None`: anywhere. See /// [`Self::with_automation_roots`]. automation_roots: Option>, - /// The last root frame of a drop of files the OS made in a pass that carried injected input: the drag session - /// delivers that drop in the next frame, which [`Self::ui`] confines to the automation roots as well. - confined_drop: Option, + /// The files the OS dropped in a pass that carried injected input, while the drag session holds them: every pass + /// until the session lets them go, the one that delivers them included, is confined to the automation roots as well + /// ([`Self::ui`]). + confined_drop: Option>, /// The agents link while the ArtCraft Launcher's switch may let agents in ([`Self::with_agents`]). #[cfg(not(target_arch = "wasm32"))] pub(crate) agents: Option>, diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 84125b1a43..56b6d2ce80 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -277,16 +277,19 @@ pub(crate) fn command_input(app: &VectorcraftApp) -> CommandInput { input.gate(CommandGate::new(gate_state(app), gate_open)) } -/// What the commands' gate reads: whether a file dialog is open or a shortcut is being recorded, and whether the app -/// presents. -fn gate_state(app: &VectorcraftApp) -> (bool, bool) { - (app.file_dialog_open() || recording_shortcut(app), app.ui.screen_mode == 3) +/// What the commands' gate reads: whether a file dialog is open or a shortcut is being recorded, whether the app +/// presents, and whether the Type tool edits text. +fn gate_state(app: &VectorcraftApp) -> (bool, bool, bool) { + (app.file_dialog_open() || recording_shortcut(app), app.ui.screen_mode == 3, app.session.tool_wants_text()) } -/// Whether `command` may run now: nothing while a file dialog is open or a shortcut is being recorded, and only -/// Presentation Mode's own toggle while presenting. -fn gate_open(&(blocked, presenting): &(bool, bool), command: &CommandRef) -> bool { - !blocked && (!presenting || command.id == "view.presentation") +/// Whether `command` may run now: nothing while a file dialog is open or a shortcut is being recorded, only +/// Presentation Mode's own toggle while presenting, and neither panels toggle while the Type tool edits text, where +/// Tab types a tab. Workaround for craft-libs#4783: the framework also sends the Tab the Type tool keeps to the panels +/// toggle. The craft-libs pin bump that includes #4783 removes the third rule. +fn gate_open(&(blocked, presenting, typing): &(bool, bool, bool), command: &CommandRef) -> bool { + let panels_toggle = matches!(ChromeCommand::from_ref(command), Some(ChromeCommand::TogglePanels | ChromeCommand::TogglePanelsKeepTools)); + !blocked && (!presenting || command.id == "view.presentation") && !(typing && panels_toggle) } /// [`gate_open`] for `command` in the app's state now. diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 68243adb08..db8df536e6 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -102,13 +102,6 @@ pub struct GradientUi { /// `paint.editGradient` sorts the stops, so the gradient shown mid-gesture is the last preview /// re-sorted: the editor's tags name stops of this one. pub(crate) begun: Option>, - /// The press of a double click that asked for a stop's color is still held. Until craft-libs#5131 reaches the - /// pin, the slider also drags the stop when the pointer drifts during that press, and the moved stop closes the - /// popover the double click opened: the panel drops that press's slider edits. - pub(crate) color_press: bool, - /// The slider's gesture that the press above began, dropped until its `Commit` or `Cancel`, which can arrive in a - /// pass after the button is up. - pub(crate) color_drag: bool, } /// Select stop `i` (the session's selected stop, shared with the Gradient tool's annotator, the @@ -838,21 +831,6 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra .shared_selection(Bind::bound(&mut shared)) .drop_target::() .show(ui); - let panel = &mut app.ui.gradient_panel; - let color_press = panel.color_press || out.color_requested.is_some(); - let held = craft::ui::runtime::pointer::press_state(ui.ctx()).buttons.contains(craft::behavior::Buttons::PRIMARY); - let dropping = panel.color_drag || (color_press && out.edit.events.began()); - let ended = matches!(out.edit.events.last(), Some(EditEvent::Commit { .. } | EditEvent::Cancel { .. } | EditEvent::Set { .. })); - panel.color_press = color_press && held; - panel.color_drag = dropping && !ended; - if color_press || dropping { - // The drift of the press that asked for the color moves no stop (craft-libs#5131). - if is_grad && let Some(request) = &out.color_requested { - let at = request.rect.map_or(out.edit.response.rect.left_bottom(), |r| r.left_bottom()); - open_popover(app, request.index, at); - } - return; - } let events = &out.edit.events; if !is_grad { // The slider shows the default gradient: an edit of it applies a gradient first. diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f1b6155f6e..cfc38a0be6 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -104,6 +104,10 @@ pub struct View { /// How the canvas reaches the view the app last set ([`Self::set_canvas`] callers). #[serde(skip)] pub moved: Option, + /// What the canvas's last pan left to move ([`crate::canvas::PanRest`]). Temporary, removed with the craft-libs pin + /// bump that brings in storytold/craft-libs#5411. + #[serde(skip)] + pub(crate) pan_rest: Option, } impl Default for View { @@ -122,6 +126,7 @@ impl Default for View { rect: egui::Rect::NOTHING, request: None, moved: None, + pan_rest: None, } } } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 139e7a94f0..06b1d8b30b 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -31,6 +31,7 @@ pub(super) mod picks; mod place; mod plugin_runs; mod plugins; +mod preview_canvas; mod printps; mod printtiling; mod quickpenbar; diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index c6bc026980..a3601e2d3a 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -619,10 +619,24 @@ fn a_drop_in_a_pass_with_one_step_of_injected_input_is_confined_when_delivered() drop_in_an_injected_pass_is_confined("ui.text", json!({"text": "a"})); } +/// The OS held the file under the pointer and drops it in a pass with no pointer position: the drag +/// session holds the drop until a later pass resolves its target, and the drop is still refused when +/// it is delivered there. +#[test] +fn a_drop_that_waits_for_its_target_is_confined_when_delivered() { + drop_is_confined("ui.text", json!({"text": "a"}), true); +} + /// Injects `method` with `params`, has the person drop a file outside the automation roots in the /// same pass, and checks that the drop opens nothing, then that a later drop of the person's opens /// the file. fn drop_in_an_injected_pass_is_confined(method: &str, params: Value) { + drop_is_confined(method, params, false); +} + +/// [`drop_in_an_injected_pass_is_confined`]; `pointer`: the pass that hovers the file carries a +/// pointer position and the drop's pass none, so the drag session delivers the drop a pass later. +fn drop_is_confined(method: &str, params: Value, pointer: bool) { #[derive(Debug)] struct Dropped(PathBuf); impl egui::DroppedFile for Dropped { @@ -633,7 +647,8 @@ fn drop_in_an_injected_pass_is_confined(method: &str, params: Value) { std::fs::read(&self.0).map_err(|e| e.to_string()) } } - let (mut app, tx, base) = confined(&format!("synthetic-{method}")); + // Each scenario has its own directory, so tests running in parallel do not remove each other's files. + let (mut app, tx, base) = confined(&format!("synthetic-{method}-{}", if pointer { "pointer" } else { "nopointer" })); let ctx = crate::testing::ui_context(); let outside = base.join("outside/b.svg"); // The OS holds the file over the window in the pass before it drops it (`hovered`), as a desktop drag does. @@ -641,6 +656,12 @@ fn drop_in_an_injected_pass_is_confined(method: &str, params: Value) { let mut raw = egui::RawInput::default(); if hovered { raw.hovered_files.push(egui::HoveredFile { path: Some(outside.clone()), mime: String::new() }); + if pointer { + raw.events.push(egui::Event::PointerMoved(egui::pos2(300.0, 300.0))); + } + } + if dropped && pointer { + raw.events.push(egui::Event::PointerGone); } if dropped { raw.dropped_files.push(std::sync::Arc::new(Dropped(outside.clone()))); @@ -653,13 +674,13 @@ fn drop_in_an_injected_pass_is_confined(method: &str, params: Value) { tx.send(req).unwrap(); app.run_control(&ctx); pass(&mut app, false, true); - // The drag session delivers a drop of files in the pass after the one the OS dropped them in. - assert_eq!(pass(&mut app, false, false), 0, "{method}: the drop of the pass carrying the input is confined"); - for _ in 0..4 { - pass(&mut app, false, false); + // The drag session delivers a drop of files in a pass after the one the OS dropped them in. + for _ in 0..5 { + assert_eq!(pass(&mut app, false, false), 0, "{method}: the drop of the pass carrying the input is confined"); } pass(&mut app, true, false); pass(&mut app, false, true); + pass(&mut app, false, false); assert_eq!(pass(&mut app, false, false), 1, "{method}: the person's pass is not"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 50991b8d8c..77748f68f5 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -125,6 +125,50 @@ fn home_screen(app: VectorcraftApp) -> Panel { home } +/// Where one frame of the whole window `size` big painted Home's title, after `events`. +fn home_title_after(app: &mut VectorcraftApp, ctx: &egui::Context, size: egui::Vec2, events: Vec) -> egui::Rect { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }; + let out = crate::testing::app_frame(app, ctx, raw); + let titles: Vec = crate::tests_labels::painted_shapes(&out.shapes) + .into_iter() + .filter_map(|(shape, transform, _)| match shape { + egui::Shape::Text(t) if t.galley.text() == "Welcome to VectorCraft" => Some(transform * t.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert_eq!(titles.len(), 1, "Home paints its title once: {titles:?}"); + titles[0] +} + +/// How far a wheel turned to the end over Home's title moves the title, with no recent files in a window `size` big. +fn home_title_moved_by_a_wheel(size: egui::Vec2) -> f32 { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + home_title_after(&mut app, &ctx, size, vec![]); + } + assert!(crate::menus::home_showing(&app), "Home with no document open"); + let before = home_title_after(&mut app, &ctx, size, vec![]); + home_title_after(&mut app, &ctx, size, vec![egui::Event::PointerMoved(before.center())]); + home_title_after(&mut app, &ctx, size, vec![craft::ui::testing::pointer::wheel(-2000.0)]); + let mut after = before; + for _ in 0..3 { + after = home_title_after(&mut app, &ctx, size, vec![]); + } + after.top() - before.top() +} + +/// At the app's default window size, Home's column fits the canvas view, so the page has no room to scroll and shows no +/// scroll bar beside the docks: a wheel leaves the title where it is. In a smaller window, where the Learn cards stand +/// two by two and the column is taller than the view, the page scrolls. +#[test] +fn home_scrolls_only_when_its_column_is_taller_than_the_window() { + let moved = home_title_moved_by_a_wheel(egui::vec2(1440.0, 900.0)); + assert!(moved.abs() < 0.5, "at 1440 by 900 the column fits, so the page does not scroll: moved {moved}"); + let moved = home_title_moved_by_a_wheel(egui::vec2(1280.0, 800.0)); + assert!(moved < -1.0, "at 1280 by 800 the column is taller than the view, so the page scrolls: moved {moved}"); +} + /// Home's Open while a file dialog is still open (a window the system may have placed out of sight) /// says so in the status bar and asks for no second picker; once the first answers, Open asks again /// (#6160). diff --git a/crates/ui-egui/src/tests/preview_canvas.rs b/crates/ui-egui/src/tests/preview_canvas.rs new file mode 100644 index 0000000000..6f9a5d0b0b --- /dev/null +++ b/crates/ui-egui/src/tests/preview_canvas.rs @@ -0,0 +1,82 @@ +//! Dialogs that preview on the canvas keep the canvas open under their modal layer (#10706): the scrim leaves it +//! undimmed, so the preview shows its true colors, and the wheel over it still scrolls the view. + +use serde_json::{Map, json}; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; + +fn step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); +} + +/// A window on a drawing of two squares, both selected, after the frames that lay out its canvas. +fn app() -> (VectorcraftApp, egui::Context) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + for x in [0, 200] { + app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + for _ in 0..3 { + step(&mut app, &ctx, vec![]); + } + (app, ctx) +} + +/// Whether the wheel over the canvas scrolls the view while a dialog is open on top. +fn wheel_scrolls_the_view(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { + for _ in 0..3 { + step(app, ctx, vec![]); + } + assert!(crate::dialogs::host::top_dialog(app).is_some(), "a dialog is open"); + let at = app.canvas_view().unwrap().rect.left_top() + egui::vec2(20.0, 20.0); + for _ in 0..3 { + step(app, ctx, vec![egui::Event::PointerMoved(at)]); + } + let before = app.canvas_view().unwrap().center; + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -3.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..5 { + step(app, ctx, vec![egui::Event::PointerMoved(at), wheel.clone()]); + } + app.canvas_view().unwrap().center != before +} + +#[test] +fn blend_options_on_a_blend_keeps_the_canvas_open() { + let (mut app, ctx) = app(); + app.run("object.blend.make", json!({"smooth": true})).unwrap(); + app.run("ui.blendOptions", json!({})).unwrap(); + assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under Blend Options"); +} + +/// With no blend selected, Blend Options sets the defaults and has nothing to preview, so the canvas stays covered. +#[test] +fn blend_options_for_the_defaults_leaves_the_canvas_covered() { + let (mut app, ctx) = app(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.blendOptions", json!({})).unwrap(); + assert!(!wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas does not reach the view"); +} + +#[test] +fn an_add_on_dialog_keeps_the_canvas_open() { + let (mut app, ctx) = app(); + crate::addons::dialogs::open_from_menu(&mut app, crate::addons::select::points_only::COMMAND).unwrap().unwrap(); + assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under Edit Points Only"); +} + +#[test] +fn a_previewing_command_dialog_keeps_the_canvas_open() { + let (mut app, ctx) = app(); + crate::dialogs::command::open(&mut app, crate::addons::pathtools::BOUNDING_RECTANGLE, "Bounding Rectangle", Map::new()).unwrap(); + assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under the command's dialog"); +} diff --git a/crates/ui-egui/src/tests/selectall.rs b/crates/ui-egui/src/tests/selectall.rs index d7ae5f9b04..1f68db8f0b 100644 --- a/crates/ui-egui/src/tests/selectall.rs +++ b/crates/ui-egui/src/tests/selectall.rs @@ -2,7 +2,8 @@ //! a focused text field selects its own text, the Type tool editing selects the text being edited, //! the Artboards panel selects every artboard after a click on one of its rows with the Artboard //! tool, and only otherwise are all the objects selected. The clipboard keys follow it too: Copy -//! and Cut copy the text selected in a field or in a panel's label before the art. +//! and Cut copy the text selected in a field or in a panel's label before the art. Tab while the +//! Type tool edits types a tab and leaves the panels. use egui::accesskit::{Node, NodeId}; use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, pos2, vec2}; @@ -206,6 +207,51 @@ fn cmd_a_while_editing_type_selects_all_of_its_text() { assert!(names.contains(&json!("Z")), "{names:?}"); } +/// #10817: while the Type tool edits, Tab types a tab character and Shift+Tab does nothing; neither +/// hides the panels. Once the edit ends, Tab hides them again. +#[test] +fn tab_while_editing_type_types_a_tab_and_keeps_the_panels() { + let mut a = App::new(); + a.app.select_tool("type"); + let view = a.app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + a.app.session.pointer(&PointerEvent::new(kind, 100.0, 200.0), view).unwrap(); + } + a.frame(vec![]); + a.frame(vec![Event::Text("abc".into())]); + let text = |a: &App| { + let (id, _, _) = crate::panels::character::text_editing(&a.app).expect("the Type tool edits"); + match &a.app.session.active().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(text(&a), "abc"); + assert!(crate::panel_docking::panels_shown(&a.app)); + // A press and its release, as a keyboard sends them. + let tap = |key, modifiers| [press(key, modifiers), Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }]; + a.frame(tap(Key::Tab, Modifiers::NONE).to_vec()); + a.frame(vec![]); + assert_eq!(text(&a), "abc\t", "Tab types a tab"); + assert!(crate::panel_docking::panels_shown(&a.app), "Tab leaves the panels"); + a.frame(tap(Key::Tab, Modifiers::SHIFT).to_vec()); + a.frame(vec![]); + assert_eq!(text(&a), "abc\t", "Shift+Tab types nothing"); + assert!(crate::panel_docking::panels_shown(&a.app), "Shift+Tab leaves the panels"); + // Two taps in one frame type two tabs. + a.frame([tap(Key::Tab, Modifiers::NONE), tap(Key::Tab, Modifiers::NONE)].concat()); + a.frame(vec![]); + assert_eq!(text(&a), "abc\t\t\t"); + assert!(crate::panel_docking::panels_shown(&a.app)); + // Escape ends the edit: Tab hides the panels again. + a.frame(tap(Key::Escape, Modifiers::NONE).to_vec()); + a.frame(vec![]); + assert!(crate::panels::character::text_editing(&a.app).is_none(), "the edit ended"); + a.frame(tap(Key::Tab, Modifiers::NONE).to_vec()); + a.frame(vec![]); + assert!(!crate::panel_docking::panels_shown(&a.app), "Tab hides the panels outside an edit"); +} + /// With the Artboard tool, Cmd+A after a click on an Artboards panel row selects every artboard /// and leaves the active artboard and the art as they are; so does the macOS menu bar's Select All. /// After a press on the canvas, with the panel closed, or with the Selection tool, Cmd+A selects diff --git a/docs/mcp.md b/docs/mcp.md index 3febb923a8..1699bbeaf8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8069,6 +8069,11 @@ become the `weights` field, which moves the rows' current colors and previews th beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors of the rows that are not excluded, hold current colors or were added on the Edit tab, and still have one, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +While the Recolor Artwork dialog is open, the canvas of the window it opened in is not dimmed, so the preview shows the +art's true colors; the wheel scrolls and zooms the view. While the Color Theme Picker is on, its clicks and +Shift-drags on the art reach the canvas; other presses on the canvas stay blocked. A Color Picker opened from a row +leaves the canvas undimmed too. + The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The Show Color Groups button beside the tabs shows or hides the list (the `groupStorage` field, true when the dialog @@ -9486,6 +9491,14 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. `path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that keeps its kind, leave the document as it is and record no undo step. +`path.convertAnchor`, `path.reshapeSegment`, `path.setHandle`, `path.moveAnchor`, `path.insertAnchor` and +`path.removeAnchor` also take the `id` of type on a path outside perspective and edit its path in document space, so +the Anchor Point, Add Anchor Point and Delete Anchor Point tools, the Pen with Alt and the Pen's Auto Add/Delete work +on selected type on a path as on a path (#10862); the type lays out again along the edited path, and its brackets keep +their fractions of the path. `path.removeAnchor` refuses to leave the type's path with fewer than two anchors, and an +edit that would put it past the canvas is refused; the document does not change. `path.insertAnchor` leaves the type +selected whole, with no direct-selected anchors, so the arrow keys and `path.moveAnchors` move the whole type. The +Scissors tool does not cut type on a path. On a path with Live Corners that store a radius (rounded, or straightened by an earlier move), `path.moveAnchor` and `path.moveAnchors` (and the arrow keys) move the uncut corner each moved anchor belongs to by the drag delta and cut the corners again at their radii. The corners stay live; a live @@ -11610,13 +11623,26 @@ a pin back restores the original; every pin must be on the art's mesh, and empty Initially (and after `paint.default`) new art has a white fill and a 1 pt black stroke. New objects take the fill and stroke proxies (`paint.setFill` / `paint.setStroke` and the weight, whatever is selected) on top of a template. With nothing selected, `stroke.set` / `stroke.setAdvanced` (cap, join, dashes, -arrowheads, profile…) and `graphicStyle.apply` (every fill, stroke and effect, opacity, blend mode and the link to the -style; `add: true` stacks it) set that template instead of editing art. With the Appearance panel's New Art Has Basic +arrowheads, profile…) and `graphicStyle.apply` (every fill, stroke and effect, opacity, blend mode, isolate, knockout and +the link to the style; `add: true` stacks it) set that template instead of editing art. With the Appearance panel's New Art Has Basic Appearance on (the default), a `select.*` command or `layer.target` that changes the selection loads the proxies and the weight from it: only a paint or weight the selected objects share, and art without paint (a placed image that isn't colorized) changes nothing. With the option off (`appearance.setNewArtBasic {on: false}`, the preference `newArtBasic`) new art takes the whole appearance of the last selected object. `appearance.newArt` reports what the next object gets; `paint.default` resets it. +New type (`text.create`) takes the template's fills, strokes and effects when the template is more than one plain fill +and stroke or comes from a graphic style; otherwise it has no fills or strokes of its own and its characters keep their +color. The look `paint.default` gives in a document whose Default Graphic Style was redefined is the document's default, +and new type made with it keeps its characters' color too. The same look taken from a selection (New Art Has Basic +Appearance off) gives new type its fills, strokes and effects. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a +graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. Type made with a graphic +style's look takes the style's opacity and blend mode and is linked to it; otherwise the type keeps its own opacity and +blend mode. New art and type are linked to the style only in the document the style was picked in, or the selection +it was taken from was in; in another document they take the look, with the style's opacity and blend mode, without +the link. A style redefined after it was picked gives new art and type the look picked, without the link, its isolate +or its knockout. When text wrap moves new area type as it is made (an Auto Size frame below a wrap object grows), the +template's placed gradients fit the frame the type ends with. Area type made with `text.create` and `area` takes the +template too; Type on a Path and area type made with `text.createInPath` keep the default appearance. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. `appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?, strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its @@ -17592,6 +17618,9 @@ without `spacing` are errors that change nothing, and a call that changes no blend records no undo step. With no blend selected and no `id`, the call sets the spacing and orientation new blends start with. The Blend panel's Ramp and Shift sliders run it on the selected blends: a drag previews and its release records one undo step. Blend Options sends only the spacing or orientation set in the dialog. +While Blend Options previews a selected blend, the canvas of the current window is not dimmed under the dialog, and the +wheel over it still scrolls the view. Other dialogs with a Preview box on the canvas (envelope, path, Flare Tool, +Justification, Proof Setup, Swatch Options, add-on and command dialogs) work the same way. `object.blend.setEasing {id?, easingType?, ramp?, colorShift?}` sets one blend's easing and color shift (the first selected blend without `id`) and returns `{id, easingType, ramp, colorShift, changed}`; omitted values are kept. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50cb4adeba..c2655b7491 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,6 +783,7 @@ since 2026-10-01. - **PDF editable import:** Place from bytes or a path with `link: false`, and `clipboard.importPdf` followed by Paste, preserve live type on the selected page. Place still honors `textAs: "outlines"`. Synthetic two-page regressions: `crates/engine/src/cmd/fileio/tests_pdffidelity.rs`. No change to the PDF reader's existing fallback rules. - **Tab stops in `.ai`/EPS type and right-aligned lines with tabs (#6147):** type from the text document keeps its paragraphs' tab stops (key 30: positions and left, center, right and decimal alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. In right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none when the tab ends the line, with its hyphen when the line is hyphenated) against the right edge; centred and justified lines, point type and right-to-left paragraphs are aligned as a whole as before. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`. Scores unchanged. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. +- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with `text.create` (the Type and Vertical Type tools) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint, except that a `color` given to `text.create` keeps the characters' fill. Its placed gradients fit the frame the type has once text wrap has moved it. Type made with a style's look is linked to the style, in the document the style was picked in; in another document it takes the look, with the style's opacity and blend mode, without the link. Area type dragged with the Type tool (`text.create` with `area`) takes the template too; Type on a Path and area type made with `text.createInPath` keep the default appearance. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`, `tests::newart::a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type`, `tests::newart::new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with`, `tests::newart::new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name`, `tests::newart::new_type_in_another_document_takes_a_basic_styles_look_and_transparency`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. - **Graph legend swatches have their series' stroke:** a default legend swatch of a stacked column, stacked bar, area or pie series has the thin white stroke of the series' marks (VectorCraft's own rule), beside the plot or across the top, and a stroke kept on the series is on the swatch too. Each series' group then paints with one stroke, so a stacked column or area graph the graph tools draw is saved to `.ai` with its data and settings and opens again as a live graph; a stacked bar graph is still written as its art, as the reader has no type for it. Evidence: `cmd::graph::tests::a_legend_swatch_has_the_stroke_of_its_series_marks`, `cmd::graph::tests::a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`. Scores unchanged. @@ -832,6 +833,7 @@ since 2026-10-01. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. - **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/it/direct_handle_mirror.rs`. +- **Anchor tools on type on a path (#10862):** on selected type on a path outside perspective, the Anchor Point tool and the Pen with Alt (which uses the Anchor Point tool's gestures) pull handles out of, convert, move and bend the type's path, and the Add and Delete Anchor Point tools and the Pen's Auto Add/Delete add and delete its anchors, as on a path; the type lays out again along the edited path, and its path keeps two anchors at least. Type on a path in perspective is not edited by these tools. An anchor added to the type leaves the type selected whole. Regression tests: `anchor_point_tool_pulls_handles_out_of_type_on_a_path`, `anchor_point_tool_reshapes_type_on_a_path`, `add_delete_and_pen_alt_edit_type_on_a_path` and `an_anchor_added_to_type_on_a_path_leaves_it_selected_whole` in `crates/engine/src/tests/pathtype.rs`, `anchor_tools_edit_selected_type_on_a_path` in `crates/tools/src/draw2/anchor/tests.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`. @@ -1932,7 +1934,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. - **Find Font works out the document's fonts once per version:** while Type › Find Font… is open, its Document list (`text.fonts`) and whether it shows Find in Folder… (the document misses a font) are worked out once for each version of the document's content and of the available fonts, and later frames reuse them. The list and the button are the same as before; an edit, an undo, another document in front, entering or leaving pattern editing, a composite font defined or taken out, and fonts added or scanned again give them anew. With 2,000 point-type objects of 50 characters each, set in five installed faces and a missing family, working them out took a median 1.53 ms of thread CPU time per frame in a release build on Linux; the first frame after a change still takes about as long, and later frames take about 10 ns. With 20 such objects it took 58 µs per frame. Tests: `find_font::tests::the_font_list_is_worked_out_once_per_document_version`, `an_edit_works_the_font_list_out_again`, `other_available_fonts_work_the_font_list_out_again`, `the_font_list_follows_the_document_in_front`; the timing probe is `find_font::tests::find_font_list_timing`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). It also takes the font, style, size and other character attributes of a redefined [Normal Character Style], so redefining that style in a New Document profile sets the default font of the profile's documents ([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)); a `font`, `style` or `size` given to the command still wins. Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`, `tests::newdoc::a_profiles_normal_character_style_is_the_default_font`. +- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). When `text.create` type takes the new-art template's fills and strokes (New type takes new art's appearance), Override Character Color takes the characters' fill and stroke away, and only a `color` given to the command keeps their fill. It also takes the font, style, size and other character attributes of a redefined [Normal Character Style], so redefining that style in a New Document profile sets the default font of the profile's documents ([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)); a `font`, `style` or `size` given to the command still wins. Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`, `tests::newdoc::a_profiles_normal_character_style_is_the_default_font`. The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. The Single-line Composer measures a line's room across the height of its tallest character too: a line that takes in a taller character is placed again and broken again in the room there. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`).