Merge main into fix/raster-effect-whole-object-reuse

This commit is contained in:
dotCooCoo committed 2026-12-04 23:11:54 -08:00
commit f44e80f09e
40 files changed
+1925 -56

No files matched your search

+8 -1
View File
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fix All Issues",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}",
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents. An error, with nothing fixed, when the fixes would delete the artboard an open Create Font Sheet dialog uses → {scope, total, fixed: {kind: count}}",
has_doc,
fix
),
@@ -262,6 +262,13 @@ fn fix(s: &mut Session, p: &Value) -> Result<Value> {
}
// With nothing to fix, the document and its undo history stay as they are.
if total > 0 {
if let Some(guard) = &s.artboard_deletion_guard {
let st = s.doc()?;
let protected = |doc: &Document| doc.artboards.iter().any(|a| a.id == guard.artboard);
if (st.uid, st.reverts) == guard.document && protected(&st.doc) && !protected(&d) {
return Err(EngineError::Other(guard.message.clone()));
}
}
sel.prune(&d);
s.edit("Fix Issues", |doc, selection| {
*doc = d;
+6 -1
View File
@@ -5,8 +5,10 @@
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Release Type on a Path
//! splits type on a path into point type holding the same text and the plain path it was set on
//! (#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.
//! parity score. Create Font Sheet ([`font_sheet`]) sets a line of sample text in every font. Its
//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
pub mod font_sheet;
pub mod numbers;
#[cfg(test)]
mod tests;
@@ -76,6 +78,9 @@ pub fn specs() -> Vec<CommandSpec> {
numbers::make_numbers
),
]
.into_iter()
.chain(font_sheet::specs())
.collect()
}
/// Release Type on a Path's command (the id in [`specs`]).
@@ -0,0 +1,376 @@
//! Create Font Sheet (`addon.type.fontSheet`; Object › Plug-ins › Type Tools › Create Font
//! Sheet…): a line of sample text set once in each font the font menus list (or in the fonts a
//! filter or a list names), each labeled with its font's name, flowed down columns on the active
//! artboard and on new artboards to its right when it fills, as one group made in one undo step.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun};
use vectorcraft_geom::{Affine, Point, Rect, Shape};
use vectorcraft_text::{FontDb, FontMatch};
use super::super::super::create::{new_type_para, new_type_style};
use super::super::super::panelcmds::artboard_at;
use super::super::super::typecmd::refresh_bounds;
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
use crate::{Result, Session};
/// The command.
pub const COMMAND: &str = "addon.type.fontSheet";
/// The sample text when none is given.
pub const DEFAULT_TEXT: &str = "The quick brown fox jumps over the lazy dog";
/// Most fonts one sheet sets.
pub const MAX_FONTS: usize = 5000;
/// Most characters the sample text has.
pub const MAX_CHARS: usize = 1000;
/// The largest size a label is set at; a smaller sample's label is set at the sample's size.
const LABEL_SIZE: f64 = 9.0;
/// The space between the artboards the sheet adds, as `artboard.new` leaves it.
const ARTBOARD_GAP: f64 = 20.0;
/// The page a document without artboards lays the sheet out on (US Letter).
const LETTER: Rect = Rect { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 };
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.type.fontSheet",
"Create Font Sheet",
["Object", "Plug-ins", "Type Tools"],
None,
"{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An entry whose font lacks a glyph needed by the sample stays on the sheet, and is listed in `fallback` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}",
has_doc,
font_sheet
)]
}
/// `key` of `p`: `default` when omitted, else a number in `range`.
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
match p.get(key) {
None | Some(Value::Null) => Ok(default),
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && range.contains(n))
.ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
}
}
/// The sample text of `p`: one line, not empty, at most [`MAX_CHARS`] characters.
fn sample_text(p: &Value) -> Result<String> {
let text = match p.get("text") {
None | Some(Value::Null) => return Ok(DEFAULT_TEXT.into()),
Some(Value::String(t)) => t.clone(),
Some(_) => return Err(bad(COMMAND, "`text` must be a string")),
};
if text.trim().is_empty() {
return Err(bad(COMMAND, "`text` must not be empty"));
}
// The line and paragraph separators break a line too.
if text.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) {
return Err(bad(COMMAND, "`text` must be one line, without line breaks or other control characters"));
}
if text.chars().count() > MAX_CHARS {
return Err(bad(COMMAND, format!("`text` must be at most {MAX_CHARS} characters")));
}
Ok(text)
}
/// The families the sheet sets, in order: those `families` names, else those the font menus of
/// `db` list whose name contains `filter`.
fn families(p: &Value, db: &FontDb) -> Result<Vec<String>> {
let filter = match p.get("filter") {
None | Some(Value::Null) => None,
Some(Value::String(f)) => Some(f.trim().to_lowercase()).filter(|f| !f.is_empty()),
Some(_) => return Err(bad(COMMAND, "`filter` must be a string")),
};
let listed = match p.get("families") {
None | Some(Value::Null) => {
let menu = db.menu_family_list();
let wanted = |f: &&String| filter.as_ref().is_none_or(|w| f.to_lowercase().contains(w.as_str()));
let found: Vec<String> = menu.iter().filter(wanted).cloned().collect();
if found.is_empty() {
return Err(bad(COMMAND, "no font family matches `filter`"));
}
return Ok(found);
}
Some(_) if p.get("filter").is_some_and(|f| !f.is_null()) => return Err(bad(COMMAND, "give `families` or `filter`, not both")),
Some(Value::Array(a)) => a,
Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")),
};
if listed.is_empty() {
return Err(bad(COMMAND, "`families` must name at least one family"));
}
let mut out: Vec<String> = Vec::with_capacity(listed.len());
for f in listed {
let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?;
if !db.has_family(f) {
return Err(bad(COMMAND, format!("font family `{f}` is not available")));
}
// The name as the font menus spell it, looked up as the database compares names.
let name = match db.composite_font(f) {
Some(c) => c.name.clone(),
None => db.canonical(f, "").0,
};
if out.iter().any(|o| o.to_lowercase() == name.to_lowercase()) {
return Err(bad(COMMAND, format!("`families` names `{name}` twice")));
}
out.push(name);
}
Ok(out)
}
/// The index of the artboard the view has active, else the one the document opened on, else the first.
fn active_artboard(st: &crate::DocState) -> usize {
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
}
fn font_sheet(s: &mut Session, p: &Value) -> Result<Value> {
font_sheet_in(s, p, FontDb::global())
}
/// [`font_sheet`] over the fonts of `db`.
fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
const C: &str = COMMAND;
let text = sample_text(p)?;
let size = number(p, "size", 12.0, 1.0..=1296.0)?;
let columns = number(p, "columns", 2.0, 1.0..=50.0)?;
if columns.fract() != 0.0 {
return Err(bad(C, "`columns` must be a whole number 1..50"));
}
let columns = columns as usize;
let gap = number(p, "gap", 12.0, 0.0..=1000.0)?;
let margin = number(p, "margin", 36.0, 0.0..=1000.0)?;
let all_styles = switch_or(p, "allStyles", false, C)?;
let labels = switch_or(p, "labels", true, C)?;
let new_artboards = switch_or(p, "newArtboards", true, C)?;
let families = families(p, db)?;
// Each entry's font: (family, style); no style for the family's Regular or closest style.
let mut fonts: Vec<(String, Option<String>)> = vec![];
for f in &families {
let styles = if all_styles { db.styles(f) } else { vec![] };
if styles.is_empty() {
fonts.push((f.clone(), None));
} else {
fonts.extend(styles.into_iter().map(|st| (f.clone(), Some(st))));
}
if fonts.len() > MAX_FONTS {
return Err(bad(C, format!("a sheet sets at most {MAX_FONTS} fonts: give `filter` or `families`")));
}
}
let label = size.min(LABEL_SIZE);
// The artboard named, else `activeArtboard` (a replay of the journal), else the view's active
// one, which the journal entry then records as `activeArtboard` so a replay uses the same artboard.
let named = artboard_at(&s.doc()?.doc, p, "artboard", C)?;
let active = match named.or(artboard_at(&s.doc()?.doc, p, "activeArtboard", C)?) {
Some(i) => i,
None => {
let st = s.doc()?;
let i = active_artboard(st);
if i < st.doc.artboards.len() {
s.note_journal("activeArtboard", json!(i));
}
i
}
};
let st = s.doc()?;
let d = &st.doc;
let template = d.artboards.get(active).cloned();
let page = template.as_ref().map_or(LETTER, |a| a.rect);
let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max);
let system_layout = d.setup.system_layout;
let parent = st.target_parent()?;
// An entry's first baseline is at least one line's size below its top, and the entry at least
// this tall; the fonts are only laid out when the page has room for that.
let (least_above, least_height) = (if labels { label } else { size }, if labels { label } else { 0.0 } + size * 1.5);
let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin);
let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64;
let no_room = || bad(C, "the margin, gap and columns leave no room for a font on the artboard");
if column_w <= 0.0 || inner_h < least_height {
return Err(no_room());
}
let label_style = {
let mut style = new_type_style(s, &json!({ "size": label }), C)?;
style.leading = Some(label * 1.2);
style
};
// Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline.
let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len());
let mut skipped: Vec<String> = vec![];
// The entries whose font lacks a glyph needed by the sample.
let mut fallback: Vec<String> = vec![];
for (family, style) in fonts {
let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?;
sample.leading = Some(size * 1.2);
let name = match &style {
Some(st) => format!("{family} {st}"),
None => family.clone(),
};
// A font that doesn't load is drawn in the fallback font, and a style that doesn't in the
// family's closest style: either is left out. A composite font is left out when a part
// that sets the sample names a font or style that doesn't load.
let composite = db.composite_font(&family).is_some();
// Layout picks a font for each character as typed, then draws All Caps type, and the
// lowercase letters of Small Caps type, in capitals in that font, so coverage is checked on both.
let caps = sample.all_caps || sample.small_caps.is_some();
let (loads, covers) = if composite {
// Glyph coverage is checked on the characters layout draws, in the sample's numeral system.
let covers = db.composite_cased_coverage(&family, &[text.as_str()], sample.digits, caps).is_none_or(|c| c.lacking.is_empty());
(db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers)
} else {
let wanted = db.canonical(&family, "").0;
match db.face(&sample.font_family, &sample.font_style) {
Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => {
let drawn = |t: &str| vectorcraft_text::drawn_chars(t, sample.digits).all(|c| face.covers(c));
let capitals = || text.chars().flat_map(char::to_uppercase).collect::<String>();
(true, drawn(&text) && (!caps || drawn(&capitals())))
}
_ => (false, true),
}
};
if !loads {
skipped.push(name);
continue;
}
if !covers {
fallback.push(name.clone());
}
let (first, more) = if labels {
(TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample)))
} else {
(TextRun::new(text.clone(), sample), None)
};
let t = laid_out(first, more, system_layout);
let extent = ink_extent(&t);
laid.push((name, t, extent));
}
if laid.is_empty() {
return Err(bad(C, "none of the fonts could be loaded"));
}
// Each page's layout: each entry's first baseline as far below its top as its ink reaches above
// it, a row as tall as the tallest entry with the gap below it, and the rows that fit inside the margin.
let height = laid.iter().map(|(.., (a, b))| a.max(least_above) + b).fold(least_height, f64::max);
let pitch = height + gap;
if inner_h < height {
return Err(no_room());
}
let rows = (((inner_h + gap) / pitch).floor() as usize).max(1);
let per_page = rows * columns;
// Where page `k` starts: the active artboard, then to the right of every artboard.
let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) };
let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(laid.len());
for (i, (name, mut t, (above, _))) in laid.into_iter().enumerate() {
let (k, j) = (i / per_page, i % per_page);
let (col, row) = (j / rows, j % rows);
let x = page_x(k) + margin + col as f64 * (column_w + gap);
let baseline = page.y0 + margin + row as f64 * pitch + above.max(least_above);
// The layout is in text space, so moving the type keeps it.
t.xf = Affine::translate((x, baseline));
entries.push((name, t));
}
let count = entries.len();
let pages = count.div_ceil(per_page);
let boards: Vec<Rect> = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect();
let template = template.filter(|_| new_artboards);
let (gid, added) = s.edit("Create Font Sheet", |d, sel| {
let mut added = vec![];
if let Some(template) = template {
for rect in boards {
let mut a = template.clone();
a.id = d.next_artboard_id();
a.name = format!("Artboard {}", d.artboards.len() + 1);
a.rect = rect;
a.locked = false;
d.artboards.push(a);
added.push(d.artboards.len() - 1);
}
}
let children: Vec<Arc<Node>> = entries
.into_iter()
.map(|(name, t)| {
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
n.name = Some(name);
Arc::new(n)
})
.collect();
let gid = d.alloc_id();
let mut g = Node::new(gid, NodeKind::Group { children, clip: false });
g.name = Some("Font Sheet".into());
d.insert(parent, usize::MAX, g)?;
sel.set([gid]);
Ok((gid, added))
})?;
let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "fallback": fallback, "artboards": added });
let warnings: Vec<String> = skipped_warning(&skipped).into_iter().chain(fallback_warning(&fallback)).collect();
if !warnings.is_empty() {
out["warning"] = json!(warnings.join("; "));
}
Ok(out)
}
/// The warning a sheet with entries whose font lacks a glyph of the sample gives, naming the first few.
fn fallback_warning(fallback: &[String]) -> Option<String> {
const NAMED: usize = 5;
let (first, more) = (fallback.iter().take(NAMED).cloned().collect::<Vec<_>>(), fallback.len().saturating_sub(NAMED));
match (first.is_empty(), more) {
(true, _) => None,
(false, 0) => Some(format!("{} font(s) lack glyphs for the sample: {}", fallback.len(), first.join(", "))),
(false, more) => Some(format!("{} font(s) lack glyphs for the sample: {} and {more} more", fallback.len(), first.join(", "))),
}
}
/// Point type set in `first` and then `more`, with its first baseline at the origin, laid out.
fn laid_out(first: TextRun, more: Option<TextRun>, system_layout: bool) -> TextObject {
let mut t = TextObject::point(Point::ZERO, "", first.style.clone());
t.runs = std::iter::once(first).chain(more).collect();
// Every paragraph is aligned left, right-to-left ones too, so each starts at the column's edge.
t.para = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Left, ..new_type_para() };
t.system_layout = system_layout;
t.normalize_paras();
let layout = vectorcraft_text::layout(FontDb::global(), &t);
t.cached_bounds = Some(layout.bounds);
t.cached_baselines = layout.baselines();
let mut ink = layout.run_ink_bounds.clone();
for (run, bar) in vectorcraft_text::decorations(&layout, FontDb::global(), &t) {
if let Some(bounds) = ink.get_mut(run) {
let bar = bar.bounding_box();
*bounds = Some(bounds.map_or(bar, |bounds| bounds.union(bar)));
}
}
t.cached_ink = Some((layout.bounds, ink.iter().copied().flatten().reduce(|a, b| a.union(b))));
if t.runs.len() == 2
&& let (Some(label), Some(sample)) = (ink[0], ink[1])
{
let overlap = label.y1 - sample.y0;
if overlap > 0.0
&& let Some(run) = t.runs.get_mut(1)
{
run.style.leading = Some(run.style.leading.unwrap_or(run.style.size * 1.2) + overlap);
refresh_bounds(&mut t);
}
}
t
}
/// How far the ink of laid-out type `t` reaches above and below its first baseline, underline and
/// strikethrough bars included; none when nothing draws.
fn ink_extent(t: &TextObject) -> (f64, f64) {
t.cached_ink.and_then(|(_, ink)| ink).map_or((0.0, 0.0), |b| ((-b.y0).max(0.0), b.y1.max(0.0)))
}
/// The warning a sheet that left fonts out gives, naming the first few.
fn skipped_warning(skipped: &[String]) -> Option<String> {
const NAMED: usize = 5;
let (first, more) = (skipped.iter().take(NAMED).cloned().collect::<Vec<_>>(), skipped.len().saturating_sub(NAMED));
match (first.is_empty(), more) {
(true, _) => None,
(false, 0) => Some(format!("{} font(s) could not be loaded and were left out: {}", skipped.len(), first.join(", "))),
(false, more) => Some(format!("{} font(s) could not be loaded and were left out: {} and {more} more", skipped.len(), first.join(", "))),
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,636 @@
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
use vectorcraft_text::FontDb;
use super::{COMMAND, DEFAULT_TEXT, MAX_CHARS};
use crate::Session;
/// The bundled families, available on every platform.
const BUNDLED: [&str; 3] = ["Inter", "Source Serif 4", "JetBrains Mono"];
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn group(s: &Session, r: &Value) -> Node {
s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone()
}
/// Each entry of the sheet `g`: its name and its type.
fn entries(g: &Node) -> Vec<(String, TextObject)> {
g.children()
.unwrap()
.iter()
.map(|n| match &n.kind {
NodeKind::Text(t) => (n.name.clone().unwrap_or_default(), (**t).clone()),
_ => panic!("a font sheet holds only type"),
})
.collect()
}
/// Where the first baseline of `t` starts.
fn origin(t: &TextObject) -> (f64, f64) {
let [.., x, y] = t.xf.as_coeffs();
(x, y)
}
#[test]
fn a_sheet_sets_the_text_in_each_family_labeled_in_columns_in_one_undo_step() {
let mut s = session();
let undo = steps(&s);
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 2, "size": 12, "gap": 10, "margin": 20, "text": "Hamburgefonstiv"})).unwrap();
assert_eq!(r["count"], 3);
assert_eq!(r["skipped"], json!([]));
assert_eq!(r["artboards"], json!([]), "three entries fit on the artboard");
assert_eq!(steps(&s), undo + 1, "one undo step");
let g = group(&s, &r);
assert_eq!(g.name.as_deref(), Some("Font Sheet"));
assert_eq!(s.doc().unwrap().selection.objects, [g.id], "the sheet is selected");
let e = entries(&g);
assert_eq!(e.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), BUNDLED, "in the order given, each named after its font");
for ((name, t), family) in e.iter().zip(BUNDLED) {
assert_eq!(t.plain_text(), format!("{name}\nHamburgefonstiv"), "a label line, then the sample");
let [label, sample] = &t.runs[..] else { panic!("a label run and a sample run: {:?}", t.runs.len()) };
assert_eq!(sample.style.font_family, family);
assert!((sample.style.size - 12.0).abs() < 1e-9 && (label.style.size - 9.0).abs() < 1e-9, "the label is set at 9 pt");
assert_eq!(label.style.font_family, "Source Sans 3", "the label is in the normal type font");
}
// Down the first column, 9 + 18 + 10 pt apart, inside the 20 pt margin, the first baseline one label below the top.
let board = s.doc().unwrap().doc.artboards[0].rect;
let (a, b) = (origin(&e[0].1), origin(&e[1].1));
assert!((a.0 - board.x0 - 20.0).abs() < 1e-9 && (a.1 - board.y0 - 29.0).abs() < 1e-9, "{a:?}");
assert!((b.0 - a.0).abs() < 1e-9 && (b.1 - a.1 - 37.0).abs() < 1e-9, "{b:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(g.id).is_none(), "undo removes the sheet");
}
#[test]
fn a_full_artboard_continues_on_new_artboards_to_the_right() {
let mut s = session();
let undo = steps(&s);
// 400 pt tall less 2 × 100 pt of margin: 200 pt, room for two 72 pt entries (9 + 54 + 9).
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100})).unwrap();
assert_eq!(r["count"], 3);
assert_eq!(r["artboards"], json!([1]), "the third entry goes on a new artboard");
assert_eq!(steps(&s), undo + 1, "the new artboard is in the same undo step");
let doc = &s.doc().unwrap().doc;
let (first, added) = (doc.artboards[0].rect, doc.artboards[1].rect);
assert!((added.x0 - first.x1 - 20.0).abs() < 1e-9 && (added.y0 - first.y0).abs() < 1e-9, "{added:?}");
assert!((added.width() - first.width()).abs() < 1e-9 && (added.height() - first.height()).abs() < 1e-9, "the same size");
let e = entries(&group(&s, &r));
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9, "inset by the margin on the new artboard");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "undo removes the artboard too");
// Without new artboards, the page after the first is laid out in the same place with none.
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100, "newArtboards": false})).unwrap();
assert_eq!(r["artboards"], json!([]));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
let e = entries(&group(&s, &r));
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9);
}
#[test]
fn a_filter_picks_families_and_all_styles_lists_each_style() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"filter": " sOURCE s ", "labels": false})).unwrap();
let e = entries(&group(&s, &r));
let names: Vec<&str> = e.iter().map(|(n, _)| n.as_str()).collect();
assert!(e.len() >= 2 && names.len() == e.len(), "{names:?}");
assert!(names.contains(&"Source Sans 3") && names.contains(&"Source Serif 4"), "{names:?}");
assert!(names.iter().all(|n| n.to_lowercase().contains("source s")), "{names:?}");
assert!(e.iter().all(|(_, t)| t.runs.len() == 1 && t.plain_text() == DEFAULT_TEXT), "no labels: the sample alone");
let r = s.execute(COMMAND, &json!({"families": ["Source Sans 3"], "allStyles": true})).unwrap();
let e = entries(&group(&s, &r));
let styles: Vec<String> = vectorcraft_text::FontDb::global().styles("Source Sans 3");
assert!(styles.len() > 1, "{styles:?}");
assert_eq!(e.len(), styles.len(), "one entry for each style");
for ((name, t), style) in e.iter().zip(&styles) {
assert_eq!(name, &format!("Source Sans 3 {style}"));
assert_eq!(&t.runs[1].style.font_style, style);
}
}
/// Columns sit side by side, each `gap` apart and as wide as the room inside the margin allows.
#[test]
fn columns_share_the_room_inside_the_margin() {
let mut s = session();
// 400 pt less 2 × 50 pt of margin leaves 300 pt: eight 39 pt entries (9 + 18 + 12) fit in a column.
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12})).unwrap();
let board = s.doc().unwrap().doc.artboards[0].rect;
let e = entries(&group(&s, &r));
// The first column fills before the second starts, so all three share it.
let xs: Vec<f64> = e.iter().map(|(_, t)| origin(t).0).collect();
assert!(!xs.is_empty(), "the sheet has entries");
assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}");
// One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart.
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap();
let e = entries(&group(&s, &r));
let step = (500.0 - 24.0) / 3.0 + 12.0;
for (i, (_, t)) in e.iter().enumerate() {
let (x, y) = origin(t);
assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}");
}
assert_eq!(r["artboards"], json!([]));
}
/// The journal records the active artboard, so a replay in a new session lays the sheet out on the
/// same one; an action leaves it out, and a named artboard goes ahead of it.
#[test]
fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
let second = s.doc().unwrap().doc.artboards[1].clone();
s.doc_mut().unwrap().active_artboard = Some(second.id);
let start = s.journal.len();
let params = json!({"families": ["Inter"], "margin": 10});
let r = s.execute(COMMAND, &params).unwrap();
let e = entries(&group(&s, &r));
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard");
let (id, recorded) = s.journal.last().unwrap().clone();
assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1)));
assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays");
// A replay in a session whose view has no active artboard uses the recorded one.
let mut fresh = session();
fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
let r = fresh.replay(COMMAND, &recorded).unwrap();
let e = entries(&group(&fresh, &r));
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard");
// A named artboard goes ahead of the recorded one.
let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap();
let e = entries(&group(&fresh, &r));
let first = fresh.doc().unwrap().doc.artboards[0].rect;
assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9);
assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard");
}
/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column.
#[test]
fn a_right_to_left_sample_stays_inside_its_column() {
let mut s = session();
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
let board = s.doc().unwrap().doc.artboards[0].rect;
// Alone, and under a left-to-right label: each line starts at the column's left edge.
for labels in [false, true] {
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap();
assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
for (name, t) in &entries(&group(&s, &r)) {
let x = origin(t).0;
assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}");
let layout = vectorcraft_text::layout(FontDb::global(), t);
for line in &layout.lines {
let left = x + line.x0;
assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge");
}
}
}
}
#[test]
fn a_variation_selector_does_not_require_a_separate_glyph() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
assert!(face.covers('A'));
assert!(!face.covers('\u{fe0f}'));
let text = "A\u{fe0f}";
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
assert_eq!(r["count"], 1);
assert_eq!(r["skipped"], json!([]));
assert_eq!(r["fallback"], json!([]));
assert!(r.get("warning").is_none(), "{r}");
let e = entries(&group(&s, &r));
assert_eq!(e.len(), 1);
assert_eq!(e[0].1.plain_text(), text);
}
#[test]
fn coverage_uses_the_samples_numeral_system() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
assert!(face.covers('1'));
assert!(!face.covers('\u{661}'));
for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] {
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}}))
.unwrap();
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
assert_eq!(r["count"], 1);
assert_eq!(r["skipped"], json!([]));
assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}");
if missing {
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
} else {
assert!(r.get("warning").is_none(), "{r}");
}
let e = entries(&group(&s, &r));
assert_eq!(e.len(), 1);
assert_eq!(e[0].1.plain_text(), text);
assert_eq!(e[0].1.runs[0].style.digits.id(), digits);
}
}
/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase
/// letter but not its capital is named in `fallback`, plain and composite fonts alike.
#[test]
fn coverage_checks_the_capitals_all_caps_draws() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
let lower = (0x80..0x3000u32)
.filter_map(char::from_u32)
.find(|&c| {
let mut up = c.to_uppercase();
face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
})
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let text = lower.to_string();
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}");
let e = entries(&group(&s, &r));
assert!(e[0].1.runs[0].style.all_caps);
assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case");
// Layout picks the font for the character as typed, so one the font lacks still falls back
// when the font has its capitals.
let uncased = (0x80..0x3000u32)
.filter_map(char::from_u32)
.find(|&c| {
let up: String = c.to_uppercase().collect();
!face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u))
})
.unwrap_or_else(|| panic!("Inter has every character whose capitals it has"));
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap();
assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}");
}
/// Small Caps in the normal character style draws lowercase letters as capitals too, so a font with
/// a lowercase letter but not its capital is named in `fallback`, plain and composite fonts alike.
#[test]
fn coverage_checks_the_capitals_small_caps_draws() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
let lower = (0x80..0x3000u32)
.filter_map(char::from_u32)
.find(|&c| {
let mut up = c.to_uppercase();
c.is_lowercase() && face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
})
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
let font = json!({"name": "CF Sheet Small Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let text = lower.to_string();
let families = json!(["Inter", "CF Sheet Small Caps"]);
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"small_caps": 70}})).unwrap();
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
let e = entries(&group(&s, &r));
assert_eq!(e.len(), 2);
assert!(e[0].1.runs[0].style.small_caps.is_some());
assert_eq!(r["fallback"], families, "{lower:?}: {r}");
}
#[test]
fn bad_params_are_refused_without_a_change() {
let mut s = session();
let before = steps(&s);
let long = "x".repeat(MAX_CHARS + 1);
for bad in [
json!({"text": ""}),
json!({"text": " "}),
json!({"text": "two\nlines"}),
json!({"text": "two\u{2028}lines"}),
json!({"text": "two\u{2029}paragraphs"}),
json!({"text": long}),
json!({"text": 5}),
json!({"size": 0.5}),
json!({"size": "12"}),
json!({"columns": 0}),
json!({"columns": 1.5}),
json!({"gap": -1}),
json!({"margin": 2000}),
json!({"margin": 300}),
json!({"columns": 50, "gap": 1000}),
json!({"filter": "no family is called this"}),
json!({"filter": 3}),
json!({"families": []}),
json!({"families": "Inter"}),
json!({"families": ["Inter", "inter"]}),
json!({"families": ["No Such Family Anywhere"]}),
json!({"families": [""]}),
json!({"families": ["Inter"], "filter": "Inter"}),
json!({"families": ["Inter"], "filter": ""}),
json!({"families": ["Inter"], "filter": " "}),
json!({"labels": "yes"}),
json!({"allStyles": 1}),
json!({"newArtboards": "no"}),
] {
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
}
assert_eq!(steps(&s), before);
let layers = &s.doc().unwrap().doc.layers;
assert!(!layers.is_empty(), "the document keeps its layers");
assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn");
}
/// Fonts left out are named in the warning, the first five of them, with a count of the rest.
#[test]
fn fonts_left_out_are_named_in_a_warning() {
let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::<Vec<_>>();
assert_eq!(super::skipped_warning(&[]), None);
assert_eq!(super::skipped_warning(&names(2)).as_deref(), Some("2 font(s) could not be loaded and were left out: Font 1, Font 2"));
assert_eq!(
super::skipped_warning(&names(7)).as_deref(),
Some("7 font(s) could not be loaded and were left out: Font 1, Font 2, Font 3, Font 4, Font 5 and 2 more")
);
let mut s = session();
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
assert!(r.get("warning").is_none(), "nothing left out: no warning");
}
/// A family the font menus list whose file no longer reads as a font is left out, as is a style
/// that would be drawn in another style of its family; the rest of the sheet is made.
#[test]
fn fonts_that_do_not_load_are_left_out_and_named() {
use vectorcraft_text::test_fonts::named_copy;
let dir = vectorcraft_testkit::temp_dir("font-sheet-unreadable");
let file = |family: &str, style: &str| dir.join(format!("{}-{style}.ttf", family.replace(' ', "")));
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Regular"), ("Sheet Half", "Bold")] {
let postscript = format!("{}-{style}", family.replace(' ', ""));
std::fs::write(file(family, style), named_copy(false, (family, style, "Version 1.000", &postscript)).unwrap()).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir.clone()]);
// Cataloged while every file reads; then two of them stop reading as fonts.
assert_eq!(db.styles("Sheet Half").len(), 2, "{:?}", db.styles("Sheet Half"));
assert!(db.menu_family_list().iter().any(|f| f == "Sheet Gone"));
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Bold")] {
std::fs::write(file(family, style), b"not a font").unwrap();
}
let mut s = session();
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone", "Inter"]}), &db).unwrap();
assert_eq!(r["skipped"], json!(["Sheet Gone"]), "drawn in the fallback font, it is left out: {r}");
assert_eq!(r["count"], 1);
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: Sheet Gone");
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Half"], "allStyles": true}), &db).unwrap();
assert_eq!(r["skipped"], json!(["Sheet Half Bold"]), "drawn in its Regular, the Bold is left out: {r}");
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Sheet Half Regular"]);
// Nothing that loads: an error, with nothing changed.
let before = steps(&s);
assert!(super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone"]}), &db).is_err());
assert_eq!(steps(&s), before);
}
/// Where the ink of `t` starts and ends down the page.
fn ink_rows(t: &TextObject) -> (f64, f64) {
let (_, y) = origin(t);
let b = vectorcraft_text::layout(FontDb::global(), t).ink_bounds().unwrap();
(y + b.y0, y + b.y1)
}
/// A composite font whose Roman part sets the sample at four times its size gets rows as tall as
/// its laid-out ink: the first entry stays inside the margin, the second starts below the first,
/// and each sample starts below its own label.
#[test]
fn rows_fit_the_laid_out_ink_of_a_composite_font() {
let mut s = session();
let big = |name: &str| json!({"name": name, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter", "size": 400}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [big("CF Sheet Big A"), big("CF Sheet Big B")]})).unwrap();
let p = json!({"families": ["CF Sheet Big A", "CF Sheet Big B"], "columns": 1, "size": 12, "gap": 10, "margin": 20, "text": "Hamburg"});
let r = s.execute(COMMAND, &p).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
let board = s.doc().unwrap().doc.artboards[0].rect;
let e = entries(&group(&s, &r));
let ((top0, bottom0), (top1, _)) = (ink_rows(&e[0].1), ink_rows(&e[1].1));
assert!(top0 >= board.y0 + 20.0 - 1e-6, "the first entry reaches into the margin: {top0}");
assert!(top1 >= bottom0 - 1e-6, "the second entry overlaps the first: {top1} < {bottom0}");
for (name, t) in &e {
let mut label = t.clone();
label.runs.truncate(1);
let mut sample = t.clone();
sample.runs.remove(0);
let (y0, y1) = (t.cached_baselines[0].0.y, t.cached_baselines[1].0.y);
let label_bottom = y0 + vectorcraft_text::layout(FontDb::global(), &label).ink_bounds().unwrap().y1;
let sample_top = y1 + vectorcraft_text::layout(FontDb::global(), &sample).ink_bounds().unwrap().y0;
assert!(sample_top >= label_bottom - 1e-6, "{name}: the sample reaches into its label: {sample_top} < {label_bottom}");
}
}
/// A composite font named in other letter case, accented letters included, is found by its own name.
#[test]
fn a_composite_font_named_in_other_case_is_set() {
let mut s = session();
let font = json!({"name": "\u{c9}preuve Sheet", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["\u{e9}preuve sheet"], "text": "Hamburg"})).unwrap();
assert_eq!((r["skipped"].clone(), r["count"].clone()), (json!([]), json!(1)), "{r}");
assert_eq!(entries(&group(&s, &r))[0].0, "\u{c9}preuve Sheet");
let twice = s.execute(COMMAND, &json!({"families": ["\u{c9}preuve Sheet", "\u{e9}PREUVE SHEET"]})).unwrap_err().to_string();
assert!(twice.contains("twice"), "{twice}");
}
/// A composite font whose part setting the sample names a font that doesn't load is left out and
/// named, as a family that doesn't load is.
#[test]
fn a_composite_font_with_a_missing_part_is_left_out() {
let mut s = session();
let font = json!({"name": "CF Sheet Gone", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Sheet Font"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Gone", "Inter"], "text": "Hamburg"})).unwrap();
assert_eq!(r["skipped"], json!(["CF Sheet Gone"]), "{r}");
assert_eq!(r["count"], 1);
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
}
#[test]
fn a_composite_font_with_an_unavailable_part_style_is_left_out() {
let mut s = session();
let font = json!({
"name": "CF Sheet Missing Style",
"parts": {
"kanji": {"font": "Source Sans 3"},
"roman": {"font": "Inter", "style": "No Such Sheet Style"}
}
});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let coverage = FontDb::global().composite_coverage("CF Sheet Missing Style", &["Hamburg"]).unwrap();
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Style);
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style", "Inter"], "text": "Hamburg"})).unwrap();
assert_eq!(r["skipped"], json!(["CF Sheet Missing Style"]));
assert_eq!(r["count"], 1);
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: CF Sheet Missing Style");
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
let before = (s.doc().unwrap().doc.clone(), steps(&s));
assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err());
assert_eq!(s.doc().unwrap().doc, before.0);
assert_eq!(steps(&s), before.1);
}
/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is
/// named in `fallback`, as a plain font is.
#[test]
fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() {
let mut s = session();
let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap();
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact);
assert!(!coverage.lacking.is_empty());
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}");
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}");
// A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system.
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap();
assert_eq!(r["fallback"], json!([]), "{r}");
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}}))
.unwrap();
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap();
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
}
#[test]
fn labels_without_overlap_need_no_additional_layouts() {
use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread};
let mut counts = vec![];
for labels in [false, true] {
let mut s = session();
let before = layouts_on_this_thread();
let ink_before = ink_work_on_this_thread();
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap();
let ink_after = ink_work_on_this_thread();
counts.push(layouts_on_this_thread() - before);
assert_eq!(r["count"], BUNDLED.len());
let mut outlines = 0;
for (_, t) in entries(&group(&s, &r)) {
assert!(t.cached_ink.unwrap().1.is_some());
assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 });
let layout = vectorcraft_text::layout(FontDb::global(), &t);
outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64;
assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
}
assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once");
assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry");
}
assert!(counts[0] > 0);
assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts");
}
#[test]
fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() {
use vectorcraft_doc::{CharStyle, TextRun};
for text in ["Hamburg", " "] {
for labels in [false, true] {
let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() };
let sample = TextRun::new(text, style.clone());
let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) };
let t = super::laid_out(first, more, false);
let layout = vectorcraft_text::layout(FontDb::global(), &t);
let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t);
assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars");
let ink = t.cached_ink.unwrap().1;
assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
let ink = ink.unwrap();
for (_, bar) in bars {
let bounds = vectorcraft_geom::Shape::bounding_box(&bar);
assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1);
}
}
}
}
#[test]
fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() {
let mut s = Session::new();
s.execute("file.new", &json!({"artboards": 3})).unwrap();
let state = s.doc().unwrap();
let document = (state.uid, state.reverts);
let artboard = state.doc.artboards[1].id;
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
let before = (s.doc().unwrap().doc.clone(), steps(&s));
for params in [json!({"index": 0}), json!({"indices": [1, 0]})] {
let error = s.execute("artboard.delete", &params).unwrap_err();
assert_eq!(error.to_string(), "The artboard is in use.");
assert_eq!(s.doc().unwrap().doc, before.0);
assert_eq!(steps(&s), before.1);
}
s.execute("file.new", &json!({"artboards": 2})).unwrap();
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected");
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.doc_mut().unwrap().reverts += 1;
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected");
}
/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too.
#[test]
fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() {
let mut s = Session::new();
s.execute("file.new", &json!({"artboards": 3})).unwrap();
let state = s.doc().unwrap();
let document = (state.uid, state.reverts);
let artboard = state.doc.artboards[1].id;
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
let before = (s.doc().unwrap().doc.clone(), steps(&s));
for (command, params) in [
("artboard.cut", json!({"index": 1})),
("artboard.deleteEmpty", json!({})),
("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})),
] {
let error = s.execute(command, &params).unwrap_err();
assert_eq!(error.to_string(), "The artboard is in use.", "{command}");
assert_eq!(s.doc().unwrap().doc, before.0, "{command}");
assert_eq!(steps(&s), before.1, "{command}");
}
s.execute("artboard.cut", &json!({"index": 2})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut");
}
#[test]
fn it_needs_a_document() {
let mut s = Session::new();
assert!(s.execute(COMMAND, &json!({})).is_err());
}
#[test]
fn a_locked_layer_takes_no_sheet() {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
let before = steps(&s);
assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err());
assert_eq!(steps(&s), before);
}
#[test]
fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() {
let mut s = session();
let editable = s.doc().unwrap().doc.layers[0].id;
let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
let gid = NodeId(r["id"].as_u64().unwrap());
let doc = &s.doc().unwrap().doc;
let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid));
assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked");
assert!(!holds(locked));
}
+17 -2
View File
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Artboard",
["Window", "Artboards"],
None,
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one is an error",
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one, or the one an open Create Font Sheet dialog uses, is an error",
has_doc,
artboard_delete
),
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Empty Artboards",
["Window", "Artboards"],
None,
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go) → {deleted: [index…]} (the indices before deleting)",
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go); an error, with nothing deleted, when one of them is the artboard an open Create Font Sheet dialog uses → {deleted: [index…]} (the indices before deleting)",
has_empty_artboards,
artboard_delete_empty
),
@@ -1225,11 +1225,25 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
fn artboard_delete(s: &mut Session, p: &Value) -> Result<Value> {
let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?;
refuse_guarded(s, &indices)?;
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?;
ok()
}
/// The session's artboard deletion guard's message when deleting artboards `indices` of the
/// active document would delete the artboard it protects.
pub(crate) fn refuse_guarded(s: &Session, indices: &[usize]) -> Result<()> {
let Some(guard) = &s.artboard_deletion_guard else { return Ok(()) };
let state = s.doc()?;
if (state.uid, state.reverts) == guard.document
&& indices.iter().any(|&index| state.doc.artboards.get(index).is_some_and(|a| a.id == guard.artboard))
{
return Err(EngineError::Other(guard.message.clone()));
}
Ok(())
}
/// Delete artboards `indices` (sorted, each once) of `d` with their guides; at least one must be
/// left. The other artboards keep their order, no later artboard takes a deleted one's id, and
/// `sel` forgets the deleted guides. One walk over the artboards and one over the ruler guides,
@@ -1306,6 +1320,7 @@ fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result<Value> {
if indices.is_empty() {
return Err(EngineError::Other("no empty artboards to delete".into()));
}
refuse_guarded(s, &indices)?;
s.edit("Delete Empty Artboards", |d, sel| remove_artboards(d, sel, &indices))?;
Ok(json!({ "deleted": indices }))
}
+2 -1
View File
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut Artboard",
[],
None,
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
has_doc,
|s, p| {
boards_and_art_noted(s, p, "artboard.cut")?;
@@ -366,6 +366,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
return Err(EngineError::Other("a document needs at least one artboard".into()));
}
if cut {
super::layer::refuse_guarded(s, &indices)?;
refuse_locked(&st.doc, &indices)?;
}
let art = st.doc.paint_order(arts.into_iter().flat_map(|(_, a)| a));
@@ -767,6 +767,7 @@ pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
"addon.pen.nextSegment",
"addon.type.fontSheet",
"addon.type.numbers",
"color.contrast",
"effect.refreshDeferred",
+2 -1
View File
@@ -39,7 +39,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
/// ([`Session::journal_for_action`]).
const REPLAY_ONLY: [(&str, &str); 39] = [
const REPLAY_ONLY: [(&str, &str); 40] = [
("edit.copy", "artboard"),
("edit.cut", "artboard"),
("file.new", "created"),
@@ -70,6 +70,7 @@ const REPLAY_ONLY: [(&str, &str); 39] = [
("artboard.distribute", "activeArtboard"),
("artboard.distributeSpacing", "selectedArtboards"),
("artboard.distributeSpacing", "activeArtboard"),
("addon.type.fontSheet", "activeArtboard"),
("addon.document.floodFillArtboards", "activeArtboard"),
("edit.copy", "selectedArtboards"),
("edit.copy", "art"),
+7
View File
@@ -58,6 +58,12 @@ pub use vectorcraft_tools as tools;
pub use vectorcraft_doc::MAX_COORD;
const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap");
pub struct ArtboardDeletionGuard {
pub document: (u64, u64),
pub artboard: u32,
pub message: String,
}
/// The maximum number of newest swatch renames a session keeps until they are taken.
pub(crate) const MAX_SWATCH_RENAMES: usize = 64;
@@ -67,6 +73,7 @@ pub struct Session {
pub prefs: Prefs,
/// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences.
pub caps_lock: bool,
pub artboard_deletion_guard: Option<ArtboardDeletionGuard>,
/// Fill/stroke for new art (the toolbar proxy).
pub paint: PaintDefaults,
/// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles.
+1
View File
@@ -51,6 +51,7 @@ impl Session {
active: None,
prefs: Prefs::default(),
caps_lock: false,
artboard_deletion_guard: None,
paint: PaintDefaults::default(),
fill_active: true,
clipboard: Clipboard::default(),
+1 -1
View File
@@ -1555,7 +1555,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.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|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`); addon.arrange.artboardGuides fails when the document has no artboards; 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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|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`); addon.arrange.artboardGuides fails when the document has no artboards; 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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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",
+31 -2
View File
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use unicode_segmentation::UnicodeSegmentation;
use vectorcraft_doc::text::CompositeClasses;
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, TextObject, TextRun};
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, Digits, TextObject, TextRun};
use super::face::FALLBACK_FAMILY;
use super::{Arc, FontDb, FontFace, FontMatch};
@@ -242,6 +242,24 @@ impl FontDb {
/// match, and the characters (neither whitespace nor control characters, sorted, each once)
/// that their part's face lacks. `None` when `name` is no composite font.
pub fn composite_coverage(&self, name: &str, texts: &[&str]) -> Option<CompositeCoverage> {
self.coverage_of(name, texts, None)
}
/// [`FontDb::composite_coverage`] of the characters layout draws in numeral system `digits`:
/// each grapheme cluster's part is chosen by its own first character, and the part's face is
/// checked for the cluster's drawn characters ([`crate::drawn_chars`]).
pub fn composite_drawn_coverage(&self, name: &str, texts: &[&str], digits: Digits) -> Option<CompositeCoverage> {
self.coverage_of(name, texts, Some((digits, false)))
}
/// [`FontDb::composite_drawn_coverage`] of type set in All Caps when `all_caps` is on: each
/// cluster's part is still chosen by its own first character, and the part's face is also
/// checked for the capitals layout draws.
pub fn composite_cased_coverage(&self, name: &str, texts: &[&str], digits: Digits, all_caps: bool) -> Option<CompositeCoverage> {
self.coverage_of(name, texts, Some((digits, all_caps)))
}
fn coverage_of(&self, name: &str, texts: &[&str], digits: Option<(Digits, bool)>) -> Option<CompositeCoverage> {
let f = self.composite_font(name)?;
let rank = |m: FontMatch| match m {
FontMatch::Exact => 0,
@@ -272,7 +290,18 @@ impl FontDb {
if worst.as_ref().is_none_or(|(w, _)| rank(m) > rank(*w)) {
worst = Some((m, found.as_ref().map(|(face, _)| face.clone())));
}
lacking.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c))));
match digits {
Some((d, caps)) => {
let missing = |c: &char| !found.as_ref().is_some_and(|(face, _)| face.covers(*c));
lacking.extend(crate::drawn_chars(g, d).filter(missing));
if caps {
let upper: String = g.chars().flat_map(char::to_uppercase).collect();
lacking.extend(crate::drawn_chars(&upper, d).filter(missing));
}
}
None => lacking
.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))),
}
}
lacking.sort_unstable();
lacking.dedup();
+11 -1
View File
@@ -99,6 +99,8 @@ pub fn fit_source_lines(db: &FontDb, t: &mut TextObject, lines: usize) -> bool {
/// own underline and strikeout metrics through the glyph's transform (so the size, baseline shift
/// and scaling follow) → (run, bar in text space). Type on a path and vertical type have none yet.
pub fn decorations(layout: &TextLayout, db: &FontDb, t: &TextObject) -> Vec<(usize, BezPath)> {
#[cfg(any(test, feature = "test-fonts"))]
crate::test_fonts::count_decorations();
let mut out = vec![];
if layout.on_path || layout.vertical {
return out;
@@ -449,6 +451,14 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout
let original = |run: &mut usize| *run = from.get(*run).copied().unwrap_or(*run);
l.glyphs.iter_mut().chain(l.ruby.iter_mut()).for_each(|g| original(&mut g.run));
l.inlines.iter_mut().for_each(|i| original(&mut i.run));
let mut ink: Vec<Option<Rect>> = vec![None; t.runs.len()];
for (mut run, bounds) in std::mem::take(&mut l.run_ink_bounds).into_iter().enumerate() {
original(&mut run);
if let (Some(ink), Some(bounds)) = (ink.get_mut(run), bounds) {
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
}
}
l.run_ink_bounds = ink;
l
}
@@ -572,6 +582,6 @@ fn layout_runs(db: &FontDb, t: &TextObject, opts: &LayoutOptions, set: Option<&T
cx.out.line_xf = line_xf;
}
keep_lone_ligature_carets(&mut cx.out.glyphs);
finish_bounds(&mut cx.out);
finish_bounds(&mut cx.out, t.runs.len());
cx.out
}
+10 -2
View File
@@ -402,9 +402,17 @@ pub(super) fn stands_upright(g: &SGlyph) -> bool {
!needs_vertical_form || g.gid != g.face.glyph_for(g.ch)
}
pub(super) fn finish_bounds(out: &mut TextLayout) {
pub(super) fn finish_bounds(out: &mut TextLayout, runs: usize) {
let xf = out.line_xf;
let mut b: Option<Rect> = out.ink_bounds();
let mut ink: Vec<Option<Rect>> = vec![None; runs];
let mut b: Option<Rect> = None;
out.for_each_ink(|run, bounds| {
b = Some(b.map_or(bounds, |b| b.union(bounds)));
if let Some(ink) = ink.get_mut(run) {
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
}
});
out.run_ink_bounds = ink;
let mut add = |r: Rect| b = Some(b.map_or(r, |b| b.union(r)));
if !out.on_path {
for l in &out.lines {
+30 -8
View File
@@ -60,7 +60,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader};
pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout};
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled};
pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
pub use shape::{aki_space, drawn_chars, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
pub use vectorcraft_doc::TextObject;
pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign};
@@ -388,6 +388,9 @@ pub struct TextLayout {
pub lines: Vec<LineInfo>,
/// Ink/advance bounds in text space.
pub bounds: Rect,
/// Ink bounds per text run when layout completed, excluding decorations. These bounds do
/// not update when glyph geometry changes; [`Self::ink_bounds`] measures the current geometry.
pub run_ink_bounds: Vec<Option<Rect>>,
/// True if area text did not fit its frame (the red overflow "+" marker), or on-path text ran
/// past the end of the path.
pub overflow: bool,
@@ -422,6 +425,7 @@ impl Default for TextLayout {
ruby: Vec::new(),
lines: Vec::new(),
bounds: Rect::ZERO,
run_ink_bounds: Vec::new(),
overflow: false,
on_path: false,
frames: Vec::new(),
@@ -477,16 +481,34 @@ impl TextLayout {
/// inline graphics included, without the lines' em boxes that [`Self::bounds`] also covers.
/// What Align to Glyph Bounds aligns. `None` when nothing draws (only spaces, or no text).
pub fn ink_bounds(&self) -> Option<Rect> {
let outlined = |g: &PositionedGlyph| (!g.outline.elements().is_empty()).then(|| g.outline.bounding_box());
let glyphs = self.glyphs.iter().flat_map(|g| {
let mut bounds: Option<Rect> = None;
self.for_each_ink(|_, ink| bounds = Some(bounds.map_or(ink, |bounds| bounds.union(ink))));
bounds
}
fn for_each_ink(&self, mut add: impl FnMut(usize, Rect)) {
let outlined = |g: &PositionedGlyph| {
(!g.outline.elements().is_empty()).then(|| {
#[cfg(any(test, feature = "test-fonts"))]
test_fonts::count_ink_outline();
g.outline.bounding_box()
})
};
for g in &self.glyphs {
let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect()));
let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b));
[outlined(g), image, colour]
});
for ink in [outlined(g), image, colour].into_iter().flatten() {
add(g.run, ink);
}
}
// Ruby is covered by its line's ascent, but its ink can overhang sideways past the line.
let ruby = self.ruby.iter().map(outlined);
let inlines = self.inlines.iter().map(|i| Some(i.bounds));
glyphs.chain(ruby).chain(inlines).flatten().reduce(|a, b| a.union(b))
for g in &self.ruby {
if let Some(ink) = outlined(g) {
add(g.run, ink);
}
}
for inline in &self.inlines {
add(inline.run, inline.bounds);
}
}
/// The box of [`Self::ink_bounds`]' ink with text space mapped by `m`: the glyph and ruby
/// outlines are mapped point by point, so a rotated or sheared `m` gives the outlines' own
+3 -3
View File
@@ -1382,11 +1382,11 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
&& ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking)
}
/// The characters of a grapheme cluster that need a glyph of their own, in the numeral system
/// The characters of the text that need a glyph of their own, in the numeral system
/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or
/// variation selectors.
fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
craft::font_catalog::drawable_characters(cluster, move |c| digits.map(c))
pub fn drawn_chars(text: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
craft::font_catalog::drawable_characters(text, move |c| digits.map(c))
}
/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)?
+14
View File
@@ -29,6 +29,20 @@ pub(crate) fn keeps_shape_plans() -> bool {
std::thread_local! {
/// How many layouts this thread has started ([`layouts_on_this_thread`]).
static LAYOUTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static INK_OUTLINES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static DECORATIONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
pub(crate) fn count_ink_outline() {
INK_OUTLINES.with(|n| n.set(n.get() + 1));
}
pub(crate) fn count_decorations() {
DECORATIONS.with(|n| n.set(n.get() + 1));
}
pub fn ink_work_on_this_thread() -> (u64, u64) {
(INK_OUTLINES.with(std::cell::Cell::get), DECORATIONS.with(std::cell::Cell::get))
}
pub(crate) fn count_layout() {
+10 -10
View File
@@ -89,16 +89,16 @@ pub fn menu() -> Vec<Node> {
]
}
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None };
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None };
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None, pin_opening_artboard: false };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None, pin_opening_artboard: false };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None, pin_opening_artboard: false };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None, pin_opening_artboard: false };
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None, pin_opening_artboard: false };
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None, pin_opening_artboard: false };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None, pin_opening_artboard: false };
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None, pin_opening_artboard: false };
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None, pin_opening_artboard: false };
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None, pin_opening_artboard: false };
/// The dialog over `rows`, titled by the heading of `command`.
fn dialog<'a>(command: &str, rows: Vec<Param>) -> ParamDialog<'a> {
+1 -1
View File
@@ -19,7 +19,7 @@ const SCOPES: [(&str, &str); 2] = [("selection", "Selection"), ("document", "Doc
const KINDS: [(&str, &str); 3] = [("groups", "Groups"), ("clipGroups", "Clipping Masks"), ("compoundPaths", "Compound Paths")];
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
/// The dialog's rows.
fn rows() -> Vec<Param> {
+1 -1
View File
@@ -17,7 +17,7 @@ pub const COMMAND: &str = "addon.color.swatchLegend";
pub const VALUES: [(&str, &str); 5] = [("hex", "HEX"), ("rgb", "RGB"), ("cmyk", "CMYK"), ("lab", "Lab"), ("gray", "Grayscale")];
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
/// The command's params from the dialog's fields.
pub(crate) fn params(fields: &DialogFields) -> Value {
@@ -21,7 +21,7 @@ const SEEDS: u64 = 1_000_000;
/// The schemes the Colors choice offers: (`scheme`, label).
const SCHEMES: [(&str, &str); 3] = [("color", "Any Color"), ("tint", "Tints of a Swatch"), ("gray", "Grays")];
static SPEC: Spec = Spec { command: COMMAND, params, found: None };
static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
fn percent(key: &str, label: &'static str, default: f64) -> Param {
Param::number(key, tl!(label), default, 1.0, 0).bounds(Some(0.0), Some(100.0)).unit(UnitKind::Percent).enabled_when_in("scheme", ["tint", "gray"])
+70 -3
View File
@@ -27,6 +27,7 @@ pub(crate) struct Spec {
pub params: fn(&DialogFields) -> Value,
/// Receives the answer of each preview run (or its error), to show it in the dialog.
pub found: Option<Found>,
pub pin_opening_artboard: bool,
}
impl Spec {
@@ -45,6 +46,8 @@ pub(crate) struct AddonDialogs {
open: Option<Open>,
preview: LivePreview,
preview_error: Option<(u64, String)>,
/// Preview and OK are running with the dialog's opening artboard.
pub(crate) using_opening_artboard: bool,
/// The open Tangent Circle Tool radius dialog.
pub(crate) tangent_radius: Option<super::pathtools::tangent_circle_radius::Open>,
}
@@ -55,6 +58,8 @@ struct Open {
spec: &'static Spec,
/// The opening document's uid and revert count: File › Revert keeps the uid but replaces the drawing.
document: Option<(u64, u64)>,
/// The view's active artboard when the dialog opened.
artboard: Option<u32>,
}
impl Open {
@@ -73,6 +78,40 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> {
app.session.active().map(|state| (state.uid, state.reverts))
}
/// Runs the open dialog's command with its opening artboard, then restores the saved artboard.
pub(crate) fn with_opening_artboard<T>(app: &mut VectorcraftApp, command: &str, run: impl FnOnce(&mut VectorcraftApp) -> T) -> T {
let saved =
app.addon_dialogs.open.filter(|open| open.spec.pin_opening_artboard && open.spec.command == command && open.on_document(app)).and_then(
|open| {
let state = app.session.active_mut()?;
let saved = (state.uid, state.active_artboard);
state.active_artboard = open.artboard;
Some(saved)
},
);
let using_opening_artboard = app.addon_dialogs.using_opening_artboard;
if saved.is_some() {
app.addon_dialogs.using_opening_artboard = true;
}
let answer = run(app);
app.addon_dialogs.using_opening_artboard = using_opening_artboard;
if let Some((uid, artboard)) = saved
&& let Some(state) = app.session.document_mut(uid)
{
state.active_artboard = artboard;
}
answer
}
pub(crate) fn artboard_deletion_guard(app: &VectorcraftApp) -> Option<vectorcraft_engine::ArtboardDeletionGuard> {
let open = app.addon_dialogs.open.filter(|open| open.spec.pin_opening_artboard)?;
Some(vectorcraft_engine::ArtboardDeletionGuard {
document: open.document?,
artboard: open.artboard?,
message: "Close Create Font Sheet before deleting its opening artboard.".to_owned(),
})
}
/// Closes the open add-on dialog without an answer and rolls its preview back.
pub(crate) fn close_open(app: &mut VectorcraftApp) {
let Some(open) = app.addon_dialogs.open.take() else { return };
@@ -97,14 +136,28 @@ pub(crate) fn open(
spec: &'static Spec,
fields: DialogFields,
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
) -> Result<Value, String> {
open_with(app, spec, fields, build, true)
}
/// [`open`], with the Preview box on at the start when `previewing`, else off.
pub(crate) fn open_with(
app: &mut VectorcraftApp,
spec: &'static Spec,
fields: DialogFields,
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
previewing: bool,
) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, spec.command, fields, build);
let dialog = if previewing { dialog } else { dialog.preview_off() };
let host = app.dialogs().ok_or("no window")?;
close_open(app);
crate::io::remember_active_artboard(app);
let artboard = app.session.active().and_then(|state| state.active_artboard);
let id = dialog.id();
host.with(|h| h.open(dialog));
app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app) });
app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app), artboard });
Ok(json!({ "dialog": spec.command }))
}
@@ -120,6 +173,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::font_sheet::COMMAND => typetools::font_sheet::open,
typetools::numbers::COMMAND => typetools::numbers::open,
color::legend::COMMAND => color::legend::open,
color::nearest::COMMAND => color::nearest::open,
@@ -147,13 +201,23 @@ fn pump_commit(app: &mut VectorcraftApp) {
let Some(host) = app.dialogs() else { return };
let Open { id, spec, .. } = open;
let on_document = open.on_document(app);
let missing_artboard = spec.pin_opening_artboard
&& on_document
&& open.artboard.is_some_and(|id| app.session.active().is_some_and(|state| !state.doc.artboards.iter().any(|artboard| artboard.id == id)));
if !on_document {
// Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing.
app.addon_dialogs.preview = LivePreview::default();
app.addon_dialogs.preview_error = None;
}
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), spec.params(app, d.fields()))));
if on_document && let Some((previewing, params)) = &live {
if missing_artboard {
mem::take(&mut app.addon_dialogs.preview).cancel(app);
app.status(tl!("The opening artboard was deleted. Reopen this dialog to continue."));
}
if on_document
&& !missing_artboard
&& let Some((previewing, params)) = &live
{
let mut preview = mem::take(&mut app.addon_dialogs.preview);
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
let answer = match params {
@@ -187,13 +251,15 @@ fn pump_commit(app: &mut VectorcraftApp) {
}
match host.with(|h| h.take_by_id::<HostedParamDialog>(id)).map(DialogResult::ok) {
Some(Some(result)) => {
app.addon_dialogs.open = None;
let preview = mem::take(&mut app.addon_dialogs.preview);
// The dialog is closed already, so a refusal can only go to the status line.
if open.reverted(app) {
app.status("The document was reverted. Reopen this dialog to continue.");
} else if !on_document {
app.status("The add-on settings apply only to the drawing where the dialog opened.");
} else if missing_artboard {
preview.cancel(app);
app.status(tl!("The opening artboard was deleted. Reopen this dialog to continue."));
} else {
let answer = match spec.params(app, &result.fields) {
Ok(params) if spec.command == super::select::points_only::COMMAND => preview.commit_selection(app, spec.command, params),
@@ -209,6 +275,7 @@ fn pump_commit(app: &mut VectorcraftApp) {
clear_preview_error(app);
}
}
app.addon_dialogs.open = None;
app.addon_dialogs.preview_error = None;
}
Some(None) => {
@@ -229,6 +229,28 @@ fn rows() -> Vec<Row> {
assert!(label.contains("#123456") && label.contains("C="), "{label}");
},
},
Row {
group: "Type Tools",
label: "Create Font Sheet…",
setup: new_app,
refused: || vec![("text", json!(" "))],
values: || vec![("text", json!("Sample")), ("filter", json!("JetBrains Mono"))],
check: |app| {
let doc = &app.session.doc().unwrap().doc;
let sheet = doc.layers[0].children().unwrap().last().unwrap();
assert_eq!(sheet.name.as_deref(), Some("Font Sheet"));
let texts: Vec<String> = sheet
.children()
.unwrap()
.iter()
.filter_map(|c| match &c.kind {
NodeKind::Text(t) => Some(t.plain_text()),
_ => None,
})
.collect();
assert!(texts.contains(&"JetBrains Mono\nSample".to_string()), "{texts:?}");
},
},
Row {
group: "Color Effects",
label: "Randomize Fill Colors…",
+1 -1
View File
@@ -33,7 +33,7 @@ const FLOOD_LAYER: &str = "Flood Fill";
/// The color the Flood Fill Artboards dialog opens with when the current fill is not a solid color.
const GRAY: [f32; 3] = [0.5, 0.5, 0.5];
static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None };
static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None, pin_opening_artboard: false };
/// Object › Plug-ins › Document Tools.
pub fn menu() -> Vec<Node> {
@@ -16,7 +16,7 @@ const DASHES: std::ops::RangeInclusive<f64> = 0.01..=1e6;
const GAPS: std::ops::RangeInclusive<f64> = 0.0..=1e6;
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
/// The command's parameters from the dialog's fields.
pub(crate) fn params(fields: &DialogFields) -> Value {
@@ -23,7 +23,7 @@ const EVERY: [(&str, &str); 3] = [("all", "All Anchors"), ("odd", "Odd-Numbered
const ANGLES: std::ops::RangeInclusive<f64> = 0.0..=180.0;
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
/// The command's parameters from the dialog's fields.
pub(crate) fn params(fields: &DialogFields) -> Value {
@@ -20,7 +20,7 @@ const MAX_CIRCLES: u64 = 64;
const RADIUS: f64 = 36.0;
/// How the dialog's values reach the command; the preview's answer says how many circles were found.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: Some(found) };
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: Some(found), pin_opening_artboard: false };
/// The circle number the choice holds (an option id): 0 is every circle, `k` the k-th, counted from 1.
fn circle(fields: &DialogFields) -> u64 {
@@ -36,7 +36,7 @@ const REACHES: std::ops::RangeInclusive<f64> = 0.0..=10000.0;
const REACH: f64 = 10.0;
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None };
pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None, pin_opening_artboard: false };
/// Whether the fields ask for a curved bridge: External with Curved.
fn curved(fields: &DialogFields) -> bool {
@@ -17,7 +17,7 @@ use crate::menus::c;
/// Edit Points Only: the dialog's key and the command its OK runs.
pub const COMMAND: &str = "addon.select.editPointsOnly";
static SPEC: Spec = Spec { command: COMMAND, params, found: None };
static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
/// The menu item.
pub fn menu() -> Vec<Node> {
+5 -2
View File
@@ -1,6 +1,8 @@
//! Type Tools in the interface: its submenu (Object › Plug-ins › Type Tools) and Text Tweaker's
//! dialog, which picks an attribute, its start and end values and a shape, previews on the canvas
//! and runs `addon.type.textTweaker` on OK.
//! and runs `addon.type.textTweaker` on OK. Create Font Sheet's dialog is [`font_sheet`]'s.
pub mod font_sheet;
use craft::menu::Node;
use craft::ui::contract::Bind;
@@ -45,6 +47,7 @@ pub fn menu() -> Vec<Node> {
vec![
c("Text Tweaker…", COMMAND),
cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})),
c("Create Font Sheet…", font_sheet::COMMAND),
c("Make Numbers Sequence…", numbers::COMMAND),
]
}
@@ -55,7 +58,7 @@ fn attribute(key: &str) -> &'static Attribute {
}
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
/// The command's parameters from the dialog's fields; an end of the ramp not set yet is the attribute's own.
pub(crate) fn params(fields: &DialogFields) -> Value {
@@ -0,0 +1,84 @@
//! Create Font Sheet in the interface (Object › Plug-ins › Type Tools › Create Font Sheet…): a
//! dialog for the sample text, its size, a filter on the family names, whether each style gets an
//! entry and a label, and the columns, gap and margin of the pages. Its Preview box starts off;
//! switched on, it previews on the canvas. It runs `addon.type.fontSheet` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::UnitKind;
use serde_json::{Value, json};
use crate::VectorcraftApp;
use crate::addons::dialogs::{self, Spec};
use crate::canvas::rulers::general_lengths;
/// The command.
pub const COMMAND: &str = "addon.type.fontSheet";
/// The sample text the dialog opens on.
const SAMPLE: &str = "The quick brown fox jumps over the lazy dog";
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: true };
/// The command's parameters from the dialog's fields; an empty filter sets every family.
pub(crate) fn params(fields: &DialogFields) -> Value {
let mut p = json!({
"text": fields.text("text").unwrap_or(SAMPLE),
"size": fields.number("size").unwrap_or(12.0),
"allStyles": fields.bool("allStyles").unwrap_or(false),
"labels": fields.bool("labels").unwrap_or(true),
"columns": fields.int("columns").unwrap_or(2),
"gap": fields.number("gap").unwrap_or(12.0),
"margin": fields.number("margin").unwrap_or(36.0),
"newArtboards": fields.bool("newArtboards").unwrap_or(true),
});
if let Some(filter) = fields.text("filter").map(str::trim).filter(|f| !f.is_empty()) {
p["filter"] = json!(filter);
}
p
}
/// Opens Create Font Sheet's dialog on the command's defaults, with Preview off: each preview sets
/// the whole sheet again.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields = DialogFields::from_pairs([
("text", FieldValue::Text(SAMPLE.into())),
("size", FieldValue::Number(12.0)),
("filter", FieldValue::Text(String::new())),
("allStyles", FieldValue::Bool(false)),
("labels", FieldValue::Bool(true)),
("columns", FieldValue::Int(2)),
("gap", FieldValue::Number(12.0)),
("margin", FieldValue::Number(36.0)),
("newArtboards", FieldValue::Bool(true)),
]);
let lengths = general_lengths(app);
dialogs::open_with(
app,
&SPEC,
fields,
move |fields| {
let written = fields.text("text").is_some_and(|t| !t.trim().is_empty());
let rows = vec![
Param::new("text", tl!("Sample Text:"), ParamKind::text(SAMPLE)),
Param::number("size", tl!("Size:"), 12.0, 1.0, 1).unit(UnitKind::Points).bounds(Some(1.0), Some(1296.0)),
Param::new("filter", tl!("Font Names Containing:"), ParamKind::text("")),
Param::new("allStyles", tl!("Every Style"), ParamKind::bool(false)),
Param::new("labels", tl!("Label Each Font"), ParamKind::bool(true)),
Param::new("columns", tl!("Columns:"), ParamKind::int(Some(1), Some(50), 2)),
Param::number("gap", tl!("Gap:"), 12.0, 1.0, 2).length(lengths).bounds(Some(0.0), Some(1000.0)),
Param::number("margin", tl!("Margin:"), 36.0, 1.0, 2).length(lengths).bounds(Some(0.0), Some(1000.0)),
Param::new("newArtboards", tl!("Add Artboards When Full"), ParamKind::bool(true)),
];
ParamDialog::new(COMMAND, tl!("Create Font Sheet"), rows)
.ok_enabled(written)
.ok_reason(tl!("Type a sample text.").into())
.values(Bind::bound(fields))
.previews(true)
},
false,
)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,457 @@
use craft::behavior::Mixed;
use craft::ui::contract::Role;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
use serde_json::json;
use vectorcraft_doc::{NodeKind, TextObject};
use crate::VectorcraftApp;
use crate::tests::panel_harness::Panel;
/// The entries of the selected font sheet.
fn sheet(app: &VectorcraftApp) -> Vec<TextObject> {
let state = app.session.active().unwrap();
let group = state.doc.node(state.selection.objects[0]).unwrap();
assert_eq!(group.name.as_deref(), Some("Font Sheet"));
group
.children()
.unwrap()
.iter()
.map(|node| match &node.kind {
NodeKind::Text(text) => (**text).clone(),
_ => panic!("a font sheet holds only type"),
})
.collect()
}
fn assert_typed_sheet(app: &VectorcraftApp) {
let entries = sheet(app);
assert_eq!(entries.len(), 1, "the typed filter picks one family");
let entry = &entries[0];
assert_eq!(entry.plain_text(), "Hamburg", "the typed text, with the label switched off");
assert_eq!(entry.runs[0].style.font_family, "Source Serif 4");
assert!((entry.runs[0].style.size - 20.0).abs() < 1e-9, "the typed size reaches the sample");
}
/// The dialog opens with Preview off. The keyboard and checkbox edits reach the preview once it is
/// switched on, and OK; Cancel restores the drawing, while OK with Preview left off applies the
/// same fields in one undo step.
#[test]
fn keyboard_and_checkbox_edits_reach_font_sheet_preview_ok_and_cancel() {
for commit in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
let before = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(false)), "Preview starts off");
assert!(!panel.app().session.in_interaction(), "the opening sheet is not previewed");
assert!(panel.app().session.active().unwrap().doc == before);
if !commit {
panel.click_role("Preview", Role::CHECK_BOX);
panel.frame();
assert!(panel.app().session.in_interaction(), "switched on, Preview shows the sheet");
}
for (label, input) in [("Sample Text", "Hamburg"), ("Font Names Containing", "Source Serif 4")] {
panel.click_role(label, Role::TEXT_INPUT);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(input);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
}
for (label, input) in [("Size", "20"), ("Columns", "1")] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(input);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
}
panel.click_role("Label Each Font", Role::CHECK_BOX);
if commit {
assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone");
panel.click("OK");
assert_typed_sheet(&panel.app());
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "one undo step");
panel.app().run("edit.undo", json!({})).unwrap();
} else {
assert_typed_sheet(&panel.app());
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step");
panel.click("Cancel");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
}
assert!(!panel.app().session.in_interaction());
assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing");
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
}
}
/// Asserts that every entry of the selected font sheet starts on artboard `index`.
fn assert_on_artboard(app: &VectorcraftApp, index: usize, case: &str) {
let board = app.session.active().unwrap().doc.artboards[index].rect;
let entries = sheet(app);
assert!(!entries.is_empty(), "{case}");
for entry in &entries {
let [.., x, _] = entry.xf.as_coeffs();
assert!(x >= board.x0 && x <= board.x1, "{case}: entry at {x} lies outside artboard {index} {board:?}");
}
}
/// Preview and OK with Preview off use the artboard picked in the view before the dialog opens.
#[test]
fn font_sheet_preview_and_ok_use_the_views_current_artboard() {
for preview in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
app.sync_views();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
panel.type_text("Source Serif 4");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.app().view_mut().unwrap().artboard = 0;
if preview {
panel.click_role("Preview", Role::CHECK_BOX);
panel.frame();
assert!(panel.app().session.in_interaction());
assert_on_artboard(&panel.app(), 1, "the preview on the opening artboard");
}
panel.click("OK");
assert_on_artboard(&panel.app(), 1, if preview { "OK after Preview" } else { "OK with Preview off" });
}
}
#[test]
fn deleting_the_opening_artboard_refuses_font_sheet_preview_and_ok() {
for preview in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
app.sync_views();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
panel.type_text("Source Serif 4");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.app().session.execute("artboard.delete", &json!({"index": 1})).unwrap();
let before = panel.app().session.active().unwrap().doc.clone();
let undo = panel.app().session.active().unwrap().history.undo.len();
if preview {
panel.click_role("Preview", Role::CHECK_BOX);
panel.frame();
assert!(!panel.app().session.in_interaction());
assert_eq!(panel.app().session.active().unwrap().doc, before);
assert_eq!(panel.app().ui.status, "The opening artboard was deleted. Reopen this dialog to continue.");
assert_eq!(panel.app().ui.status, tl!("The opening artboard was deleted. Reopen this dialog to continue."));
}
panel.click("OK");
assert_eq!(panel.app().session.active().unwrap().doc, before, "OK creates no sheet entries after the opening artboard is deleted");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
assert!(!panel.app().session.in_interaction());
assert_eq!(panel.app().ui.status, "The opening artboard was deleted. Reopen this dialog to continue.");
assert_eq!(panel.app().ui.status, tl!("The opening artboard was deleted. Reopen this dialog to continue."));
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
}
}
#[test]
fn deleting_the_opening_artboard_is_refused_before_it_changes_a_font_sheet_preview() {
for preview in [false, true] {
for commit in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap();
app.sync_views();
let original = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
panel.type_text("Source Serif 4");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
if preview {
panel.click_role("Preview", Role::CHECK_BOX);
}
let before = panel.app().session.active().unwrap().doc.clone();
let selection = panel.app().session.active().unwrap().selection.clone();
for params in [json!({"index": 1}), json!({"indices": [2, 1, 1]})] {
let (request, _) = craft::automation::ControlRequest::new("engine.execute", json!({"command": "artboard.delete", "params": params}));
let craft::automation::Reply::Done(answer) = crate::control::handle(&mut panel.app(), &egui::Context::default(), &request) else {
panic!("the deletion did not finish");
};
assert_eq!(answer["ok"], false, "{answer}");
assert!(answer.to_string().contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{answer}");
panel.frame();
assert_eq!(panel.app().session.active().unwrap().doc, before);
assert_eq!(panel.app().session.active().unwrap().selection, selection);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
assert_eq!(panel.app().session.in_interaction(), preview);
assert!(panel.app().session.artboard_deletion_guard.is_none());
}
panel.click(if commit { "OK" } else { "Cancel" });
assert!(!panel.app().session.in_interaction());
if commit {
assert_on_artboard(&panel.app(), 1, "OK after a refused deletion");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
}
assert_eq!(panel.app().session.active().unwrap().doc, original);
panel.app().run("artboard.delete", json!({"index": 1})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 2);
}
}
}
#[test]
fn a_batch_cannot_delete_the_font_sheet_dialogs_opening_artboard() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap();
app.sync_views();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
let before = panel.app().session.active().unwrap().doc.clone();
let undo = panel.app().session.active().unwrap().history.undo.len();
let error = panel
.app()
.run(
"command.batch",
json!({"commands": [
{"command": "artboard.delete", "params": {"index": 0}},
{"command": "artboard.delete", "params": {"index": 0}}
]}),
)
.unwrap_err();
assert!(error.contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{error}");
assert_eq!(panel.app().session.active().unwrap().doc, before, "the earlier deletion is rolled back");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
assert!(panel.app().session.artboard_deletion_guard.is_none());
panel.click("Cancel");
assert_eq!(panel.app().session.active().unwrap().doc, before);
}
#[test]
fn a_script_slice_cannot_delete_the_font_sheet_dialogs_opening_artboard() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
app.sync_views();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
let before = panel.app().session.active().unwrap().doc.clone();
panel.app().session.script_frames = true;
let started = panel.app().run("script.run", json!({"source": "vc.run('artboard.delete', {index: 1});", "name": "t.js"}));
assert_eq!(started.map(|v| v["running"].clone()), Ok(json!(true)), "the run goes on in the frames");
for _ in 0..1_000 {
if !panel.app().session.script_running() {
break;
}
crate::script_runs::poll(&mut panel.app());
}
assert!(!panel.app().session.script_running());
let status = panel.app().ui.status.clone();
assert!(status.contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{status}");
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 2, "the opening artboard is kept");
assert_eq!(panel.app().session.active().unwrap().doc, before);
assert!(panel.app().session.artboard_deletion_guard.is_none());
panel.click("Cancel");
}
#[test]
fn font_sheet_allows_deleting_another_artboard() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap();
app.sync_views();
let opening = app.session.active().unwrap().doc.artboards[1].id;
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
panel.app().run("artboard.delete", json!({"index": 0})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc.artboards[0].id, opening);
assert!(panel.app().run("artboard.delete", json!({"index": 0})).is_err(), "the protection follows the artboard ID");
let before = panel.app().session.active().unwrap().doc.clone();
panel.click("Cancel");
assert_eq!(panel.app().session.active().unwrap().doc, before);
}
#[test]
fn another_addon_uses_the_current_artboard_and_survives_deleting_its_opening_artboard() {
use crate::addons::dialogs::tests as host;
for commit in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.sync_views();
let current = app.session.active().unwrap().doc.artboards[0].id;
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
let command = "addon.arrange.randomizeOpacity";
crate::menus::invoke(&mut panel.app(), command, json!({}));
panel.frame();
panel.click_role("Preview", Role::CHECK_BOX);
panel.app().view_mut().unwrap().artboard = 0;
crate::io::remember_active_artboard(&mut panel.app());
let active = crate::addons::dialogs::with_opening_artboard(&mut panel.app(), command, |app| app.session.active().unwrap().active_artboard);
assert_eq!(active, Some(current), "the other dialog does not pin the opening artboard");
panel.app().run("artboard.delete", json!({"index": 1})).unwrap();
let before = panel.app().session.active().unwrap().doc.clone();
let undo = panel.app().session.active().unwrap().history.undo.len();
let dialog = host::dialog_id(&panel.app());
host::set(&panel.app(), dialog, "min", json!(37));
host::set(&panel.app(), dialog, "max", json!(37));
panel.click_role("Preview", Role::CHECK_BOX);
panel.frame();
assert!(panel.app().session.in_interaction());
assert!((panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().opacity - 0.37).abs() < 1e-6);
panel.click(if commit { "OK" } else { "Cancel" });
assert!(!panel.app().session.in_interaction());
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 1);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + usize::from(commit));
if commit {
assert!((panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().opacity - 0.37).abs() < 1e-6);
} else {
assert_eq!(panel.app().session.active().unwrap().doc, before);
}
}
}
#[test]
fn font_sheet_frames_restore_the_active_artboard_after_preview_and_commit() {
for commit in [false, true] {
for preview_at_close in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
app.sync_views();
let current = app.session.active().unwrap().doc.artboards[0].id;
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
panel.app().view_mut().unwrap().artboard = 1;
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
panel.type_text("Source Serif 4");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.app().view_mut().unwrap().artboard = 0;
crate::io::remember_active_artboard(&mut panel.app());
for _ in 0..2 {
panel.frame();
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "Preview off preserves the active artboard");
}
for preview in [true, false, true, false] {
panel.click_role("Preview", Role::CHECK_BOX);
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "toggling Preview preserves the active artboard");
for _ in 0..2 {
panel.frame();
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "idle frames preserve the active artboard");
}
assert_eq!(panel.app().session.in_interaction(), preview);
if preview {
assert_on_artboard(&panel.app(), 1, "Preview uses the opening artboard");
}
}
if preview_at_close {
panel.click_role("Preview", Role::CHECK_BOX);
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current));
}
panel.click(if commit { "OK" } else { "Cancel" });
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "closing the dialog preserves the active artboard");
assert!(!panel.app().session.in_interaction());
if commit {
assert_on_artboard(&panel.app(), 1, "OK uses the opening artboard");
}
}
}
}
#[test]
fn a_standalone_font_sheet_uses_the_current_artboard_with_its_dialog_open() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
app.sync_views();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
panel.app().view_mut().unwrap().artboard = 1;
let (request, _) = craft::automation::ControlRequest::new(
"engine.execute",
json!({"command": super::COMMAND, "params": {"families": ["Inter"], "labels": false}}),
);
let craft::automation::Reply::Done(answer) = crate::control::handle(&mut panel.app(), &egui::Context::default(), &request) else {
panic!("the font sheet command did not finish");
};
assert_eq!(answer["ok"], true, "{answer}");
assert_on_artboard(&panel.app(), 1, "a standalone command while Preview is off");
panel.click("Cancel");
assert_on_artboard(&panel.app(), 1, "Cancel keeps the standalone sheet");
}
/// The sheet stays on its opening artboard when a preview removes the page shown in the view.
#[test]
fn going_to_a_page_the_font_sheet_preview_added_keeps_its_start() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
app.sync_views();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
let original_artboards = panel.app().session.active().unwrap().doc.artboards.len();
// Each page holds one 100 pt entry.
let edits = [("Font Names Containing", Role::TEXT_INPUT, "Source S"), ("Size", Role::SPIN_BUTTON, "100"), ("Columns", Role::SPIN_BUTTON, "1")];
for (label, role, input) in edits {
panel.click_role(label, role);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(input);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
}
panel.click_role("Preview", Role::CHECK_BOX);
panel.frame();
assert!(panel.app().session.active().unwrap().doc.artboards.len() > original_artboards, "the preview adds a page");
panel.app().view_mut().unwrap().artboard = original_artboards;
panel.frame();
let first_on_opening_artboard = |panel: &Panel| {
let app = panel.app();
let [.., x, _] = sheet(&app)[0].xf.as_coeffs();
let board = app.session.active().unwrap().doc.artboards[0].rect;
assert!(x >= board.x0 && x <= board.x1, "the first entry stays on the opening artboard: {x}, {board:?}");
};
first_on_opening_artboard(&panel);
panel.click_role("Add Artboards When Full", Role::CHECK_BOX);
panel.frame();
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), original_artboards);
panel.app().sync_views();
assert_eq!(panel.app().view().unwrap().artboard, original_artboards - 1, "the view clamps to the last original artboard");
panel.frame();
first_on_opening_artboard(&panel);
panel.click_role("Preview", Role::CHECK_BOX);
panel.frame();
assert!(!panel.app().session.in_interaction());
panel.click("OK");
first_on_opening_artboard(&panel);
}
/// An empty filter sends none, so the sheet sets every family; a filter is sent trimmed.
#[test]
fn params_sends_a_filter_only_when_one_is_typed() {
let mut fields = DialogFields::from_pairs([("text", FieldValue::Text("Abc".into())), ("filter", FieldValue::Text(" ".into()))]);
let p = super::params(&fields);
assert!(p.get("filter").is_none(), "{p}");
assert_eq!((&p["text"], &p["columns"], &p["labels"], &p["newArtboards"]), (&json!("Abc"), &json!(2), &json!(true), &json!(true)));
fields.set("filter", FieldValue::Text(" Inter ".into()));
assert_eq!(super::params(&fields)["filter"], json!("Inter"));
}
@@ -19,7 +19,7 @@ const SEEDS: u64 = 1_000_000;
const MAX_VALUE: f64 = 1e12;
/// How the dialog's values reach the command.
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
/// The command's parameters from the dialog's fields.
pub(crate) fn params(fields: &DialogFields) -> Value {
+6 -1
View File
@@ -88,7 +88,10 @@ impl VectorcraftApp {
let touch_workspace = self.session.prefs.touch_workspace;
// A `prefs.reset` that ran straight on the session applies before this command can switch workspaces.
crate::prefs_dialog::apply_prefs_resets(self);
let guard = crate::addons::dialogs::artboard_deletion_guard(self);
let previous_guard = std::mem::replace(&mut self.session.artboard_deletion_guard, guard);
let result = self.run_now(id, params);
self.session.artboard_deletion_guard = previous_guard;
crate::prefs_dialog::apply_prefs_resets(self);
if id == "prefs.import" && result.is_ok() {
crate::prefs_dialog::imported(self, touch_workspace);
@@ -162,7 +165,9 @@ impl VectorcraftApp {
self.wait_for_tool_edit(id);
// A `.ai` file a command writes (a save, an export, a timestamped copy, a batch's save) names
// the view's active artboard.
io::remember_active_artboard(self);
if !self.addon_dialogs.using_opening_artboard {
io::remember_active_artboard(self);
}
let artboards = self.artboard_tool_state();
if let Some(r) = menus::run_ui_command(self, id, &params) {
self.ui.recording_base = None;
+27
View File
@@ -7039,6 +7039,33 @@ fn a_wheel_pan_under_a_resting_pointer_keeps_the_tool_cursor() {
assert!(asks() > before, "once the view is still, the tool gives the cursor again");
}
/// Artboards made with no spacing touch, and the canvas paints every artboard's drop shadow before any artboard's
/// paper, so the lower artboard's shadow does not darken the upper one along the shared edge.
#[test]
fn touching_artboards_cast_no_shadow_on_each_other() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200, "artboards": 2, "artboardLayout": {"layout": "column", "spacing": 0}})).unwrap();
let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|ab| ab.rect).collect();
assert_eq!(boards[0].y1, boards[1].y0, "the artboards touch");
app.ui.task_bar = false;
app.ui.view.rulers = false;
app.canvas.worker_started = true;
let ctx = crate::testing::ui_context();
let _ = shapes(&mut app, &ctx);
let view = app.view_mut().unwrap();
(view.zoom, view.center) = (1.0, Point::new(100.0, 200.0));
let all = shapes(&mut app, &ctx);
let papers: Vec<usize> = all
.iter()
.enumerate()
.filter(|(_, s)| matches!(s, Shape::Mesh(m) if m.texture_id == egui::TextureId::default() && m.vertices.first().is_some_and(|v| v.color == Color32::WHITE)))
.map(|(at, _)| at)
.collect();
let shadows: Vec<usize> = all.iter().enumerate().filter(|(_, s)| matches!(s, Shape::Rect(r) if r.blur_width > 0.0)).map(|(at, _)| at).collect();
assert_eq!((papers.len(), shadows.len()), (2, 2), "each artboard paints its paper and casts a shadow");
assert!(shadows.iter().all(|s| papers.iter().all(|p| s < p)), "every shadow lies under both papers: shadows {shadows:?}, papers {papers:?}");
}
#[test]
fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_into() {
let (doc, key) = pan_doc();
+3 -3
View File
@@ -92,7 +92,7 @@ impl LivePreview {
app.status(e);
return None;
}
let answer = match app.session.preview(cmd, params) {
let answer = match crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.session.preview(cmd, params)) {
Ok(v) => Ok(v),
Err(e) => {
app.status(e.to_string());
@@ -123,9 +123,9 @@ impl LivePreview {
if app.session.in_interaction() {
return Err(tl!("Finish the active edit first.").to_owned());
}
return app.run(cmd, params);
return crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.run(cmd, params));
}
let result = app.session.preview(cmd, &params).and_then(|answer| {
let result = crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.session.preview(cmd, &params)).and_then(|answer| {
app.session.commit_interaction()?;
Ok(answer)
});
+1 -1
View File
@@ -1556,7 +1556,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.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|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`); addon.arrange.artboardGuides fails when the document has no artboards; 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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|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`); addon.arrange.artboardGuides fails when the document has no artboards; 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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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",
+4
View File
@@ -42,6 +42,9 @@ pub fn poll(app: &mut VectorcraftApp) {
let name = app.session.script_name().unwrap_or_default();
let startup = app.session.startup_script_running();
let shared = share_views(app);
// A slice may delete an artboard; the one an open Create Font Sheet dialog uses is refused.
let guard = crate::addons::dialogs::artboard_deletion_guard(app);
let previous_guard = std::mem::replace(&mut app.session.artboard_deletion_guard, guard);
// Between two queued runs, this pump starts the next one: it lists the printers listed when the
// runs were queued.
if app.session.script_name().is_none() {
@@ -49,6 +52,7 @@ pub fn poll(app: &mut VectorcraftApp) {
}
let pumped = app.session.script_pump();
app.session.script_printers = None;
app.session.artboard_deletion_guard = previous_guard;
if !app.session.script_running() {
app.queued_script_printers = None;
}
+66 -3
View File
@@ -17909,7 +17909,9 @@ envelopes, graphs, symbols), are left out.
- `addon.cleanup.check {scope?, kinds?}` changes nothing and lists `findings`: for each kind found, its `count`, the
`ids` of the objects it is on (at most 1,000) and, for empty artboards, their indexes.
- `addon.cleanup.show {kind, scope?}` selects the objects with that issue.
- `addon.cleanup.fix {scope?, kinds?}` fixes the issues as one undo step and reports how many of each kind it fixed.
- `addon.cleanup.fix {scope?, kinds?}` fixes the issues as one undo step and reports how many of each kind it fixed. When the fixes would delete the
artboard an open Create Font Sheet… dialog uses, it returns an error and fixes nothing; close the dialog or leave
`emptyArtboards` out of `kinds`.
The kinds run in a fixed order, so art removed by one kind can leave a group that a later kind unwraps, and they
run again (three rounds at most) while a round still fixes something.
@@ -19469,8 +19471,8 @@ 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`, `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,
Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker`, `addon.type.releasePath`,
`addon.type.fontSheet` 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
type it is the size shown.
@@ -19534,6 +19536,67 @@ Path Options' Preview does (#5360).
{"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}}
```
### Create Font Sheet
`addon.type.fontSheet` makes a font specimen sheet in the active document: a line of sample text set once in each
font family the font menus list (the bundled, added and installed fonts), each entry labeled with its font's name, so
the fonts can be compared on the artboard or printed.
- **Entries** are point type, one per family in the font menus' order (or in the order `families` gives), each named
after its font. With `labels` on, an entry starts with a line naming its font in the document's normal type font, at
the sample's size up to 9 pt, and the sample follows on the next line. With `allStyles` each style of a family gets
its own entry, labeled with the family and style; otherwise the family's Regular is used, else its closest style.
- **Layout:** the entries flow down the columns of the active artboard (or the one `artboard` names), inside `margin`, with `gap` between entries
and between columns. Every line is aligned left, right-to-left samples too, so each starts at its column's left
edge. A sample wider than its column runs on past it. When the artboard is full, the sheet continues
on new artboards of the same size to the right of the rightmost artboard, 20 pt apart; with `newArtboards` off the
later pages are laid out in the same places without artboards. A document without artboards lays the sheet out on a
612 × 792 pt page at the origin and adds no artboards.
- **Fonts that don't load:** a family whose font can't be loaded (text in it would be drawn in the fallback font), or
with `allStyles` a style that can't (it would be drawn in the family's closest style), is left out, listed in
`skipped` and named in `warning`, which the status bar shows. A composite font is left out the same way when a part
that sets the sample text names a font or style that can't be loaded.
- **Missing glyphs:** an entry whose font lacks a glyph needed by the sample text stays on the sheet, and is listed
in `fallback` and named in `warning`.
- Each row is as tall as the tallest laid-out entry needs, so a composite font whose part enlarges or raises the
sample does not overlap the entry above it or reach into the margin.
- The sheet is one group named Font Sheet, made in one undo step and selected. It goes where new art goes: the current
layer, or, when that layer is locked or hidden, the topmost layer that is shown and unlocked. Nothing changes, and an
error is returned, when no family matches, when there would be more than 5000 entries, when no font loads, when the
margin, gap and columns leave no room for one entry, or when no layer is shown and unlocked.
| Parameter | Values (default) |
|---|---|
| `text` | one line of sample text, at most 1000 characters, without line or paragraph breaks or other control characters (`The quick brown fox jumps over the lazy dog`) |
| `size` | the sample's size, pt 1…1296 (12) |
| `filter` | only the families whose name contains this text, in any case; empty: every family |
| `families` | instead of `filter`: these family names, in this order; each must be available and named once. Giving both is an error, even with an empty `filter` |
| `allStyles` | false; true: one entry for each style of each family |
| `labels` | true; false: the sample alone |
| `columns` | whole number 1…50 (2) |
| `gap` | pt 0…1000, between entries and between columns (12) |
| `margin` | pt 0…1000, inside each page (36) |
| `newArtboards` | true; false: the pages after the first get no artboards |
| `artboard` | 0-based index of the artboard the first page is laid out on (the active artboard) |
| `activeArtboard` | the journal records the active artboard here when `artboard` is left out, so a replay uses the same artboard; `artboard` goes ahead of it, and an action leaves it out |
In `addon.type.fontSheet`, a parameter given as `null` is the same as one left out and takes its default; any other
value of the wrong type or out of range is an error. While the Create Font Sheet… dialog is open, Delete Artboard, Cut
Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error and change nothing when they
would delete the artboard the dialog opened on, and so does a running script's `vc.run` of one of them (a script
that does not catch the error ends with it); close the dialog first.
→ `{id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}`.
`fallback` lists entries kept on the sheet whose font lacks a glyph needed by the sample. Create Font Sheet… opens a dialog
(`ui.menuDialog {command}`) whose fields are the command's parameters except `families`, `artboard` and `activeArtboard` (it lays the sheet out on the artboard that was active when it opened), with Preview, which starts
off: switched on, it sets the whole sheet again after each change. OK is off while the sample text is empty. Plug-ins can't call the command, since the sheet lists the installed fonts as
`text.fontList` does.
```json
{"name":"run_command","arguments":{"command":"addon.type.fontSheet","params":{"text":"Hamburgefonstiv","size":18,"filter":"sans"}}}
{"name":"run_command","arguments":{"command":"addon.type.fontSheet","params":{"families":["Inter","JetBrains Mono"],"allStyles":true,"columns":1}}}
```
### Make Numbers Sequence
`addon.type.numbers` numbers the type objects among `ids` (or `id`, else the selection), groups included, from `start`
+4
View File
@@ -3237,6 +3237,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: Create Font Sheet (2026-11-29)
A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Create Font Sheet… sets a line of sample text once in each font family the font menus list, or in the families whose name contains a filter, each entry labeled with its font's name unless labels are switched off, as point type flowed down columns on the active artboard (or the one `artboard` names; the journal records the active one, so a replay uses the same artboard). Every line is aligned left, right-to-left samples too, so each starts at its column's left edge. When the artboard is full, Add Artboards When Full (on by default) adds new artboards of the same size to its right for the rest; with it off, the rest is laid out in the same places to the right without artboards. Every Style gives each style of a family its own entry; families whose font can't be loaded, and composite fonts whose part setting the sample can't, are left out, listed in `skipped` and named in `warning`. Entries whose font lacks a glyph needed by the sample stay on the sheet, are listed in `fallback` and named in `warning`. Each row is as tall as the tallest laid-out entry, so a composite font that enlarges the sample does not overlap. The sheet is one selected group made in one undo step, from a dialog whose Preview starts off (`addon.type.fontSheet`); its preview and OK set the sheet on the artboard active in the view when it opens, and while it is open, Delete Artboard, Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards return an error when they would delete that artboard, also when a running script calls them through `vc.run`. Tests: `cmd::addons::typetools::font_sheet::tests` in `vectorcraft-engine` (labels, columns and margins, new artboards and none, the filter, every style, fonts and styles that don't load, composite fonts' row heights and missing parts, undo, a locked layer, bad params refused), `addons::typetools::font_sheet::tests` (including the artboard active when the dialog opens) and the Create Font Sheet row of `add_on_dialogs_preview_cancel_and_run_their_command` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Type Tools add-on › Create Font Sheet.
## 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, an unthreaded object that holds none, and a threaded frame whose whole story holds none, are skipped before the ordering, so they take no number and are never deleted. A threaded frame is checked once per thread, against its whole story. Locked and hidden type is left alone, a clipping mask is not deleted, and bad parameters are refused. Any other threaded type is 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.