mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 12:21:08 +01:00
Plug-ins: check every number in the type styles a filter writes
Type a filter returned went to layout with its character and paragraph styles only parsed, and a style equal to one of the type's runs was not checked at all, so a filter could set leading of 1e9, 100,000 tab stops, a scale of 0 or a Kinsoku set the document does not have. - The ranges the character and paragraph style commands keep each attribute to move to CharStyle::check_ranges and ParaStyle::check_ranges in vectorcraft-doc (text/attr_ranges.rs). charStyle.new, charStyle.edit, charStyle.setAttrs and the paragraph style commands call them, and so does the filter write path, for every run and paragraph style, including one the type already has. - A paragraph style's custom Kinsoku set must name one of the document's sets, and takes that set's characters. - The character style commands now also refuse tracking and kerning outside -1000 to 10000, rotation outside -360 to 360, a miter limit outside 1 to 500, Small Caps outside 1 to 200, negative dash lengths and a variable font axis setting that is not a number. Each refusal names the object and the field, and the document does not change. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
ed50dd06f4
commit
945d0a42b0
12 files changed
+422
-158
No files matched your search
@@ -7,6 +7,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2};
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};
|
||||
|
||||
mod area;
|
||||
mod attr_ranges;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod kinsoku_set;
|
||||
@@ -17,6 +18,9 @@ mod tabs_lists;
|
||||
mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
pub use attr_ranges::{
|
||||
AttrRangeError, CHAR_MITER_LIMIT, CHAR_ROTATION, CHAR_SCALE, CHAR_SPACING, FONT_SIZE, LEADING, MAX_BASELINE_SHIFT, MAX_PARA_DISTANCE,
|
||||
};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! The ranges the character and paragraph style commands keep each numeric attribute to, checked
|
||||
//! in one place: the style commands check the attributes a call changes, and type a plug-in
|
||||
//! returns has every attribute checked.
|
||||
|
||||
use std::fmt;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use super::{CharStyle, JustificationOptions, ParaStyle, TabStop};
|
||||
|
||||
/// Font size ([`CharStyle::size`]), in points.
|
||||
pub const FONT_SIZE: RangeInclusive<f64> = 0.1..=1296.0;
|
||||
/// Leading ([`CharStyle::leading`]) other than Auto, in points.
|
||||
pub const LEADING: RangeInclusive<f64> = 0.1..=5000.0;
|
||||
/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent.
|
||||
pub const CHAR_SCALE: RangeInclusive<f64> = 1.0..=10000.0;
|
||||
/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`],
|
||||
/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em.
|
||||
pub const CHAR_SPACING: RangeInclusive<f64> = -1000.0..=10000.0;
|
||||
/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points.
|
||||
pub const MAX_BASELINE_SHIFT: f64 = 1296.0;
|
||||
/// Character rotation ([`CharStyle::rotation`]), in degrees.
|
||||
pub const CHAR_ROTATION: RangeInclusive<f64> = -360.0..=360.0;
|
||||
/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]).
|
||||
pub const CHAR_MITER_LIMIT: RangeInclusive<f64> = 1.0..=500.0;
|
||||
/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points.
|
||||
pub const MAX_PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// An attribute outside the range the style commands keep it to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AttrRangeError {
|
||||
/// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`).
|
||||
pub key: String,
|
||||
/// What is wrong, naming the attribute.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for AttrRangeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AttrRangeError {}
|
||||
|
||||
fn out(key: &str, message: String) -> AttrRangeError {
|
||||
AttrRangeError { key: key.to_string(), message }
|
||||
}
|
||||
|
||||
/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside).
|
||||
fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
}
|
||||
|
||||
impl CharStyle {
|
||||
/// Checks each numeric attribute `check` names, by its JSON key, against the range the
|
||||
/// character style commands keep it to: size, leading, scales, tracking, kerning, baseline
|
||||
/// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert
|
||||
/// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the
|
||||
/// variable font axes. The first attribute out of its range is the error.
|
||||
pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> {
|
||||
for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] {
|
||||
if check(key) {
|
||||
within(key, value, *range.start(), *range.end())?;
|
||||
}
|
||||
}
|
||||
if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) {
|
||||
let (lo, hi) = (LEADING.start(), LEADING.end());
|
||||
return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto")));
|
||||
}
|
||||
let shift = MAX_BASELINE_SHIFT;
|
||||
for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] {
|
||||
if check(key) {
|
||||
within(key, value, -shift, shift)?;
|
||||
}
|
||||
}
|
||||
let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))];
|
||||
for (key, value) in spacing {
|
||||
if check(key)
|
||||
&& let Some(value) = value
|
||||
{
|
||||
within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?;
|
||||
}
|
||||
}
|
||||
if check("rotation") {
|
||||
within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?;
|
||||
}
|
||||
for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] {
|
||||
if check(key) {
|
||||
within(key, value, 0.0, super::MAX_AKI)?;
|
||||
}
|
||||
}
|
||||
if check("tsume") {
|
||||
within("tsume", self.tsume, 0.0, super::MAX_TSUME)?;
|
||||
}
|
||||
let hi = super::MAX_DIACRITIC_POSITION;
|
||||
for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] {
|
||||
if check(key) {
|
||||
within(key, value, -hi, hi)?;
|
||||
}
|
||||
}
|
||||
let lines = super::WARICHU_LINES;
|
||||
if check("warichuLines") && !lines.contains(&self.warichu_lines) {
|
||||
return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = super::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in
|
||||
[("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())]
|
||||
{
|
||||
if check(key) {
|
||||
within(key, value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("stroke_width") {
|
||||
within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("stroke_miter_limit") {
|
||||
within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?;
|
||||
}
|
||||
if check("stroke_dash")
|
||||
&& let Some(dash) = &self.stroke_dash
|
||||
{
|
||||
for value in &dash.pattern {
|
||||
within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("small_caps")
|
||||
&& let Some(value) = self.small_caps
|
||||
{
|
||||
within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?;
|
||||
}
|
||||
if check("fontAxes")
|
||||
&& let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite())
|
||||
{
|
||||
return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ParaStyle {
|
||||
/// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its
|
||||
/// field, against the range the paragraph style commands keep it to: the indents and the space
|
||||
/// before and after, each Hyphenation option, each Justification option in `justification`
|
||||
/// (the options as given, since reading a paragraph style brings them into range) with
|
||||
/// Minimum, Desired and Maximum in order, and the number of tab stops with the position and
|
||||
/// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the
|
||||
/// error.
|
||||
pub fn check_ranges(
|
||||
&self,
|
||||
justification: Option<&JustificationOptions>,
|
||||
kept_tabs: &[TabStop],
|
||||
check: impl Fn(&str, Option<&str>) -> bool,
|
||||
) -> Result<(), AttrRangeError> {
|
||||
for (key, value) in [
|
||||
("left_indent", self.left_indent),
|
||||
("right_indent", self.right_indent),
|
||||
("first_line_indent", self.first_line_indent),
|
||||
("space_before", self.space_before),
|
||||
("space_after", self.space_after),
|
||||
] {
|
||||
if check(key, None) {
|
||||
within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &self.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, MAX_PARA_DISTANCE),
|
||||
] {
|
||||
if check("hyphenation", Some(field)) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if let Some(j) = justification {
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !check("justification", Some(field)) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if check("justification", Some("auto_leading")) {
|
||||
let (lo, hi) = JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("tabs", None) {
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if self.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(out("tabs", format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(out("tabs.leader", format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -801,3 +801,42 @@ fn auto_alignment_saves_readable_by_older_builds() {
|
||||
// Files from before the flag keep their alignment.
|
||||
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
|
||||
}
|
||||
|
||||
/// The default character and paragraph styles are in range, and each number outside its range,
|
||||
/// one that is not a number included, is the error naming its attribute; an attribute the check
|
||||
/// is not asked about is not checked.
|
||||
#[test]
|
||||
fn style_ranges_name_the_attribute_out_of_range() {
|
||||
let all = |_: &str| true;
|
||||
assert_eq!(CharStyle::default().check_ranges(all), Ok(()));
|
||||
let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key);
|
||||
let d = CharStyle::default();
|
||||
assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into()));
|
||||
assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into()));
|
||||
assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into()));
|
||||
assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into()));
|
||||
assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into()));
|
||||
assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into()));
|
||||
assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into()));
|
||||
assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into()));
|
||||
let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect();
|
||||
assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into()));
|
||||
let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false });
|
||||
assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into()));
|
||||
assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(()));
|
||||
|
||||
let all = |_: &str, _: Option<&str>| true;
|
||||
let p = ParaStyle::default();
|
||||
assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(()));
|
||||
let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key);
|
||||
assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into()));
|
||||
let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into()));
|
||||
let far = TabStop { position: -1.0, ..stop.clone() };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into()));
|
||||
assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop");
|
||||
let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() };
|
||||
assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into()));
|
||||
let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() };
|
||||
assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into()));
|
||||
}
|
||||
@@ -420,7 +420,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector
|
||||
// ---------- text ----------
|
||||
|
||||
/// Largest indent or paragraph spacing (points; Illustrator's limit).
|
||||
const MAX_PARA: f64 = 1296.0;
|
||||
const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE;
|
||||
|
||||
/// `text.setFormat`'s `bullet` values and the bullets they pick.
|
||||
const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [
|
||||
|
||||
@@ -1317,7 +1317,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs and 256 KiB of text; a style of its own needs a font family and a size of 0.1 to 1296 pt) and text.paragraphs (one style per paragraph), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. An output that changes nothing records no undo step. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. An output that changes nothing records no undo step. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
|
||||
@@ -157,13 +157,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"charStyle",
|
||||
"Character Styles",
|
||||
"Character",
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt"
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings"
|
||||
);
|
||||
v.push(spec(
|
||||
"charStyle.edit",
|
||||
"Edit Character Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings",
|
||||
|s, p| edit_style(s, p, Kind::Char),
|
||||
true,
|
||||
));
|
||||
@@ -636,52 +636,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
|
||||
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
|
||||
for (key, value, lo, hi) in
|
||||
[("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)]
|
||||
{
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) {
|
||||
return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto"));
|
||||
}
|
||||
let shift_max = 1296.0;
|
||||
for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] {
|
||||
if changed(key) && !(-shift_max..=shift_max).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
|
||||
}
|
||||
}
|
||||
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
|
||||
for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME);
|
||||
if changed(key) && !(lo..=hi).contains(&st.tsume) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
|
||||
let lo = -hi;
|
||||
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let lines = vectorcraft_doc::text::WARICHU_LINES;
|
||||
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
|
||||
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = vectorcraft_doc::text::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in [
|
||||
("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP),
|
||||
("warichuScale", st.warichu_scale, *scale.start(), *scale.end()),
|
||||
] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
st.check_ranges(changed).map_err(|e| bad(&c, e.message))?;
|
||||
// A language of the list, stored as its tag (as text.setFormat takes it).
|
||||
if let Some(l) = &st.language
|
||||
&& kept.and_then(|k| k.get("language")) != m.get("language")
|
||||
@@ -693,10 +648,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
style_paint(d, paint, key, &c)?;
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD);
|
||||
if changed(key) && !(lo..=hi).contains(&st.stroke_width) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
if changed("features") {
|
||||
style_features(&st.features, kept, &c)?;
|
||||
}
|
||||
@@ -753,85 +704,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt),
|
||||
/// as `text.setFormat` keeps them.
|
||||
const PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
|
||||
/// `kept` does not hold. A value `kept` has is not checked.
|
||||
/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options
|
||||
/// as `attrs` gives them. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
};
|
||||
let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key);
|
||||
let nested_changed = |key: &str, field: &str| {
|
||||
changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field))
|
||||
let check = |key: &str, field: Option<&str>| match field {
|
||||
None => changed(key),
|
||||
Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)),
|
||||
};
|
||||
for (key, value) in [
|
||||
("left_indent", st.left_indent),
|
||||
("right_indent", st.right_indent),
|
||||
("first_line_indent", st.first_line_indent),
|
||||
("space_before", st.space_before),
|
||||
("space_after", st.space_after),
|
||||
] {
|
||||
if changed(key) {
|
||||
within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &st.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, PARA_DISTANCE),
|
||||
] {
|
||||
if nested_changed("hyphenation", field) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
// Read as given: a paragraph's attributes keep justification options in range as they load.
|
||||
if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) {
|
||||
let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?;
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !nested_changed("justification", field) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if nested_changed("justification", "auto_leading") {
|
||||
let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs = kept_tab_stops(kept);
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if st.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(bad(c, format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(bad(c, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
let given = attrs.get("justification").filter(|_| changed("justification"));
|
||||
let justification: Option<vectorcraft_doc::JustificationOptions> =
|
||||
given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?;
|
||||
st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message))
|
||||
}
|
||||
|
||||
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
|
||||
@@ -1204,7 +1090,8 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps,
|
||||
/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
|
||||
@@ -401,6 +401,11 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
json!({"tsume": 100.1}),
|
||||
json!({"diacriticHorizontal": -1000.1}),
|
||||
json!({"diacriticVertical": 1000.1}),
|
||||
json!({"tracking": -1000.1}),
|
||||
json!({"kerning": 10000.1}),
|
||||
json!({"rotation": 360.1}),
|
||||
json!({"stroke_miter_limit": 0.9}),
|
||||
json!({"small_caps": 200.1}),
|
||||
] {
|
||||
let key = attrs.as_object().unwrap().keys().next().unwrap();
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
@@ -425,7 +430,9 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
|
||||
"akiLeft": 0.0, "akiRight": 1000.0,
|
||||
"tsume": 100.0,
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0,
|
||||
"tracking": 10000.0, "kerning": -1000.0, "rotation": -360.0,
|
||||
"stroke_miter_limit": 500.0, "small_caps": 200.0
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -1275,7 +1275,7 @@ fn bad_writes_are_refused_naming_the_object_and_the_field() {
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.size: must be 0.1 to 1296 pt".into(),
|
||||
"text.runs[0].style.size: `size` must be from 0.1 to 1296".into(),
|
||||
),
|
||||
(text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()),
|
||||
(
|
||||
@@ -1444,6 +1444,86 @@ fn written_runs_without_paragraphs_keep_each_paragraph_s_style() {
|
||||
assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
}
|
||||
|
||||
/// Every number in the character and paragraph styles a filter writes is checked against the range
|
||||
/// the style commands keep it to, in a style of the filter's own and in one the type already has,
|
||||
/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the
|
||||
/// object and the field, and the document stays as it was. A set of the document's, given by
|
||||
/// name, takes the document's characters.
|
||||
#[test]
|
||||
fn written_style_numbers_are_checked_even_in_a_style_the_type_has() {
|
||||
use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() });
|
||||
let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() };
|
||||
let bad_chars: [(&str, CharStyle, &str); 5] = [
|
||||
("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"),
|
||||
("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"),
|
||||
("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"),
|
||||
("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"),
|
||||
("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"),
|
||||
];
|
||||
let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() };
|
||||
let bad_paras: [(&str, ParaStyle, &str); 4] = [
|
||||
("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"),
|
||||
("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"),
|
||||
(
|
||||
"hyphenation",
|
||||
ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() },
|
||||
"paragraphs[0].hyphenation.after_first",
|
||||
),
|
||||
("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"),
|
||||
];
|
||||
// `own`: the type already has the bad style, and the filter changes only its other run or
|
||||
// paragraph; otherwise the bad style is the filter's own.
|
||||
let run = |id: NodeId, own: bool, bad: &CharStyle| {
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
|
||||
if own {
|
||||
t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())];
|
||||
}
|
||||
let mut doc = d.clone();
|
||||
let n = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
let id = doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
(doc, id)
|
||||
};
|
||||
let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| {
|
||||
let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let mut entry = entry;
|
||||
entry["id"] = json!(id.0);
|
||||
let mut changed = doc.clone();
|
||||
let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}");
|
||||
assert_eq!(&changed, doc, "{what}: nothing changed");
|
||||
};
|
||||
let fresh = d.clone().alloc_id();
|
||||
for (what, bad, says) in &bad_chars {
|
||||
let (doc, id) = run(fresh, false, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, what);
|
||||
let (doc, id) = run(fresh, true, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() };
|
||||
for (what, bad, says) in &bad_paras {
|
||||
let (doc, id) = run(fresh, false, &CharStyle::default());
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what);
|
||||
let mut doc = doc;
|
||||
if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) {
|
||||
t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]);
|
||||
}
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
// A set the document has, by name, takes the document's characters.
|
||||
let (mut doc, id) = run(fresh, false, &CharStyle::default());
|
||||
let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() });
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]});
|
||||
write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、']));
|
||||
}
|
||||
|
||||
/// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON
|
||||
/// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output.
|
||||
#[test]
|
||||
|
||||
@@ -5,18 +5,16 @@
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::text::INLINE_CHAR;
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, ParaStyle, TextObject, TextRun};
|
||||
use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR};
|
||||
use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::{
|
||||
MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err,
|
||||
read_only_changed,
|
||||
};
|
||||
use crate::{InputKind, Result};
|
||||
use crate::{Error, InputKind, Result};
|
||||
|
||||
/// The smallest and largest font size a filter may set, in points (as the Character panel's).
|
||||
const FONT_SIZE: std::ops::RangeInclusive<f64> = 0.1..=1296.0;
|
||||
/// The longest font family name a filter may set, in characters.
|
||||
const MAX_FAMILY: usize = 256;
|
||||
/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object.
|
||||
@@ -224,9 +222,10 @@ pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map<String, Value>,
|
||||
/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an
|
||||
/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they
|
||||
/// were, in the same order, and the characters of threaded type or type with ruby stay as they
|
||||
/// were. A run whose style isn't one of the type's own has a font family and a size in
|
||||
/// [`FONT_SIZE`], and its paints are checked as an object's are. Paragraph styles are one per
|
||||
/// paragraph. With runs alone, each paragraph keeps its style when the number of paragraphs stays
|
||||
/// were. Every number of every run's style is in the range the character style commands keep it
|
||||
/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font
|
||||
/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph
|
||||
/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays
|
||||
/// the same, and otherwise the styles move with the text as typing the change moves them.
|
||||
fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> {
|
||||
if let Some(runs) = runs {
|
||||
@@ -252,6 +251,8 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va
|
||||
if text.contains(INLINE_CHAR) {
|
||||
return Err(out_err(&at, "`text` holds the character of an inline graphic"));
|
||||
}
|
||||
// Every number goes to the layout, so it is checked even in a style the type has.
|
||||
style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?;
|
||||
if !own.contains(style_v) {
|
||||
check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?;
|
||||
}
|
||||
@@ -298,8 +299,7 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va
|
||||
if list.len() != count {
|
||||
return Err(out_err(&at, format!("expected {count} paragraph styles, one per paragraph")));
|
||||
}
|
||||
let styles =
|
||||
list.iter().enumerate().map(|(i, p)| strict::<ParaStyle>(p, &format!("{at}[{i}]"), "a paragraph style")).collect::<Result<_>>()?;
|
||||
let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &format!("{at}[{i}]"))).collect::<Result<_>>()?;
|
||||
t.set_paragraph_styles(styles);
|
||||
}
|
||||
None => t.normalize_paras(),
|
||||
@@ -320,17 +320,40 @@ fn changed_range(old: &str, new: &str) -> (usize, usize, usize) {
|
||||
(start, old.len() - same, new.len() - same)
|
||||
}
|
||||
|
||||
/// An attribute of the style at `at` out of its range, naming the attribute.
|
||||
fn range_err(at: &str, e: &AttrRangeError) -> Error {
|
||||
out_err(&format!("{at}.{}", e.key), &e.message)
|
||||
}
|
||||
|
||||
/// Paragraph style `v` from a filter's output, at `at`: each attribute one a paragraph reads, each
|
||||
/// number in the range the paragraph style commands keep it to ([`ParaStyle::check_ranges`], the
|
||||
/// Justification options as given), and a custom Kinsoku set one of `doc`'s, by name, whose
|
||||
/// characters it takes.
|
||||
fn para_style(doc: &Document, v: &Value, at: &str) -> Result<ParaStyle> {
|
||||
let mut st: ParaStyle = strict(v, at, "a paragraph style")?;
|
||||
let justification = match v.get("justification") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(j) => Some(serde_json::from_value::<JustificationOptions>(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?),
|
||||
};
|
||||
st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(at, &e))?;
|
||||
if let Some(set) = &st.kinsoku_set {
|
||||
let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| {
|
||||
let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD);
|
||||
out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'"))
|
||||
})?;
|
||||
st.kinsoku_set = Some(std::sync::Arc::new(found.clone()));
|
||||
}
|
||||
Ok(st)
|
||||
}
|
||||
|
||||
/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before):
|
||||
/// its font family is 1 to [`MAX_FAMILY`] printable characters, its size is in [`FONT_SIZE`], and
|
||||
/// its fill and stroke are admitted as an object's paints are.
|
||||
/// its font family is 1 to [`MAX_FAMILY`] printable characters, and its fill and stroke are
|
||||
/// admitted as an object's paints are. Its numbers are checked for every run ([`set_text`]).
|
||||
fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> {
|
||||
let family = s.font_family.trim();
|
||||
if family.is_empty() || family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) {
|
||||
return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters")));
|
||||
}
|
||||
if !FONT_SIZE.contains(&s.size) {
|
||||
return Err(out_err(&format!("{at}.size"), format!("must be {} to {} pt", FONT_SIZE.start(), FONT_SIZE.end())));
|
||||
}
|
||||
let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| {
|
||||
let at = format!("{at}.{key}");
|
||||
let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?;
|
||||
|
||||
+4
-2
@@ -13126,8 +13126,10 @@ its features turned off, distinct from unset.
|
||||
not a global swatch of the document, a stroke weight outside 0 to 4000000, more than 256 feature tags and an
|
||||
OpenType feature tag the shaper does not know, unless the style or the text it is made from already has that value.
|
||||
They also reject a size outside 0.1 to 1296, explicit leading outside 0.1 to 5000, horizontal or vertical scale
|
||||
outside 1 to 10000, and baseline shift or Tate-chu-yoko offsets outside -1296 to 1296. `leading: null` keeps
|
||||
Auto leading. An invalid value leaves the style, its text, and Undo history unchanged.
|
||||
outside 1 to 10000, baseline shift or Tate-chu-yoko offsets outside -1296 to 1296, tracking or kerning
|
||||
outside -1000 to 10000, rotation outside -360 to 360, a stroke miter limit outside 1 to 500, a
|
||||
stroke dash length outside 0 to 4000000 or offset outside -4000000 to 4000000, Small Caps outside 1 to 200 and a
|
||||
variable font axis setting that is not a number. `leading: null` keeps Auto leading. An invalid value leaves the style, its text, and Undo history unchanged.
|
||||
The New Character Style dialog accepts the same character fields and starts with the selected text's
|
||||
captured attributes. Without selected text, it starts with the character defaults for the interface language
|
||||
(including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes.
|
||||
|
||||
+15
-8
@@ -759,14 +759,21 @@ exactly as given, or with the fields it changes; a field it leaves out keeps its
|
||||
by the change from its given transform, so an image's distorted corners move with it.
|
||||
- `text.runs` replaces the type's runs: each is `{text, style, inline?}` with the character attributes as the native
|
||||
file stores them, and an attribute the host doesn't know is refused. There is at least one run, at most 4,096, and at
|
||||
most 256 KiB of UTF-8 text; the runs written in one output take at most 16 MiB. A style that none of the type's runs
|
||||
has needs a font family of 1 to 256 printable characters, a size from 0.1 to 1296 pt, and fills and strokes that a
|
||||
path's appearance would take. Inline graphics stay where they were: the runs keep each `inline` run as it was given,
|
||||
in the same order. The characters of threaded type, and of type with ruby, can't change, though their attributes can.
|
||||
The runs and paragraphs of type given with `truncated: true` can't change.
|
||||
- `text.paragraphs` holds one paragraph style per paragraph of the new text. With `text.runs` alone, each paragraph
|
||||
keeps its style when the number of paragraphs stays the same; runs that add or join paragraphs move the styles with
|
||||
the text, as typing the same change does.
|
||||
most 256 KiB of UTF-8 text; the runs written in one output take at most 16 MiB. Every number in every run's style is
|
||||
checked against the range `charStyle.new` keeps it to, including a style one of the type's runs already has: size
|
||||
0.1 to 1296 pt, leading 0.1 to 5000 pt, tracking and kerning -1000 to 10000, horizontal and vertical scale 1 to
|
||||
10000 %, baseline shift -1296 to 1296 pt, rotation -360 to 360°, and the ranges `docs/mcp.md` gives for
|
||||
`charStyle.new` for the East Asian, Warichu and stroke attributes. A style that none of the type's runs has also needs a font family of 1 to 256
|
||||
printable characters, and fills and strokes that a path's appearance would take. Inline graphics stay where they
|
||||
were: the runs keep each `inline` run as it was given, in the same order. The characters of threaded type, and of
|
||||
type with ruby, can't change, though their attributes can. The runs and paragraphs of type given with
|
||||
`truncated: true` can't change.
|
||||
- `text.paragraphs` holds one paragraph style per paragraph of the new text, each checked as `paraStyle.new` checks
|
||||
its attributes: indents and space before and after within ±1296 pt, the Hyphenation and Justification options in
|
||||
their ranges, at most 256 tab stops at 0 to 100,000 pt, and a custom Kinsoku set only by the name of one of the
|
||||
document's sets, whose characters the paragraph takes. With `text.runs` alone, each paragraph keeps its style when
|
||||
the number of paragraphs stays the same; runs that add or join paragraphs move the styles with the text, as typing
|
||||
the same change does.
|
||||
- `opacity` is a number from 0 to 1.
|
||||
- `symbolId` names a symbol in the document. An instance that shows another symbol loses its overrides, as Replace
|
||||
Symbol does.
|
||||
|
||||
@@ -828,7 +828,7 @@ since 2026-10-01.
|
||||
- **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated).
|
||||
- **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated).
|
||||
- **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html).
|
||||
- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls.
|
||||
- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt, tracking and kerning from -1000 to 10,000, rotation from -360° to 360°, a stroke miter limit from 1 to 500, Small Caps from 1% to 200%, finite stroke dashes and variable font axis settings. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls.
|
||||
- **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html).
|
||||
- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (1% to 10,000%), Baseline Shift (-1296 pt to 1296 pt), the Tate-chu-yoko Settings Up/Down and Left/Right (-1296 pt to 1296 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0 pt, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these seven. Language sets the language the characters are shaped in, not hyphenation or spelling. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html).
|
||||
- **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html).
|
||||
@@ -2662,7 +2662,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Bulk memory fuzz cases use the host's fuel constants:** `crates/engine/tests/plugin_fuzz.rs` samples runs around one slice of the instruction budget and lengths around the bytes one unit of fuel pays for with `vectorcraft_plugins`' own `FUEL_SLICE` and `BYTES_COPIED_PER_FUEL`, so the sampled cases move when either value changes. Regressions: `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged.
|
||||
- **Plug-in permissions (G17):** a manifest may list `permissions` (`doc.read`, `doc.write`, `state`, `effect.render`, `export.write`; the first three follow storytold/photocraft#662) and an `api` level; without the list a plug-in gets what its kind implies and installs as before. Install Plug-in… and File › Open show the name, id, version, file SHA-256 and each permission in plain words, with control and bidirectional characters escaped, and install nothing on Cancel; for a plug-in that lists permissions, `plugin.install` needs `grant` and folders install it only when it is granted. The grant is kept with the module's hash, a module asking for more asks again, and a filter run refuses output its permissions don't allow. Regressions: `crates/plugins/src/permissions.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged.
|
||||
- **Filter plug-ins change type, images and symbol instances (G17):** a filter at plug-in API level 3 lists in `writes` the kinds among its `inputs` it may change, with `doc.write` in its `permissions`, and may return those objects with changed fields: type's runs (characters and character attributes, inline graphics kept as they were) and paragraph styles, an image's transform and opacity, an instance's transform and the symbol it shows (one already in the document; its overrides are cleared as Replace Symbol clears them), and each one's name. Runs are held to the input's limits (4,096 runs and 256 KiB of text a type object, 16 MiB over the output), a style of the filter's own needs a font family and a size of 0.1 to 1296 pt and its paints are checked as a path's are, and the characters of threaded type and type with ruby stay as they were. Any other changed field, or a value out of range, refuses the run naming the object and the field, with the document unchanged. The changes are one undo step, and an output that changes nothing, for every filter, records none. Images now also come with their `opacity`. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **Filter plug-ins change type, images and symbol instances (G17):** a filter at plug-in API level 3 lists in `writes` the kinds among its `inputs` it may change, with `doc.write` in its `permissions`, and may return those objects with changed fields: type's runs (characters and character attributes, inline graphics kept as they were) and paragraph styles, an image's transform and opacity, an instance's transform and the symbol it shows (one already in the document; its overrides are cleared as Replace Symbol clears them), and each one's name. Runs are held to the input's limits (4,096 runs and 256 KiB of text a type object, 16 MiB over the output), every number in every run's and paragraph's style is checked against the range `charStyle.new` and `paraStyle.new` keep it to (one shared check, also for a style the type already has), a custom Kinsoku set must be one of the document's, a style of the filter's own needs a font family and its paints are checked as a path's are, and the characters of threaded type and type with ruby stay as they were. Any other changed field, or a value out of range, refuses the run naming the object and the field, with the document unchanged. The changes are one undo step, and an output that changes nothing, for every filter, records none. Images now also come with their `opacity`. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged.
|
||||
- **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `<kind>` dialog cannot set protected field `<field>`"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged.
|
||||
|
||||
Reference in new issue
Block a user