Merge pull request #10448 from dotCooCoo/fix/make-numbers-sequence

Type Tools: Make Numbers Sequence numbers the selected type objects
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-02 01:10:32 -08:00
commit 0c6aaa074d
12 files changed
+947 -6

No files matched your search

+10
View File
@@ -7,6 +7,7 @@
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
pub mod numbers;
#[cfg(test)]
mod tests;
@@ -65,6 +66,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
release_path
),
cmd!(
"addon.type.numbers",
"Make Numbers Sequence…",
["Object", "Plug-ins", "Type Tools"],
None,
"{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}",
has_selection,
numbers::make_numbers
),
]
}
@@ -0,0 +1,384 @@
//! Make Numbers Sequence (`addon.type.numbers`): numbers the selected type objects from a start
//! value by a step, replacing each object's whole text, the numbers in it, or a `{%n}` placeholder.
//! The objects are taken in stacking order, by rows or by columns. Leading and trailing zeros pad
//! the numbers to one width. Based on Sergey Osokin's MIT-licensed MakeNumbersSequence script
//! (<https://github.com/creold/illustrator-scripts/blob/master/md/Text.md#makenumberssequence>).
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::Rect;
use vectorcraft_render::effects;
use vectorcraft_text::edit;
use vectorcraft_text::retype::is_combining_mark;
use super::super::super::menucmds::whole_or;
use super::super::super::object::choice;
use super::super::super::textedit::text_mut;
use super::super::super::threads;
use super::super::super::typecmd::refresh_bounds;
use super::super::super::typemenu::text_ids;
use super::super::super::{bad, number_or, switch_or, targets};
use crate::{EngineError, Result, Session};
/// The command id.
pub const COMMAND: &str = "addon.type.numbers";
/// The orders the objects are numbered in.
pub const ORDERS: [&str; 3] = ["stacking", "rows", "columns"];
/// What each object's number replaces.
pub const REPLACES: [&str; 3] = ["all", "numbers", "placeholder"];
/// The placeholder `replace: "placeholder"` replaces, in any case.
pub const PLACEHOLDER: &str = "{%n}";
/// The largest start, end or step.
const MAX_VALUE: f64 = 1e12;
/// The most decimal places a number keeps.
const MAX_DECIMALS: usize = 6;
/// The largest fixed number of digits.
pub const MAX_DIGITS: u64 = 30;
/// The most type objects one run numbers.
const MAX_TEXTS: usize = 100_000;
/// The most numbers or placeholders one run replaces.
pub(crate) const MAX_MATCHES: usize = 10_000;
/// What one run does, read from its params.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Options {
pub start: f64,
/// None: the numbers run to the last type object.
pub end: Option<f64>,
pub step: f64,
pub order: &'static str,
pub replace: &'static str,
/// Some(seed): the numbers go to the objects in random order.
pub shuffle: Option<u64>,
pub leading_zeros: bool,
/// The least number of whole digits with leading zeros; None: as many as the widest number.
pub digits: Option<usize>,
pub trailing_zeros: bool,
pub remove_unused: bool,
}
impl Options {
pub(crate) fn parse(p: &Value) -> Result<Self> {
const C: &str = COMMAND;
let value = |key: &str, default: f64| -> Result<f64> {
let v = number_or(p, key, default, C)?;
if !v.is_finite() || v.abs() > MAX_VALUE {
return Err(bad(C, format!("`{key}` must be from -{MAX_VALUE} to {MAX_VALUE}")));
}
Ok(v)
};
let start = value("start", 1.0)?;
let step = value("step", 1.0)?;
let end = match p.get("end") {
None | Some(Value::Null) => None,
Some(_) => Some(value("end", 0.0)?),
};
let order = pick(choice(p, C, "order", &ORDERS)?.unwrap_or("stacking"), &ORDERS);
let replace = pick(choice(p, C, "replace", &REPLACES)?.unwrap_or("all"), &REPLACES);
let seed = whole_or(p, "seed", 0, C)?;
let shuffle = if switch_or(p, "shuffle", false, C)? { Some(seed) } else { None };
let digits = match p.get("digits") {
None | Some(Value::Null) => None,
Some(_) => {
let d = whole_or(p, "digits", 1, C)?;
if !(1..=MAX_DIGITS).contains(&d) {
return Err(bad(C, format!("`digits` must be from 1 to {MAX_DIGITS}")));
}
Some(usize::try_from(d).unwrap_or(1))
}
};
let remove_unused = switch_or(p, "removeUnused", false, C)?;
if remove_unused && end.is_none() {
return Err(bad(C, "`removeUnused` needs an `end`"));
}
Ok(Self {
start,
end,
step,
order,
replace,
shuffle,
leading_zeros: switch_or(p, "leadingZeros", true, C)?,
digits,
trailing_zeros: switch_or(p, "trailingZeros", false, C)?,
remove_unused,
})
}
}
/// `v` as the static entry of `list` it equals.
fn pick(v: &str, list: &[&'static str]) -> &'static str {
list.iter().copied().find(|x| *x == v).unwrap_or(list[0])
}
/// The decimal places `v` is written with, at most [`MAX_DECIMALS`].
fn decimals(v: f64) -> usize {
let s = format!("{v}");
s.split_once('.').map_or(0, |(_, f)| f.len()).min(MAX_DECIMALS)
}
/// Round the shortest decimal representation of `v` to fixed point at `places`.
fn scaled(v: f64, places: usize) -> i128 {
let s = format!("{v}");
let magnitude = s.trim_start_matches('-');
let (whole, fraction) = magnitude.split_once('.').unwrap_or((magnitude, ""));
let digits = whole.bytes().chain(fraction.bytes().chain(std::iter::repeat(b'0')).take(places));
let mut value = digits.fold(0_i128, |n, digit| n * 10 + i128::from(digit - b'0'));
if fraction.as_bytes().get(places).is_some_and(|digit| *digit >= b'5') {
value += 1;
}
if v < 0.0 { -value } else { value }
}
/// `v` scaled by `10^places`, without trailing zeros and with no minus sign on zero.
fn write(v: i128, places: usize) -> String {
let scale = 10_u128.pow(places as u32);
let magnitude = v.unsigned_abs();
let sign = if v < 0 { "-" } else { "" };
let whole = magnitude / scale;
if places == 0 {
return format!("{sign}{whole}");
}
let fraction = magnitude % scale;
let s = format!("{sign}{whole}.{fraction:0places$}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
}
/// The numbers for `count` objects as text: from `start` by `step` (its sign set to run toward
/// `end`), stopping past `end`, then padded with zeros as `o` says.
pub(crate) fn sequence(o: &Options, count: usize) -> Vec<String> {
let places = [Some(o.start), Some(o.step), o.end].into_iter().flatten().map(decimals).max().unwrap_or(0);
let step = match o.end {
Some(end) if (o.start <= end) == (o.step < 0.0) => -o.step,
_ => o.step,
};
// Count steps at the supported decimal precision so an inclusive end survives rounding.
let scaled = |v: f64| scaled(v, places);
let start_i = scaled(o.start);
let step_i = scaled(step);
let fit = match o.end {
Some(end) if step_i != 0 => usize::try_from((scaled(end) - start_i) / step_i + 1).unwrap_or(usize::MAX),
_ => count,
};
let values: Vec<i128> = (0..count.min(fit)).map(|i| start_i + i as i128 * step_i).collect();
let mut out: Vec<String> = values.iter().map(|v| write(*v, places)).collect();
if o.trailing_zeros {
let most = out.iter().map(|s| s.split_once('.').map_or(0, |(_, f)| f.len())).max().unwrap_or(0);
if most > 0 {
for s in &mut out {
let have = s.split_once('.').map_or(0, |(_, f)| f.len());
if have == 0 {
s.push('.');
}
s.extend(std::iter::repeat_n('0', most - have));
}
}
}
if o.leading_zeros {
let last = o.end.map(scaled).unwrap_or_else(|| values.last().copied().unwrap_or(start_i));
// Whole digits as written, after rounding to `places`.
let whole = |v: i128| {
let s = write(v, places);
let s = s.trim_start_matches('-');
s.split_once('.').map_or(s.len(), |(w, _)| w.len())
};
let width = whole(start_i).max(whole(last)).max(o.digits.unwrap_or(1));
for s in &mut out {
if s.starts_with('-') {
continue;
}
let have = s.split_once('.').map_or(s.len(), |(w, _)| w.len());
if have < width {
s.insert_str(0, &"0".repeat(width - have));
}
}
}
out
}
/// The byte ranges of `text` a number replaces: each run of ASCII digits, with any `.` or `,`
/// followed by more digits inside it, and a `-` before it that does not follow a letter or digit.
pub(crate) fn number_spans(text: &str) -> Vec<(usize, usize)> {
let b = text.as_bytes();
let mut out = vec![];
let mut i = 0;
while i < b.len() {
if !b[i].is_ascii_digit() {
i += 1;
continue;
}
let signed = i > 0 && b[i - 1] == b'-' && !text[..i - 1].chars().rev().find(|c| !is_combining_mark(*c)).is_some_and(char::is_alphanumeric);
let start = if signed { i - 1 } else { i };
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
while i + 1 < b.len() && matches!(b[i], b'.' | b',') && b[i + 1].is_ascii_digit() {
i += 1;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
}
out.push((start, i));
}
out
}
/// The byte ranges of `text` that hold the placeholder, in any case.
pub(crate) fn placeholder_spans(text: &str) -> Vec<(usize, usize)> {
let lower = text.to_ascii_lowercase();
lower.match_indices(PLACEHOLDER).map(|(i, m)| (i, i + m.len())).collect()
}
/// `ids` in rows (top to bottom, each row left to right) or columns (left to right, each top to
/// bottom), by the centres of `bounds`. Objects whose centres are within half the median height
/// (width for columns) of a row's first object share its row.
fn by_position(ids: Vec<(NodeId, Rect)>, rows: bool) -> Vec<NodeId> {
let along = |r: &Rect| if rows { r.center().y } else { r.center().x };
let across = |r: &Rect| if rows { r.center().x } else { r.center().y };
let mut sizes: Vec<f64> = ids.iter().map(|(_, r)| if rows { r.height() } else { r.width() }).collect();
sizes.sort_by(f64::total_cmp);
let n = sizes.len();
let median = match n {
0 | 1 => 0.0,
_ if n.is_multiple_of(2) => (sizes[n / 2 - 1] + sizes[n / 2]) / 2.0,
_ => sizes[n / 2],
};
let tolerance = median / 2.0;
let mut ids = ids;
ids.sort_by(|a, b| along(&a.1).total_cmp(&along(&b.1)));
let mut out = Vec::with_capacity(ids.len());
let mut row: Vec<(NodeId, Rect)> = vec![];
for item in ids {
if row.first().is_some_and(|first| along(&item.1) - along(&first.1) > tolerance) {
row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1)));
out.extend(row.drain(..).map(|(id, _)| id));
}
row.push(item);
}
row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1)));
out.extend(row.into_iter().map(|(id, _)| id));
out
}
/// One replacement in a text: its start and end bytes and the number that goes there.
type Edit = (usize, usize, String);
/// Each span of `spans` in `text` replaced by `number`, as edits from the last to the first. A
/// span that already reads `number` is left out, so its formatting stays.
pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec<Edit> {
spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect()
}
pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let o = Options::parse(p)?;
let named = targets(s, p)?;
let d = &s.doc()?.doc;
if let Some(id) = named.iter().find(|id| d.node(**id).is_none()) {
return Err(EngineError::NoNode(*id));
}
// Type objects, groups' included, in stacking order from the back; locked or hidden ones stay.
let mut texts = text_ids(d, &named);
{
let editable = d.editable();
texts.retain(|id| editable(*id));
}
let paths = d.index_paths(texts.iter().copied());
texts.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
if texts.len() > MAX_TEXTS {
return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}")));
}
let threads = threads::ThreadIndex::of(d);
if texts.iter().any(|id| threads.threaded(*id)) {
return Err(bad(C, "threaded type can't be numbered: its frames share one story"));
}
let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t.plain_text(),
_ => String::new(),
};
// Only objects that hold a number or the placeholder count, for the order too.
let mut texts: Vec<(NodeId, String)> = texts
.into_iter()
.map(|id| (id, plain(id)))
.filter(|(_, t)| match o.replace {
"numbers" => t.bytes().any(|b| b.is_ascii_digit()),
"placeholder" => !placeholder_spans(t).is_empty(),
_ => true,
})
.collect();
if o.order != "stacking" && o.shuffle.is_none() {
let placed: Vec<(NodeId, Rect)> = texts
.iter()
.map(|(id, _)| (*id, effects::preview::bounds_of(d, &[*id], false).unwrap_or(Rect::new(f64::MAX, f64::MAX, f64::MAX, f64::MAX))))
.collect();
let mut by_id: std::collections::HashMap<NodeId, String> = texts.into_iter().collect();
texts = by_position(placed, o.order == "rows").into_iter().filter_map(|id| by_id.remove(&id).map(|t| (id, t))).collect();
}
// The objects are shuffled, not the numbers, so an end limit can number any of them.
if let Some(seed) = o.shuffle {
let mut rng = Rng::new(seed);
for i in (1..texts.len()).rev() {
let j = usize::try_from(rng.next_u64() % (i as u64 + 1)).unwrap_or(0);
texts.swap(i, j);
}
}
let numbers = sequence(&o, texts.len());
let mut plans: Vec<(NodeId, Vec<Edit>)> = vec![];
let mut matches = 0;
for ((id, text), number) in texts.iter().zip(&numbers) {
let spans = match o.replace {
"numbers" => number_spans(text),
"placeholder" => placeholder_spans(text),
_ => vec![],
};
// Checked before any replacement text is made.
matches += spans.iter().filter(|(a, b)| text.get(*a..*b) != Some(number.as_str())).count();
if matches > MAX_MATCHES {
return Err(bad(C, format!("too many numbers or placeholders to replace: at most {MAX_MATCHES}")));
}
let changes = match o.replace {
"numbers" | "placeholder" => edits(text, spans, number),
_ => vec![(0, text.len(), number.clone())],
};
// The text it would have, to leave out objects that already read so.
let mut after = text.clone();
for (a, b, n) in &changes {
after.replace_range(*a..*b, n);
}
if after != *text {
plans.push((*id, changes));
}
}
let numbered: Vec<u64> = texts.iter().take(numbers.len()).map(|(id, _)| id.0).collect();
// A clipping group's or layer's mask is its first child; removing it would make the next child the mask.
let mask = |id: NodeId| {
d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| g.clips() && g.children().and_then(|c| c.first()).is_some_and(|c| c.id == id))
};
let removed: Vec<NodeId> =
if o.remove_unused { texts.iter().skip(numbers.len()).map(|(id, _)| *id).filter(|id| !mask(*id)).collect() } else { vec![] };
if plans.is_empty() && removed.is_empty() {
return Ok(json!({ "count": 0, "ids": numbered, "removed": [] }));
}
let count = plans.len();
s.edit("Make Numbers Sequence", |d, sel| {
for (id, changes) in &plans {
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
for (a, b, n) in changes {
t.splice_paras(*a, *b, n);
edit::replace_range(&mut t.runs, *a, *b, n);
t.ruby_after_replace(*a, *b, n.len());
}
refresh_bounds(t);
}
d.remove_many(&removed)?;
if !removed.is_empty() {
sel.remove_all(removed.iter().copied());
}
Ok(())
})?;
Ok(json!({ "count": count, "ids": numbered, "removed": removed.iter().map(|id| id.0).collect::<Vec<_>>() }))
}
@@ -0,0 +1,337 @@
//! Make Numbers Sequence: the numbers a sequence gives, what each replace mode changes, the
//! orders, removed objects, one undo step, and bad params refused without a change.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
fn text_at(s: &mut Session, x: f64, y: f64, words: &str) -> NodeId {
NodeId(s.execute("text.create", &json!({"x": x, "y": y, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap())
}
fn plain(s: &Session, id: NodeId) -> String {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => t.plain_text(),
_ => panic!("not text"),
}
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn seq(p: Value, count: usize) -> Vec<String> {
sequence(&Options::parse(&p).unwrap(), count)
}
#[test]
fn a_sequence_steps_toward_its_end_and_pads_with_zeros() {
assert_eq!(seq(json!({"start": 1, "step": 5, "end": 20}), 10), ["01", "06", "11", "16"], "stops past the end");
assert_eq!(seq(json!({"start": 10, "step": 3, "end": 1, "leadingZeros": false}), 10), ["10", "7", "4", "1"], "the step turns to run down");
assert_eq!(seq(json!({"start": 8, "digits": 3}), 3), ["008", "009", "010"]);
assert_eq!(seq(json!({"start": -1, "step": 1}), 3), ["-1", "0", "1"], "negative numbers get no zeros");
assert_eq!(seq(json!({"start": 0.1, "step": 0.1, "leadingZeros": false}), 3), ["0.1", "0.2", "0.3"], "no rounding noise");
assert_eq!(seq(json!({"start": 1, "step": 0.25, "trailingZeros": true}), 3), ["1.00", "1.25", "1.50"]);
assert_eq!(seq(json!({"start": 4, "step": 0}), 3), ["4", "4", "4"]);
assert_eq!(
seq(json!({"start": 1e9 + 0.1, "step": 0.1, "end": 1e9 + 0.3}), 5),
["1000000000.1", "1000000000.2", "1000000000.3"],
"a value that rounds to the end counts"
);
assert_eq!(
seq(json!({"start": 10000000000.1, "step": 0.1, "end": 10000000000.3}), 5),
["10000000000.1", "10000000000.2", "10000000000.3"],
"large values keep the inclusive decimal end"
);
assert_eq!(seq(json!({"start": 1e12, "step": 0.000001, "end": 1e12}), 3), ["1000000000000"], "an end equal to the start counts");
assert_eq!(
seq(json!({"start": 999999999999.9_f64, "step": 0.000001}), 3),
["999999999999.9", "999999999999.900001", "999999999999.900002"],
"large values keep their decimal digits when scaled for a small step"
);
assert_eq!(
seq(json!({"start": 999999999999.9_f64, "step": 0.000001, "end": 999999999999.9_f64}), 3),
["999999999999.9"],
"the end uses the same decimal scaling as the start"
);
assert_eq!(seq(json!({"start": 0.1, "step": 3.3}), 4), ["00.1", "03.4", "06.7", "10"], "padded to the rounded last number");
assert_eq!(seq(json!({"start": 1, "step": 1_000_000_000_000_u64}), 9009).last().map(String::as_str), Some("9008000000000001"));
assert_eq!(seq(json!({"start": -0.25, "step": 0.125}), 5), ["-0.25", "-0.125", "0", "0.125", "0.25"]);
assert_eq!(seq(json!({"start": -0.0000001, "step": 0}), 1), ["0"], "rounded zero has no minus sign");
assert_eq!(seq(json!({"start": 9.9999999, "step": 0}), 1), ["10"], "width uses the rounded whole part");
assert_eq!(seq(json!({"start": -0.0000005, "step": 0}), 1), ["-0.000001"], "decimal ties round away from zero");
}
#[test]
fn unthreaded_type_checks_the_threads_once() {
let mut s = session();
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
let scans = super::threads::thread_scans();
super::make_numbers(&mut s, &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
assert_eq!(super::threads::thread_scans() - scans, 1, "selection size does not multiply thread scans");
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "2", "3"]);
}
#[test]
fn threaded_type_is_refused() {
let mut s = session();
let a =
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "1 2 3", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let n = steps(&s);
assert!(s.execute(C, &json!({"ids": [a, b]})).is_err());
assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n));
}
#[test]
fn the_spans_find_numbers_and_placeholders() {
assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]);
assert!(number_spans("none").is_empty());
assert_eq!(placeholder_spans("a{%N}b{%n}"), [(1, 5), (6, 10)]);
}
#[test]
fn the_whole_text_gets_numbered_in_stacking_order_as_one_step() {
let mut s = session();
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
let n = steps(&s);
let out = s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[1].0], "start": 7})).unwrap();
assert_eq!(out["count"], json!(3));
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["7", "8", "9"], "from the back");
assert_eq!(steps(&s), n + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert!(ids.iter().all(|id| plain(&s, *id) == "x"), "undone");
}
#[test]
fn numbers_and_placeholders_are_replaced_inside_the_text() {
let mut s = session();
let a = text_at(&mut s, 40.0, 100.0, "Seat 99, row 4");
let b = text_at(&mut s, 40.0, 140.0, "no digits");
let c = text_at(&mut s, 40.0, 180.0, "Seat 1");
s.execute(C, &json!({"ids": [a.0, b.0, c.0], "replace": "numbers", "start": 5})).unwrap();
assert_eq!([plain(&s, a), plain(&s, b), plain(&s, c)], ["Seat 5, row 5", "no digits", "Seat 6"], "text with no number is skipped");
let d = text_at(&mut s, 40.0, 220.0, "Tag {%N} / {%n}");
let e = text_at(&mut s, 40.0, 260.0, "Tag 3");
s.execute(C, &json!({"ids": [d.0, e.0], "replace": "placeholder", "start": 2})).unwrap();
assert_eq!([plain(&s, d), plain(&s, e)], ["Tag 2 / 2", "Tag 3"]);
}
#[test]
fn ruby_follows_each_number_or_placeholder_replacement() {
let mut s = session();
let word = "漢字";
for (replace, words) in [("numbers", "1 2 漢字"), ("placeholder", "{%n} {%N} 漢字")] {
let id = text_at(&mut s, 40.0, 100.0, words);
let start = words.find(word).unwrap();
s.execute("type.ruby", &json!({"ids": [id.0], "start": start, "end": start + word.len(), "text": "かんじ"})).unwrap();
s.execute(C, &json!({"ids": [id.0], "replace": replace, "start": 123456})).unwrap();
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") };
let text = t.plain_text();
assert_eq!(text, "123456 123456 漢字");
assert_eq!(t.ruby.len(), 1);
let ruby = &t.ruby[0];
assert_eq!(&text[ruby.start..ruby.end], word, "ruby follows both replacements in {replace} mode");
assert_eq!(ruby.text, "かんじ");
}
}
#[test]
fn rows_and_columns_order_by_position() {
let mut s = session();
// Created bottom-right first, so stacking order differs from both positions.
let br = text_at(&mut s, 300.0, 200.0, "x");
let tl = text_at(&mut s, 40.0, 100.0, "x");
let bl = text_at(&mut s, 40.0, 200.0, "x");
let tr = text_at(&mut s, 300.0, 102.0, "x");
let ids = json!([br.0, tl.0, bl.0, tr.0]);
s.execute(C, &json!({"ids": ids, "order": "rows"})).unwrap();
assert_eq!([tl, tr, bl, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"], "a small offset stays in its row");
s.execute(C, &json!({"ids": ids, "order": "columns"})).unwrap();
assert_eq!([tl, bl, tr, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"]);
}
#[test]
fn an_end_leaves_the_rest_or_removes_it() {
let mut s = session();
let ids: Vec<NodeId> = (0..4).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
s.execute(C, &json!({"ids": all, "end": 2})).unwrap();
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "2", "x", "x"]);
let out = s.execute(C, &json!({"ids": all, "start": 5, "end": 6, "removeUnused": true})).unwrap();
assert_eq!(out["removed"], json!([ids[2].0, ids[3].0]));
assert!(s.doc().unwrap().doc.node(ids[3]).is_none());
}
#[test]
fn shuffle_gives_every_number_once() {
let mut s = session();
let ids: Vec<NodeId> = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect();
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 3, "leadingZeros": false})).unwrap();
let mut got: Vec<String> = ids.iter().map(|id| plain(&s, *id)).collect();
assert_ne!(got, ["1", "2", "3", "4", "5", "6"], "seed 3 moves them");
got.sort();
assert_eq!(got, ["1", "2", "3", "4", "5", "6"]);
}
#[test]
fn shuffle_with_an_end_can_number_any_object() {
let mut numbered = [false; 6];
for seed in 0..40 {
let mut s = session();
let ids: Vec<NodeId> = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect();
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": seed, "end": 2, "removeUnused": true})).unwrap();
assert_eq!(out["removed"].as_array().unwrap().len(), 4);
for (i, id) in ids.iter().enumerate() {
numbered[i] |= s.doc().unwrap().doc.node(*id).is_some();
}
}
assert_eq!(numbered, [true; 6], "every object is numbered for some seed");
}
#[test]
fn the_same_seed_numbers_and_removes_the_same_objects() {
let run = || {
let mut s = session();
let ids: Vec<NodeId> = (0..8).map(|i| text_at(&mut s, 40.0, 40.0 + 40.0 * f64::from(i), "x")).collect();
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 11, "end": 4, "removeUnused": true})).unwrap();
let texts: Vec<Option<String>> = ids.iter().map(|id| s.doc().unwrap().doc.node(*id).map(|_| plain(&s, *id))).collect();
let removed: Vec<usize> =
out["removed"].as_array().unwrap().iter().map(|r| ids.iter().position(|id| Some(id.0) == r.as_u64()).unwrap()).collect();
(texts, removed)
};
let (texts, removed) = run();
assert_eq!(removed.len(), 4);
assert_eq!(run(), (texts, removed), "seed 11 gives each object the same number and removes the same ones");
}
fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId {
s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.doc().unwrap().doc.parent_of(ids[0]).unwrap()
}
#[test]
fn a_negative_number_in_the_text_is_replaced_with_its_sign() {
assert_eq!(number_spans("Seat -4, A-4"), [(5, 7), (11, 12)], "a hyphen after a letter is not a sign");
assert_eq!(number_spans("É-4"), [(3, 4)], "nor after a letter outside ASCII");
assert_eq!(number_spans("E\u{301}-4"), [(4, 5)], "nor after a letter with a combining mark");
assert_eq!(number_spans("क्-4"), [(7, 8)], "nor after a letter with a virama");
let mut s = session();
let a = text_at(&mut s, 40.0, 100.0, "Seat -4");
let b = text_at(&mut s, 40.0, 140.0, "Seat 9");
s.execute(C, &json!({"ids": [a.0, b.0], "replace": "numbers", "start": 2, "step": -3})).unwrap();
assert_eq!([plain(&s, a), plain(&s, b)], ["Seat 2", "Seat -1"]);
}
#[test]
fn a_match_that_already_reads_the_number_is_not_edited() {
let text = "5 and 4";
assert_eq!(super::edits(text, number_spans(text), "5"), [(6, 7, "5".to_string())]);
}
#[test]
fn too_many_matches_in_one_run_are_refused() {
let mut unchanged = session();
let text = vec!["1"; super::MAX_MATCHES + 1].join(" ");
let id = text_at(&mut unchanged, 40.0, 100.0, &text);
let before = steps(&unchanged);
let out = unchanged.execute(C, &json!({"ids": [id.0], "start": 1, "replace": "numbers"})).unwrap();
assert_eq!(out["count"], 0);
assert_eq!(plain(&unchanged, id), text);
assert_eq!(steps(&unchanged), before);
let mut s = session();
let a = text_at(&mut s, 40.0, 100.0, &"{%n}".repeat(super::MAX_MATCHES + 1));
let n = steps(&s);
assert!(s.execute(C, &json!({"ids": [a.0], "replace": "placeholder"})).is_err());
assert_eq!(steps(&s), n);
// Whole texts are not matches: the object limit covers them.
s.execute("edit.undo", &json!({})).unwrap();
text_at(&mut s, 40.0, 140.0, "x");
// Each duplicate of the whole selection doubles it: 2^14 objects in 14 steps.
for _ in 0..14 {
s.execute("edit.duplicate", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
}
let count = s.doc().unwrap().selection.objects.len();
assert!(count > super::MAX_MATCHES, "{count} objects");
let out = s.execute(C, &json!({"step": 0}));
assert!(out.is_ok());
let out = out.unwrap();
assert!(out["count"].as_u64().unwrap() > super::MAX_MATCHES as u64);
}
#[test]
fn locked_and_hidden_type_in_a_group_is_left_alone() {
let mut s = session();
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
let group = group_of(&mut s, &ids);
s.execute("object.setProps", &json!({"ids": [ids[1].0], "locked": true})).unwrap();
s.execute("object.setProps", &json!({"ids": [ids[2].0], "visible": false})).unwrap();
let out = s.execute(C, &json!({"ids": [group.0], "end": 1, "removeUnused": true})).unwrap();
assert_eq!(out["removed"], json!([]));
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "x", "x"]);
}
#[test]
fn removing_unused_type_keeps_a_clipping_mask_and_the_selection() {
let mut s = session();
let a = text_at(&mut s, 40.0, 100.0, "x");
let b = text_at(&mut s, 40.0, 140.0, "x");
// The top object becomes the mask; it sits lowest on the page, so rows number it last.
let mask = text_at(&mut s, 40.0, 300.0, "x");
s.execute("select.set", &json!({"ids": [a.0, b.0, mask.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
let group = s.doc().unwrap().doc.parent_of(mask).unwrap();
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
let out = s.execute(C, &json!({"order": "rows", "end": 1, "removeUnused": true})).unwrap();
assert_eq!(out["removed"], json!([b.0]), "the mask stays");
assert!(s.doc().unwrap().doc.node(mask).is_some());
assert_eq!(s.doc().unwrap().selection.objects, [group], "the group stays selected");
}
#[test]
fn rows_are_found_among_the_type_that_gets_numbers() {
let mut s = session();
let upper = text_at(&mut s, 300.0, 100.0, "1");
let lower = text_at(&mut s, 40.0, 135.0, "1");
let h1 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 400, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap());
let h2 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 700, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap());
s.execute(C, &json!({"ids": [upper.0, lower.0, h1.0, h2.0], "replace": "numbers", "order": "rows", "start": 1, "leadingZeros": false})).unwrap();
assert_eq!([plain(&s, upper), plain(&s, lower)], ["1", "2"], "headings without numbers do not merge the rows");
}
#[test]
fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() {
let mut s = session();
let a = text_at(&mut s, 40.0, 100.0, "1");
let n = steps(&s);
assert_eq!(s.execute(C, &json!({"ids": [a.0]})).unwrap()["count"], json!(0));
assert_eq!(steps(&s), n);
for p in [
json!({"ids": [a.0], "start": "one"}),
json!({"ids": [a.0], "step": 1e13}),
json!({"ids": [a.0], "order": "diagonal"}),
json!({"ids": [a.0], "digits": 0}),
json!({"ids": [a.0], "removeUnused": true}),
json!({"ids": [a.0], "shuffle": "yes"}),
json!({"ids": [a.0], "seed": "x"}),
] {
assert!(s.execute(C, &p).is_err(), "{p} fails");
}
assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n));
}
@@ -758,12 +758,13 @@ pub(super) const ALLOWED: &[&str] = &[
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
/// report where it is on disk.
/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and
/// report where it is on disk, or edit text once per match with no limit on the matches in one call.
pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
"addon.pen.nextSegment",
"addon.type.numbers",
"color.contrast",
"effect.refreshDeferred",
"graphicStyle.setOptions",
+1 -1
View File
@@ -1543,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
),
(
"ui.widthPointEdit",
+1
View File
@@ -108,6 +108,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
pathtools::tangents::BRIDGE => pathtools::tangents::open_connected,
pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open,
typetools::COMMAND => typetools::open,
typetools::numbers::COMMAND => typetools::numbers::open,
color::legend::COMMAND => color::legend::open,
color::nearest::COMMAND => color::nearest::open,
color::random_fill::COMMAND => color::random_fill::open,
+7 -1
View File
@@ -12,6 +12,8 @@ use crate::VectorcraftApp;
use crate::addons::dialogs::{self, Spec};
use crate::menus::{c, cp};
pub mod numbers;
/// The command the dialog runs.
pub const COMMAND: &str = "addon.type.textTweaker";
/// An attribute: (param, label, unit, decimals, values taken, default start and end), as the
@@ -40,7 +42,11 @@ pub const RELEASE_MODES: &[(&str, &str)] = &[("Text and Path", "both"), ("Path O
/// Object › Plug-ins › Type Tools.
pub fn menu() -> Vec<Node> {
vec![c("Text Tweaker…", COMMAND), cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false}))]
vec![
c("Text Tweaker…", COMMAND),
cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})),
c("Make Numbers Sequence…", numbers::COMMAND),
]
}
/// The attribute row of param `key` (the first, Font Size, for an unknown one).
@@ -0,0 +1,97 @@
//! Make Numbers Sequence's dialog: the start, end and step, zeros, the order the type objects are
//! numbered in and what each number replaces. It previews on the canvas and runs
//! `addon.type.numbers` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
use crate::VectorcraftApp;
use crate::addons::dialogs::{self, Spec};
/// The command the dialog runs.
pub const COMMAND: &str = "addon.type.numbers";
const ORDERS: [(&str, &str); 3] = [("stacking", "By Stacking Order"), ("rows", "By Rows"), ("columns", "By Columns")];
const REPLACES: [(&str, &str); 3] = [("all", "Whole Text"), ("numbers", "Numbers in Text"), ("placeholder", "Only {%n} Placeholder")];
/// The seeds the dialog offers.
const SEEDS: u64 = 1_000_000;
/// The largest start, end or step, as the command takes it.
const MAX_VALUE: f64 = 1e12;
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
/// The command's parameters from the dialog's fields.
pub(crate) fn params(fields: &DialogFields) -> Value {
let to_last = fields.bool("toLast").unwrap_or(true);
let mut p = json!({
"start": fields.number("start").unwrap_or(1.0),
"step": fields.number("step").unwrap_or(1.0),
"order": fields.text("order").unwrap_or("stacking"),
"replace": fields.text("replace").unwrap_or("all"),
"shuffle": fields.bool("shuffle").unwrap_or(false),
"seed": fields.int("seed").unwrap_or(0),
"leadingZeros": fields.bool("leadingZeros").unwrap_or(true),
"trailingZeros": fields.bool("trailingZeros").unwrap_or(false),
});
if !to_last {
p["end"] = json!(fields.number("end").unwrap_or(10.0));
p["removeUnused"] = json!(fields.bool("removeUnused").unwrap_or(false));
}
if fields.bool("leadingZeros").unwrap_or(true) && fields.bool("fixedDigits").unwrap_or(false) {
p["digits"] = json!(fields.int("digits").unwrap_or(3));
}
p
}
/// The radio choice over `list`'s `(id, label)` pairs, on its first.
fn radio(list: &[(&str, &'static str)]) -> ParamKind {
ParamKind::radio(list.iter().map(|&(id, label)| (id.to_string(), tl!(label).into())).collect(), list.first().map(|(id, _)| id.to_string()))
}
/// Opens the dialog numbering from 1 by 1 to the last type object, in stacking order, replacing the
/// whole text, with a new seed each time the document has changed.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let seed = app.session.active().map_or(0, |st| st.revision % SEEDS);
let fields = DialogFields::from_pairs([
("start", FieldValue::Number(1.0)),
("step", FieldValue::Number(1.0)),
("toLast", FieldValue::Bool(true)),
("end", FieldValue::Number(10.0)),
("removeUnused", FieldValue::Bool(false)),
("shuffle", FieldValue::Bool(false)),
("seed", FieldValue::Int(i64::try_from(seed).unwrap_or(0))),
("leadingZeros", FieldValue::Bool(true)),
("fixedDigits", FieldValue::Bool(false)),
("digits", FieldValue::Int(3)),
("trailingZeros", FieldValue::Bool(false)),
("order", FieldValue::Text("stacking".into())),
("replace", FieldValue::Text("all".into())),
]);
dialogs::open(app, &SPEC, fields, |fields| {
let value = |key: &'static str, label, start| Param::number(key, label, start, 1.0, 6).bounds(Some(-MAX_VALUE), Some(MAX_VALUE));
let last = FieldValue::Bool(false);
let rows = vec![
Param::section(tl!("Numbers")),
value("start", tl!("Start:"), 1.0),
value("step", tl!("Step:"), 1.0),
Param::new("toLast", tl!("Number to Last Text"), ParamKind::bool(true)),
value("end", tl!("End:"), 10.0).enabled_when("toLast", last.clone()),
Param::new("removeUnused", tl!("Remove Unused Texts"), ParamKind::bool(false)).enabled_when("toLast", last),
Param::new("shuffle", tl!("Shuffle Numbers"), ParamKind::bool(false)),
Param::new("seed", tl!("Seed:"), ParamKind::int(Some(0), Some(i64::try_from(SEEDS - 1).unwrap_or(i64::MAX)), 0))
.enabled_when("shuffle", FieldValue::Bool(true)),
Param::section(tl!("Zeros")),
Param::new("leadingZeros", tl!("Leading Zeros"), ParamKind::bool(true)),
Param::new("fixedDigits", tl!("Fixed Number of Digits"), ParamKind::bool(false)).enabled_when("leadingZeros", FieldValue::Bool(true)),
Param::new("digits", tl!("Digits:"), ParamKind::int(Some(1), Some(30), 3)).enabled_when("fixedDigits", FieldValue::Bool(true)),
Param::new("trailingZeros", tl!("Trailing Zeros"), ParamKind::bool(false)),
Param::new("order", tl!("Order:"), radio(&ORDERS)).enabled_when("shuffle", FieldValue::Bool(false)),
Param::new("replace", tl!("Replace:"), radio(&REPLACES)),
];
ParamDialog::new(COMMAND, tl!("Make Numbers Sequence"), rows).values(Bind::bound(fields)).previews(true)
})
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,58 @@
use serde_json::json;
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
use crate::addons::dialogs::tests::{confirm, dialog_id, frame, open_item, read, set};
/// A window's app with three type objects in a column, selected.
fn app() -> (VectorcraftApp, Vec<u64>) {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = (0..3)
.map(|i| app.run("text.create", json!({"x": 40, "y": 60 + 40 * i, "text": "Seat 0", "size": 20})).unwrap()["id"].as_u64().unwrap())
.collect();
app.run("select.set", json!({"ids": ids})).unwrap();
(app, ids)
}
fn texts(app: &VectorcraftApp, ids: &[u64]) -> Vec<String> {
let state = app.session.active().unwrap();
ids.iter()
.map(|id| match &state.doc.node(vectorcraft_doc::NodeId(*id)).unwrap().kind {
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
_ => panic!("not text"),
})
.collect()
}
/// The dialog's fields reach the command: an end and fixed digits only when turned on, and OK
/// numbers the objects as one undo step.
#[test]
fn the_dialog_numbers_the_selection_on_ok() {
let (mut app, ids) = app();
let undo = app.session.active().unwrap().history.undo.len();
open_item(&mut app, "Type Tools", "Make Numbers Sequence…");
let dialog = dialog_id(&app);
let p = read(&app, dialog, super::params);
assert!(p.get("end").is_none() && p.get("digits").is_none(), "to the last text, auto digits: {p}");
for (key, value) in [("start", json!(5.0)), ("replace", json!("numbers")), ("fixedDigits", json!(true)), ("digits", json!(2))] {
set(&app, dialog, key, value);
}
set(&app, dialog, "toLast", json!(false));
set(&app, dialog, "end", json!(6.0));
frame(&mut app);
let p = read(&app, dialog, super::params);
assert_eq!(
(p["start"].clone(), p["end"].clone(), p["digits"].clone(), p["replace"].clone()),
(json!(5.0), json!(6.0), json!(2), json!("numbers"))
);
let mut expected = self::app();
expected.0.run(super::COMMAND, p).unwrap();
let want = texts(&expected.0, &expected.1);
assert_eq!(want, ["Seat 05", "Seat 06", "Seat 0"]);
assert!(confirm(&app, dialog));
frame(&mut app);
assert!(!app.any_dialog_open());
assert_eq!(texts(&app, &ids), want);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
+1 -1
View File
@@ -1544,7 +1544,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
),
(
"ui.widthPointEdit",
+44 -1
View File
@@ -18286,7 +18286,7 @@ enabled only when a selected image has a mask. → `{changed, ids}`
## Type Tools add-on
Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker` and `addon.type.releasePath`, and
Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker`, `addon.type.releasePath` and `addon.type.numbers`, and
in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). Text Tweaker gives one character attribute to the characters letter by letter,
from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set
as `text.setRangeStyle` sets it (the Character panel), in its units and ranges ([formatting type](https://helpx.adobe.com/illustrator/using/formatting-type.html)), so on scaled
@@ -18351,6 +18351,49 @@ Path Options' Preview does (#5360).
{"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}}
```
### Make Numbers Sequence
`addon.type.numbers` numbers the type objects among `ids` (or `id`, else the selection), groups included, from `start`
by `step`, as one undo step. Each number replaces the object's whole text, every number in it, or every `{%n}`
placeholder in it. It is based on Sergey Osokin's MIT-licensed
[MakeNumbersSequence](https://github.com/creold/illustrator-scripts/blob/master/md/Text.md#makenumberssequence)
script.
- With `end` omitted the numbers run to the last object. With `end`, they stop past it and the objects after the last
number keep their text, or are deleted with `removeUnused`. A type object that is the mask of a clipping group or layer
is not deleted. The sign of `step` is set to run toward `end`.
- Locked or hidden type, also inside a selected group, is not numbered or deleted.
- With `replace` `numbers` or `placeholder`, objects that hold no number or placeholder are skipped and get no number,
and `order` leaves them out. The remaining objects are ordered before `end` limits the sequence, so objects past
`end` still count for rows and columns. A number is a run of digits with any `.` or `,` between digits,
and a `-` before it that does not follow a letter or digit. Replaced text takes the style of the text it replaces;
a number or placeholder that already reads the new number keeps its text and style. With `numbers` or
`placeholder`, one run replaces at most 10,000 numbers or placeholders; more is an error, and nothing changes.
- Values are rounded to the most decimal places among `start`, `step` and `end` (at most 6), so 0.1 by 0.1 gives
0.1, 0.2, 0.3.
- Objects that already read so are left as they are; when nothing changes no undo step is made.
- A frame of threaded type among the objects is an error, and nothing changes.
| Parameter | Values (default) |
|---|---|
| `start`, `step` | numbers −1e12…1e12 (1, 1; `step` 0: every object gets `start`) |
| `end` | number −1e12…1e12 (omitted: to the last object) |
| `order` | `stacking` (from the back), `rows` (top to bottom, each row left to right), `columns` (left to right, each column top to bottom) (`stacking`). Objects whose centers are within half the median height (width for columns) of a row's first object share its row |
| `replace` | `all`, `numbers`, `placeholder` (`all`) |
| `shuffle`, `seed` | false; true: the numbers go to the objects in random order, the same `seed` (a whole number, 0) giving the same order, and `order` is not used. A `seed` that is not a whole number is an error even with `shuffle` off |
| `leadingZeros` | true: non-negative numbers are padded with zeros to the whole digits of the wider of `start` and `end` (or the last number) |
| `digits` | 1…30: with `leadingZeros`, at least this many whole digits |
| `trailingZeros` | false; true: every number gets as many decimal places as the one with the most |
| `removeUnused` | false; true needs `end` |
→ `{count (objects changed), ids (numbered, in order), removed}`. Make Numbers Sequence… opens a dialog (`ui.menuDialog
{command}`, dialog key `addon.type.numbers`) whose fields are the command's parameters, with Preview.
```json
{"name":"run_command","arguments":{"command":"addon.type.numbers","params":{"start":1,"order":"rows"}}}
{"name":"run_command","arguments":{"command":"addon.type.numbers","params":{"start":5,"end":50,"step":5,"replace":"placeholder","digits":3}}}
```
## Unit Converter add-on
Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are
+4
View File
@@ -3191,6 +3191,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path.
## Type Tools add-on: Make Numbers Sequence (2026-12-01)
A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Make Numbers Sequence… numbers the selected type objects from a start value by a step, optionally stopping at an end value, and each number replaces the whole text, every number in it, or every `{%n}` placeholder (#10448). The objects are taken in stacking order, by rows or by columns, or in a seeded random order, with optional leading and trailing zeros, and the objects past the end can be deleted. When numbers or placeholders are replaced, objects that hold none are skipped before the ordering, so they take no number and are never deleted. Locked and hidden type is left alone, a clipping mask is not deleted, and threaded type and bad parameters are refused. A run that changes the document is one undo step, and a run that changes nothing makes none. The dialog has Preview. It is based on Sergey Osokin's MIT-licensed MakeNumbersSequence script. Tests: `cmd::addons::typetools::numbers::tests` in `vectorcraft-engine`, `addons::typetools::numbers::tests` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on.
## Unit Converter add-on (2026-11-14)
A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`.