Compare commits

..
Author SHA1 Message Date
bflatasticandClaude Opus 5.5 0916534db9 Fix #392: Cmd+A selects a focused field's text or the type being edited
Select All (Cmd/Ctrl+A) now follows the keyboard, as in Illustrator:

- macOS menu bar: the system menu takes Cmd+A/X/C/V before the window
  sees them, so a focused panel, dialog or search field got the document
  command. `menus::invoke_from_system_menu` (used by `NativeMenu::poll`)
  hands Select All, Cut, Copy and Paste to a focused text field as the
  events its keys would send; clicks on those menu items follow the same
  rule. Other commands, and these with no field focused, run as before.
- Type tool: `select.all` itself selects all of the text being edited
  while the Type tool edits (returns {editing, start, end}), so the menu,
  the shortcut, the control channel and headless MCP (`press_key`) agree.
  The UI's own Select All interception and the Type tool's hard-wired
  Cmd+A are gone; Cmd+A reaches it through the Select All shortcut.
- Windows, Linux and the web already left Cmd+A to a focused field; now
  covered by headless app-frame tests (field, Type tool, canvas).

Docs: docs/mcp.md (Select All while editing type), ROADMAP. Not yet:
Select All across threaded frames (one frame's text is selected).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:18:52 +07:00
bflatasticandClaude Opus 5.5 ffed92aba5 Fix #396: SVG type opens at the size it draws at
SVG import kept a <text>'s nominal font-size and left the scale of the
transforms and viewBox above it in the type's transform, so the Character
panel showed one size and the canvas drew another (7 pt under scale(3)
drew at 21 pt).

The importer now moves that scale into the type: the scale across the
baseline (the mean scale for type on a path) multiplies the size,
leading, baseline shift, character stroke weights and dashes and the
text path, and the transform keeps only the rest (a stretch along the
baseline, a skew, a rotation or a reflection). The type draws exactly as
before. Paints resolve in the grown text space, non-scaling strokes and
the stroke under the characters are worked out before the fold, the
factor is rounded to 6 significant digits (usvg's transforms are single
precision) and never pushes sizes past the Character panel's
0.1–1296 pt (the rest stays in the transform).

Tests: a group's, the text's own and a viewBox scale; rotated and scaled
text equal to the same text written at twice the size; stretch and skew;
type on a scaled path; the size limits; gradients on scaled text; SVG
export → import of scaled type (stable over two round trips).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 07:18:34 +07:00
19 changed files with 506 additions and 32 deletions

No files matched your search

+3 -2
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374) and PDF/`.ai` import keeping strokes live and hidden and nested layers (#372) and per-corner Live Corners (#381); see [Honest assessment](#honest-assessment-2026-10-05))._
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381) and SVG type opening at the size it draws at (#396); see [Honest assessment](#honest-assessment-2026-10-05))._
## Where we are
@@ -105,6 +105,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- Four brightness themes, persistent preferences.
- Dialogs open with their first field focused and its value selected: type a value and press Enter (Move, Rotate, Scale…). Number fields in panels and dialogs step with Up/Down (Shift: ten, Ctrl/Cmd: a tenth of their unit), applied at once.
- Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields.
- Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too. Not yet: Select All across threaded frames (one frame's text is selected).
- On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one.
- **Tools:**
- **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it).
@@ -145,7 +146,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
- **Files (M4):**
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export.
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units; PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers; strokes kept live, a fill and a stroke of one outline as one object; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers; strokes kept live, a fill and a stroke of one outline as one object; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs Illustrator's AGM/CoolType prologs (resource categories, `resourceforall`, `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters, `cshow`, metadata skipped with `flushfile`), so Illustrator 30 EPS files open as vectors, and falls back to its palette TIFF preview. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours.
- **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped.
+1 -1
View File
@@ -61,7 +61,7 @@ impl eframe::App for App {
self.menu = Some(native_menu::NativeMenu::install(&mut self.app));
}
if let Some(m) = &mut self.menu {
m.poll(&mut self.app);
m.poll(&mut self.app, ctx);
}
open_files(&mut self.app, open_documents::take());
}
+5 -4
View File
@@ -33,7 +33,7 @@ pub struct NativeMenu {
}
/// Accelerator for a shortcut like "Cmd+Shift+]" (modifier-less shortcuts stay in the app so they
/// don't steal keys from text fields).
/// don't steal keys from text fields; a focused field still gets Cmd+A/X/C/V, see [`NativeMenu::poll`]).
fn accel(sc: &str) -> Option<Accelerator> {
if !(sc.contains("Cmd") || sc.contains("Ctrl") || sc.contains("Alt") || sc.starts_with('F')) {
return None;
@@ -72,12 +72,13 @@ impl NativeMenu {
}
}
/// Dispatch clicked items and refresh state.
pub fn poll(&mut self, app: &mut VectorcraftApp) {
/// Dispatch chosen items (a focused text field takes Select All and the clipboard) and refresh
/// state.
pub fn poll(&mut self, app: &mut VectorcraftApp, ctx: &egui::Context) {
while let Ok(ev) = MenuEvent::receiver().try_recv() {
if let Some((cmd, params, _, _)) = self.items.get(ev.id.as_ref()) {
let p = if params.is_null() { serde_json::json!({}) } else { params.clone() };
menus::invoke(app, cmd, p);
menus::invoke_from_system_menu(app, ctx, cmd, p);
}
}
let now = vectorcraft_ui_egui::now_ms();
+21 -1
View File
@@ -9,7 +9,15 @@ use super::*;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, all),
cmd!(
"select.all",
"All",
["Select"],
Some("Cmd+A"),
"{} → {count}; while the Type tool edits text, all of that text instead → {editing, start, end} (byte offsets)",
has_doc,
all
),
cmd!("select.allOnArtboard", "All on Active Artboard", ["Select"], Some("Cmd+Alt+A"), "{artboard?: index}", has_doc, all_on_artboard),
cmd!("select.none", "Deselect", ["Select"], Some("Cmd+Shift+A"), "{}", has_doc, none),
cmd!("select.reselect", "Reselect", ["Select"], Some("Cmd+6"), "{}", has_doc, reselect),
@@ -107,6 +115,18 @@ fn selectable(d: &Document, iso: Option<NodeId>) -> Vec<NodeId> {
}
fn all(s: &mut Session, _: &Value) -> Result<Value> {
// While the Type tool edits text, Select All takes all of that text and leaves the art
// selection as it is (Illustrator: text cursor in a text object).
if s.tool_wants_text() {
s.set_tool_option("selectAll", &json!(true));
let editing = s.tool_options()["editing"].clone();
let id = editing.as_u64().map(NodeId);
let end = id.and_then(|id| match &s.doc().ok()?.doc.node(id)?.kind {
NodeKind::Text(t) => Some(t.plain_text().len()),
_ => None,
});
return Ok(json!({ "editing": editing, "start": 0, "end": end.unwrap_or(0) }));
}
let st = s.doc()?;
let ids = selectable(&st.doc, st.isolation);
s.select(|_, sel| sel.set(ids.iter().copied()))?;
+11 -4
View File
@@ -310,15 +310,18 @@ fn character_panel_flow_styles_the_selected_range_while_editing() {
fn select_all_and_cut_like_ui() {
let mut s = session();
let v = ViewInfo::default();
s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap();
let id = text(&mut s, "abc def");
s.select_tool("type", v).unwrap();
let t = obj(&s, id);
let p = t.xf * Point::new(2.0, -5.0);
click(&mut s, p.x, p.y);
s.set_tool_option("selectAll", &json!(true));
let o = s.tool_options();
let len = obj(&s, id).plain_text().len() as u64;
let r = s.execute("text.getRange", &json!({"id": o["editing"], "start": o["start"], "end": o["end"].as_u64().unwrap().min(len)})).unwrap();
// Select All while editing takes the text, not the art (the rectangle stays unselected).
assert!(s.tool_wants_text());
let o = s.execute("select.all", &json!({})).unwrap();
assert_eq!(o, json!({"editing": id.0, "start": 0, "end": 7}));
assert_eq!(s.doc().unwrap().selection.objects, [id]);
let r = s.execute("text.getRange", &json!({"id": o["editing"], "start": o["start"], "end": o["end"]})).unwrap();
assert_eq!(r["text"], json!("abc def"));
s.set_tool_option("copy", &r["runs"]);
key(&mut s, ToolKey::Delete, Mods::default());
@@ -326,6 +329,10 @@ fn select_all_and_cut_like_ui() {
s.tool_text("abc def", v).unwrap();
s.tool_text("abc def", v).unwrap();
assert_eq!(obj(&s, id).plain_text(), "abc defabc def");
// Not editing: Select All selects the art again.
key(&mut s, ToolKey::Escape, Mods::default());
assert!(!s.tool_wants_text());
assert_eq!(s.execute("select.all", &json!({})).unwrap(), json!({"count": 2}));
}
#[test]
+14 -1
View File
@@ -1,5 +1,6 @@
//! `press_key` with the Width and Puppet Warp tools: Delete and Backspace reach the selected width
//! point or pin, and clear the selected art when the tool has nothing selected.
//! point or pin, and clear the selected art when the tool has nothing selected. Cmd+A while the
//! Type tool edits selects the text, not the art.
use serde_json::{Value, json};
@@ -64,3 +65,15 @@ fn delete_and_backspace_reach_the_puppet_warp_tool() {
assert!(!exists(&h, id), "{key} cleared the art");
}
}
#[test]
fn cmd_a_while_the_type_tool_edits_selects_the_text() {
let mut h = session();
run(&mut h, "shape.rectangle", json!({"x": 300, "y": 300, "width": 20, "height": 20}));
let id = run(&mut h, "text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20}))["id"].as_u64().unwrap();
click(&mut h, "type", 102.0, 95.0);
let r = ok(&mut h, "press_key", json!({"key": "A", "mods": {"cmd": true}}));
assert_eq!(r["command"], "select.all");
assert_eq!(r["result"], json!({"editing": id, "start": 0, "end": 5}));
assert_eq!(h.session.doc().unwrap().selection.objects, [vectorcraft_doc::NodeId(id)], "the art selection stays");
}
+6 -2
View File
@@ -677,9 +677,12 @@ impl Importer {
return Some(vec![]);
}
let text::PendingText { name, mut obj, servers, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone();
// The scale the type draws at becomes its size (last, below): text space grows by `grow`.
let xf = ts * obj.xf;
let grow = text::size_scale(&obj, xf);
// usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user
// space; runs paint in text space.
let to_text = obj.xf.inverse();
let to_text = Affine::scale(grow) * obj.xf.inverse();
let slot_paint = |im: &mut Self, k: usize, m: Affine| match kids.get(main + 1 + k) {
Some(usvg::Node::Path(p)) => p.fill().map_or(Paint::None, |f| {
let area = kurbo::Shape::bounding_box(&bezpath(p.data(), m));
@@ -697,7 +700,7 @@ impl Importer {
run.style.stroke = server(k);
}
}
obj.xf = ts * obj.xf;
obj.xf = xf;
if non_scaling && !vector_effect::unscale_text(&mut obj, self.screen) {
let label = if name.is_empty() || made_up(&name) { "a text".to_string() } else { format!("text '{name}'") };
self.warn(format!("non-scaling stroke on {label} approximated: the text is stretched or skewed"));
@@ -712,6 +715,7 @@ impl Importer {
ap.set_contents_at(1);
ap
});
text::fold_scale(&mut obj, grow);
let mut n = self.named(&name, NodeKind::Text(Box::new(obj)));
if let Some(ap) = under {
n.appearance = ap;
+51 -1
View File
@@ -15,12 +15,16 @@
//! line spacing), other vertical moves become baseline shift, horizontal moves become kerning (an
//! absolute `x` is measured against the laid-out text), and rotations become character rotation.
//! `<textPath>` becomes type on a path; vertical `writing-mode` becomes type on a vertical path.
//!
//! Type takes the size it draws at: the scale of the transforms and `viewBox` above a `<text>`
//! moves into its sizes ([`size_scale`], [`fold_scale`]), and the rest (a stretch, skew,
//! rotation or reflection) stays its transform.
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::ops::Range;
use std::ops::{Range, RangeInclusive};
use std::rc::Rc;
use std::str::FromStr;
@@ -653,6 +657,52 @@ fn stroke_under(cells: &mut [Cell], label: &str, warnings: &mut Vec<String>) ->
first
}
/// The type sizes the Character panel takes, in points.
const SIZES: RangeInclusive<f64> = 0.1..=1296.0;
/// How much of `xf` (text space → document) [`fold_scale`] makes the type's size: the scale
/// across the baseline for point type (a stretch along it, a skew, a rotation and a reflection
/// stay in the transform), the mean scale for type on a path, whose baseline turns. Not past the
/// Character panel's sizes (the rest stays in the transform); 1 when `xf` collapses the text.
pub(super) fn size_scale(t: &TextObject, xf: Affine) -> f64 {
let [a, b, ..] = xf.as_coeffs();
let det = xf.determinant().abs();
let k = match t.kind {
TextKind::OnPath { .. } => det.sqrt(),
_ => det / a.hypot(b),
};
// To 6 significant digits: usvg's transforms are single precision, and `rotate(30) scale(2)`
// makes 7 pt type 14 pt, not 13.9999998 pt (the type draws the same either way).
let p = 10f64.powi((5.0 - k.log10().floor()) as i32);
let k = (k * p).round() / p;
if !(k.is_finite() && k > 0.0) {
return 1.0;
}
let (lo, hi) = t.runs.iter().map(|r| r.style.size).fold((f64::INFINITY, 0.0f64), |(lo, hi), s| (lo.min(s), hi.max(s)));
// Sizes already outside the range don't move further out.
if k > 1.0 { k.min((SIZES.end() / hi).max(1.0)) } else { k.max((SIZES.start() / lo).min(1.0)) }
}
/// Make text space `k` times larger and the transform `1 / k` times smaller, so the type draws
/// the same at `k` times its size (and leading, baseline shift, character strokes and path): the
/// size the Character panel shows is the size it draws at.
pub(super) fn fold_scale(t: &mut TextObject, k: f64) {
for r in &mut t.runs {
let st = &mut r.style;
st.size *= k;
st.leading = st.leading.map(|l| l * k);
st.baseline_shift *= k;
}
t.scale_char_strokes(k);
let up = Affine::scale(k);
match &mut t.kind {
TextKind::OnPath { path, .. } | TextKind::Area { frame: path } => path.transform(up),
TextKind::Point => {}
}
t.cached_bounds = t.cached_bounds.map(|b| up.transform_rect_bbox(b));
t.xf *= Affine::scale(1.0 / k);
}
/// `v`, or 0 when far-off positions added up past f64's range.
fn finite(v: f64) -> f64 {
if v.is_finite() { v } else { 0.0 }
+133
View File
@@ -385,3 +385,136 @@ fn far_off_positions_stay_finite() {
assert!(r.style.baseline_shift.is_finite() && r.style.kerning.is_none_or(f64::is_finite) && r.style.rotation.is_finite(), "{r:?}");
}
}
/// Drawn bounds of the laid-out text in the document.
fn drawn(t: &TextObject) -> Rect {
t.xf.transform_rect_bbox(layout(FontDb::global(), t).bounds)
}
/// The linear part of a transform.
fn linear(t: &TextObject) -> [f64; 4] {
let [a, b, c, d, ..] = t.xf.as_coeffs();
[a, b, c, d]
}
fn close4(a: [f64; 4], b: [f64; 4]) -> bool {
// usvg's transforms are single precision.
a.iter().zip(b).all(|(a, b)| close(*a, b, 1e-6))
}
#[test]
fn a_scale_above_text_becomes_its_size() {
// #396: a group's or the text's own scale is the size the type shows and draws at.
let d = open(
r#"<text x="50" y="100" font-size="7">HHHH Hamburg</text>
<g transform="scale(3)"><text x="16" y="60" font-size="7">HHHH Hamburg</text></g>
<text x="50" y="400" font-size="7" transform="scale(2)">HHHH Hamburg</text>"#,
);
let t = texts(&d);
let sizes: Vec<f64> = t.iter().map(|t| t.first_style().size).collect();
assert!(close(sizes[0], 7.0, 1e-9) && close(sizes[1], 21.0, 1e-9) && close(sizes[2], 14.0, 1e-9), "{sizes:?}");
for t in &t {
assert!(close4(linear(t), [1.0, 0.0, 0.0, 1.0]), "{:?}", t.xf);
}
assert!(t[1].xf.translation().to_point().distance(Point::new(48.0, 180.0)) < 1e-9, "{:?}", t[1].xf);
assert!(t[2].xf.translation().to_point().distance(Point::new(100.0, 800.0)) < 1e-9, "{:?}", t[2].xf);
// Drawn as large as their sizes say.
let h: Vec<f64> = t.iter().map(|t| drawn(t).height() / t.first_style().size).collect();
assert!(close(h[1], h[0], 1e-6) && close(h[2], h[0], 1e-6), "{h:?}");
}
#[test]
fn a_viewbox_scale_becomes_the_size() {
let d = import(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="306" height="396" viewBox="0 0 612 792"><text x="50" y="100" font-size="7">HH</text></svg>"#,
)
.unwrap();
let t = only_text(&d);
assert!(close(t.first_style().size, 3.5, 1e-9), "{}", t.first_style().size);
assert!(close4(linear(t), [1.0, 0.0, 0.0, 1.0]), "{:?}", t.xf);
assert!(t.xf.translation().to_point().distance(Point::new(25.0, 50.0)) < 1e-9, "{:?}", t.xf);
}
#[test]
fn a_rotated_scale_scales_every_length_and_keeps_the_rotation() {
// The same text written at twice the size: the scale moves into size, leading, baseline
// shift and the character strokes; spacing in ems stays.
let scaled = open(
r#"<text transform="translate(100 50) rotate(30) scale(2)" x="5" y="10" font-size="7" letter-spacing="1" word-spacing="2" stroke="red" stroke-width="0.5" stroke-dasharray="1 2">Ab <tspan baseline-shift="3">c</tspan><tspan x="5" dy="12">Two</tspan></text>"#,
);
let written = open(
r#"<text transform="translate(100 50) rotate(30)" x="10" y="20" font-size="14" letter-spacing="2" word-spacing="4" stroke="red" stroke-width="1" stroke-dasharray="2 4">Ab <tspan baseline-shift="6">c</tspan><tspan x="10" dy="24">Two</tspan></text>"#,
);
let (s, w) = (only_text(&scaled), only_text(&written));
assert_eq!(s.runs, w.runs);
assert!(s.runs.iter().any(|r| r.style.leading == Some(24.0) && r.text.contains("Two")), "{:?}", s.runs);
assert!(close(s.xf.determinant(), 1.0, 1e-6), "{:?}", s.xf);
let r = 30f64.to_radians();
assert!(close4(linear(s), [r.cos(), r.sin(), -r.sin(), r.cos()]), "{:?}", s.xf);
for (a, b) in glyph_origins(s).iter().zip(glyph_origins(w)) {
assert!(a.distance(b) < 1e-6, "{a:?} {b:?}");
}
}
#[test]
fn a_stretch_or_skew_stays_the_transform() {
// The scale across the baseline is the size; a stretch along it or a skew stays.
let d = open(
r#"<text x="10" y="20" font-size="7" transform="scale(3 1)">HH</text>
<text x="10" y="20" font-size="7" transform="scale(1 3)">HH</text>
<text x="10" y="20" font-size="7" transform="skewX(20)">HH</text>"#,
);
let t = texts(&d);
let sizes: Vec<f64> = t.iter().map(|t| t.first_style().size).collect();
assert!(close(sizes[0], 7.0, 1e-9) && close(sizes[1], 21.0, 1e-9) && close(sizes[2], 7.0, 1e-9), "{sizes:?}");
assert!(close4(linear(t[0]), [3.0, 0.0, 0.0, 1.0]), "{:?}", t[0].xf);
assert!(close4(linear(t[1]), [1.0 / 3.0, 0.0, 0.0, 1.0]), "{:?}", t[1].xf);
assert!(close4(linear(t[2]), [1.0, 0.0, 20f64.to_radians().tan(), 1.0]), "{:?}", t[2].xf);
// `scale(1 3)` draws three times as tall as `scale(3 1)`, a third as wide.
let (wide, tall) = (drawn(t[0]), drawn(t[1]));
assert!(close(tall.height(), 3.0 * wide.height(), 1e-6) && close(3.0 * tall.width(), wide.width(), 1e-6), "{wide:?} {tall:?}");
assert!(t[1].xf.translation().to_point().distance(Point::new(10.0, 60.0)) < 1e-9, "{:?}", t[1].xf);
}
#[test]
fn type_on_a_scaled_path_takes_the_scale() {
let d = open(
r##"<g transform="scale(2)"><path id="p" d="M10 100 L110 100" fill="none"/>
<text font-size="10"><textPath href="#p">Curve</textPath></text></g>"##,
);
let t = only_text(&d);
assert!(close(t.first_style().size, 20.0, 1e-9), "{}", t.first_style().size);
assert!(close(t.xf.determinant(), 1.0, 1e-6), "{:?}", t.xf);
let TextKind::OnPath { path, .. } = &t.kind else { panic!("{:?}", t.kind) };
let b = t.xf.transform_rect_bbox(path.bounds().unwrap());
assert!(close(b.x0, 20.0, 1e-9) && close(b.x1, 220.0, 1e-9) && close(b.y0, 200.0, 1e-9), "{b:?}");
}
#[test]
fn folded_sizes_stay_in_the_character_panels_range() {
// Past 1296 pt (or under 0.1 pt) the rest of the scale stays the transform.
let d = open(
r#"<g transform="scale(20)"><text y="10" font-size="100">Big</text></g>
<g transform="scale(0.001)"><text y="10" font-size="7">Small</text></g>
<text y="10" font-size="2000">Huge</text>"#,
);
let t = texts(&d);
let size = |i: usize| t[i].first_style().size;
assert!(close(size(0), 1296.0, 1e-9) && close(size(0) * linear(t[0])[0], 2000.0, 1e-9), "{:?}", t[0].xf);
assert!(close(size(1), 0.1, 1e-9) && close(size(1) * linear(t[1])[0], 0.007, 1e-9), "{:?}", t[1].xf);
assert!(close(size(2), 2000.0, 1e-9) && close4(linear(t[2]), [1.0, 0.0, 0.0, 1.0]), "unscaled type keeps its size");
}
#[test]
fn gradients_on_scaled_text_stay_in_place() {
let d = open(
r##"<defs><linearGradient id="user" gradientUnits="userSpaceOnUse" x1="20" y1="0" x2="120" y2="0"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>
<g transform="scale(2)"><text x="20" y="50" font-size="20" fill="url(#user)">Gradient</text></g>"##,
);
let t = only_text(&d);
assert!(close(t.first_style().size, 40.0, 1e-9));
let Paint::Gradient(g) = &t.runs[0].style.fill else { panic!("{:?}", t.runs[0].style.fill) };
let geom = g.geom.unwrap();
let (start, end) = (t.xf * geom.start, t.xf * geom.end);
assert!(start.distance(Point::new(40.0, 0.0)) < 1e-6 && end.distance(Point::new(240.0, 0.0)) < 1e-6, "{start:?} {end:?}");
}
+4 -5
View File
@@ -115,11 +115,10 @@ fn text_lengths_in_physical_units() {
assert!(close(o.x, 72.0) && close(o.y, 144.0), "{o:?}");
let st = t.first_style();
assert!(close(st.tracking, 100.0), "{}", st.tracking);
// User units of a physical root are CSS pixels (0.75 pt): the text carries that scale.
let scale = t.xf.as_coeffs()[0];
assert!(close(scale, 0.75), "{:?}", t.xf);
assert!(close(st.stroke_width * scale, 1.0), "{}", st.stroke_width);
assert!(close(st.size * scale, 15.0), "{}", st.size);
// User units of a physical root are CSS pixels (0.75 pt): that scale moves into the type.
assert!(close(t.xf.as_coeffs()[0], 1.0), "{:?}", t.xf);
assert!(close(st.stroke_width, 1.0), "{}", st.stroke_width);
assert!(close(st.size, 15.0), "{}", st.size);
}
#[test]
+3 -2
View File
@@ -84,9 +84,10 @@ fn type_keeps_its_non_scaling_stroke_width() {
let (d, warnings) = import_with_report(svg).unwrap();
let t = text(&d);
let st = &t.runs[0].style;
// Text space is scaled 2×: half the width there is the width on screen.
// The scale became the type's size: the stroke and its dashes keep their width on screen.
assert!(close(st.size, 40.0) && close(t.xf.determinant(), 1.0), "{} {:?}", st.size, t.xf);
assert!(close(st.stroke_width * t.xf.determinant().sqrt(), 3.0), "{} {:?}", st.stroke_width, t.xf);
assert_eq!(st.stroke_dash.as_ref().map(|d| d.pattern.clone()), Some(vec![2.0, 1.0]));
assert_eq!(st.stroke_dash.as_ref().map(|d| d.pattern.clone()), Some(vec![4.0, 2.0]));
assert!(warnings.is_empty(), "{warnings:?}");
let (_, warnings) = import_with_report(&svg.replace("scale(2)", "scale(2 1)")).unwrap();
+27
View File
@@ -386,6 +386,33 @@ fn text_roundtrip_and_escaping() {
assert!(t.xf.translation().to_point().distance(Point::new(20.0, 50.0)) < 0.01);
}
#[test]
fn scaled_text_roundtrips_at_the_size_it_draws() {
// Type scaled with its object (its transform scales it) comes back at the size it draws at,
// drawn the same, and stays so on the next round trip; a stretch stays the transform.
let at = Affine::translate((20.0, 50.0));
let stretch = at * Affine::rotate(0.5) * Affine::scale_non_uniform(2.0, 1.0);
for (xf, size) in [(at * Affine::scale(2.0), 18.0), (at * Affine::rotate(0.5) * Affine::scale(3.0), 27.0), (stretch, 9.0)] {
let mut t = TextObject::point(Point::ZERO, "Scaled\ntype", CharStyle { size: 9.0, leading: Some(11.0), ..CharStyle::default() });
t.xf = xf;
let drawn = |t: &TextObject| t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds);
let before = drawn(&t);
let id = Document::new(200.0, 200.0).alloc_id();
let d = doc_with(vec![Node::new(id, NodeKind::Text(Box::new(t)))]);
let once = roundtrip(&d);
let NodeKind::Text(t) = &art(&once)[0].kind else { panic!() };
// Within the precision of the exported matrix (3 decimals); the second line carries the
// leading.
let near = |a: f64, b: f64| (a - b).abs() < b * 1e-3;
let st = &t.runs.last().unwrap().style;
assert!(near(st.size, size) && near(st.leading.unwrap(), 11.0 * size / 9.0), "{xf:?}: {st:?}");
assert!(close_rect(drawn(t), before, 0.05), "{xf:?}: {:?} {before:?}", drawn(t));
let twice = roundtrip(&once);
let NodeKind::Text(t2) = &art(&twice)[0].kind else { panic!() };
assert!(near(t2.first_style().size, size) && close_rect(drawn(t2), before, 0.05), "{xf:?}: {:?} {:?}", t2.runs, drawn(t2));
}
}
#[test]
fn text_on_path_roundtrip() {
let mut d = Document::new(200.0, 200.0);
+2
View File
@@ -106,6 +106,8 @@ mod tests_save;
#[cfg(test)]
mod tests_saveext;
#[cfg(test)]
mod tests_selectall;
#[cfg(test)]
mod tests_slices;
#[cfg(test)]
mod tests_svg;
+26
View File
@@ -2653,6 +2653,32 @@ fn menu_dialog(id: &str) -> Option<(&'static str, Value)> {
})
}
/// The event a focused text field takes for Edit-menu command `id` (Select All, Cut, Copy,
/// Paste), as the same keys would send it.
fn field_event(app: &mut VectorcraftApp, id: &str) -> Option<egui::Event> {
Some(match id {
"select.all" => egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND },
"edit.copy" => egui::Event::Copy,
"edit.cut" => egui::Event::Cut,
"edit.paste" | "edit.pasteWithoutFormatting" => egui::Event::Paste(app.system_clipboard_text()?),
_ => return None,
})
}
/// Invoke an item of the system menu bar (macOS), chosen by a click or by its key equivalent: the
/// system takes those keys before the window sees them. While a text field has the keyboard,
/// Select All, Cut, Copy and Paste act on the field's text, as their keys do in the window;
/// everything else (and those commands with no field focused) goes to [`invoke`].
pub fn invoke_from_system_menu(app: &mut VectorcraftApp, ctx: &egui::Context, id: &str, p: Value) {
if ctx.text_edit_focused()
&& let Some(e) = field_event(app, id)
{
ctx.input_mut(|i| i.events.push(e));
return;
}
invoke(app, id, p);
}
/// Invoke a menu/command id with UI side effects (dialogs for "…" commands that need input).
pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) {
if waits_for_ime(app, id) {
+5 -8
View File
@@ -123,8 +123,8 @@ fn text_paste(app: &mut VectorcraftApp, s: Option<String>) {
}
}
/// Edit-menu commands while the Type tool edits text act on the text (Cut/Copy/Paste/Select
/// All/Clear). `None` = not intercepted.
/// Edit-menu commands while the Type tool edits text act on the text (Cut/Copy/Paste/Clear;
/// Select All is the engine's `select.all`). `None` = not intercepted.
pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, String>> {
if !app.session.tool_wants_text() {
return None;
@@ -139,7 +139,6 @@ pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Opti
}
}
"edit.paste" | "edit.pasteWithoutFormatting" => text_paste(app, None),
"select.all" => app.session.set_tool_option("selectAll", &json!(true)),
"edit.clear" => text_key(app, ToolKey::Delete, Mods::default()),
_ => return None,
}
@@ -152,10 +151,10 @@ enum TextInput {
Copy,
Cut,
Paste(Option<String>),
SelectAll,
}
/// Route editing keys (with modifiers), clipboard events and Cmd+A/C/X/V to the Type tool.
/// Route editing keys (with modifiers), clipboard events and Cmd+C/X/V to the Type tool (Cmd+A is
/// left to the Select All shortcut, which selects the text being edited).
pub(crate) fn route_type_input(app: &mut VectorcraftApp, ctx: &egui::Context) {
CTX.get_or_init(|| ctx.clone());
let mut todo = vec![];
@@ -193,10 +192,9 @@ pub(crate) fn route_type_input(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
return false;
}
if m.command && !m.shift && !m.alt && matches!(key, Key::A | Key::C | Key::X | Key::V) {
if m.command && !m.shift && !m.alt && matches!(key, Key::C | Key::X | Key::V) {
if *pressed {
todo.push(match key {
Key::A => TextInput::SelectAll,
Key::C => TextInput::Copy,
Key::X => TextInput::Cut,
_ => TextInput::Paste(None),
@@ -221,7 +219,6 @@ pub(crate) fn route_type_input(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
}
TextInput::Paste(s) => text_paste(app, s),
TextInput::SelectAll => app.session.set_tool_option("selectAll", &json!(true)),
}
}
}
+1 -1
View File
@@ -261,7 +261,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) {
});
return;
}
// Editing keys with modifiers, clipboard and Cmd+A.
// Editing keys with modifiers and the clipboard (Cmd+A is Select All's, below: the text).
crate::panels::character::route_type_input(app, ctx);
// Enter was already delivered above as ToolKey::Enter (newline).
let fire = all_shortcuts().into_iter().filter(|(sc, ..)| sc.modifiers.command).find(|(sc, ..)| ctx.input_mut(|i| consume(i, sc, false)));
+8
View File
@@ -89,6 +89,14 @@ impl VectorcraftApp {
})
}
/// The text on the system clipboard, if any.
pub(crate) fn system_clipboard_text(&mut self) -> Option<String> {
match self.services.system_clipboard.as_mut() {
Some(cb) => cb.read(&[TEXT]).map(|f| String::from_utf8_lossy(&f.data).into_owned()),
None => self.services.clipboard_read.as_mut().and_then(|read| read()),
}
}
/// Does the system clipboard hold something Paste can take (with nothing copied in the app)?
pub(crate) fn system_clipboard_pasteable(&mut self) -> bool {
match self.services.system_clipboard.as_mut() {
+173
View File
@@ -0,0 +1,173 @@
//! Select All (Cmd+A) follows the keyboard, from the window and from the system menu bar (macOS):
//! a focused text field selects its own text, the Type tool editing selects the text being edited,
//! and only otherwise are all the objects selected.
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, vec2};
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_tools::{PointerEvent, PointerKind};
use crate::{VectorcraftApp, menus};
struct App {
app: VectorcraftApp,
ctx: egui::Context,
time: f64,
}
impl App {
/// A document with a 37 pt wide rectangle (selected) and a second, unselected one.
fn new() -> Self {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 37, "height": 40})).unwrap();
let mut a = Self { app, ctx: egui::Context::default(), time: 0.0 };
for _ in 0..3 {
a.frame(vec![]);
}
a
}
/// One whole app frame with `events`; `menu`: a system menu item chosen first, as the macOS
/// host dispatches it before the app's logic.
fn frame_with(&mut self, events: Vec<Event>, menu: Option<&str>) -> egui::FullOutput {
self.time += 0.1;
let raw = egui::RawInput {
events,
time: Some(self.time),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0))),
..Default::default()
};
let app = &mut self.app;
let mut out = self.ctx.run_ui(raw, |ui| {
if let Some(id) = menu {
menus::invoke_from_system_menu(app, ui.ctx(), id, json!({}));
}
app.logic(ui.ctx());
app.ui(ui);
});
out.textures_delta.clear();
out
}
fn frame(&mut self, events: Vec<Event>) -> egui::FullOutput {
self.frame_with(events, None)
}
fn menu(&mut self, id: &str) -> egui::FullOutput {
self.frame_with(vec![], Some(id))
}
fn selected(&self) -> usize {
self.app.session.active().unwrap().selection.objects.len()
}
/// The panel number field showing `text` (the field keeps its text under its id): id, rect.
fn field(&self, text: &str) -> (egui::Id, Rect) {
let widgets: Vec<(egui::Id, Rect)> =
self.ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).map(|w| (w.id, w.rect)).collect());
widgets
.into_iter()
.find(|&(id, _)| {
self.ctx.data(|d| d.get_temp::<String>(id)).is_some_and(|t| t == text) && egui::TextEdit::load_state(&self.ctx, id).is_some()
})
.unwrap_or_else(|| panic!("no field shows {text:?}"))
}
/// The selected character range of text field `id`.
fn field_selection(&self, id: egui::Id) -> Option<(usize, usize)> {
let r = egui::TextEdit::load_state(&self.ctx, id)?.cursor.char_range()?;
let (a, b) = (r.primary.index, r.secondary.index);
Some((a.min(b).into(), a.max(b).into()))
}
}
fn press(key: Key, modifiers: Modifiers) -> Event {
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }
}
fn click(at: Pos2, pressed: bool) -> Event {
Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
}
#[test]
fn cmd_a_in_a_panel_field_selects_its_text_and_leaves_the_art() {
let mut a = App::new();
assert_eq!(a.selected(), 1);
let (id, rect) = a.field("37 pt");
a.frame(vec![Event::PointerMoved(rect.center()), click(rect.center(), true)]);
a.frame(vec![click(rect.center(), false)]);
a.frame(vec![]);
assert!(a.ctx.text_edit_focused(), "the W field has the keyboard");
let all = Some((0, "37 pt".chars().count()));
// The window's Cmd+A (Windows, Linux, the web, macOS without the system menu).
a.frame(vec![press(Key::End, Modifiers::NONE)]);
assert_eq!(a.field_selection(id), Some((5, 5)), "End collapses the selection");
a.frame(vec![press(Key::A, Modifiers::COMMAND)]);
assert_eq!(a.field_selection(id), all, "Cmd+A selects the field's text");
assert_eq!(a.selected(), 1, "and not the art");
// Select All from the macOS menu bar (its key equivalent or a click): the same.
a.frame(vec![press(Key::End, Modifiers::NONE)]);
a.menu("select.all");
a.frame(vec![]);
assert_eq!(a.field_selection(id), all, "the menu's Select All selects the field's text");
assert_eq!(a.selected(), 1, "and not the art");
// The menu's Copy copies the field's text, not the art.
let out = a.menu("edit.copy");
let copied: Vec<_> = out
.platform_output
.commands
.iter()
.filter_map(|c| match c {
egui::OutputCommand::CopyText(t) => Some(t.as_str()),
_ => None,
})
.collect();
assert_eq!(copied, ["37 pt"]);
assert!(a.app.session.clipboard.is_empty(), "no art copied");
assert!(a.ctx.text_edit_focused(), "the field keeps the keyboard");
}
#[test]
fn cmd_a_while_editing_type_selects_all_of_its_text() {
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![Event::Text("abc".into())]);
let text = a.app.session.active().unwrap().selection.objects.clone();
let range = |a: &App| {
let o = a.app.session.tool_options();
(o["start"].as_u64().unwrap(), o["end"].as_u64().unwrap().min(3))
};
assert_eq!(range(&a), (3, 3), "the caret after the text");
// The window's Cmd+A.
a.frame(vec![press(Key::A, Modifiers::COMMAND)]);
assert_eq!(range(&a), (0, 3), "Cmd+A selects the text being edited");
assert_eq!(a.app.session.active().unwrap().selection.objects, text, "and not the art");
a.frame(vec![press(Key::End, Modifiers::NONE)]);
assert_eq!(range(&a), (3, 3));
// The macOS menu bar's Select All.
a.menu("select.all");
assert_eq!(range(&a), (0, 3), "the menu's Select All selects the text being edited");
assert_eq!(a.app.session.active().unwrap().selection.objects, text);
// Typing replaces it.
a.frame(vec![Event::Text("Z".into())]);
let doc = a.app.session.execute("document.inspect", &json!({})).unwrap();
let names: Vec<_> = doc["layers"][0]["children"].as_array().unwrap().iter().map(|c| c["name"].clone()).collect();
assert!(names.contains(&json!("Z")), "{names:?}");
}
#[test]
fn cmd_a_on_the_canvas_selects_all_objects() {
let mut a = App::new();
assert!(!a.ctx.egui_wants_keyboard_input());
a.frame(vec![press(Key::A, Modifiers::COMMAND)]);
assert_eq!(a.selected(), 2, "Cmd+A selects every object");
a.app.run("select.none", json!({})).unwrap();
a.menu("select.all");
assert_eq!(a.selected(), 2, "so does the menu's Select All");
}
+12
View File
@@ -1890,6 +1890,18 @@ square to the page. `object.resetBoundingBox` squares the box again without movi
{"name":"run_command","arguments":{"command":"object.rotate","params":{"angle":45,"absolute":true}}}
```
## Select All while editing type
While the Type tool edits text (a click into type, `pointer_gesture` with `"tool":"type"`), `select.all` (Cmd+A,
`press_key {key: "A", mods: {cmd: true}}`) selects all of that text instead of the art, as in the reference app, and
returns `{editing, start, end}` (the text's id and the selected byte range, which `text.getRange` and
`text.setRangeStyle` take); the art selection stays as it is. Without text being edited it selects every object and
returns `{count}`. Text in threaded frames is selected one frame at a time.
```json
{"name":"press_key","arguments":{"key":"A","mods":{"cmd":true}}}
```
## Empty point type
Point type the Type tool places with a click and leaves empty is discarded when editing ends: Escape, another tool,